From 13a29c2c2a7562a649e0cb1869d191e79dd20f2d Mon Sep 17 00:00:00 2001 From: Florian Krieger Date: Sun, 25 Oct 2026 15:38:10 +0100 Subject: [PATCH 001/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] =?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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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/491] 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 ac5928d41d157e6a20b6359a0ac3a7a30815461a Mon Sep 17 00:00:00 2001 From: Christopher Hawker Date: Thu, 29 Oct 2026 21:16:21 +1100 Subject: [PATCH 108/491] A carrier's own transit port takes its traffic, with a Carry here switch for other POPs Transit ports at a POP shared load by free capacity whatever the traffic was for, so Level Tree's own traffic went out of a Tell-Ya port about half the time. Traffic bound for a carrier, or for a network that buys transit from it, now goes out of that carrier's port at the same POP first (the shorter AS path). Each such port is still an ordinary transit exit, so POPs without one use it when nothing nearer has room. A new switch on each transit port, Carry here, pulls that traffic from every POP across your network to this port. The default, Nearest port, keeps using the closest transit port from POPs that have no port of the carrier. The switch only shows when another carrier's port could take the traffic instead. Prefer-marked ports, Backup only, RouteScript and Auto-TE keep their say, and any Prefer-marked transit port switches the rule off. Traceroute follows the same rule and says why it picked an exit. The setting is repaired in sanitize(); old saves load with it off. The routing reference test now has several carriers sharing POPs, ports that carry, backup ports and RouteScript, and its reference loop knows the new ranks. --- CHANGELOG.md | 2 + docs/ARCHITECTURE.md | 9 +- site/i18n/de.js | 7 + site/i18n/es.js | 7 + site/i18n/fr.js | 7 + site/i18n/it.js | 7 + site/i18n/pt.js | 7 + src/game/60-features/50-traceroute.js | 10 +- src/game/80-simulation/25-direct-egress.js | 7 + src/game/80-simulation/30-compute.js | 18 ++- src/game/80-simulation/50-sanitize.js | 2 +- src/game/90-actions/60-links.js | 1 + src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/70-link-panels.js | 4 + src/i18n/en.js | 7 + tests/direct-egress.test.js | 160 +++++++++++++++++++++ tests/helpers/reference-allocation.js | 4 +- tests/routing-reference.test.js | 8 ++ 18 files changed, 257 insertions(+), 12 deletions(-) create mode 100644 src/game/80-simulation/25-direct-egress.js create mode 100644 tests/direct-egress.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index eb2f3d5..e5ab832 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Traffic for a carrier now leaves through that carrier's own transit port at the same POP, instead of being shared with every other transit port there. Networks that buy transit from the carrier get the same treatment, and a new switch on each transit port, Carry here, pulls that traffic across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win. + ## [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/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b3eb5ec..64120f3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -112,12 +112,17 @@ never freezes the game. handed back to links the active ones fill first and standby links take the rest. 2. Builds the exit list `E`: embedded caches (rank 0), PNIs (1), IX ports (2), transit (3). Each exit has a capacity, the networks it can reach (`ok(net)`) and an - egress preference (`high`, `normal`, `low` = backup only). + egress preference (`high`, `normal`, `low` = backup only). A transit port can also be set to + carry (`t.carry`): see step 4. 3. Builds flows: for every POP, its demand (eyeballs and customers) split across destination networks by their traffic share (`NSH`, with regional variants for China, Russia and Korea). Incidents can add junk flows or scale demand. 4. Routes flows rank by rank: the nearest usable exit first, ECMP across equal exits, - consuming link, router (`nodeCap`) and exit capacity. With Auto-TE, overflow spills + consuming link, router (`nodeCap`) and exit capacity. A carrier's own transit port also + goes first, before plain transit, for traffic bound for that carrier or for a network that buys + transit from it (`25-direct-egress.js`: the shorter AS path): always at its own POP, and from every + POP when the port is set to carry. Such a port is still an ordinary transit exit for the other + POPs. A Prefer-marked port, backup, RouteScript and Auto-TE rules keep their say. With Auto-TE, overflow spills onto alternate paths; RouteScript rules (`teRules()`) can prefer, avoid, cap, drain or blackhole. 5. Layer-2 customers (L2VPN, SD-WAN, waves) are carved out of link capacity first. diff --git a/site/i18n/de.js b/site/i18n/de.js index 0b751b2..812fad5 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2102,12 +2102,14 @@ "link_panels.abandon_the_fiber":"Glasfaser aufgeben", "link_panels.add_parallel_link":"Parallelen Link hinzufügen", "link_panels.apply_for_a_license_price_mo":"Lizenz beantragen {price} + {mo}/Monat · ~45 Tage", +"link_panels.at_this_pop_net_s_traffic_always":"In diesem POP nimmt der Verkehr zu {net} immer diesen Port. POPs ohne einen nehmen ihren nächsten Transit-Port.", "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.", "link_panels.biggest_feeder_egress_in_city_set":"Größter Zubringer: {egress} in {city}. Stell ihn auf „Nur Backup“, gib den Kunden einen näheren Ausgang (Peering, einen Cache, lokalen Transit) oder erhöhe die Metrik dieses Links.", "link_panels.build_a_pop_here_first":"Bau hier zuerst einen POP.", "link_panels.cancel_the_iru":"IRU kündigen", +"link_panels.carry_here":"Hierher leiten", "link_panels.click_to_tear_down":"Klicken zum Abbauen", "link_panels.collecting_data_check_back_in_a":"Daten werden gesammelt. Schau in ein paar Tagen wieder rein.", "link_panels.congested_upgrade_it_or_add_a":"Überlastet. Rüste ihn auf oder füg einen parallelen Pfad hinzu.", @@ -2116,6 +2118,7 @@ "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Personalisierte DE-KICKS-Preise: {p} % von dem, was ein normaler IX verlangen würde.", "link_panels.each_channel_is_a_pair_of":"Jeder Kanal ist ein Paar Optiken, eine pro Ende. ZR+-Optiken stecken direkt in deinen Routern. Transponder sitzen in einem Shelf.", "link_panels.enters_your_network_at":"Kommt in dein Netz bei", +"link_panels.every_pop_carries_net_s_traffic":"Jeder POP leitet den Verkehr zu {net} durch dein Netz bis zu diesem Port.", "link_panels.finish_in_1_day_price":"In 1 Tag fertigstellen {price}", "link_panels.foreign_networks_need_a_local_joint":"Ausländische Netze brauchen ein lokales Joint Venture und eine Betriebslizenz, um hier Infrastruktur zu bauen.", "link_panels.found_your_own_ix_cost_mo":"Eigenen IX gründen {cost} + {mo}/Monat", @@ -2148,6 +2151,7 @@ "link_panels.name_is_down_nothing_you_can":"{name} ist down. Da hilft nur Warten, oder ein anderer Pfad.", "link_panels.name_parallel_link":"Paralleler Link {name}", "link_panels.name_wave":"{name}-Wave", +"link_panels.nearest_port":"Nächster Port", "link_panels.needs_a_pop_in_cities_too":"Braucht auch einen POP in {cities}.", "link_panels.needs_what":"braucht {what}", "link_panels.needs_your_own_scrubbing_center":"Braucht ein eigenes Scrubbing-Center (Tab Infra).", @@ -2207,6 +2211,7 @@ "link_panels.this_is_the_only_link_between":"Das ist der einzige Link zwischen diesen Städten. Füg einen parallelen hinzu oder einen Pfad über eine andere Stadt.", "link_panels.tier_1_only_a_pni_and":"Tier 1: nur ein PNI, und nur, wenn du groß genug für den Tier-1-Club bist", "link_panels.totals_for_all_n_links_between":"Summen für alle {n} Links zwischen diesen Städten.", +"link_panels.traffic_for_net":"Verkehr zu {net}", "link_panels.unplugged_optics_go_on_the_spares":"Ausgesteckte Optiken kommen ins Ersatzteilregal und werden beim nächsten Mal zuerst verwendet.", "link_panels.upgrade_fabric_to_name_cost_mo":"Fabric auf {name} upgraden {cost} + {mo}/Monat", "link_panels.upgrade_to_sys_price":"Upgrade auf {sys} {price}", @@ -3050,6 +3055,7 @@ "traceroute.ix_peering_beats_transit":"IX-Peering schlägt Transit", "traceroute.n_network_unreachable":"!N Netz nicht erreichbar", "traceroute.name_transit":"Transit von {name}", +"traceroute.net_buys_transit_from_carrier_so_that":"{net} kauft Transit bei {carrier}, daher schlägt dieser Port die anderen Transit-Ports.", "traceroute.net_carries_it_to_city":"{net} bringt es nach {city}", "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.", @@ -3058,6 +3064,7 @@ "traceroute.pnis_beat_ix_peering":"PNIs schlagen IX-Peering", "traceroute.private_cross_connect":"privater Cross-Connect", "traceroute.rule_and_closer_exits_win_ties":"{rule}, und bei Gleichstand gewinnt der nähere Ausgang", +"traceroute.the_carrier_s_own_port_beats_other":"Dieser Port führt direkt zu {net} und schlägt daher die anderen Transit-Ports.", "traceroute.this_one_is_set_to_mode":"; dieser steht auf {mode}", "traceroute.transit_is_the_last_resort":"Transit ist der letzte Ausweg", "tutorial.businesses_pop_up_as_bubbles_on":"Unternehmen tauchen als $-Blasen auf der Karte auf. Öffne Deals und gewinne deinen ersten Kunden.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2f2a645..88d06ce 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2100,12 +2100,14 @@ "link_panels.abandon_the_fiber":"Abandonar la fibra", "link_panels.add_parallel_link":"Añadir enlace paralelo", "link_panels.apply_for_a_license_price_mo":"Solicitar una licencia {price} + {mo}/mes · ~45 días", +"link_panels.at_this_pop_net_s_traffic_always":"En este POP, el tráfico de {net} siempre usa este puerto. Los POP que no tienen uno usan su puerto de tránsito más cercano.", "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.", "link_panels.biggest_feeder_egress_in_city_set":"Mayor alimentador: {egress} en {city}. Ponlo en «Solo respaldo», dale a los clientes una salida más cercana (peering, una caché, tránsito local) o sube la métrica de este enlace.", "link_panels.build_a_pop_here_first":"Construye primero un POP aquí.", "link_panels.cancel_the_iru":"Cancelar la IRU", +"link_panels.carry_here":"Llevar aquí", "link_panels.click_to_tear_down":"Haz clic para desmontar", "link_panels.collecting_data_check_back_in_a":"Recopilando datos. Vuelve en unos días.", "link_panels.congested_upgrade_it_or_add_a":"Congestionado. Mejóralo o añade una ruta paralela.", @@ -2114,6 +2116,7 @@ "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Precio personalizado de DE-KICKS: {p} % de lo que cobraría un IX normal.", "link_panels.each_channel_is_a_pair_of":"Cada canal es un par de ópticas, una por extremo. Las ópticas ZR+ se enchufan directo a tus routers. Los transpondedores van en un estante.", "link_panels.enters_your_network_at":"Entra en tu red por", +"link_panels.every_pop_carries_net_s_traffic":"Cada POP lleva el tráfico de {net} por tu red hasta este puerto.", "link_panels.finish_in_1_day_price":"Terminar en 1 día {price}", "link_panels.foreign_networks_need_a_local_joint":"Las redes extranjeras necesitan una empresa conjunta local y una licencia de operación para construir infraestructura aquí.", "link_panels.found_your_own_ix_cost_mo":"Funda tu propio IX {cost} + {mo}/mes", @@ -2146,6 +2149,7 @@ "link_panels.name_is_down_nothing_you_can":"{name} está caído. No puedes hacer nada salvo esperar, o tener otra ruta.", "link_panels.name_parallel_link":"Enlace paralelo {name}", "link_panels.name_wave":"Onda {name}", +"link_panels.nearest_port":"Puerto más cercano", "link_panels.needs_a_pop_in_cities_too":"Necesita también un POP en {cities}.", "link_panels.needs_what":"necesita {what}", "link_panels.needs_your_own_scrubbing_center":"Necesita tu propio centro de depuración (pestaña Infra).", @@ -2205,6 +2209,7 @@ "link_panels.this_is_the_only_link_between":"Este es el único enlace entre estas ciudades. Añade uno paralelo, o una ruta por otra ciudad.", "link_panels.tier_1_only_a_pni_and":"Tier 1: solo un PNI, y solo cuando seas lo bastante grande para el club de los Tier 1", "link_panels.totals_for_all_n_links_between":"Totales de los {n} enlaces entre estas ciudades.", +"link_panels.traffic_for_net":"Tráfico hacia {net}", "link_panels.unplugged_optics_go_on_the_spares":"Las ópticas desenchufadas van al estante de repuestos y se usan primero la próxima vez.", "link_panels.upgrade_fabric_to_name_cost_mo":"Mejorar la fabric a {name} {cost} + {mo}/mes", "link_panels.upgrade_to_sys_price":"Mejorar a {sys} {price}", @@ -3048,6 +3053,7 @@ "traceroute.ix_peering_beats_transit":"el peering en IX gana al tránsito", "traceroute.n_network_unreachable":"!N red inalcanzable", "traceroute.name_transit":"Tránsito de {name}", +"traceroute.net_buys_transit_from_carrier_so_that":"{net} compra tránsito a {carrier}, así que ese puerto gana a los otros puertos de tránsito.", "traceroute.net_carries_it_to_city":"{net} lo lleva hasta {city}", "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.", @@ -3056,6 +3062,7 @@ "traceroute.pnis_beat_ix_peering":"los PNIs ganan al peering en IX", "traceroute.private_cross_connect":"interconexión cruzada privada", "traceroute.rule_and_closer_exits_win_ties":"{rule}, y las salidas más cercanas ganan los empates", +"traceroute.the_carrier_s_own_port_beats_other":"Este puerto va directo a {net}, así que gana a los otros puertos de tránsito.", "traceroute.this_one_is_set_to_mode":"; esta está en {mode}", "traceroute.transit_is_the_last_resort":"el tránsito es el último recurso", "tutorial.businesses_pop_up_as_bubbles_on":"Las empresas aparecen como burbujas de $ en el mapa. Abre Tratos y firma a tu primer cliente.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 413ae5f..a08a01d 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2100,12 +2100,14 @@ "link_panels.abandon_the_fiber":"Abandonner la fibre", "link_panels.add_parallel_link":"Ajouter un lien parallèle", "link_panels.apply_for_a_license_price_mo":"Demander une licence {price} + {mo}/mois · ~45 jours", +"link_panels.at_this_pop_net_s_traffic_always":"Dans ce POP, le trafic de {net} passe toujours par ce port. Les POP qui n’en ont pas utilisent leur port de transit le plus proche.", "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.", "link_panels.biggest_feeder_egress_in_city_set":"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.", "link_panels.build_a_pop_here_first":"Construis d’abord un POP ici.", "link_panels.cancel_the_iru":"Résilier l’IRU", +"link_panels.carry_here":"Acheminer ici", "link_panels.click_to_tear_down":"Clique pour couper la session", "link_panels.collecting_data_check_back_in_a":"Collecte des données en cours. Repasse dans quelques jours.", "link_panels.congested_upgrade_it_or_add_a":"Saturé. Augmente sa capacité ou ajoute un chemin parallèle.", @@ -2114,6 +2116,7 @@ "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Tarif personnalisé DE-KICKS : {p} % de ce que facturerait un IX normal.", "link_panels.each_channel_is_a_pair_of":"Chaque canal, c’est une paire d’optiques, une à chaque bout. Les optiques ZR+ se branchent directement dans tes routeurs. Les transpondeurs vivent sur une étagère.", "link_panels.enters_your_network_at":"Entre dans ton réseau à", +"link_panels.every_pop_carries_net_s_traffic":"Chaque POP achemine le trafic de {net} à travers ton réseau jusqu’à ce port.", "link_panels.finish_in_1_day_price":"Terminer en 1 jour {price}", "link_panels.foreign_networks_need_a_local_joint":"Les réseaux étrangers ont besoin d’une coentreprise locale et d’une licence d’opérateur pour construire ici.", "link_panels.found_your_own_ix_cost_mo":"Fonder ton propre IX {cost} + {mo}/mois", @@ -2146,6 +2149,7 @@ "link_panels.name_is_down_nothing_you_can":"{name} est en panne. Rien à faire à part attendre, ou avoir un autre chemin.", "link_panels.name_parallel_link":"Lien parallèle {name}", "link_panels.name_wave":"Longueur d’onde {name}", +"link_panels.nearest_port":"Port le plus proche", "link_panels.needs_a_pop_in_cities_too":"Il faut aussi un POP à {cities}.", "link_panels.needs_what":"requiert {what}", "link_panels.needs_your_own_scrubbing_center":"Il faut ton propre centre de scrubbing (onglet Infra).", @@ -2205,6 +2209,7 @@ "link_panels.this_is_the_only_link_between":"C’est le seul lien entre ces villes. Ajoutes-en un parallèle, ou un chemin via une autre ville.", "link_panels.tier_1_only_a_pni_and":"Tier 1 : PNI uniquement, et seulement quand tu seras assez gros pour le club des Tier 1", "link_panels.totals_for_all_n_links_between":"Totaux des {n} liens entre ces villes.", +"link_panels.traffic_for_net":"Trafic vers {net}", "link_panels.unplugged_optics_go_on_the_spares":"Les optiques débranchées vont sur l’étagère de rechange et sont utilisées en premier la fois suivante.", "link_panels.upgrade_fabric_to_name_cost_mo":"Passer au fabric {name} {cost} + {mo}/mois", "link_panels.upgrade_to_sys_price":"Passer à {sys} {price}", @@ -3048,6 +3053,7 @@ "traceroute.ix_peering_beats_transit":"le peering IX bat le transit", "traceroute.n_network_unreachable":"!N réseau injoignable", "traceroute.name_transit":"Transit {name}", +"traceroute.net_buys_transit_from_carrier_so_that":"{net} achète du transit chez {carrier}, donc ce port passe avant les autres ports de transit.", "traceroute.net_carries_it_to_city":"{net} l’achemine jusqu’à {city}", "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.", @@ -3056,6 +3062,7 @@ "traceroute.pnis_beat_ix_peering":"les PNI battent le peering IX", "traceroute.private_cross_connect":"cross-connect privé", "traceroute.rule_and_closer_exits_win_ties":"{rule}, et la sortie la plus proche l’emporte en cas d’égalité", +"traceroute.the_carrier_s_own_port_beats_other":"Ce port mène directement chez {net}, donc il passe avant les autres ports de transit.", "traceroute.this_one_is_set_to_mode":" ; celle-ci est réglée sur {mode}", "traceroute.transit_is_the_last_resort":"le transit est le dernier recours", "tutorial.businesses_pop_up_as_bubbles_on":"Les entreprises apparaissent sous forme de bulles $ sur la carte. Ouvre Offres et signe ton premier client.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 103bc61..b763e03 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2100,12 +2100,14 @@ "link_panels.abandon_the_fiber":"Abbandona la fibra", "link_panels.add_parallel_link":"Aggiungi link parallelo", "link_panels.apply_for_a_license_price_mo":"Richiedi una licenza {price} + {mo}/mese · ~45 giorni", +"link_panels.at_this_pop_net_s_traffic_always":"In questo POP il traffico di {net} usa sempre questa porta. I POP che non ne hanno una usano la porta di transit più vicina.", "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.", "link_panels.biggest_feeder_egress_in_city_set":"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.", "link_panels.build_a_pop_here_first":"Prima costruisci un POP qui.", "link_panels.cancel_the_iru":"Disdici l’IRU", +"link_panels.carry_here":"Porta qui", "link_panels.click_to_tear_down":"Clicca per chiudere la sessione", "link_panels.collecting_data_check_back_in_a":"Raccolta dati in corso. Ripassa tra qualche giorno.", "link_panels.congested_upgrade_it_or_add_a":"Congestionato. Potenzialo o aggiungi un percorso parallelo.", @@ -2114,6 +2116,7 @@ "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Prezzi personalizzati DE-KICKS: {p}% di quanto chiederebbe un IX normale.", "link_panels.each_channel_is_a_pair_of":"Ogni canale è una coppia di ottiche, una per estremità. Le ottiche ZR+ si infilano direttamente nei tuoi router. I transponder stanno su uno scaffale.", "link_panels.enters_your_network_at":"Entra nella tua rete a", +"link_panels.every_pop_carries_net_s_traffic":"Ogni POP porta il traffico di {net} attraverso la tua rete fino a questa porta.", "link_panels.finish_in_1_day_price":"Termina in 1 giorno {price}", "link_panels.foreign_networks_need_a_local_joint":"Per costruire infrastrutture qui, le reti straniere hanno bisogno di una joint venture locale e di una licenza operativa.", "link_panels.found_your_own_ix_cost_mo":"Fonda il tuo IX {cost} + {mo}/mese", @@ -2146,6 +2149,7 @@ "link_panels.name_is_down_nothing_you_can":"{name} è giù. Non puoi far altro che aspettare, o avere un altro percorso.", "link_panels.name_parallel_link":"Link parallelo {name}", "link_panels.name_wave":"Wave {name}", +"link_panels.nearest_port":"Porta più vicina", "link_panels.needs_a_pop_in_cities_too":"Serve un POP anche a {cities}.", "link_panels.needs_what":"serve {what}", "link_panels.needs_your_own_scrubbing_center":"Serve il tuo centro di scrubbing (scheda Infra).", @@ -2205,6 +2209,7 @@ "link_panels.this_is_the_only_link_between":"È l’unico link tra queste città. Aggiungine uno parallelo, o un percorso che passi da un’altra città.", "link_panels.tier_1_only_a_pni_and":"Tier 1: solo un PNI, e solo quando sarai abbastanza grande per il club dei Tier 1", "link_panels.totals_for_all_n_links_between":"Totali di tutti i {n} link tra queste città.", +"link_panels.traffic_for_net":"Traffico per {net}", "link_panels.unplugged_optics_go_on_the_spares":"Le ottiche scollegate vanno sullo scaffale dei ricambi e la volta dopo si usano per prime.", "link_panels.upgrade_fabric_to_name_cost_mo":"Passa al fabric {name} {cost} + {mo}/mese", "link_panels.upgrade_to_sys_price":"Passa a {sys} {price}", @@ -3048,6 +3053,7 @@ "traceroute.ix_peering_beats_transit":"il peering IX batte il transit", "traceroute.n_network_unreachable":"!N rete irraggiungibile", "traceroute.name_transit":"Transit {name}", +"traceroute.net_buys_transit_from_carrier_so_that":"{net} compra transit da {carrier}, quindi quella porta batte le altre porte di transit.", "traceroute.net_carries_it_to_city":"{net} lo porta fino a {city}", "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.", @@ -3056,6 +3062,7 @@ "traceroute.pnis_beat_ix_peering":"i PNI battono il peering IX", "traceroute.private_cross_connect":"cross-connect privato", "traceroute.rule_and_closer_exits_win_ties":"{rule}, e a parità vince l’uscita più vicina", +"traceroute.the_carrier_s_own_port_beats_other":"Questa porta va direttamente a {net}, quindi batte le altre porte di transit.", "traceroute.this_one_is_set_to_mode":"; questa è impostata su {mode}", "traceroute.transit_is_the_last_resort":"il transit è l’ultima spiaggia", "tutorial.businesses_pop_up_as_bubbles_on":"Le aziende spuntano come bolle $ sulla mappa. Apri Offerte e firma il tuo primo cliente.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 046f9a8..7241d44 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2100,12 +2100,14 @@ "link_panels.abandon_the_fiber":"Abandonar a fibra", "link_panels.add_parallel_link":"Adicionar link paralelo", "link_panels.apply_for_a_license_price_mo":"Pedir licença {price} + {mo}/mês · ~45 dias", +"link_panels.at_this_pop_net_s_traffic_always":"Neste POP, o tráfego de {net} sempre usa esta porta. POPs sem uma usam a porta de transit mais próxima.", "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.", "link_panels.biggest_feeder_egress_in_city_set":"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.", "link_panels.build_a_pop_here_first":"Construa um POP aqui primeiro.", "link_panels.cancel_the_iru":"Cancelar o IRU", +"link_panels.carry_here":"Trazer para cá", "link_panels.click_to_tear_down":"Clique para encerrar", "link_panels.collecting_data_check_back_in_a":"Coletando dados. Volte em alguns dias.", "link_panels.congested_upgrade_it_or_add_a":"Congestionado. Faça upgrade ou adicione um caminho paralelo.", @@ -2114,6 +2116,7 @@ "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Preço personalizado DE-KICKS: {p}% do que um IX normal cobraria.", "link_panels.each_channel_is_a_pair_of":"Cada canal é um par de ópticas, uma em cada ponta. Ópticas ZR+ encaixam direto nos seus routers. Transponders ficam numa prateleira.", "link_panels.enters_your_network_at":"Entra na sua rede em", +"link_panels.every_pop_carries_net_s_traffic":"Cada POP leva o tráfego de {net} pela sua rede até esta porta.", "link_panels.finish_in_1_day_price":"Concluir em 1 dia {price}", "link_panels.foreign_networks_need_a_local_joint":"Redes estrangeiras precisam de uma joint venture local e de uma licença de operação para construir infraestrutura aqui.", "link_panels.found_your_own_ix_cost_mo":"Fundar seu próprio IX {cost} + {mo}/mês", @@ -2146,6 +2149,7 @@ "link_panels.name_is_down_nothing_you_can":"{name} caiu. Não há o que fazer além de esperar, ou ter outro caminho.", "link_panels.name_parallel_link":"Link paralelo {name}", "link_panels.name_wave":"Wave {name}", +"link_panels.nearest_port":"Porta mais próxima", "link_panels.needs_a_pop_in_cities_too":"Requer um POP em {cities} também.", "link_panels.needs_what":"requer {what}", "link_panels.needs_your_own_scrubbing_center":"Requer seu próprio centro de scrubbing (aba Infra).", @@ -2205,6 +2209,7 @@ "link_panels.this_is_the_only_link_between":"É o único link entre essas cidades. Adicione um paralelo, ou um caminho passando por outra cidade.", "link_panels.tier_1_only_a_pni_and":"Tier 1: só PNI, e só quando você for grande o bastante para o clube dos Tier 1", "link_panels.totals_for_all_n_links_between":"Totais de todos os {n} links entre essas cidades.", +"link_panels.traffic_for_net":"Tráfego para {net}", "link_panels.unplugged_optics_go_on_the_spares":"Ópticos desconectados vão para a prateleira de reservas e são usados primeiro na próxima vez.", "link_panels.upgrade_fabric_to_name_cost_mo":"Upgrade para fabric {name} {cost} + {mo}/mês", "link_panels.upgrade_to_sys_price":"Atualizar para {sys} {price}", @@ -3048,6 +3053,7 @@ "traceroute.ix_peering_beats_transit":"peering no IX vence transit", "traceroute.n_network_unreachable":"!N rede inalcançável", "traceroute.name_transit":"Transit {name}", +"traceroute.net_buys_transit_from_carrier_so_that":"{net} compra transit de {carrier}, então essa porta vence as outras portas de transit.", "traceroute.net_carries_it_to_city":"{net} leva até {city}", "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.", @@ -3056,6 +3062,7 @@ "traceroute.pnis_beat_ix_peering":"PNIs vencem peering no IX", "traceroute.private_cross_connect":"cross-connect privado", "traceroute.rule_and_closer_exits_win_ties":"{rule}, e no empate vence a saída mais próxima", +"traceroute.the_carrier_s_own_port_beats_other":"Esta porta vai direto para {net}, então vence as outras portas de transit.", "traceroute.this_one_is_set_to_mode":"; esta está configurada como {mode}", "traceroute.transit_is_the_last_resort":"transit é o último recurso", "tutorial.businesses_pop_up_as_bubbles_on":"Empresas aparecem como bolhas de $ no mapa. Abra Negócios e feche seu primeiro cliente.", diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js index dd7ad77..db19a5f 100644 --- a/src/game/60-features/50-traceroute.js +++ b/src/game/60-features/50-traceroute.js @@ -10,7 +10,7 @@ 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}); 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)}); - 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)}); + 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',carry:!!t.carry,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; const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);}; @@ -20,8 +20,12 @@ function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[] const N=NET[to.net],ex=trExits(to.net).filter(e=>P.dist[e.city]!==undefined); lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`); if(!ex.length){lines.push(' 2 * * *\n 3 * * * ← '+tr('traceroute.n_network_unreachable'));return {text:lines.join('\n'),why:tr('traceroute.nothing_on_your_network_reaches_net',{net:N.name,city:CITY[src].name}),asPath:null};} - ex.sort((a,b)=>(a.pref==='low'?4:a.rank)-(b.pref==='low'?4:b.rank)||(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||P.dist[a.city]-P.dist[b.city]); + // As in compute(): a carrier's own port (or its customers' carrier) goes before other transit, at this POP or anywhere when it carries. + const hiAny=S.transit.some(t=>t.pref==='high'&&popUp(t.city)&&!(t.down>S.day)&&liveN(t.city,t.site,t.n)),dtier=e=>hiAny||e.k!=='t'||e.pref==='low'?0:directTier(e.tnet,N.id); + const rk=e=>{const r=e.pref==='low'?4:e.rank,t=dtier(e);return t&&(e.carry||e.city===src)?Math.min(r,DIRECT_RANK[t][e.carry?0:1]):r;}; + ex.sort((a,b)=>rk(a)-rk(b)||(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||P.dist[a.city]-P.dist[b.city]); const e=ex.find(x=>x.usedkmBetween(e.city,c)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};} + 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')}):''}.${direct}${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]; const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t; const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)}):traceroute(src,{city:t.slice(5)}); diff --git a/src/game/80-simulation/25-direct-egress.js b/src/game/80-simulation/25-direct-egress.js new file mode 100644 index 0000000..e02750f0 --- /dev/null +++ b/src/game/80-simulation/25-direct-egress.js @@ -0,0 +1,7 @@ +/* A carrier's own transit port beats other transit ports for traffic bound for that carrier (tier 1) or for a network + that buys transit from it (tier 2): the shorter AS path. A port set to carry pulls that traffic from every POP; any + other only takes it at the POP it sits in. These ranks come after RouteScript's `prefer transit` (2.9) and before plain + transit (3), and each port stays in the plain transit list too, so POPs far from it can still use it. + DIRECT_RANK[tier] = [carries, this POP only]. compute() and traceroute() share this. */ +const DIRECT_RANK=[null,[2.92,2.93],[2.94,2.95]]; +const directTier=(carrier,dest)=>carrier===dest?1:(NET[dest].up&&NET[dest].up.includes(carrier))?2:0; diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index cbe0fd6..c0e882d 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -19,7 +19,7 @@ function compute(){ 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',carry:!!t.carry,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}; 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; @@ -150,12 +150,19 @@ function compute(){ 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;}; - 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]; + // A carrier's own port for traffic bound for it or for its customers (25-direct-egress.js): tried before plain transit, but + // never over RouteScript, a Prefer-marked port or a port set to backup, which all keep the say they had. Such a port is + // also an ordinary transit exit (rank 3), so POPs without one of its own can still use it. + const hiAny=E.some(e=>e.k==='t'&&e.pref==='high'); + const dr=(e,n)=>{if(hiAny||e.k!=='t')return 0;const t=directTier(e.net,n);return t&&eff(e,n)===3?DIRECT_RANK[t][e.carry?0:1]:0;}; + const RANKS=TR?[0,0.5,1,2,2.9,2.92,2.93,2.94,2.95,3,3.5,4,4.4,4.5,4.6]:[0,1,2,2.92,2.93,2.94,2.95,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);} + // usedRank: the ranks that have a list for some network, so a rank nobody sits at costs no pass over the flows. + const byRank={},usedRank=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);(m[r]||(m[r]=[])).push(e);usedRank.add(r); + const d=dr(e,id);if(d){(m[d]||(m[d]=[])).push(e);usedRank.add(d);}} 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,12 +207,15 @@ 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(!usedRank.has(rank))continue; + // A carrier's own port that is not set to carry only takes the traffic of the POP it sits in. + const LOC=rank===DIRECT_RANK[1][1]||rank===DIRECT_RANK[2][1]; // Index loops in here: plain for…of allocates an iterator per loop until V8 has optimised compute(). for(let fi=0,FN=flows.length;fiv&&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.premium=premOnlyAt(NET[t.net],t.city)||!!t.premium&&premCity(NET[t.net],t.city),t)); + 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.carry===true||delete t.carry,t.premium=premOnlyAt(NET[t.net],t.city)||!!t.premium&&premCity(NET[t.net],t.city),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)); // PNIs on order (#…): delivery day, a pending augment, and 1G for the one network that sells it for(const x of s.pni){if(x.ready!==undefined)x.ready=num(x.ready,0);if(x.g1)x.g1=x.tier===0&&x.net==='dtk'?true:undefined;else delete x.g1;if(x.up){const u=x.up;x.up=u&&typeof u==='object'?{tier:tier(u.tier),n:lag(u.n),ready:num(u.ready,0),g1:!!u.g1&&x.net==='dtk'&&tier(u.tier)===0}:undefined;if(!x.up)delete x.up;}} diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index 0e6faff..4b940cc 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -29,6 +29,7 @@ Object.assign(ACT,{ cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);prunePairMet();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;const m=S.pairMet||(S.pairMet={}),k=edgeKey(l);if(v==='normal')delete m[k];else m[k]=v;sfx('click');after();}, + setCarry:({id,on})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;if(on)t.carry=true;else delete t.carry;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();}, goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();}, }); diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 90aa26a..fd44aba 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -45,7 +45,7 @@ function cityPanel(c){ for(const n of prov){const t=S.transit.find(x=>x.city===c&&x.net===n.id);const pr=transitPerG(n,c,premOnlyAt(n,c)||!!(t&&premOn(t)))*S.priceMul; h+=`
${logo(n)}
${esc(n.name)} ${TYPE_L[n.type]}
${tr('city_panel.price_per_gbps_month_billed_on',{price:pr.toFixed(2)})}
${premOnlyAt(n,c)&&!t?`
${tr('city_panel.only_the_cn_too_premium_crossing')}
`:''}`; if(t){const u=R.useT[t.id]||0,cap=lagCap(PORT[t.tier].g,t.n),tdown=t.down>S.day; - h+=`
${lagName(t.tier,t.n)}${tdown?' · '+tr('common.outage')+'':''}${fmtG(u)}
${prefCtl('t',t.id,t.pref)}${siteCtl('t',t.id,c,t.site)}${premOnlyAt(n,c)?`

${tr('city_panel.only_the_cn_too_premium_crossing')}

`:premCity(n,c)?`
${btn(t.premium?tr('city_panel.cn_too_premium_on'):tr('city_panel.switch_to_cn_too_premium_x',{x:n.premium}),'togglePrem',{id:t.id},t.premium?'green sm':'sm')}
`:''}${(()=>{const top=transitTop([t.id],4);return top.length?`
${tr('city_panel.top_destinations_on_this_port')}
${top.map(([id,v])=>`
${esc(NET[id].name)} · ${fmtG(v)} · ${esc(offTransitHint(id,c))}
`).join('')}
`:'';})()}
${tr('city_panel.95th_pct_p95_commit_commit_bill',{p95:fmtG(R.p95[t.id]||0),commit:fmtG(cap*.2),bill:fmt$(Math.max(R.p95[t.id]||0,PORT[t.tier].g*(t.n||1)*.2)*pr+PORT[t.tier].tmo*(t.n||1))})}
+ h+=`
${lagName(t.tier,t.n)}${tdown?' · '+tr('common.outage')+'':''}${fmtG(u)}
${prefCtl('t',t.id,t.pref)}${carryCtl(t)}${siteCtl('t',t.id,c,t.site)}${premOnlyAt(n,c)?`

${tr('city_panel.only_the_cn_too_premium_crossing')}

`:premCity(n,c)?`
${btn(t.premium?tr('city_panel.cn_too_premium_on'):tr('city_panel.switch_to_cn_too_premium_x',{x:n.premium}),'togglePrem',{id:t.id},t.premium?'green sm':'sm')}
`:''}${(()=>{const top=transitTop([t.id],4);return top.length?`
${tr('city_panel.top_destinations_on_this_port')}
${top.map(([id,v])=>`
${esc(NET[id].name)} · ${fmtG(v)} · ${esc(offTransitHint(id,c))}
`).join('')}
`:'';})()}
${tr('city_panel.95th_pct_p95_commit_commit_bill',{p95:fmtG(R.p95[t.id]||0),commit:fmtG(cap*.2),bill:fmt$(Math.max(R.p95[t.id]||0,PORT[t.tier].g*(t.n||1)*.2)*pr+PORT[t.tier].tmo*(t.n||1))})}
${PORT.map((P2,i)=>i>t.tier&&portShown(i)?btn((t.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}):tr('common.upgrade_port_cost_mo_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}),'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash1?btn(tr('common.member'),'lagT',{id:t.id,d:-1},'ghost sm'):''}${btn(t.clean?tr('city_panel.clean_pipe_on'):tr('city_panel.clean_pipe_mo_mo_scrubs_ddos',{mo:fmt$(cleanMo(t))}),'cleanPipe',{id:t.id},t.clean?'green sm':'sm')}${btn(UI.confirm===t.id?tr('common.really_cancel'):tr('common.cancel'),'cancelTransit',{id:t.id},'ghost sm')}
`;} else h+=`
${PORT.map((P2,i)=>portShown(i)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(P2.setup),mo:fmt$(P2.tmo)}),'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash`; h+=`
`;} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 0378b3f..820f834 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -34,6 +34,10 @@ 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('')}
`;} +// At its own POP a carrier's port always takes that carrier's traffic (25-direct-egress.js). From POPs with no port of it, the +// traffic goes to the nearest transit port, or across your network to this one. Only worth asking when something else could take it. +function carryCtl(t){if(Object.keys(S.pops).length<2||!S.transit.some(x=>x.net!==t.net))return '';const n=esc(NET[t.net].name); + return `
${tr('link_panels.traffic_for_net',{net:n})}${btn(tr('link_panels.nearest_port'),'setCarry',{id:t.id,on:0},t.carry?'ghost sm':'pink sm')}${btn(tr('link_panels.carry_here'),'setCarry',{id:t.id,on:1},t.carry?'pink sm':'ghost sm')}
${t.carry?tr('link_panels.every_pop_carries_net_s_traffic',{net:n}):tr('link_panels.at_this_pop_net_s_traffic_always',{net:n})}
`;} function trafficSection(l){ const rec=R.ef[edgeKey(l)],n=pairLinks(l.a,l.b).length; let h=`

${tr('link_panels.what_s_on_this_link')}

`; diff --git a/src/i18n/en.js b/src/i18n/en.js index 008cdfd..fe529d6 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2101,12 +2101,14 @@ "link_panels.abandon_the_fiber":"Abandon the fiber", "link_panels.add_parallel_link":"Add parallel link", "link_panels.apply_for_a_license_price_mo":"Apply for a license {price} + {mo}/mo · ~45 days", +"link_panels.at_this_pop_net_s_traffic_always":"At this POP, {net}'s traffic always uses this port. POPs without one use their nearest transit port.", "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.", "link_panels.biggest_feeder_egress_in_city_set":"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.", "link_panels.build_a_pop_here_first":"Build a POP here first.", "link_panels.cancel_the_iru":"Cancel the IRU", +"link_panels.carry_here":"Carry here", "link_panels.click_to_tear_down":"Click to tear down", "link_panels.collecting_data_check_back_in_a":"Collecting data. Check back in a few days.", "link_panels.congested_upgrade_it_or_add_a":"Congested. Upgrade it or add a parallel path.", @@ -2115,6 +2117,7 @@ "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"DE-KICKS personalised pricing: {p}% of what a normal IX would charge.", "link_panels.each_channel_is_a_pair_of":"Each channel is a pair of optics, one per end. ZR+ optics plug straight into your routers. Transponders sit on a shelf.", "link_panels.enters_your_network_at":"Enters your network at", +"link_panels.every_pop_carries_net_s_traffic":"Every POP carries {net}'s traffic across your network to this port.", "link_panels.finish_in_1_day_price":"Finish in 1 day {price}", "link_panels.foreign_networks_need_a_local_joint":"Foreign networks need a local joint venture and an operating license to build infrastructure here.", "link_panels.found_your_own_ix_cost_mo":"Found your own IX {cost} + {mo}/mo", @@ -2147,6 +2150,7 @@ "link_panels.name_is_down_nothing_you_can":"{name} is down. Nothing you can do but wait, or have another path.", "link_panels.name_parallel_link":"{name} parallel link", "link_panels.name_wave":"{name} wave", +"link_panels.nearest_port":"Nearest port", "link_panels.needs_a_pop_in_cities_too":"Needs a POP in {cities} too.", "link_panels.needs_what":"needs {what}", "link_panels.needs_your_own_scrubbing_center":"Needs your own scrubbing center (Infra tab).", @@ -2206,6 +2210,7 @@ "link_panels.this_is_the_only_link_between":"This is the only link between these cities. Add a parallel one, or a path through another city.", "link_panels.tier_1_only_a_pni_and":"Tier 1: only a PNI, and only once you are big enough for the Tier 1 club", "link_panels.totals_for_all_n_links_between":"Totals for all {n} links between these cities.", +"link_panels.traffic_for_net":"Traffic for {net}", "link_panels.unplugged_optics_go_on_the_spares":"Unplugged optics go on the spares shelf and are used first next time.", "link_panels.upgrade_fabric_to_name_cost_mo":"Upgrade fabric to {name} {cost} + {mo}/mo", "link_panels.upgrade_to_sys_price":"Upgrade to {sys} {price}", @@ -3049,6 +3054,7 @@ "traceroute.ix_peering_beats_transit":"IX peering beats transit", "traceroute.n_network_unreachable":"!N network unreachable", "traceroute.name_transit":"{name} transit", +"traceroute.net_buys_transit_from_carrier_so_that":"{net} buys transit from {carrier}, so that port beats the other transit ports.", "traceroute.net_carries_it_to_city":"{net} carries it to {city}", "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.", @@ -3057,6 +3063,7 @@ "traceroute.pnis_beat_ix_peering":"PNIs beat IX peering", "traceroute.private_cross_connect":"private cross-connect", "traceroute.rule_and_closer_exits_win_ties":"{rule}, and closer exits win ties", +"traceroute.the_carrier_s_own_port_beats_other":"This port goes straight to {net}, so it beats the other transit ports.", "traceroute.this_one_is_set_to_mode":"; this one is set to {mode}", "traceroute.transit_is_the_last_resort":"transit is the last resort", "tutorial.businesses_pop_up_as_bubbles_on":"Businesses pop up as $ bubbles on the map. Open Deals and sign your first customer.", diff --git a/tests/direct-egress.test.js b/tests/direct-egress.test.js new file mode 100644 index 0000000..fd279e1 --- /dev/null +++ b/tests/direct-egress.test.js @@ -0,0 +1,160 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const port = (ev, carrier, city) => ev(`S.transit.find(t=>t.net==='${carrier}'${city ? `&&t.city==='${city}'` : ''}).id`); +const via = (ev, id, dest) => ev(`((R.tNet['${id}']||{})['${dest}'])||0`); + +// New York with eyeballs, and Level Tree and Tell-Ya ports in the same POP. +function newYork(lvlTier = 1, demand = 800) { + const g = load(); + g.ev(`ACT.pickStart({city:'nyc'});ACT.start({});S.cash=1e9;ACT.launchBB({city:'nyc'});S.pops.nyc.bb.d=${demand}; + ACT.buyTransit({city:'nyc',net:'lvl',tier:${lvlTier}});ACT.buyTransit({city:'nyc',net:'tly',tier:1});compute()`); + g.lvl = port(g.ev, 'lvl'); g.tly = port(g.ev, 'tly'); + return g; +} + +// Chicago has the eyeballs; Level Tree is in New York, Tell-Ya in Chicago, and a 100G wave joins them. +function twoPops() { + const g = load(); + g.ev(`ACT.pickStart({city:'nyc'});ACT.start({});S.cash=1e9;ACT.buildPop({city:'chi'}); + UI.via=null;UI.route='same';UI.lmode=null;openLinkModal('nyc','chi');ACT.buildLink({tier:1});closeModal(); + ACT.launchBB({city:'chi'});S.pops.chi.bb.d=80; + ACT.buyTransit({city:'nyc',net:'lvl',tier:1});ACT.buyTransit({city:'chi',net:'tly',tier:1});compute()`); + g.lvl = port(g.ev, 'lvl'); g.tly = port(g.ev, 'tly'); + g.link = g.ev("S.links[0].id"); + return g; +} + +test('at its own POP a carrier\'s port takes the traffic bound for that carrier, not an even split', () => { + const { ev, lvl, tly, errors } = newYork(); + assert.ok(via(ev, lvl, 'lvl') > 1, 'Level Tree traffic goes out of the Level Tree port'); + assert.equal(via(ev, tly, 'lvl'), 0, 'and none of it out of Tell-Ya'); + assert.ok(via(ev, tly, 'tly') > 1 && via(ev, lvl, 'tly') === 0, 'the same for Tell-Ya'); + assert.ok(via(ev, lvl, 'cog') > 1 && via(ev, tly, 'cog') > 1, 'traffic for a carrier you have no port of still shares both ports'); + assert.deepEqual(errors, []); +}); + +test('traffic for a carrier\'s customers prefers that carrier too, and a carrier beats its own customers\' other upstreams', () => { + const { ev, lvl, tly, errors } = newYork(); + // Tee-Hee Mobile buys from Level Tree and Not That Telecom, not from Tell-Ya. + assert.deepEqual(JSON.parse(ev("JSON.stringify(NET.tmo.up)")), ['lvl', 'ntt']); + assert.ok(via(ev, lvl, 'tmo') > 0 && via(ev, tly, 'tmo') === 0, 'Tee-Hee Mobile goes out of the Level Tree port'); + // Add Not That Telecom: it is just as good an upstream for Tee-Hee, so the two share it. Its own traffic stays on its own port. + ev("ACT.buyTransit({city:'nyc',net:'ntt',tier:1});compute()"); + const ntt = port(ev, 'ntt'); + assert.ok(via(ev, lvl, 'tmo') > 0 && via(ev, ntt, 'tmo') > 0 && via(ev, tly, 'tmo') === 0, 'two upstreams of the same network share its traffic'); + assert.ok(via(ev, ntt, 'ntt') > 0 && via(ev, lvl, 'ntt') === 0 && via(ev, tly, 'ntt') === 0); + assert.deepEqual(errors, []); +}); + +test('when the carrier\'s own port is full, the rest spills onto the other transit ports', () => { + const { ev, lvl, tly, errors } = newYork(0); // a 10G Level Tree port + assert.ok(ev(`R.useT['${lvl}']`) > 9.99, 'the small port is full'); + assert.ok(via(ev, lvl, 'lvl') > 9, 'mostly with Level Tree traffic'); + assert.ok(via(ev, tly, 'lvl') > 1, 'and the rest of Level Tree\'s traffic goes out of Tell-Ya'); + assert.deepEqual(errors, []); +}); + +test('Prefer, Backup only and RouteScript keep the say they had', () => { + // A Prefer-marked port of another carrier takes everything first, as it always did. + let g = newYork(1, 150); + g.ev(`ACT.setPref({kind:'t',id:'${g.tly}',v:'high'});compute()`); + assert.ok(via(g.ev, g.tly, 'lvl') > 1 && via(g.ev, g.lvl, 'lvl') === 0, 'Prefer on Tell-Ya sends Level Tree traffic there too'); + assert.deepEqual(g.errors, []); + // A port set to Backup only is the last resort, even for its own traffic. + g = newYork(1, 150); + g.ev(`ACT.setPref({kind:'t',id:'${g.lvl}',v:'low'});compute()`); + assert.equal(via(g.ev, g.lvl, 'lvl'), 0, 'Level Tree on backup carries none of its own traffic while Tell-Ya has room'); + assert.ok(via(g.ev, g.tly, 'lvl') > 1); + assert.deepEqual(g.errors, []); + // RouteScript's avoid transit is policy, and beats the shorter path. + g = newYork(1, 150); + g.ev("S.te={on:true,script:'avoid transit level tree'};compute()"); + assert.ok(g.ev("!!teRules()"), 'the script is active'); + assert.equal(via(g.ev, g.lvl, 'lvl'), 0, 'avoid transit level tree keeps even its own traffic off it'); + assert.ok(via(g.ev, g.tly, 'lvl') > 1); + assert.deepEqual(g.errors, []); +}); + +test('from a POP without the carrier\'s port, traffic uses the nearest port, or crosses your network when the port carries', () => { + const { ev, lvl, tly, link, errors } = twoPops(); + ev("S.te=null"); + assert.ok(via(ev, tly, 'lvl') > 1, 'by default Chicago sends Level Tree traffic out of its own nearest port, Tell-Ya'); + assert.equal(via(ev, lvl, 'lvl'), 0); + assert.equal(ev(`R.load['${link}']||0`), 0, 'nothing crosses the link'); + ev(`ACT.setCarry({id:'${lvl}',on:1})`); + assert.equal(ev(`S.transit.find(t=>t.id==='${lvl}').carry`), true); + assert.ok(via(ev, lvl, 'lvl') > 1, 'with Carry here, it crosses to New York and leaves by Level Tree'); + assert.ok(via(ev, tly, 'lvl') < 0.001, 'and not by Tell-Ya'); + assert.ok(ev(`R.load['${link}']`) > 1, 'over the circuit'); + assert.ok(via(ev, tly, 'tly') > 1 && via(ev, lvl, 'tly') === 0, 'Tell-Ya\'s own traffic is not affected'); + ev(`ACT.setCarry({id:'${lvl}',on:0})`); + assert.equal(ev(`S.transit.find(t=>t.id==='${lvl}').carry`), undefined, 'switching it off removes the flag'); + assert.ok(via(ev, tly, 'lvl') > 1, 'and the nearest port is used again'); + assert.deepEqual(errors, []); +}); + +test('traceroute shows the exit that routing uses, and says why', () => { + const { ev, lvl, errors } = twoPops(); + const why = (to, from = 'chi') => ev(`traceroute('${from}',{net:'${to}'}).why`); + const tly = port(ev, 'tly'); + assert.match(why('lvl'), /Tell-Ya.*Chicago/, 'nearest port from Chicago'); + assert.doesNotMatch(why('lvl'), /straight to/); + assert.ok(via(ev, tly, 'lvl') > 1 && via(ev, lvl, 'lvl') === 0, 'and that is the port routing really uses'); + ev(`ACT.setCarry({id:'${lvl}',on:1})`); + assert.ok(via(ev, lvl, 'lvl') > 1 && via(ev, tly, 'lvl') < 0.001, 'routing now uses the carrying port too'); + assert.match(why('lvl'), /Level Tree.*New York/, 'the carrying port, in New York'); + assert.match(why('lvl'), /straight to Level Tree/, 'because it goes straight to the carrier'); + assert.match(why('tmo'), /Tee-Hee Mobile buys transit from Level Tree/, 'and for its customers'); + assert.match(why('lvl', 'nyc'), /Level Tree.*New York/, 'at its own POP the carrier\'s port wins without carrying'); + ev(`ACT.setCarry({id:'${lvl}',on:0})`); + assert.match(why('lvl', 'nyc'), /Level Tree.*New York.*straight to Level Tree/, 'also with carry off'); + assert.deepEqual(errors, []); +}); + +test('the carry setting is saved, repaired and optional', () => { + const { ev, errors } = twoPops(); + ev(`ACT.setCarry({id:'${port(ev, 'lvl')}',on:1});save(true)`); + const saved = ev("localStorage.getItem('sot-save-v1')"); + const again = load({ storage: { 'sot-save-v1': saved } }); + assert.equal(again.ev("S.transit.find(t=>t.net==='lvl').carry"), true, 'survives a reload'); + assert.equal(again.ev("S.transit.find(t=>t.net==='tly').carry"), undefined, 'and is off for the others'); + // Hand-edited or imported garbage is dropped; an old save without the field just loads. + const bad = JSON.parse(saved); + bad.transit.forEach((t, i) => { t.carry = i ? 'yes' : 1; }); + const fixed = load({ storage: { 'sot-save-v1': JSON.stringify(bad) } }); + assert.equal(fixed.ev("S.transit.some(t=>'carry' in t)"), false); + const old = JSON.parse(saved); + old.transit.forEach((t) => { delete t.carry; }); + assert.equal(load({ storage: { 'sot-save-v1': JSON.stringify(old) } }).ev("S.transit.length"), 2); + assert.deepEqual([...errors, ...again.errors, ...fixed.errors], []); +}); + +test('each port offers the choice when it can matter, on a desktop and a phone', () => { + for (const w of [1280, 360]) { + const { ev, dom, errors } = load(); + ev(`window.innerWidth=${w};ACT.pickStart({city:'nyc'});ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.buyTransit({city:'nyc',net:'lvl',tier:1});UI.sel={type:'city',id:'nyc'};UI.tab='up';renderPanel()`); + const body = () => dom.window.document.getElementById('panelBody'); + assert.equal(body().querySelectorAll('[data-act="setCarry"]').length, 0, `${w}px: one POP, one carrier: nothing to choose`); + ev("ACT.buildPop({city:'chi'});ACT.buyTransit({city:'chi',net:'tly',tier:1});UI.sel={type:'city',id:'nyc'};UI.tab='up';renderPanel()"); + assert.equal(body().querySelectorAll('[data-act="setCarry"]').length, 2, `${w}px: Nearest port and Carry here for the Level Tree port`); + assert.match(body().textContent, /Traffic for Level Tree/); + assert.match(body().textContent, /At this POP, Level Tree's traffic always uses this port/); + body().querySelector('[data-act="setCarry"][data-args*="\\"on\\":1"]').click(); + assert.equal(ev("S.transit.find(t=>t.net==='lvl').carry"), true, `${w}px: the button works`); + assert.match(body().textContent, /Every POP carries Level Tree's traffic across your network to this port/); + assert.deepEqual(errors, []); + } +}); + +test('the control reads right in every language', () => { + for (const lang of ['it', 'pt', 'fr', 'es', 'de']) { + const { ev, dom, errors } = load({ lang }); + ev("ACT.pickStart({city:'nyc'});ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.buyTransit({city:'nyc',net:'lvl',tier:1});ACT.buildPop({city:'chi'});ACT.buyTransit({city:'chi',net:'tly',tier:1});UI.sel={type:'city',id:'nyc'};UI.tab='up';renderPanel()"); + const text = dom.window.document.getElementById('panelBody').textContent; + assert.ok(!/\{net\}|link_panels\./.test(text), `${lang}: no raw placeholders or labels`); + assert.notEqual(ev("tr('link_panels.carry_here')"), 'Carry here', `${lang}: translated`); + assert.deepEqual(errors, []); + } +}); diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index a5c557c..0a36e7c 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -5,8 +5,10 @@ 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++; + // A carrier's own port (dr) is also a plain transit exit; one not set to carry only takes its own POP's traffic. 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(jt.net==='lvl').forEach((t,i)=>{if(i%2===0)t.carry=true})", + "S.transit.filter(t=>t.net==='tly').forEach(t=>{t.carry=true})", + "S.transit.filter(t=>t.net==='lvl').forEach((t,i)=>{t.pref=i%2?'low':'normal'})", "S.pni.forEach((p,i)=>p.pref=i%3===0?'high':i%3===1?'low':'normal')", "S.te={on:true,script:''}", "S.te.script='prefer pni for goggle\\nspill at 80%\\navoid transit for netchill'", + "S.te.script='avoid transit level tree\\nprefer transit tell-ya\\nspill at 80%'", "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'}}", From 2eb22d1df34b93fc9b1471b521a4271ff8e21755 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 11:31:46 +0100 Subject: [PATCH 109/491] 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 110/491] 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 111/491] 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 112/491] 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 113/491] 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 114/491] 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 115/491] 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 116/491] 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 117/491] 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 118/491] 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 119/491] 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 120/491] 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 121/491] 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 122/491] 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 123/491] 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 124/491] 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 125/491] 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 126/491] 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 127/491] 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 128/491] 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 129/491] 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 130/491] 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 131/491] 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 132/491] 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 133/491] 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 134/491] 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 135/491] 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 136/491] 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 137/491] 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 138/491] 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 139/491] 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 140/491] 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 141/491] 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 850145810155e6e058029142b3242337e03aa6d8 Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Thu, 29 Oct 2026 21:54:47 +1100 Subject: [PATCH 142/491] Manila: GotchaFIX, Bayanihan-IX, In-Vitro-IX and four Philippine networks Manila gets its real exchanges: GotchaFIX Manila (neutral), the free community Bayanihan-IX and the incumbent-run In-Vitro-IX. Snow Globe, Diverge, Smarty Pants and Ditto join as Philippine networks. PLDTea Time and Snow Globe now sell transit, and a PLDTea Time PNI also reaches Smarty Pants. Old saves with a player-founded Manila exchange keep it. --- CHANGELOG.md | 2 + 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/20-world/50-cities.js | 2 +- src/game/30-networks/10-networks.js | 6 ++- src/game/30-networks/20-rival-exchanges.js | 2 + src/i18n/en.js | 6 +++ tests/philippines.test.js | 53 ++++++++++++++++++++++ 11 files changed, 99 insertions(+), 2 deletions(-) create mode 100644 tests/philippines.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index eb2f3d5..2173063 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants and Ditto join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. + ## [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..fca225d 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2433,6 +2433,7 @@ "networks.philippine_giant_peering_requests":"Philippinischer Riese. Peering-Anfragen werden bei einer Tasse Tee geprüft.", "networks.pink_eyeball_giant_peering_is":"Pinker Privatkunden-Riese. Peering gibt es ... gegen eine monatliche Gebühr.", "networks.pink_loud_and_almost_entirely_ipv6":"Pink, laut und fast komplett IPv6-only. Kichert über dein IPv4-only-CDN.", +"networks.pldtea_time_s_mobile_sibling_buy":"Das Mobilfunk-Geschwister von PLDTea Time. Kauf beim Großen, dann erreichst du den Kleinen gleich mit.", "networks.polite_enormous_and_sorry_about_the":"Höflich, riesig und entschuldigt sich für die Rechnung.", "networks.portugal_s_incumbent_purrs_when_you":"Portugals Platzhirsch. Schnurrt, wenn du ihm Traffic schickst.", "networks.prepaid_mobile_from_paraguay_to":"Prepaid-Mobilfunk von Paraguay bis Guatemala, mit einem Logo, das brüllt.", @@ -2444,6 +2445,7 @@ "networks.search_maps_and_a_cheerful_goodbye":"Suche, Karten und ein fröhliches Tschüss.", "networks.search_taxis_and_maps_slightly":"Suche, Taxis und Karten. Etwas verschlafen.", "networks.search_video_and_goggles_mostly":"Suche, Video und Taucherbrillen. Vor allem Taucherbrillen.", +"networks.shake_it_and_coverage_falls_gently":"Einmal schütteln, und die Abdeckung rieselt sanft über 7.641 Inseln. Peert mit fast jedem.", "networks.shields_half_the_web_from_crowds":"Schützt das halbe Web vor Horden von Bots. Das Rackstar Partner Program (RPP) stellt dir einen Cache ins Rack, sobald du genug Traffic schickst.", "networks.ships_parcels_and_packets_both":"Verschickt Pakete und Pakete, beide über Nacht.", "networks.shopping_festivals_that_melt_traffic":"Shopping-Festivals, bei denen Traffic-Graphen schmelzen.", @@ -2465,6 +2467,7 @@ "networks.the_biggest_network_in_china_its":"Das größte Netz Chinas. Seine CN-Too-Premiumroute umgeht die verstopfte Grenze, gegen Aufpreis.", "networks.the_cheapest_plan_in_the_country":"Der günstigste Tarif im Land. Riecht nach Schnäppchen.", "networks.the_cloud_it_s_just_someone":"Die Cloud. Ist doch nur das Ashburn von jemand anderem.", +"networks.the_fiber_upstart_from_the_provinces":"Der Glasfaser-Emporkömmling aus der Provinz, der seinen eigenen Weg gegangen ist. Offen für alle.", "networks.the_kingdom_s_incumbent_once_you":"Der Platzhirsch des Königreichs. Wer einmal drin ist, bleibt drin.", "networks.the_largest_mobile_network_on_earth":"Das größte Mobilfunknetz der Welt. Nur Paid Peering.", "networks.the_national_carrier_every_punchline":"Der nationale Carrier. Jede Pointe ist vorab genehmigt.", @@ -2472,6 +2475,7 @@ "networks.the_other_half_of_the_duopoly":"Die andere Hälfte des Duopols, auf Kupfer und Glasfaser. Streng national: Die Welt erreicht es über seinen Wholesale-Arm.", "networks.the_other_half_of_the_uae":"Die andere Hälfte des Duopols in den VAE. Macht dasselbe wie Etis-a-lot, nur in einer anderen Farbe.", "networks.the_phone_company_s_favourite_child":"Das Lieblingskind der Telefongesellschaft. Hundert Millionen Handys dahinter, und deine Peering-Anfrage ist seit 1996 „in Prüfung“.", +"networks.the_third_mobile_network_same_towers":"Das dritte Mobilfunknetz: dasselbe noch mal, nur neuer. Peert offen, um aufzuholen.", "networks.the_tier_1_that_grew_up":"Der Tier 1, der in Sizilien aufgewachsen ist. Sein Seabone-Backbone beherrscht das Mittelmeer und reicht tief nach Amerika, und trotzdem nennt er Palermo sein Zuhause.", "networks.ukraine_s_biggest_mobile_network_has":"Das größte Mobilfunknetz der Ukraine. Hat Dinge überstanden, die die meisten Netze nie einplanen müssen.", "networks.updates_so_many_updates":"Updates. So viele Updates.", @@ -2690,6 +2694,7 @@ "rival_exchanges.dense_filling_and_very_cheap":"Dicht, sättigend und sehr günstig.", "rival_exchanges.every_session_comes_with_a_coffee":"Zu jeder Session gibt es eine Kaffeepause. Wird streng durchgesetzt.", "rival_exchanges.grilled_ports_served_with_mustard":"Gegrillte Ports, serviert mit Senf und einem kalten Bier.", +"rival_exchanges.grown_in_a_lab_by_the":"Vom Platzhirsch im Labor gezüchtet. Die eigene Familie ist drauf; alle anderen zahlen fürs Zuschauen.", "rival_exchanges.layered_resilient_and_somehow_always":"Geschichtet, robust und irgendwie immer geöffnet.", "rival_exchanges.lots_of_small_sessions_on_little":"Viele kleine Sessions auf kleinen Tellern.", "rival_exchanges.member_owned_and_not_for_profit":"Gehört den Mitgliedern und ist gemeinnützig. Kleiner als LYNX, aber bei der Mitgliederversammlung gibt es Kekse.", @@ -2707,6 +2712,7 @@ "rival_exchanges.the_challenger_to_the_de_kicks":"Der Herausforderer der DE-KICKS-Fabric, eingewickelt und zum Mitnehmen.", "rival_exchanges.the_long_established_madrid_exchange":"Der alteingesessene Madrider Exchange. Neutrale Interconnection, lokales Flair und ein Route Server, der nie Siesta macht.", "rival_exchanges.the_older_johannesburg_exchange_run":"Der ältere Exchange in Johannesburg, betrieben vom lokalen ISP-Verband. Vor jedem Wartungsfenster auf Holz klopfen.", +"rival_exchanges.the_whole_neighbourhood_carries_the":"Die ganze Nachbarschaft trägt das Haus gemeinsam. Kostenlos dabei, mit dem Segen der Regierung.", "rival_exchanges.tokyo_has_more_exchanges_than_anyone":"Tokio hat mehr Exchanges, als irgendwer aufzählen kann. Diesen hier hat ein Breitbandriese gegründet, und er kommt ordentlich verpackt, jedes Mitglied in seinem eigenen Fach.", "rival_exchanges.warsaw_has_more_exchanges_than":"Warschau hat mehr Exchanges, als irgendwer zählen kann. Das hier ist der zweitgrößte, diese Woche.", "rival_exchanges.you_can_t_see_the_fabric":"Man sieht die Fabric nicht, aber sie ist definitiv da.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2f2a645..8aa9fad 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2431,6 +2431,7 @@ "networks.philippine_giant_peering_requests":"Gigante filipino. Las solicitudes de peering se revisan con una taza de té.", "networks.pink_eyeball_giant_peering_is":"Gigante rosa de eyeballs. El peering está disponible... por una cuota mensual.", "networks.pink_loud_and_almost_entirely_ipv6":"Rosa, ruidosa y casi totalmente solo IPv6. Se ríe por lo bajo de tu CDN solo IPv4.", +"networks.pldtea_time_s_mobile_sibling_buy":"El hermano móvil de PLDTea Time. Compra al grande y llegas también a este.", "networks.polite_enormous_and_sorry_about_the":"Educado, enorme, y lamenta lo de la factura.", "networks.portugal_s_incumbent_purrs_when_you":"El operador histórico de Portugal. Ronronea cuando le mandas tráfico.", "networks.prepaid_mobile_from_paraguay_to":"Móvil prepago de Paraguay a Guatemala, con un logo que ruge.", @@ -2442,6 +2443,7 @@ "networks.search_maps_and_a_cheerful_goodbye":"Búsqueda, mapas y una alegre despedida.", "networks.search_taxis_and_maps_slightly":"Búsqueda, taxis y mapas. Algo adormilado.", "networks.search_video_and_goggles_mostly":"Búsqueda, vídeo y gafas. Sobre todo gafas.", +"networks.shake_it_and_coverage_falls_gently":"Agítala y la cobertura cae suave sobre 7.641 islas. Hace peering con casi cualquiera.", "networks.shields_half_the_web_from_crowds":"Protege a media web de multitudes de bots. El Rackstar Partner Program (RPP) pone una caché en tu rack cuando mandas suficiente tráfico.", "networks.ships_parcels_and_packets_both":"Envía paquetes y paquetes, ambos de un día para otro.", "networks.shopping_festivals_that_melt_traffic":"Festivales de compras que derriten las gráficas de tráfico.", @@ -2463,6 +2465,7 @@ "networks.the_biggest_network_in_china_its":"La mayor red de China. Su ruta premium CN-Too se salta la frontera congestionada, por un precio.", "networks.the_cheapest_plan_in_the_country":"El plan más barato del país. Huele a ganga.", "networks.the_cloud_it_s_just_someone":"La nube. Es solo el Ashburn de otro.", +"networks.the_fiber_upstart_from_the_provinces":"La novata de la fibra que vino de provincias y se fue por su cuenta. Abierta a todos.", "networks.the_kingdom_s_incumbent_once_you":"El operador histórico del Reino. Una vez dentro, te quedas dentro.", "networks.the_largest_mobile_network_on_earth":"La mayor red móvil de la Tierra. Solo peering de pago.", "networks.the_national_carrier_every_punchline":"El operador nacional. Cada chiste viene preaprobado.", @@ -2470,6 +2473,7 @@ "networks.the_other_half_of_the_duopoly":"La otra mitad del duopolio, en cobre y fibra. Estrictamente doméstico: el mundo llega a él por su brazo mayorista.", "networks.the_other_half_of_the_uae":"La otra mitad del duopolio de los EAU. Hace lo que hace Etis-a-lot, en otro color.", "networks.the_phone_company_s_favourite_child":"El hijo favorito de la compañía telefónica. Cien millones de teléfonos detrás, y tu solicitud de peering está «en revisión» desde 1996.", +"networks.the_third_mobile_network_same_towers":"El tercer operador móvil: ídem, pero más nuevo. Hace peering abierto para ponerse al día.", "networks.the_tier_1_that_grew_up":"El Tier 1 que creció en Sicilia. Su backbone Seabone es dueño del Mediterráneo y llega hondo en las Américas, y aun así llama hogar a Palermo.", "networks.ukraine_s_biggest_mobile_network_has":"La mayor red móvil de Ucrania. Ha seguido funcionando en situaciones que la mayoría de las redes nunca tienen que planear.", "networks.updates_so_many_updates":"Actualizaciones. Tantas actualizaciones.", @@ -2688,6 +2692,7 @@ "rival_exchanges.dense_filling_and_very_cheap":"Denso, contundente y baratísimo.", "rival_exchanges.every_session_comes_with_a_coffee":"Cada sesión viene con una pausa para el café. Se cumple a rajatabla.", "rival_exchanges.grilled_ports_served_with_mustard":"Puertos a la parrilla, servidos con mostaza y una cerveza fría.", +"rival_exchanges.grown_in_a_lab_by_the":"Cultivado en laboratorio por el operador histórico. Su familia está dentro; los demás pagan por mirar.", "rival_exchanges.layered_resilient_and_somehow_always":"En capas, resistente y, de algún modo, siempre abierto.", "rival_exchanges.lots_of_small_sessions_on_little":"Muchas sesiones pequeñas en platitos.", "rival_exchanges.member_owned_and_not_for_profit":"Propiedad de sus miembros y sin ánimo de lucro. Más pequeño que LYNX, pero la asamblea tiene galletas.", @@ -2705,6 +2710,7 @@ "rival_exchanges.the_challenger_to_the_de_kicks":"El aspirante a la fabric de DE-KICKS, envuelto y listo para llevar.", "rival_exchanges.the_long_established_madrid_exchange":"El veterano intercambio de Madrid. Interconexión neutral, sabor local y un route server que nunca hace la siesta.", "rival_exchanges.the_older_johannesburg_exchange_run":"El intercambio más antiguo de Johannesburgo, gestionado por la asociación local de ISP. Toca madera antes de cada ventana de mantenimiento.", +"rival_exchanges.the_whole_neighbourhood_carries_the":"Todo el barrio carga la casa junto. Gratis, con la bendición del gobierno.", "rival_exchanges.tokyo_has_more_exchanges_than_anyone":"Tokio tiene más intercambios de los que nadie sabría nombrar. Este lo empezó un gigante de la banda ancha y viene muy bien empaquetado, cada miembro en su compartimento.", "rival_exchanges.warsaw_has_more_exchanges_than":"Varsovia tiene más intercambios de los que nadie puede contar. Este es el segundo mayor, esta semana.", "rival_exchanges.you_can_t_see_the_fabric":"No se ve la fabric, pero desde luego está ahí.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 413ae5f..510941d 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2431,6 +2431,7 @@ "networks.philippine_giant_peering_requests":"Géant philippin. Les demandes de peering sont examinées autour d’une tasse de thé.", "networks.pink_eyeball_giant_peering_is":"Géant eyeball rose. Le peering est disponible... contre un abonnement mensuel.", "networks.pink_loud_and_almost_entirely_ipv6":"Rose, bruyant et presque entièrement IPv6-only. Ricane devant ton CDN IPv4-only.", +"networks.pldtea_time_s_mobile_sibling_buy":"Le petit frère mobile de PLDTea Time. Achetez au grand et vous l'atteignez aussi.", "networks.polite_enormous_and_sorry_about_the":"Poli, énorme, et désolé pour la facture.", "networks.portugal_s_incumbent_purrs_when_you":"L’opérateur historique du Portugal. Ronronne quand tu lui envoies du trafic.", "networks.prepaid_mobile_from_paraguay_to":"Du mobile prépayé du Paraguay au Guatemala, avec un logo qui rugit.", @@ -2442,6 +2443,7 @@ "networks.search_maps_and_a_cheerful_goodbye":"Recherche, cartes et un joyeux au revoir.", "networks.search_taxis_and_maps_slightly":"Recherche, taxis et cartes. Un peu endormi.", "networks.search_video_and_goggles_mostly":"Recherche, vidéo et lunettes. Surtout des lunettes.", +"networks.shake_it_and_coverage_falls_gently":"Secouez-la et la couverture tombe doucement sur 7 641 îles. Fait du peering avec presque tout le monde.", "networks.shields_half_the_web_from_crowds":"Protège la moitié du web des hordes de bots. Le Rackstar Partner Program (RPP) installe un cache dans ton rack dès que tu envoies assez de trafic.", "networks.ships_parcels_and_packets_both":"Expédie colis et paquets, les deux en 24 h.", "networks.shopping_festivals_that_melt_traffic":"Des festivals du shopping qui font fondre les graphes de trafic.", @@ -2463,6 +2465,7 @@ "networks.the_biggest_network_in_china_its":"Le plus grand réseau de Chine. Sa route premium CN-Too évite la frontière congestionnée, moyennant finance.", "networks.the_cheapest_plan_in_the_country":"Le forfait le moins cher du pays. Ça sent la bonne affaire.", "networks.the_cloud_it_s_just_someone":"Le cloud. C’est juste l’Ashburn de quelqu’un d’autre.", +"networks.the_fiber_upstart_from_the_provinces":"Le jeune loup de la fibre venu de province, qui a pris son propre chemin. Ouvert à tous.", "networks.the_kingdom_s_incumbent_once_you":"L’opérateur historique du Royaume. Une fois entré, tu y restes.", "networks.the_largest_mobile_network_on_earth":"Le plus grand réseau mobile de la planète. Peering payant uniquement.", "networks.the_national_carrier_every_punchline":"L’opérateur national. Chaque vanne est validée en haut lieu.", @@ -2470,6 +2473,7 @@ "networks.the_other_half_of_the_duopoly":"L’autre moitié du duopole, sur cuivre et fibre. Strictement national : le monde l’atteint via sa branche de gros.", "networks.the_other_half_of_the_uae":"L’autre moitié du duopole des Émirats. Fait ce que fait Etis-a-lot, dans une autre couleur.", "networks.the_phone_company_s_favourite_child":"L’enfant chéri de l’opérateur téléphonique. Cent millions de téléphones derrière lui, et ta demande de peering est « en cours d’examen » depuis 1996.", +"networks.the_third_mobile_network_same_towers":"Le troisième opérateur mobile : idem, mais en plus neuf. Peering ouvert pour rattraper son retard.", "networks.the_tier_1_that_grew_up":"Le Tier 1 qui a grandi en Sicile. Son backbone Seabone règne sur la Méditerranée et s’enfonce loin dans les Amériques, et il vit toujours à Palerme.", "networks.ukraine_s_biggest_mobile_network_has":"Le plus grand réseau mobile d’Ukraine. A continué de fonctionner malgré des choses que la plupart des réseaux n’ont jamais à prévoir.", "networks.updates_so_many_updates":"Des mises à jour. Tellement de mises à jour.", @@ -2688,6 +2692,7 @@ "rival_exchanges.dense_filling_and_very_cheap":"Dense, bourratif et vraiment pas cher.", "rival_exchanges.every_session_comes_with_a_coffee":"Chaque session inclut une pause café. Strictement obligatoire.", "rival_exchanges.grilled_ports_served_with_mustard":"Des ports grillés, servis avec moutarde et bière fraîche.", +"rival_exchanges.grown_in_a_lab_by_the":"Cultivé en laboratoire par l'opérateur historique. Sa famille y est ; les autres paient pour regarder.", "rival_exchanges.layered_resilient_and_somehow_always":"Tout en couches, résilient et toujours ouvert, on ne sait trop comment.", "rival_exchanges.lots_of_small_sessions_on_little":"Plein de petites sessions servies dans de petits paniers vapeur.", "rival_exchanges.member_owned_and_not_for_profit":"Détenu par ses membres et à but non lucratif. Plus petit que LYNX, mais il y a des biscuits à l’AG.", @@ -2705,6 +2710,7 @@ "rival_exchanges.the_challenger_to_the_de_kicks":"Le challenger du fabric DE-KICKS, roulé et prêt à emporter.", "rival_exchanges.the_long_established_madrid_exchange":"L’IX historique de Madrid. Interconnexion neutre, saveur locale et un route server qui ne fait jamais la sieste.", "rival_exchanges.the_older_johannesburg_exchange_run":"Le plus ancien IX de Johannesburg, géré par l’association locale des FAI. Touche du bois avant chaque fenêtre de maintenance.", +"rival_exchanges.the_whole_neighbourhood_carries_the":"Tout le quartier porte la maison ensemble. Gratuit, avec la bénédiction du gouvernement.", "rival_exchanges.tokyo_has_more_exchanges_than_anyone":"Tokyo compte plus d’IX qu’on ne peut en nommer. Celui-ci a été fondé par un géant du haut débit et arrive soigneusement emballé, chaque membre dans son compartiment.", "rival_exchanges.warsaw_has_more_exchanges_than":"Warsaw compte plus d’IX qu’on ne peut en compter. Celui-ci est le deuxième plus grand, cette semaine.", "rival_exchanges.you_can_t_see_the_fabric":"Tu ne vois pas le fabric, mais il est bien là.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 103bc61..be78346 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2431,6 +2431,7 @@ "networks.philippine_giant_peering_requests":"Gigante filippino. Le richieste di peering vengono valutate davanti a una tazza di tè.", "networks.pink_eyeball_giant_peering_is":"Gigante eyeball rosa. Il peering è disponibile... con un canone mensile.", "networks.pink_loud_and_almost_entirely_ipv6":"Rosa, rumorosa e quasi solo IPv6. Ridacchia della tua CDN solo IPv4.", +"networks.pldtea_time_s_mobile_sibling_buy":"Il fratello mobile di PLDTea Time. Compri dal grande e raggiungi anche lui.", "networks.polite_enormous_and_sorry_about_the":"Educato, enorme, e si scusa per la bolletta.", "networks.portugal_s_incumbent_purrs_when_you":"L’incumbent del Portogallo. Fa le fusa quando gli mandi traffico.", "networks.prepaid_mobile_from_paraguay_to":"Mobile prepagato dal Paraguay al Guatemala, con un logo che ruggisce.", @@ -2442,6 +2443,7 @@ "networks.search_maps_and_a_cheerful_goodbye":"Ricerca, mappe e un allegro arrivederci.", "networks.search_taxis_and_maps_slightly":"Ricerca, taxi e mappe. Un po’ assonnato.", "networks.search_video_and_goggles_mostly":"Ricerca, video e occhialini. Soprattutto occhialini.", +"networks.shake_it_and_coverage_falls_gently":"Scuotila e la copertura scende piano su 7.641 isole. Fa peering quasi con chiunque.", "networks.shields_half_the_web_from_crowds":"Protegge mezzo web dalle orde di bot. Il Rackstar Partner Program (RPP) ti mette una cache nel rack quando gli mandi abbastanza traffico.", "networks.ships_parcels_and_packets_both":"Spedisce pacchi e pacchetti, entrambi in 24 ore.", "networks.shopping_festivals_that_melt_traffic":"Festival dello shopping che fanno sciogliere i grafici del traffico.", @@ -2463,6 +2465,7 @@ "networks.the_biggest_network_in_china_its":"La rete più grande della Cina. Il suo percorso premium CN-Too evita il confine congestionato, a caro prezzo.", "networks.the_cheapest_plan_in_the_country":"Il piano più economico del paese. Profuma di affare.", "networks.the_cloud_it_s_just_someone":"Il cloud. È solo l’Ashburn di qualcun altro.", +"networks.the_fiber_upstart_from_the_provinces":"La fibra emergente dalla provincia che ha preso la sua strada. Aperta a tutti.", "networks.the_kingdom_s_incumbent_once_you":"L’incumbent del Regno. Una volta dentro, ci resti.", "networks.the_largest_mobile_network_on_earth":"La rete mobile più grande della Terra. Solo peering a pagamento.", "networks.the_national_carrier_every_punchline":"Il carrier nazionale. Ogni battuta è pre-approvata.", @@ -2470,6 +2473,7 @@ "networks.the_other_half_of_the_duopoly":"L'altra metà del duopolio, su rame e fibra. Strettamente nazionale: il mondo la raggiunge tramite il suo ramo wholesale.", "networks.the_other_half_of_the_uae":"L’altra metà del duopolio degli Emirati. Fa quello che fa Etis-a-lot, ma di un altro colore.", "networks.the_phone_company_s_favourite_child":"Il figlio prediletto della compagnia telefonica. Cento milioni di telefoni alle spalle, e la tua richiesta di peering è “in valutazione” dal 1996.", +"networks.the_third_mobile_network_same_towers":"Il terzo operatore mobile: idem, ma più nuovo. Fa peering aperto per recuperare.", "networks.the_tier_1_that_grew_up":"Il Tier 1 cresciuto in Sicilia. La sua dorsale Seabone domina il Mediterraneo e arriva in profondità nelle Americhe, e chiama ancora casa Palermo.", "networks.ukraine_s_biggest_mobile_network_has":"La più grande rete mobile dell’Ucraina. Ha continuato a funzionare attraverso cose che la maggior parte delle reti non deve mai mettere in conto.", "networks.updates_so_many_updates":"Aggiornamenti. Tantissimi aggiornamenti.", @@ -2688,6 +2692,7 @@ "rival_exchanges.dense_filling_and_very_cheap":"Denso, sostanzioso e molto economico.", "rival_exchanges.every_session_comes_with_a_coffee":"Ogni sessione include una pausa caffè. Obbligatoria.", "rival_exchanges.grilled_ports_served_with_mustard":"Porte alla griglia, servite con senape e una birra fresca.", +"rival_exchanges.grown_in_a_lab_by_the":"Coltivato in laboratorio dall'incumbent. C'è la sua famiglia; tutti gli altri pagano per guardare.", "rival_exchanges.layered_resilient_and_somehow_always":"A strati, resiliente e chissà come sempre aperto.", "rival_exchanges.lots_of_small_sessions_on_little":"Tante piccole sessioni su piattini.", "rival_exchanges.member_owned_and_not_for_profit":"Di proprietà dei membri e senza scopo di lucro. Più piccolo di LYNX, ma all’assemblea annuale ci sono i biscotti.", @@ -2705,6 +2710,7 @@ "rival_exchanges.the_challenger_to_the_de_kicks":"Lo sfidante del fabric DE-KICKS, avvolto e pronto da portar via.", "rival_exchanges.the_long_established_madrid_exchange":"Lo storico exchange di Madrid. Interconnessione neutrale, sapore locale e un route server che non fa mai la siesta.", "rival_exchanges.the_older_johannesburg_exchange_run":"Il più vecchio exchange di Johannesburg, gestito dall’associazione degli ISP locali. Tocca ferro prima di ogni finestra di manutenzione.", +"rival_exchanges.the_whole_neighbourhood_carries_the":"Tutto il quartiere porta la casa insieme. Entrare è gratis, con la benedizione del governo.", "rival_exchanges.tokyo_has_more_exchanges_than_anyone":"Tokyo ha più exchange di quanti chiunque riesca a nominarne. Questo l’ha fondato un colosso della banda larga ed è confezionato con cura, ogni membro nel suo scomparto.", "rival_exchanges.warsaw_has_more_exchanges_than":"Warsaw ha più exchange di quanti se ne possano contare. Questo è il secondo più grande, questa settimana.", "rival_exchanges.you_can_t_see_the_fabric":"Il fabric non lo vedi, ma c’è di sicuro.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 046f9a8..6206072 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2431,6 +2431,7 @@ "networks.philippine_giant_peering_requests":"Gigante filipino. Pedidos de peering são avaliados com uma xícara de chá.", "networks.pink_eyeball_giant_peering_is":"Gigante eyeball cor-de-rosa. O peering está disponível... mediante mensalidade.", "networks.pink_loud_and_almost_entirely_ipv6":"Rosa, barulhenta e quase toda só IPv6. Dá risadinha da sua CDN só IPv4.", +"networks.pldtea_time_s_mobile_sibling_buy":"O irmão móvel da PLDTea Time. Compre da grandona e chegue nele também.", "networks.polite_enormous_and_sorry_about_the":"Educado, enorme e pedindo desculpas pela conta.", "networks.portugal_s_incumbent_purrs_when_you":"A incumbent de Portugal. Ronrona quando você manda tráfego.", "networks.prepaid_mobile_from_paraguay_to":"Celular pré-pago do Paraguai à Guatemala, com um logo que ruge.", @@ -2442,6 +2443,7 @@ "networks.search_maps_and_a_cheerful_goodbye":"Busca, mapas e um tchau animado.", "networks.search_taxis_and_maps_slightly":"Busca, táxis e mapas. Meio sonolento.", "networks.search_video_and_goggles_mostly":"Busca, vídeo e óculos de natação. Principalmente óculos.", +"networks.shake_it_and_coverage_falls_gently":"Sacuda e a cobertura cai suave sobre 7.641 ilhas. Faz peering com quase todo mundo.", "networks.shields_half_the_web_from_crowds":"Protege metade da web de multidões de bots. O Rackstar Partner Program (RPP) coloca um cache no seu rack quando você envia tráfego suficiente.", "networks.ships_parcels_and_packets_both":"Entrega pacotes e pacotes, os dois em 24 horas.", "networks.shopping_festivals_that_melt_traffic":"Festivais de compras que derretem gráficos de tráfego.", @@ -2463,6 +2465,7 @@ "networks.the_biggest_network_in_china_its":"A maior rede da China. A rota premium CN-Too evita a fronteira congestionada, por um preço.", "networks.the_cheapest_plan_in_the_country":"O plano mais barato do país. Tem cheiro de pechincha.", "networks.the_cloud_it_s_just_someone":"A nuvem. É só o Ashburn de outra pessoa.", +"networks.the_fiber_upstart_from_the_provinces":"A novata da fibra que veio do interior e seguiu seu próprio caminho. Aberta a todos.", "networks.the_kingdom_s_incumbent_once_you":"A incumbent do Reino. Entrou, não sai mais.", "networks.the_largest_mobile_network_on_earth":"A maior rede mobile da Terra. Só peering pago.", "networks.the_national_carrier_every_punchline":"A operadora nacional. Toda piada é pré-aprovada.", @@ -2470,6 +2473,7 @@ "networks.the_other_half_of_the_duopoly":"A outra metade do duopólio, em cobre e fibra. Estritamente doméstica: o mundo chega nela pelo seu braço de atacado.", "networks.the_other_half_of_the_uae":"A outra metade do duopólio dos Emirados. Faz o mesmo que a Etis-a-lot, em outra cor.", "networks.the_phone_company_s_favourite_child":"O filho preferido da companhia telefônica. Cem milhões de celulares por trás, e seu pedido de peering está “em análise” desde 1996.", +"networks.the_third_mobile_network_same_towers":"A terceira operadora móvel: idem, só que mais nova. Faz peering aberto para alcançar as outras.", "networks.the_tier_1_that_grew_up":"A Tier 1 que cresceu na Sicília. Seu backbone Seabone domina o Mediterrâneo e vai fundo nas Américas, e ela ainda chama Palermo de casa.", "networks.ukraine_s_biggest_mobile_network_has":"A maior rede mobile da Ucrânia. Continuou funcionando em situações que a maioria das redes nunca precisa planejar.", "networks.updates_so_many_updates":"Atualizações. Tantas atualizações.", @@ -2688,6 +2692,7 @@ "rival_exchanges.dense_filling_and_very_cheap":"Denso, substancioso e baratíssimo.", "rival_exchanges.every_session_comes_with_a_coffee":"Toda sessão vem com pausa pro café. Obrigatória.", "rival_exchanges.grilled_ports_served_with_mustard":"Portas na brasa, servidas com mostarda e uma cerveja gelada.", +"rival_exchanges.grown_in_a_lab_by_the":"Cultivado em laboratório pela operadora dominante. A família dela está lá; o resto paga para assistir.", "rival_exchanges.layered_resilient_and_somehow_always":"Em camadas, resiliente e, não se sabe como, sempre aberto.", "rival_exchanges.lots_of_small_sessions_on_little":"Várias sessõezinhas em pratinhos.", "rival_exchanges.member_owned_and_not_for_profit":"Dos membros e sem fins lucrativos. Menor que o LYNX, mas a assembleia anual tem biscoito.", @@ -2705,6 +2710,7 @@ "rival_exchanges.the_challenger_to_the_de_kicks":"O desafiante do fabric DE-KICKS, embrulhado e pronto pra viagem.", "rival_exchanges.the_long_established_madrid_exchange":"O tradicional exchange de Madrid. Interconexão neutra, sabor local e um route server que nunca tira siesta.", "rival_exchanges.the_older_johannesburg_exchange_run":"O exchange mais antigo de Johannesburg, gerido pela associação de ISPs locais. Bata na madeira antes de cada janela de manutenção.", +"rival_exchanges.the_whole_neighbourhood_carries_the":"O bairro inteiro carrega a casa junto. Entrar é grátis, com a bênção do governo.", "rival_exchanges.tokyo_has_more_exchanges_than_anyone":"Tokyo tem mais exchanges do que alguém consegue nomear. Este foi criado por um gigante da banda larga e vem bem embalado, cada membro no seu compartimento.", "rival_exchanges.warsaw_has_more_exchanges_than":"Warsaw tem mais exchanges do que dá pra contar. Este é o segundo maior, esta semana.", "rival_exchanges.you_can_t_see_the_fabric":"Você não vê o fabric, mas ele está lá, com certeza.", diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index b6410df..dbdb7e4 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -35,7 +35,7 @@ const CITIES=[ {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:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',P:600,ix:'GotchaFIX Manila',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')}, diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index d7cad9b..d63c5fc 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -37,7 +37,11 @@ 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:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#D62027',pops:['mnl','hkg','sin'],ix:['hkg','mnl~3'],blurb:tr('networks.philippine_giant_peering_requests')}, + {id:'glb',name:'Snow Globe',asn:4775,type:'t2',pol:'open',share:.007,price:6,col:'#1A3D8F',pops:['mnl','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.shake_it_and_coverage_falls_gently')}, + {id:'cvg',name:'Diverge',asn:17639,type:'eye',pol:'open',share:.005,col:'#F26B21',pops:['mnl','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, + {id:'smt',name:'Smarty Pants',asn:10139,type:'eye',pol:'selective',up:['pld'],minIx:10,minPni:30,share:.006,col:'#00A859',pops:['mnl'],ix:[],blurb:tr('networks.pldtea_time_s_mobile_sibling_buy')}, + {id:'dto',name:'Ditto',asn:139831,type:'eye',pol:'open',share:.002,col:'#B5121B',pops:['mnl'],ix:['mnl','mnl~2'],blurb:tr('networks.the_third_mobile_network_same_towers')}, {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( diff --git a/src/game/30-networks/20-rival-exchanges.js b/src/game/30-networks/20-rival-exchanges.js index 3095e46..246c4ba 100644 --- a/src/game/30-networks/20-rival-exchanges.js +++ b/src/game/30-networks/20-rival-exchanges.js @@ -23,6 +23,8 @@ const XIX=[ {id:'lax~2',c:'lax',name:'Smog-IX',cheap:0.6,take:0.45,blurb:tr('rival_exchanges.you_can_t_see_the_fabric')}, {id:'sin~2',c:'sin',name:'Kopi-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.strong_sweet_and_cheaper_than_the')}, {id:'hkg~2',c:'hkg',name:'Dim-Sum-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.lots_of_small_sessions_on_little')}, + {id:'mnl~2',c:'mnl',name:'Bayanihan-IX',cheap:0.3,take:0.4,blurb:tr('rival_exchanges.the_whole_neighbourhood_carries_the')}, + {id:'mnl~3',c:'mnl',name:'In-Vitro-IX',cheap:1.4,take:0.2,core:['pld','smt'],blurb:tr('rival_exchanges.grown_in_a_lab_by_the')}, {id:'tok~2',c:'tok',name:'Bento-IX',cheap:0.65,take:0.5,core:['drz','akm','cfl','sgt','msf','amz'],blurb:tr('rival_exchanges.tokyo_has_more_exchanges_than_anyone')}, {id:'syd~2',c:'syd',name:'At-The-Edge IX',cheap:.7,take:0.5,core:['drz','nfx','ggl','fbk','akm','cfl','amz','msf','bdc','slw','abb','voc','stb','spl','lpt','npt','mag'],blurb:tr('rival_exchanges.the_challenger_to_ix_straya_pops')}, {id:'bom~2',c:'bom',name:'Vada-Pav-IX',cheap:0.45,take:0.45,blurb:tr('rival_exchanges.mumbai_s_street_food_exchange_fast')}, diff --git a/src/i18n/en.js b/src/i18n/en.js index 008cdfd..c896ed0 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2432,6 +2432,7 @@ "networks.philippine_giant_peering_requests":"Philippine giant. Peering requests are reviewed over a cup of tea.", "networks.pink_eyeball_giant_peering_is":"Pink eyeball giant. Peering is available... for a monthly fee.", "networks.pink_loud_and_almost_entirely_ipv6":"Pink, loud and almost entirely IPv6-only. Giggles at your IPv4-only CDN.", +"networks.pldtea_time_s_mobile_sibling_buy":"PLDTea Time's mobile sibling. Buy from the big one and you reach this one too.", "networks.polite_enormous_and_sorry_about_the":"Polite, enormous, and sorry about the bill.", "networks.portugal_s_incumbent_purrs_when_you":"Portugal’s incumbent. Purrs when you send it traffic.", "networks.prepaid_mobile_from_paraguay_to":"Prepaid mobile from Paraguay to Guatemala, with a logo that roars.", @@ -2443,6 +2444,7 @@ "networks.search_maps_and_a_cheerful_goodbye":"Search, maps and a cheerful goodbye.", "networks.search_taxis_and_maps_slightly":"Search, taxis and maps. Slightly sleepy.", "networks.search_video_and_goggles_mostly":"Search, video and goggles. Mostly goggles.", +"networks.shake_it_and_coverage_falls_gently":"Shake it and coverage falls gently over 7,641 islands. Peers with almost anyone.", "networks.shields_half_the_web_from_crowds":"Shields half the web from crowds of bots. The Rackstar Partner Program (RPP) puts a cache in your rack once you send enough traffic.", "networks.ships_parcels_and_packets_both":"Ships parcels and packets, both overnight.", "networks.shopping_festivals_that_melt_traffic":"Shopping festivals that melt traffic graphs.", @@ -2464,6 +2466,7 @@ "networks.the_biggest_network_in_china_its":"The biggest network in China. Its CN-Too premium route skips the congested border, for a price.", "networks.the_cheapest_plan_in_the_country":"The cheapest plan in the country. Smells like a bargain.", "networks.the_cloud_it_s_just_someone":"The cloud. It's just someone else's Ashburn.", +"networks.the_fiber_upstart_from_the_provinces":"The fiber upstart from the provinces that went its own way. Open to all.", "networks.the_kingdom_s_incumbent_once_you":"The Kingdom’s incumbent. Once you are in, you stay in.", "networks.the_largest_mobile_network_on_earth":"The largest mobile network on Earth. Paid peering only.", "networks.the_national_carrier_every_punchline":"The national carrier. Every punchline is pre-approved.", @@ -2471,6 +2474,7 @@ "networks.the_other_half_of_the_duopoly":"The other half of the duopoly, on copper and fiber. Strictly domestic: the world reaches it through its wholesale arm.", "networks.the_other_half_of_the_uae":"The other half of the UAE duopoly. Does what Etis-a-lot does, in a different colour.", "networks.the_phone_company_s_favourite_child":"The phone company’s favourite child. A hundred million phones behind it, and your peering request has been “under review” since 1996.", +"networks.the_third_mobile_network_same_towers":"The third mobile network: the same again, but newer. Peers openly to catch up.", "networks.the_tier_1_that_grew_up":"The Tier 1 that grew up in Sicily. Its Seabone backbone owns the Mediterranean and reaches deep into the Americas, and it still calls Palermo home.", "networks.ukraine_s_biggest_mobile_network_has":"Ukraine’s biggest mobile network. Has kept working through things most networks never have to plan for.", "networks.updates_so_many_updates":"Updates. So many updates.", @@ -2689,6 +2693,7 @@ "rival_exchanges.dense_filling_and_very_cheap":"Dense, filling and very cheap.", "rival_exchanges.every_session_comes_with_a_coffee":"Every session comes with a coffee break. Strictly enforced.", "rival_exchanges.grilled_ports_served_with_mustard":"Grilled ports, served with mustard and a cold beer.", +"rival_exchanges.grown_in_a_lab_by_the":"Grown in a lab by the incumbent. Its own family is on it; everyone else pays to watch.", "rival_exchanges.layered_resilient_and_somehow_always":"Layered, resilient and somehow always open.", "rival_exchanges.lots_of_small_sessions_on_little":"Lots of small sessions on little plates.", "rival_exchanges.member_owned_and_not_for_profit":"Member-owned and not-for-profit. Smaller than LYNX, but the AGM has biscuits.", @@ -2706,6 +2711,7 @@ "rival_exchanges.the_challenger_to_the_de_kicks":"The challenger to the DE-KICKS fabric, wrapped and ready to go.", "rival_exchanges.the_long_established_madrid_exchange":"The long-established Madrid exchange. Neutral interconnection, local flavour and a route server that never takes a siesta.", "rival_exchanges.the_older_johannesburg_exchange_run":"The older Johannesburg exchange, run by the local ISP association. Knock on wood before every maintenance window.", +"rival_exchanges.the_whole_neighbourhood_carries_the":"The whole neighbourhood carries the house together. Free to join, run with the government's blessing.", "rival_exchanges.tokyo_has_more_exchanges_than_anyone":"Tokyo has more exchanges than anyone can name. This one was started by a broadband giant and comes neatly packed, every member in its own compartment.", "rival_exchanges.warsaw_has_more_exchanges_than":"Warsaw has more exchanges than anyone can count. This is the second biggest, this week.", "rival_exchanges.you_can_t_see_the_fabric":"You can’t see the fabric, but it is definitely there.", diff --git a/tests/philippines.test.js b/tests/philippines.test.js new file mode 100644 index 0000000..cc50534 --- /dev/null +++ b/tests/philippines.test.js @@ -0,0 +1,53 @@ +// The Philippines: Manila's exchanges and networks, Cebu, Davao and the cables that really land there. +const test = require('node:test'); +const assert = require('node:assert'); +const { load } = require('./harness'); + +function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0"); } +const ids = (ev, js) => JSON.parse(ev(`JSON.stringify(${js})`)); + +test('Manila: GotchaFIX, Bayanihan-IX and the incumbent-run In-Vitro-IX', () => { + const { ev, errors } = load(); + start(ev); + assert.equal(ev('CITY.mnl.ix'), 'GotchaFIX Manila'); + assert.equal(ev("XIXM['mnl~2'].name"), 'Bayanihan-IX'); + assert.equal(ev("XIXM['mnl~3'].name"), 'In-Vitro-IX'); + // the neutral exchange has the open networks, not the PLDT family + const gotcha = ids(ev, "ixMembers('mnl')"); + for (const n of ['glb', 'cvg', 'dto']) assert.ok(gotcha.includes(n), `${n} on GotchaFIX`); + assert.ok(!gotcha.includes('pld') && !gotcha.includes('smt')); + assert.ok(gotcha.length >= 10, `GotchaFIX has ${gotcha.length} members`); + // the incumbent's own exchange is PLDT and its mobile arm + const vitro = ids(ev, "ixMembers('mnl~3')"); + assert.ok(vitro.includes('pld') && vitro.includes('smt')); + assert.ok(ids(ev, "ixMembers('mnl~2')").includes('dto')); + // the community exchange is the cheapest port in town, the incumbent's the dearest + assert.ok(ev("ixMul('mnl~2') { + const { ev, errors } = load(); + start(ev); + assert.ok(ev("sellsAt(NET.pld,'mnl')&&sellsAt(NET.glb,'mnl')")); + assert.ok(ev("!sellsAt(NET.cvg,'mnl')&&!sellsAt(NET.dto,'mnl')&&!sellsAt(NET.smt,'mnl')")); + assert.deepEqual(ids(ev, 'PNI_NETS.pld').sort(), ['pld', 'smt']); + assert.equal(ev('NET.pld.pol'), 'selective'); + assert.equal(ev('NET.glb.pol') + ev('NET.cvg.pol') + ev('NET.dto.pol'), 'openopenopen'); + assert.deepEqual(errors, []); +}); + +test('Manila: an exchange the player founded there before GotchaFIX existed keeps working', () => { + const { ev, errors } = load(); + start(ev); + ev("ACT.buildPop({city:'mnl'});S.myIx.mnl={name:'Mine-IX Manila',members:['dto','tail0'],next:0};S.ixp.mnl=2"); + ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); + assert.equal(ev('__o.myIx.mnl.name'), 'Mine-IX Manila'); + ev('S=__o;after()'); + assert.equal(ev("ixName('mnl')"), 'Mine-IX Manila'); + assert.deepEqual(ids(ev, "ixMembers('mnl')"), ['dto', 'tail0']); + // and nobody can found a second one now that a real exchange runs in Manila + ev("delete S.myIx.mnl;delete S.ixp.mnl;ACT.foundIx({city:'mnl'})"); + assert.ok(ev('!S.myIx.mnl')); + assert.deepEqual(errors, []); +}); From bb9a474923734d483f7950de6962561ef87827da Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Fri, 30 Oct 2026 15:56:29 +1100 Subject: [PATCH 143/491] RISE & Shine joins Manila as an open-peering Philippine network AS63927 is a Cebu-based Cable/DSL/ISP with an open peering policy. In PeeringDB it peers at GetaFIX Manila and PhOpenIX, in Singapore, Hong Kong and Tokyo (JPNAP), and at DE-CIX Frankfurt, AMS-IX, LINX, Netnod and Any2West; it is also on VIX, which PeeringDB does not list. So RISE & Shine is on the game's matching exchanges: GotchaFIX Manila, Bayanihan-IX, In-Vitro-IX, Lah-IX, Kopi-IX, HK-Kicks, Dim-Sum-IX, JP-Naptime, DE-KICKS, HAMS-IX, LYNX, NodNod and Any2-Anywhere. --- 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/30-networks/10-networks.js | 1 + src/i18n/en.js | 1 + tests/philippines.test.js | 11 +++++++++++ 9 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2173063..6854378 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants and Ditto join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. +- Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. ## [1.37.0] — 2026-10-28 diff --git a/site/i18n/de.js b/site/i18n/de.js index fca225d..80d3f2e 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2478,6 +2478,7 @@ "networks.the_third_mobile_network_same_towers":"Das dritte Mobilfunknetz: dasselbe noch mal, nur neuer. Peert offen, um aufzuholen.", "networks.the_tier_1_that_grew_up":"Der Tier 1, der in Sizilien aufgewachsen ist. Sein Seabone-Backbone beherrscht das Mittelmeer und reicht tief nach Amerika, und trotzdem nennt er Palermo sein Zuhause.", "networks.ukraine_s_biggest_mobile_network_has":"Das größte Mobilfunknetz der Ukraine. Hat Dinge überstanden, die die meisten Netze nie einplanen müssen.", +"networks.up_early_in_cebu_and_already":"Früh auf in Cebu und schon auf drei Kontinenten im Peering. Offen für alle.", "networks.updates_so_many_updates":"Updates. So viele Updates.", "networks.uruguay_s_state_telco_fast":"Uruguays staatliche Telco. Schnell, überall und ein bisschen stolz darauf.", "networks.vietnam_s_giant_will_tell_you":"Vietnams Riese. Sagt dir, welches Seekabel diese Woche kaputt ist.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 8aa9fad..6ff266f 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2476,6 +2476,7 @@ "networks.the_third_mobile_network_same_towers":"El tercer operador móvil: ídem, pero más nuevo. Hace peering abierto para ponerse al día.", "networks.the_tier_1_that_grew_up":"El Tier 1 que creció en Sicilia. Su backbone Seabone es dueño del Mediterráneo y llega hondo en las Américas, y aun así llama hogar a Palermo.", "networks.ukraine_s_biggest_mobile_network_has":"La mayor red móvil de Ucrania. Ha seguido funcionando en situaciones que la mayoría de las redes nunca tienen que planear.", +"networks.up_early_in_cebu_and_already":"Madruga en Cebú y ya hace peering en tres continentes. Abierto a todos.", "networks.updates_so_many_updates":"Actualizaciones. Tantas actualizaciones.", "networks.uruguay_s_state_telco_fast":"La telco estatal de Uruguay. Rápida, en todas partes, y un poco orgullosa de ello.", "networks.vietnam_s_giant_will_tell_you":"El gigante de Vietnam. Te dirá qué cable submarino está roto esta semana.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 510941d..92ab1ce 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2476,6 +2476,7 @@ "networks.the_third_mobile_network_same_towers":"Le troisième opérateur mobile : idem, mais en plus neuf. Peering ouvert pour rattraper son retard.", "networks.the_tier_1_that_grew_up":"Le Tier 1 qui a grandi en Sicile. Son backbone Seabone règne sur la Méditerranée et s’enfonce loin dans les Amériques, et il vit toujours à Palerme.", "networks.ukraine_s_biggest_mobile_network_has":"Le plus grand réseau mobile d’Ukraine. A continué de fonctionner malgré des choses que la plupart des réseaux n’ont jamais à prévoir.", +"networks.up_early_in_cebu_and_already":"Levé tôt à Cebu et déjà en peering sur trois continents. Ouvert à tous.", "networks.updates_so_many_updates":"Des mises à jour. Tellement de mises à jour.", "networks.uruguay_s_state_telco_fast":"L’opérateur public de l’Uruguay. Rapide, partout, et un peu fier de l’être.", "networks.vietnam_s_giant_will_tell_you":"Le géant du Vietnam. Te dira quel câble sous-marin est coupé cette semaine.", diff --git a/site/i18n/it.js b/site/i18n/it.js index be78346..a6ff74b 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2476,6 +2476,7 @@ "networks.the_third_mobile_network_same_towers":"Il terzo operatore mobile: idem, ma più nuovo. Fa peering aperto per recuperare.", "networks.the_tier_1_that_grew_up":"Il Tier 1 cresciuto in Sicilia. La sua dorsale Seabone domina il Mediterraneo e arriva in profondità nelle Americhe, e chiama ancora casa Palermo.", "networks.ukraine_s_biggest_mobile_network_has":"La più grande rete mobile dell’Ucraina. Ha continuato a funzionare attraverso cose che la maggior parte delle reti non deve mai mettere in conto.", +"networks.up_early_in_cebu_and_already":"Sveglia presto a Cebu e già in peering su tre continenti. Aperto a tutti.", "networks.updates_so_many_updates":"Aggiornamenti. Tantissimi aggiornamenti.", "networks.uruguay_s_state_telco_fast":"La telco di stato dell’Uruguay. Veloce, ovunque, e un po’ orgogliosa.", "networks.vietnam_s_giant_will_tell_you":"Il gigante del Vietnam. Ti dirà quale cavo sottomarino è rotto questa settimana.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 6206072..15c6c1e 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2476,6 +2476,7 @@ "networks.the_third_mobile_network_same_towers":"A terceira operadora móvel: idem, só que mais nova. Faz peering aberto para alcançar as outras.", "networks.the_tier_1_that_grew_up":"A Tier 1 que cresceu na Sicília. Seu backbone Seabone domina o Mediterrâneo e vai fundo nas Américas, e ela ainda chama Palermo de casa.", "networks.ukraine_s_biggest_mobile_network_has":"A maior rede mobile da Ucrânia. Continuou funcionando em situações que a maioria das redes nunca precisa planejar.", +"networks.up_early_in_cebu_and_already":"Acorda cedo em Cebu e já faz peering em três continentes. Aberto a todos.", "networks.updates_so_many_updates":"Atualizações. Tantas atualizações.", "networks.uruguay_s_state_telco_fast":"A telco estatal do Uruguai. Rápida, em todo lugar, e um pouco orgulhosa disso.", "networks.vietnam_s_giant_will_tell_you":"O gigante do Vietnã. Te conta qual cabo submarino está rompido esta semana.", diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index d63c5fc..e016009 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -42,6 +42,7 @@ NETS.push( {id:'cvg',name:'Diverge',asn:17639,type:'eye',pol:'open',share:.005,col:'#F26B21',pops:['mnl','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, {id:'smt',name:'Smarty Pants',asn:10139,type:'eye',pol:'selective',up:['pld'],minIx:10,minPni:30,share:.006,col:'#00A859',pops:['mnl'],ix:[],blurb:tr('networks.pldtea_time_s_mobile_sibling_buy')}, {id:'dto',name:'Ditto',asn:139831,type:'eye',pol:'open',share:.002,col:'#B5121B',pops:['mnl'],ix:['mnl','mnl~2'],blurb:tr('networks.the_third_mobile_network_same_towers')}, + {id:'rsh',name:'RISE & Shine',asn:63927,type:'eye',pol:'open',share:.002,col:'#F5A623',pops:['mnl','sin','hkg','tok','fra','ams','lon','sto','lax'],ix:['mnl','mnl~2','mnl~3','sin','sin~2','hkg','hkg~2','tok','fra','ams','lon','sto','lax'],blurb:tr('networks.up_early_in_cebu_and_already')}, {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( diff --git a/src/i18n/en.js b/src/i18n/en.js index c896ed0..12dfefd 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2477,6 +2477,7 @@ "networks.the_third_mobile_network_same_towers":"The third mobile network: the same again, but newer. Peers openly to catch up.", "networks.the_tier_1_that_grew_up":"The Tier 1 that grew up in Sicily. Its Seabone backbone owns the Mediterranean and reaches deep into the Americas, and it still calls Palermo home.", "networks.ukraine_s_biggest_mobile_network_has":"Ukraine’s biggest mobile network. Has kept working through things most networks never have to plan for.", +"networks.up_early_in_cebu_and_already":"Up early in Cebu and already peering on three continents. Open to all.", "networks.updates_so_many_updates":"Updates. So many updates.", "networks.uruguay_s_state_telco_fast":"Uruguay’s state telco. Fast, everywhere, and a little proud of it.", "networks.vietnam_s_giant_will_tell_you":"Vietnam’s giant. Will tell you which subsea cable is broken this week.", diff --git a/tests/philippines.test.js b/tests/philippines.test.js index cc50534..3ef7ac0 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -51,3 +51,14 @@ test('Manila: an exchange the player founded there before GotchaFIX existed keep assert.ok(ev('!S.myIx.mnl')); assert.deepEqual(errors, []); }); + +test('Manila: RISE & Shine peers openly on all three Manila exchanges, across Asia and in Europe', () => { + const { ev, errors } = load(); + start(ev); + assert.equal(ev('NET.rsh.name'), 'RISE & Shine'); + assert.equal(ev('NET.rsh.pol'), 'open'); + // GetaFIX Manila, PhOpenIX and VIX, Singapore, Hong Kong, JPNAP, DE-CIX, AMS-IX, LINX, Netnod, Any2 + for (const x of ['mnl', 'mnl~2', 'mnl~3', 'sin', 'sin~2', 'hkg', 'hkg~2', 'tok', 'fra', 'ams', 'lon', 'sto', 'lax']) + assert.ok(ids(ev, `ixMembers('${x}')`).includes('rsh'), `RISE & Shine on ${x}`); + assert.deepEqual(errors, []); +}); From d0d97e068eb2b283824674995083e63b3fc77674 Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Thu, 29 Oct 2026 22:38:07 +1100 Subject: [PATCH 144/491] Cebu: its own island, GotchaFIX Cebu and two domestic cables from Manila Cebu joins the map on its own landmass, with its outline taken from Natural Earth 1:50m (the simplified coastline had dropped it). GotchaFIX Cebu and Magellan's Last Rack. The Pan de Sal Cable Network (PDSCN, Luzon to Mactan) and the Philippines Long Distance Relationship (PLDT DFON, overland to Lucena then subsea to Cebu City) link it to Manila. PLDTea Time, Snow Globe and Diverge reach Cebu, and typhoons can hit it. --- CHANGELOG.md | 1 + 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/20-world/20-landmasses.js | 4 ++++ src/game/20-world/30-coastline.js | 2 ++ src/game/20-world/40-city-coords.js | 1 + src/game/20-world/50-cities.js | 2 ++ src/game/20-world/60-cables.js | 2 ++ src/game/30-networks/10-networks.js | 6 +++--- src/game/85-incidents/30-events.js | 4 ++-- src/i18n/en.js | 3 +++ tests/philippines.test.js | 22 ++++++++++++++++++++++ 15 files changed, 57 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6854378..b70eef3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. +- Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe and Diverge reach Cebu, and typhoons can hit it too. ## [1.37.0] — 2026-10-28 diff --git a/site/i18n/de.js b/site/i18n/de.js index 80d3f2e..484d4f0 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -421,8 +421,10 @@ "cables.the_emirates_oman_and_pakistan_on":"Die Emirate, Oman und Pakistan an einem leichten kleinen Kabel.", "cables.the_first_cable_from_south_america":"Das erste Kabel von Südamerika nach Ozeanien. 14.000 km sehr einsames Glas.", "cables.the_first_subsea_fiber_in_the":"Die erste Subsea-Glasfaser in der amerikanischen Arktis: Nome nach Utqiaġvik, dann über den North Slope nach Anchorage. Das Meereis hält Reparaturschiffe das halbe Jahr fern.", +"cables.the_incumbent_s_own_line_south":"Die eigene Leitung des Platzhirschs nach Süden: über Land bis Lucena, dann unter dem Meer nach Cebu. Ruft immer noch jede Nacht an.", "cables.the_newest_cable_from_south_africa":"Das neueste Kabel von Südafrika nach Madagaskar, Réunion und Mauritius, geteilt von den eigenen Telcos der Inseln.", "cables.the_old_workhorse_s_younger_sibling":"Das jüngere Geschwisterchen des alten Arbeitspferds: Los Angeles nach Sydney mit Abzweig nach Fidschi.", +"cables.the_philippines_longest_domestic_cable_fresh":"Das längste Inlandskabel der Philippinen, jeden Morgen frisch. Von Luzon nach Cebu, Insel für Insel.", "cables.the_pretty_way_around_east_asia":"Der hübsche Weg rund um Ostasien.", "cables.the_previous_generation_still":"Die vorige Generation. Trägt immer noch den Großteil von Pakistan, Sri Lanka und Bangladesch, zusammengehalten von Hoffnung.", "cables.the_sea_stallion_blackpool_to":"Der Seehengst: Blackpool nach Dänemark, galoppiert oben um Schottland herum.", @@ -633,6 +635,7 @@ "cities.the_old_gateway_to_eastern_europe":"Das alte Tor nach Osteuropa. Pakete verbeugen sich auf der Durchreise immer noch höflich.", "cities.the_only_northeastern_capital_away":"Die einzige Hauptstadt im Nordosten, die nicht am Meer liegt. Berüchtigt heiß, mit Gewittern, die den Überspannungsschutz auf Trab halten.", "cities.the_pacific_gateway_the_andes_sit":"Das Tor zum Pazifik. Die Anden liegen zwischen ihr und allem anderen, und ab und zu bebt die Erde.", +"cities.the_philippines_second_city_reached":"Die zweite Stadt der Philippinen, nur per Inlandskabel erreichbar. Taifune ziehen hier auf dem Weg nach Norden durch.", "cities.the_prairie_gateway_between":"Das Tor zur Prärie zwischen Vancouver und dem Rest Kanadas. Ein Chinook schmilzt den Schnee an einem Nachmittag, dann schneit es wieder.", "cities.the_rhine_ruhr_hub_more_carrier":"Der Rhein-Ruhr-Hub: mehr carrier-neutrale Rechenzentren als Hamburg oder München und eine Stunde von der niederländischen Grenze, also ist Glasfaser nach Amsterdam kurz und billig. Bestell hier ein Altbier, niemals ein Kölsch.", "cities.the_seychelles_capital_on_mah":"Die Hauptstadt der Seychellen auf Mahé: 115 Inseln, Riesenschildkröten und zwei Kabel zum Festland.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6ff266f..e969961 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -419,8 +419,10 @@ "cables.the_emirates_oman_and_pakistan_on":"Los Emiratos, Omán y Pakistán en un cablecito ligero.", "cables.the_first_cable_from_south_america":"El primer cable de Sudamérica a Oceanía. 14 000 km de vidrio muy solitario.", "cables.the_first_subsea_fiber_in_the":"La primera fibra submarina del Ártico estadounidense: de Nome a Utqiaġvik, y luego por el North Slope hasta Anchorage. El hielo marino mantiene alejados a los barcos de reparación la mitad del año.", +"cables.the_incumbent_s_own_line_south":"La línea propia del operador histórico hacia el sur: por tierra hasta Lucena y luego bajo el mar hasta Cebú. Sigue llamando cada noche.", "cables.the_newest_cable_from_south_africa":"El cable más nuevo de Sudáfrica a Madagascar, Reunión y Mauricio, compartido por las telcos de las propias islas.", "cables.the_old_workhorse_s_younger_sibling":"El hermano menor del viejo caballo de batalla: de Los Ángeles a Sídney con una rama a Fiyi.", +"cables.the_philippines_longest_domestic_cable_fresh":"El cable nacional más largo de Filipinas, recién hecho cada mañana. De Luzón a Cebú, isla a isla.", "cables.the_pretty_way_around_east_asia":"El camino bonito alrededor de Asia Oriental.", "cables.the_previous_generation_still":"La generación anterior. Aún lleva la mayor parte de Pakistán, Sri Lanka y Bangladés, sostenida con esperanza.", "cables.the_sea_stallion_blackpool_to":"El Semental del Mar: de Blackpool a Dinamarca, galopando por el norte de Escocia.", @@ -631,6 +633,7 @@ "cities.the_old_gateway_to_eastern_europe":"La vieja puerta de Europa del Este. Los paquetes aún hacen una reverencia educada al pasar.", "cities.the_only_northeastern_capital_away":"La única capital del noreste lejos del mar. Famosamente calurosa, con tormentas eléctricas que mantienen ocupados a los protectores contra sobretensiones.", "cities.the_pacific_gateway_the_andes_sit":"La puerta del Pacífico. Los Andes se interponen entre ella y todo lo demás, y el suelo tiembla de vez en cuando.", +"cities.the_philippines_second_city_reached":"La segunda ciudad de Filipinas, solo alcanzable por cable nacional. Los tifones pasan por aquí rumbo al norte.", "cities.the_prairie_gateway_between":"La puerta de las praderas entre Vancouver y el resto de Canadá. Un chinook derrite la nieve en una tarde, y luego vuelve a nevar.", "cities.the_rhine_ruhr_hub_more_carrier":"El hub del Rin-Ruhr: más centros de datos neutrales que Hamburgo o Múnich, y a una hora de la frontera holandesa, así que la fibra a Ámsterdam es corta y barata. Pide aquí una Altbier, nunca una Kölsch.", "cities.the_seychelles_capital_on_mah":"La capital de las Seychelles, en Mahé: 115 islas, tortugas gigantes y dos cables al continente.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 92ab1ce..19c991a 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -419,8 +419,10 @@ "cables.the_emirates_oman_and_pakistan_on":"Les Émirats, Oman et le Pakistan sur un seul petit câble léger.", "cables.the_first_cable_from_south_america":"Le premier câble entre l’Amérique du Sud et l’Océanie. 14 000 km de verre très solitaire.", "cables.the_first_subsea_fiber_in_the":"La première fibre sous-marine de l’Arctique américain : de Nome à Utqiaġvik, puis par le North Slope jusqu’à Anchorage. La banquise tient les navires de réparation à distance la moitié de l’année.", +"cables.the_incumbent_s_own_line_south":"La ligne de l'opérateur historique vers le sud : par la terre jusqu'à Lucena, puis sous la mer jusqu'à Cebu. Appelle encore tous les soirs.", "cables.the_newest_cable_from_south_africa":"Le câble le plus récent d’Afrique du Sud vers Madagascar, La Réunion et Maurice, partagé par les opérateurs des îles elles-mêmes.", "cables.the_old_workhorse_s_younger_sibling":"Le petit frère du vieux cheval de labour : de Los Angeles à Sydney, avec une dérivation vers les Fidji.", +"cables.the_philippines_longest_domestic_cable_fresh":"Le plus long câble national des Philippines, frais chaque matin. De Luçon à Cebu, île après île.", "cables.the_pretty_way_around_east_asia":"La route panoramique de l’Asie de l’Est.", "cables.the_previous_generation_still":"La génération précédente. Transporte encore l’essentiel du trafic du Pakistan, du Sri Lanka et du Bangladesh, le tout tenu par l’espoir.", "cables.the_sea_stallion_blackpool_to":"L’Étalon des mers : de Blackpool au Danemark, au galop autour du nord de l’Écosse.", @@ -631,6 +633,7 @@ "cities.the_old_gateway_to_eastern_europe":"L’ancienne porte de l’Europe de l’Est. Les paquets s’inclinent encore poliment en passant.", "cities.the_only_northeastern_capital_away":"La seule capitale du Nordeste loin de la mer. Réputée pour sa chaleur, avec des orages qui donnent du travail aux parafoudres.", "cities.the_pacific_gateway_the_andes_sit":"La porte du Pacifique. Les Andes la séparent de tout le reste, et la terre tremble de temps en temps.", +"cities.the_philippines_second_city_reached":"La deuxième ville des Philippines, joignable uniquement par câble national. Les typhons y passent en remontant vers le nord.", "cities.the_prairie_gateway_between":"La porte des Prairies entre Vancouver et le reste du Canada. Un chinook fait fondre la neige en un après-midi, puis il reneige.", "cities.the_rhine_ruhr_hub_more_carrier":"Le hub de la Rhénanie-Ruhr : plus de data centers neutres que Hamburg ou Munich, et à une heure de la frontière néerlandaise, donc la fibre vers Amsterdam est courte et pas chère. Ici, on commande une Altbier, jamais une Kölsch.", "cities.the_seychelles_capital_on_mah":"La capitale des Seychelles, sur Mahé : 115 îles, des tortues géantes et deux câbles vers le continent.", diff --git a/site/i18n/it.js b/site/i18n/it.js index a6ff74b..7dad3d5 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -419,8 +419,10 @@ "cables.the_emirates_oman_and_pakistan_on":"Emirati, Oman e Pakistan su un solo cavetto leggero.", "cables.the_first_cable_from_south_america":"Il primo cavo dal Sud America all’Oceania. 14.000 km di vetro molto solitario.", "cables.the_first_subsea_fiber_in_the":"La prima fibra sottomarina dell’Artico americano: da Nome a Utqiaġvik, poi oltre il North Slope fino ad Anchorage. Il pack tiene lontane le navi di riparazione per metà dell’anno.", +"cables.the_incumbent_s_own_line_south":"La linea dell'operatore storico verso sud: via terra fino a Lucena, poi sotto il mare fino a Cebu. Chiama ancora ogni sera.", "cables.the_newest_cable_from_south_africa":"Il cavo più recente dal Sudafrica a Madagascar, Riunione e Mauritius, condiviso dalle telco delle isole.", "cables.the_old_workhorse_s_younger_sibling":"Il fratellino del vecchio cavallo da tiro: da Los Angeles a Sydney con una diramazione per le Figi.", +"cables.the_philippines_longest_domestic_cable_fresh":"Il cavo nazionale più lungo delle Filippine, fresco ogni mattina. Da Luzon a Cebu, isola dopo isola.", "cables.the_pretty_way_around_east_asia":"Il giro panoramico dell’Asia orientale.", "cables.the_previous_generation_still":"La generazione precedente. Porta ancora quasi tutto il traffico di Pakistan, Sri Lanka e Bangladesh, tenuto insieme dalla speranza.", "cables.the_sea_stallion_blackpool_to":"Lo Stallone del Mare: da Blackpool alla Danimarca, al galoppo attorno al nord della Scozia.", @@ -631,6 +633,7 @@ "cities.the_old_gateway_to_eastern_europe":"L’antica porta verso l’Europa dell’Est. I pacchetti fanno ancora un inchino educato quando passano.", "cities.the_only_northeastern_capital_away":"L’unica capitale del Nordest lontana dal mare. Famosa per il caldo, con temporali e fulmini che tengono occupati gli scaricatori di sovratensione.", "cities.the_pacific_gateway_the_andes_sit":"La porta sul Pacifico. Le Ande stanno tra lei e tutto il resto, e ogni tanto la terra trema.", +"cities.the_philippines_second_city_reached":"La seconda città delle Filippine, raggiungibile solo con cavi nazionali. I tifoni ci passano andando verso nord.", "cities.the_prairie_gateway_between":"La porta delle praterie tra Vancouver e il resto del Canada. Un chinook scioglie la neve in un pomeriggio, poi nevica di nuovo.", "cities.the_rhine_ruhr_hub_more_carrier":"L’hub della Renania-Ruhr: più data center carrier-neutral di Amburgo o di Monaco, e a un’ora dal confine olandese, quindi la fibra fino ad Amsterdam è corta ed economica. Qui si ordina un’Altbier, mai una Kölsch.", "cities.the_seychelles_capital_on_mah":"La capitale delle Seychelles, su Mahé: 115 isole, tartarughe giganti e due cavi verso il continente.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 15c6c1e..41510d7 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -419,8 +419,10 @@ "cables.the_emirates_oman_and_pakistan_on":"Emirados, Omã e Paquistão num cabinho leve.", "cables.the_first_cable_from_south_america":"O primeiro cabo da América do Sul à Oceania. 14.000 km de vidro muito solitário.", "cables.the_first_subsea_fiber_in_the":"A primeira fibra submarina do Ártico americano: de Nome a Utqiaġvik, depois pelo North Slope até Anchorage. O gelo marinho mantém os navios de reparo longe por metade do ano.", +"cables.the_incumbent_s_own_line_south":"A linha própria da operadora histórica rumo ao sul: por terra até Lucena, depois sob o mar até Cebu. Ainda liga toda noite.", "cables.the_newest_cable_from_south_africa":"O cabo mais novo da África do Sul para Madagascar, Reunião e Maurício, compartilhado pelas operadoras das próprias ilhas.", "cables.the_old_workhorse_s_younger_sibling":"O irmão mais novo do velho burro de carga: de Los Angeles a Sydney com um ramal para Fiji.", +"cables.the_philippines_longest_domestic_cable_fresh":"O cabo nacional mais longo das Filipinas, fresquinho toda manhã. De Luzon a Cebu, ilha por ilha.", "cables.the_pretty_way_around_east_asia":"O caminho bonito pela Ásia Oriental.", "cables.the_previous_generation_still":"A geração anterior. Ainda leva quase tudo de Paquistão, Sri Lanka e Bangladesh, na base da esperança.", "cables.the_sea_stallion_blackpool_to":"O Sea Stallion: de Blackpool à Dinamarca, galopando pelo norte da Escócia.", @@ -631,6 +633,7 @@ "cities.the_old_gateway_to_eastern_europe":"A antiga porta de entrada do Leste Europeu. Os pacotes ainda fazem uma reverência educada ao passar.", "cities.the_only_northeastern_capital_away":"A única capital nordestina longe do mar. Famosa pelo calor, com tempestades de raios que mantêm os protetores de surto ocupados.", "cities.the_pacific_gateway_the_andes_sit":"A porta para o Pacífico. Os Andes ficam entre ela e todo o resto, e de vez em quando a terra treme.", +"cities.the_philippines_second_city_reached":"A segunda cidade das Filipinas, alcançada só por cabo nacional. Os tufões passam por aqui a caminho do norte.", "cities.the_prairie_gateway_between":"A porta das pradarias entre Vancouver e o resto do Canadá. Um chinook derrete a neve numa tarde, e aí neva de novo.", "cities.the_rhine_ruhr_hub_more_carrier":"O hub do Reno-Ruhr: mais data centers neutros do que Hamburgo ou Munique, e a uma hora da fronteira holandesa, então a fibra até Amsterdã é curta e barata. Aqui se pede uma Altbier, nunca uma Kölsch.", "cities.the_seychelles_capital_on_mah":"A capital das Seychelles, em Mahé: 115 ilhas, tartarugas gigantes e dois cabos para o continente.", diff --git a/src/game/20-world/20-landmasses.js b/src/game/20-world/20-landmasses.js index 6632dee..38f06aa 100644 --- a/src/game/20-world/20-landmasses.js +++ b/src/game/20-world/20-landmasses.js @@ -79,4 +79,8 @@ LANDS_LL.push( LANDS_LL.push( {id:'mv',ll:[[73.11,4.48],[73.91,4.48],[73.91,3.88],[73.11,3.88]]}, ); +// The Visayas: Cebu is its own island, reached from Luzon only by domestic cable. +LANDS_LL.push( + {id:'ceb',ll:[[123.3,11.3],[124.1,11.3],[124.1,9.4],[123.3,9.4]]}, +); const LANDS=LANDS_LL.map(l=>({id:l.id,hide:true,pts:l.ll.map(q=>proj(q[0],q[1]))})); diff --git a/src/game/20-world/30-coastline.js b/src/game/20-world/30-coastline.js index 4de48dd..594ed80 100644 --- a/src/game/20-world/30-coastline.js +++ b/src/game/20-world/30-coastline.js @@ -1,4 +1,6 @@ // Drawn coastline: Natural Earth 1:50m land, simplified (tight around cities, looser elsewhere), lon/lat rings. Built by scripts/build-land.mjs. // LANDS above is only the coarse landmass test that decides which landmass a city sits on (subsea vs overland); it is not drawn. const COAST_LL=[[[86.89,73.89],[85.79,73.44],[86.68,73.11],[85.91,73.39],[87.57,73.81],[86,74.32],[87.23,74.36],[85.79,74.65],[87.47,75.01],[87.01,75.17],[94.16,75.96],[92.86,75.98],[93.26,76.1],[95.58,76.14],[96.08,76.08],[95.65,75.89],[96.5,75.89],[98.66,76.24],[99.77,76.03],[99.54,75.8],[99.82,76.14],[98.8,76.48],[101.6,76.44],[100.93,76.56],[101.1,76.7],[100.91,76.9],[104.01,77.73],[106.06,77.39],[104.2,77.1],[107.43,76.93],[106.42,76.51],[111.11,76.72],[112.62,76.38],[112.66,76.05],[113.27,76.25],[113.56,75.89],[113.86,75.92],[113.57,75.57],[112.45,75.83],[113.73,75.45],[112.92,75.02],[107.27,73.62],[105.14,72.78],[110.87,73.73],[109.67,73.8],[110.26,74.02],[111.55,74.03],[111.23,73.97],[112.15,73.71],[113.03,73.91],[113.42,73.65],[113.16,73.46],[113.49,73.35],[113.16,72.77],[113.67,72.64],[113.22,72.81],[113.89,73.35],[113.51,73.5],[114.06,73.58],[118.45,73.59],[118.94,73.48],[118.46,73.46],[118.43,73.25],[119.75,72.98],[122.54,72.88],[123.62,73.19],[123.32,73.43],[123.41,73.64],[124.54,73.75],[126.55,73.33],[127.74,73.48],[129.1,73.11],[128.6,72.9],[129.25,72.7],[128.42,72.53],[129.28,72.44],[129.28,72.09],[127.73,72.41],[128.91,71.75],[129.21,71.92],[129.46,71.74],[128.84,71.66],[129.76,71.12],[131.02,70.75],[132.04,71.24],[132.65,71.93],[133.69,71.43],[136.09,71.62],[137.94,71.13],[138.32,71.33],[137.92,71.38],[138.23,71.6],[139.99,71.49],[139.72,71.89],[139.36,71.95],[140.19,72.19],[139.18,72.16],[139.14,72.33],[141.08,72.59],[140.65,72.84],[140.81,72.89],[146.25,72.44],[144.29,72.19],[146.83,72.29],[146.11,71.95],[146.23,72.14],[145.76,72.23],[145.76,71.94],[145.07,71.93],[145.19,71.7],[147.26,72.33],[149.5,72.16],[150.02,71.9],[148.92,71.71],[150.67,71.45],[150.1,71.23],[151.58,71.29],[152.09,71.02],[151.76,70.98],[152.51,70.83],[155.89,71.1],[158.7,70.94],[159.91,70.51],[159.83,69.78],[160.91,69.61],[161.34,68.9],[160.86,68.54],[161.56,68.9],[161.54,69.38],[163.2,69.72],[166.89,69.5],[167.86,69.73],[168.3,69.27],[169.31,69.08],[169.61,68.79],[170.54,68.83],[171,69.14],[170.58,69.58],[170.16,69.63],[170.49,70.11],[173.28,69.82],[175.92,69.9],[179.87,69.01],[180,68.98],[181.13,68.75],[181.94,68.27],[182.2,68.34],[181.63,68.57],[184.65,67.68],[184.63,67.36],[185.15,67.35],[185.08,66.62],[185.61,66.34],[185.91,66.47],[185.94,66.23],[186.22,66.43],[185.77,66.63],[185.91,66.94],[185.45,67.09],[186.84,67.07],[186.74,66.84],[187.48,66.95],[186.99,67.06],[188.2,66.93],[189.4,66.25],[190.27,66.06],[189.6,65.93],[189.33,65.62],[188.55,65.79],[188.83,65.5],[187.22,65.68],[187.77,65.45],[187.34,65.25],[187.79,65.05],[186.93,64.85],[187.62,64.43],[187.1,64.53],[186.84,64.28],[186.67,64.54],[186.27,64.36],[184.56,64.82],[183.91,65.47],[181.59,65.49],[181.06,66.03],[181.47,66.4],[181.08,66.18],[180.86,66.37],[180.22,66.02],[180.65,65.52],[179.45,64.82],[178.52,64.6],[176.41,65.07],[177.22,64.86],[176.06,64.96],[174.55,64.68],[175.68,64.78],[176.06,64.9],[176.25,64.84],[176.35,64.71],[176.14,64.59],[176.51,64.68],[176.84,64.63],[177.05,64.72],[177.39,64.77],[177.47,64.74],[177.41,64.57],[177.43,64.44],[177.95,64.22],[178.13,64.24],[178.23,64.36],[178.38,64.26],[178.48,64.13],[178.45,64.01],[178.65,63.97],[178.69,63.84],[178.47,63.57],[179.33,63.19],[179.57,62.77],[179.12,62.32],[177.02,62.78],[177.16,62.56],[172.86,61.47],[172.39,61.06],[170.61,60.43],[170.35,59.97],[169.23,60.6],[167.23,60.41],[166.27,59.86],[166.35,60.48],[165.09,60.1],[164.96,59.84],[163.74,60.03],[161.96,58.08],[162.39,57.72],[162.66,57.95],[163.23,57.79],[162.76,57.24],[162.8,56.81],[163.26,56.69],[163.34,56.23],[162.84,56.06],[162.63,56.23],[163.04,56.52],[162.67,56.49],[162.09,56.09],[161.72,55.5],[162.1,54.75],[160.07,54.19],[159.84,53.78],[159.96,53.55],[159.9,53.38],[160,53.27],[160.03,53.13],[159.95,53.13],[159.77,53.23],[159.59,53.24],[158.95,53.05],[158.75,52.91],[158.56,53.05],[158.47,53.03],[158.43,52.96],[158.61,52.87],[158.48,52.63],[158.49,52.38],[158.33,52.09],[158.1,51.81],[156.75,50.97],[155.56,55.2],[156.02,56.75],[156.85,57.29],[156.87,57.8],[158.27,58.01],[162.07,60.47],[163.71,60.92],[163.56,61.03],[164.01,61.34],[163.8,61.46],[164.21,62.29],[165.4,62.49],[164.42,62.71],[163.33,62.55],[163.09,61.57],[162.39,61.66],[160.17,60.64],[160.38,61.02],[159.79,60.96],[160.31,61.89],[157.09,61.68],[154.29,59.83],[154.15,59.53],[154.97,59.45],[155.16,59.19],[153.36,59.21],[152.82,58.93],[151.33,58.88],[151.12,59.08],[152.26,59.22],[149.64,59.77],[148.8,59.53],[148.96,59.37],[148.73,59.26],[146.54,59.46],[146.05,59.17],[145.55,59.41],[142.58,59.24],[140.79,58.3],[140.45,57.81],[138.66,56.97],[137.69,56.14],[135.26,54.94],[135.26,54.73],[135.85,54.58],[136.8,54.62],[136.72,53.8],[137.16,53.82],[137.14,54.18],[137.67,54.28],[137.34,54.1],[137.84,53.95],[137.25,53.55],[137.95,53.6],[138.53,53.96],[138.25,53.52],[138.45,53.54],[138.66,54.3],[139.71,54.28],[141.38,53.29],[141.18,53.01],[140.84,53.09],[141.26,52.84],[141.13,52.43],[141.49,52.18],[140.52,50.8],[140.38,48.96],[138.11,46.25],[135.13,43.53],[133.16,42.7],[133.06,42.72],[133,42.81],[132.86,42.79],[132.71,42.88],[132.3,42.88],[132.31,43.31],[132.03,43.12],[131.87,43.1],[132.01,43.28],[131.94,43.3],[131.72,43.2],[131.39,42.82],[131.16,42.63],[130.71,42.66],[130.83,42.52],[130.73,42.33],[129.76,41.71],[129.71,40.86],[127.57,39.78],[127.4,39.21],[128.33,38.68],[129.42,37.06],[129.56,35.95],[129.21,35.18],[128.51,35.1],[128.44,34.87],[127.71,34.96],[127.72,34.72],[127.4,34.82],[127.32,34.46],[127.25,34.76],[126.53,34.31],[126.27,34.67],[126.59,34.82],[126.29,35.15],[126.69,36.01],[126.54,36.17],[126.55,36.48],[126.49,36.69],[126.39,36.65],[126.18,36.69],[126.16,36.77],[126.22,36.87],[126.49,37.01],[126.78,36.95],[126.87,36.82],[126.98,36.94],[126.87,36.98],[126.74,37.19],[126.79,37.3],[126.65,37.45],[126.66,37.55],[126.56,37.72],[126.63,37.78],[126.37,37.88],[126.12,37.74],[126.05,37.87],[125.94,37.87],[125.77,37.99],[125.41,37.72],[124.99,37.93],[125.21,38.08],[124.69,38.13],[125.55,38.69],[125.17,38.81],[125.36,39.53],[124.64,39.61],[124.35,40.01],[122.84,39.6],[121.16,38.73],[121.11,38.92],[121.82,39.39],[121.27,39.55],[122.26,40.5],[121.83,40.97],[121.18,40.9],[120.48,40.23],[119.39,39.75],[118.98,39.18],[117.78,39.13],[117.65,38.42],[118.94,38.04],[119.11,37.2],[119.76,37.15],[120.75,37.83],[121.64,37.46],[122.67,37.4],[122.34,36.83],[121.93,36.96],[120.81,36.63],[120.64,36.13],[120.18,36.2],[120.29,35.98],[119.22,35.01],[119.2,34.75],[120.27,34.27],[120.86,32.66],[121.34,32.43],[121.4,32.37],[121.45,32.15],[121.68,32.05],[121.83,31.9],[121.87,31.7],[121.76,31.7],[121.35,31.86],[120.97,31.87],[120.79,32.03],[120.52,32.11],[120.07,31.96],[120.19,31.91],[120.5,32.02],[120.71,31.98],[120.79,31.82],[121.06,31.72],[121.66,31.32],[121.79,31.16],[121.88,30.92],[121.42,30.79],[121,30.56],[120.82,30.35],[120.45,30.39],[120.23,30.25],[120.5,30.3],[120.63,30.13],[120.91,30.16],[121.16,30.3],[121.26,30.3],[121.43,30.23],[121.68,29.98],[122.08,29.87],[121.91,29.78],[121.51,29.48],[121.97,29.49],[121.92,29.13],[121.45,29.13],[121.68,28.95],[121.47,28.64],[121.61,28.29],[121.15,28.33],[120.75,28.01],[120.09,26.67],[119.59,26.79],[119.88,26.33],[119.14,26.12],[119.62,26],[119.62,25.39],[119.18,25.45],[119.29,25.23],[118.98,25.21],[118.66,24.62],[117.84,24.47],[118.06,24.25],[117.37,23.59],[116.91,23.65],[116.47,22.95],[115.64,22.85],[115.5,22.72],[115.38,22.72],[115.2,22.82],[114.85,22.62],[114.75,22.63],[114.71,22.74],[114.65,22.75],[114.54,22.62],[114.55,22.53],[114.34,22.59],[114.27,22.54],[114.34,22.4],[114.27,22.3],[113.9,22.4],[114.01,22.51],[113.83,22.61],[113.62,22.86],[113.62,23.13],[113.45,23.05],[113.44,22.94],[113.33,22.91],[113.55,22.59],[113.59,22.35],[113.55,22.22],[113.15,22.08],[113.09,22.21],[113.01,22.12],[112.99,21.94],[112.9,21.88],[112.81,21.95],[112.66,21.86],[112.36,21.98],[112.3,21.74],[111.94,21.85],[111.6,21.56],[110.41,21.34],[110.16,20.94],[110.52,20.46],[110.12,20.26],[109.66,20.92],[109.93,21.48],[109.52,21.69],[109.08,21.44],[108.48,21.9],[108.5,21.63],[107.81,21.5],[107.16,20.95],[106.68,21],[106.52,20.29],[105.98,19.94],[105.62,18.97],[106.5,17.95],[106.35,17.77],[108.82,15.38],[109.3,13.86],[109.45,12.6],[109.22,12.65],[109.2,11.73],[108.99,11.34],[108.18,10.92],[108.1,10.9],[108,10.72],[107.84,10.7],[107.26,10.4],[107.09,10.5],[107.01,10.66],[106.95,10.4],[106.81,10.43],[106.73,10.54],[106.61,10.47],[106.74,10.44],[106.76,10.3],[106.47,10.3],[106.73,10.19],[106.79,10.12],[106.6,9.86],[106.14,10.22],[106.51,9.82],[106.57,9.64],[106.48,9.56],[106.38,9.56],[105.83,10],[106.16,9.59],[106.21,9.5],[106.17,9.4],[104.77,8.6],[105.03,10.07],[104.26,10.54],[103.59,10.55],[103.65,11.06],[103.15,10.91],[103.12,11.46],[102.65,12.15],[101.72,12.69],[101.44,12.62],[100.9,12.65],[100.86,12.72],[100.96,13.43],[100.6,13.57],[100.54,13.51],[100.23,13.48],[100.02,13.35],[99.99,13.24],[100.09,13.04],[99.96,12.69],[100.01,12.35],[99.16,10.32],[99.25,9.27],[99.83,9.29],[100.42,7.19],[101.5,6.86],[103.2,5.26],[103.45,4.67],[103.48,2.84],[103.81,2.58],[104.22,1.72],[104.28,1.42],[104.18,1.37],[103.98,1.62],[103.99,1.46],[103.69,1.45],[103.48,1.33],[103.36,1.55],[102.73,1.86],[102.55,2.04],[102.15,2.25],[101.78,2.57],[101.52,2.68],[101.3,2.89],[101.35,3.01],[101.3,3.25],[100.72,3.97],[100.8,4.02],[100.66,4.23],[100.26,6.18],[99.6,7.36],[98.24,8.42],[98.7,10.19],[98.56,10.03],[98.47,10.68],[98.88,11.72],[98.64,11.74],[98.57,13.16],[98.2,13.98],[98.11,13.71],[97.81,14.86],[97.58,16.02],[97.72,16.57],[97.38,16.52],[96.85,17.4],[96.77,16.71],[96.43,16.5],[96.19,16.77],[96.32,16.44],[95.39,15.72],[95.35,16.1],[95.18,15.83],[94.94,15.82],[94.89,16.18],[94.66,15.9],[94.7,16.51],[94.23,16.02],[94.59,17.57],[94.05,19.29],[93.93,18.9],[93.49,19.37],[93.83,19.24],[94,19.44],[93.71,19.91],[93.25,20.07],[93.13,19.86],[93.07,20.38],[92.83,20.18],[92.74,20.56],[92.72,20.3],[92.31,20.79],[91.86,22.35],[91.53,22.71],[91.48,22.88],[91.22,22.64],[90.95,22.6],[90.63,23.09],[90.6,23.59],[90.56,23.42],[90.27,23.46],[90.59,23.27],[90.6,23.13],[90.47,23.05],[90.55,22.91],[90.46,22.88],[90.43,22.75],[90.61,22.36],[90.55,22.22],[90.16,21.82],[90.21,22.16],[89.96,22.02],[89.89,22.31],[89.98,22.47],[89.88,22.39],[89.57,21.77],[89.48,22.28],[89.35,21.72],[89.05,22.09],[89.05,21.65],[88.75,21.58],[88.64,22.12],[88.58,21.66],[88.06,21.69],[88.2,22.14],[87.94,22.37],[88.16,22.12],[87.95,21.83],[86.86,21.24],[86.98,20.7],[86.75,20.31],[86.22,19.9],[85.25,19.76],[85.18,19.59],[85.44,19.63],[84.11,18.29],[82.36,17.1],[82.26,16.56],[81.29,16.34],[80.98,15.76],[80.38,15.79],[80.1,14.8],[80.18,14.48],[80.11,14.21],[80.31,13.49],[80.16,13.71],[80.06,13.61],[80.34,13.36],[80.23,12.69],[80.14,12.45],[79.86,11.99],[79.84,10.32],[79.31,10.26],[78.92,9.45],[79.41,9.19],[78.42,9.1],[78.06,8.38],[77.3,8.15],[76.4,9.24],[76.35,9.92],[74.94,12.56],[74.38,14.49],[73.47,16.05],[73.15,17.53],[72.87,18.64],[73.01,19.02],[72.97,19.15],[72.83,18.98],[72.8,19.08],[72.81,19.3],[72.99,19.28],[72.79,19.36],[72.75,19.45],[72.8,19.52],[72.73,19.58],[72.67,19.83],[72.9,20.67],[72.61,21.46],[73.11,21.75],[72.54,21.7],[72.7,21.97],[72.52,21.98],[72.81,22.23],[72.18,22.27],[72.04,21.82],[72.25,21.53],[72.02,21.16],[70.72,20.74],[68.97,22.29],[70.18,22.57],[70.49,23.09],[69.67,22.76],[69.24,22.85],[68.42,23.57],[68.78,23.85],[68.23,23.6],[68.16,23.86],[68.11,23.75],[68.04,23.85],[67.95,23.83],[67.86,23.9],[67.82,23.83],[67.67,23.81],[67.65,23.92],[67.56,23.88],[67.31,24.17],[67.17,24.76],[66.7,24.86],[66.7,25.23],[66.43,25.58],[66.22,25.59],[66.13,25.49],[66.36,25.51],[66.47,25.45],[66.24,25.46],[65.68,25.35],[61.41,25.1],[60.51,25.44],[59.05,25.42],[57.34,25.79],[57.21,26.04],[57.2,26.16],[56.73,27.13],[56.28,27.19],[55.42,26.77],[55.29,26.79],[54.9,26.56],[54.64,26.51],[54.52,26.59],[53.71,26.73],[52.48,27.62],[51.52,27.91],[50.07,30.2],[49.56,30.03],[49,30.51],[48.83,30.04],[47.98,30.01],[48.15,29.57],[47.72,29.39],[48.05,29.35],[48.8,27.72],[50.15,26.66],[50.15,26.1],[50.1,26.12],[50.08,25.96],[50.24,25.62],[50.46,25.42],[50.56,25.09],[50.81,24.79],[50.85,24.89],[50.76,25.45],[51,25.98],[51.26,26.15],[51.54,25.9],[51.57,25.78],[51.49,25.53],[51.61,25.05],[51.43,24.67],[51.27,24.61],[51.42,24.53],[51.31,24.34],[51.54,24.29],[51.6,24.34],[51.67,24.25],[51.77,24.25],[51.84,24.01],[52.12,23.97],[52.51,24.11],[53.03,24.15],[53.89,24.08],[54.4,24.28],[54.75,24.81],[55.1,25.04],[55.52,25.5],[55.94,25.79],[56.17,26.21],[56.31,26.24],[56.41,26.35],[56.37,25.8],[56.3,25.65],[56.36,25.57],[56.37,25.02],[56.64,24.47],[56.91,24.15],[57.22,23.92],[58.58,23.64],[59.84,22.42],[58.47,20.41],[58.17,20.59],[57.86,20.24],[57.81,19.02],[56.82,18.75],[56.38,17.99],[55.48,17.84],[55.06,17.04],[54.07,17],[52.45,16.39],[52.22,15.66],[51.6,15.34],[49.35,14.64],[48.67,14.05],[45.66,13.34],[45.04,12.82],[44.26,12.64],[43.49,12.7],[42.94,14.94],[42.66,15.23],[42.7,16.74],[41.66,18.01],[40.76,19.75],[40.08,20.27],[39.88,20.29],[39.73,20.39],[39.27,20.97],[39.09,21.31],[39.15,21.52],[38.99,21.88],[39.09,22.39],[39.01,22.77],[38.88,22.88],[38.94,22.88],[38.29,23.91],[37.54,24.29],[37.15,25.29],[35.18,28.04],[34.62,28.06],[34.97,29.55],[34.22,27.76],[33.25,28.57],[32.72,29.52],[32.56,29.97],[32.47,29.93],[32.49,29.85],[32.36,29.63],[32.4,29.53],[32.56,29.39],[32.66,28.93],[33.55,27.9],[33.96,26.65],[35.2,24.47],[35.78,23.94],[35.51,23.78],[35.7,22.95],[36.83,22.1],[37.26,21.11],[37.47,18.82],[38.57,18.07],[39.5,15.53],[39.79,15.12],[39.86,15.47],[40.2,15.01],[41.18,14.62],[43.3,12.46],[43.34,12.03],[42.54,11.51],[43.16,11.57],[44.28,10.47],[44.94,10.44],[45.82,10.84],[46.56,10.75],[47.4,11.17],[50.11,11.53],[50.79,11.98],[51.26,11.83],[51.03,10.44],[51.39,10.39],[50.93,10.34],[50.82,9.43],[47.98,4.5],[46.05,2.47],[43.72,0.86],[41.39,-1.87],[40.22,-2.69],[39.23,-4.67],[38.8,-6.07],[39.54,-7.02],[39.29,-7.52],[39.3,-8.44],[39.72,-10],[40.61,-10.66],[40.43,-12.94],[40.83,-14.79],[39.84,-16.44],[37.51,-17.57],[36.41,-18.77],[34.95,-19.81],[34.65,-19.7],[35.31,-22.4],[35.45,-22.12],[35.54,-22.3],[35.44,-24.17],[34.99,-24.65],[32.79,-25.64],[32.59,-26],[32.85,-26.27],[32.96,-26.08],[32.89,-26.83],[32.38,-28.5],[31.34,-29.38],[29.97,-31.32],[27.86,-33.05],[26.61,-33.71],[25.81,-33.74],[25.57,-34.04],[22.55,-34.01],[21.79,-34.37],[19.64,-34.75],[19.39,-34.6],[19.3,-34.62],[19.33,-34.49],[19.24,-34.41],[19.15,-34.42],[19.1,-34.35],[18.83,-34.36],[18.81,-34.11],[18.75,-34.08],[18.53,-34.09],[18.46,-34.17],[18.46,-34.35],[18.41,-34.3],[18.33,-34.07],[18.35,-33.94],[18.47,-33.89],[18.43,-33.72],[18.26,-33.42],[18.16,-33.36],[17.88,-32.96],[17.85,-32.83],[17.89,-32.75],[17.97,-32.71],[18.04,-32.78],[18.12,-32.75],[18.25,-32.65],[18.33,-32.5],[18.21,-31.74],[16.74,-29.01],[15.29,-27.28],[14.5,-24.2],[14.46,-22.45],[11.78,-18],[11.75,-15.83],[12.55,-13.44],[13.79,-11.81],[13.83,-10.93],[13,-9.05],[13.38,-8.37],[12.28,-6.12],[13.07,-5.87],[12.45,-6],[12.24,-5.81],[11.78,-4.57],[9.72,-2.47],[10.06,-2.55],[9.62,-2.37],[9.04,-1.31],[9.5,-1.55],[9.06,-1.3],[8.7,-0.59],[8.95,-0.69],[9.3,-0.35],[9.35,0.34],[9.8,0.04],[10,0.2],[9.33,0.55],[9.62,0.58],[9.6,1.05],[9.39,1.14],[9.81,1.93],[9.95,3.08],[9.56,3.8],[9.69,4.06],[9,4.09],[8.92,4.55],[8.57,4.53],[8.25,4.92],[8.29,4.56],[7.08,4.72],[6.92,4.39],[6.77,4.72],[6.86,4.37],[6.08,4.29],[5.49,4.84],[5.37,5.34],[5.55,5.47],[5.2,5.53],[5.46,5.61],[5.11,5.64],[4.86,6.03],[4.43,6.35],[4.13,6.41],[3.45,6.43],[3.75,6.58],[3.72,6.6],[3.43,6.52],[3.34,6.4],[1.82,6.26],[-2,4.76],[-3.25,5.11],[-3.02,5.13],[-3.2,5.35],[-3.35,5.13],[-5.28,5.21],[-5.06,5.13],[-7.54,4.35],[-8.26,4.59],[-11.73,7.09],[-12.49,7.39],[-12.48,7.75],[-12.85,7.82],[-13.27,8.43],[-12.89,8.63],[-13.18,8.58],[-13.06,8.88],[-13.69,9.54],[-13.69,9.93],[-14.43,10.25],[-14.59,10.77],[-14.89,10.97],[-15.01,10.8],[-15.05,11.14],[-15.39,11.22],[-15.43,11.5],[-15.07,11.6],[-15.5,11.78],[-15.08,11.97],[-15.94,11.79],[-16.79,12.47],[-16.44,12.61],[-16.77,12.63],[-16.75,13.43],[-16.41,13.27],[-15.43,13.47],[-16.44,13.35],[-16.77,13.9],[-16.62,14.04],[-17.53,14.75],[-16.57,15.73],[-16.08,17.55],[-16.09,18.52],[-16.52,19.36],[-16.21,20.23],[-16.88,21.09],[-17.1,20.86],[-16.93,21.9],[-16.36,22.59],[-15.9,23.84],[-14.91,24.72],[-14.47,26.16],[-13.58,26.74],[-12.95,27.91],[-11.55,28.31],[-10.2,29.38],[-9.67,30.11],[-9.81,31.42],[-9.25,32.57],[-8.51,33.25],[-6.9,33.97],[-5.92,35.79],[-5.28,35.9],[-5.25,35.61],[-4.63,35.21],[-2.97,35.41],[-2.84,35.13],[-1.91,35.09],[1.26,36.52],[3.78,36.9],[5.29,36.65],[6.49,37.09],[7.91,36.86],[9.69,37.34],[9.83,37.14],[10.2,37.21],[10.41,36.73],[10.95,37.06],[11.13,36.87],[10.49,36.26],[11.12,35.24],[10.06,34.21],[10.31,33.73],[10.96,33.63],[11.2,33.25],[12.28,32.86],[13.28,32.92],[15.18,32.39],[15.71,31.43],[17.83,30.93],[18.94,30.29],[19.59,30.41],[20.01,30.8],[19.93,31.82],[20.12,32.22],[21.63,32.94],[23.09,32.62],[23.29,32.21],[24.88,31.98],[25.23,31.53],[26.77,31.47],[29.07,30.83],[30.22,31.26],[30.57,31.47],[30.92,31.57],[30.56,31.42],[31,31.46],[31.08,31.6],[32.14,31.34],[31.89,31.48],[31.77,31.29],[32.01,31.22],[32.1,31.09],[32.28,31.2],[32.21,31.29],[32.6,31.07],[33.67,31.13],[34.48,31.59],[35.98,34.55],[35.81,36.31],[36.18,36.81],[35.39,36.57],[34.7,36.82],[33.69,36.18],[32.79,36.04],[31.24,36.82],[30.65,36.87],[30.45,36.27],[29.69,36.16],[28.97,36.72],[27.46,36.71],[28.24,37.03],[27.26,36.98],[27.53,37.16],[27.07,37.66],[27.23,37.98],[26.29,38.28],[26.44,38.64],[26.67,38.34],[27.14,38.45],[26.76,38.71],[27.01,38.89],[26.68,39.29],[26.9,39.55],[26.09,39.52],[26.18,39.99],[26.74,40.4],[27.73,40.33],[27.85,40.38],[27.73,40.48],[27.99,40.49],[27.93,40.38],[27.96,40.37],[29.01,40.39],[29.05,40.42],[28.79,40.53],[29.05,40.65],[29.85,40.74],[29.36,40.81],[29.12,40.94],[29.05,41.01],[29.15,41.22],[29.92,41.15],[30.35,41.2],[31.25,41.11],[33.28,42],[35,42.06],[35.3,41.73],[36.05,41.68],[36.41,41.27],[38.38,40.93],[39.43,41.11],[40.13,40.94],[41.41,41.42],[41.76,41.97],[41.42,42.74],[38.72,44.29],[36.63,45.15],[36.87,45.43],[37.65,45.38],[37.93,46],[38.49,46.09],[37.77,46.64],[38.5,46.66],[38.44,46.81],[39.27,47.04],[39.02,47.27],[35.83,46.62],[35.02,46.11],[35.23,46.44],[34.85,46.19],[35.02,45.7],[35.46,45.32],[36.57,45.39],[36.39,45.07],[35.47,45.1],[33.91,44.39],[33.45,44.55],[33.55,45.1],[32.51,45.4],[33.67,45.95],[33.59,46.1],[31.83,46.28],[32.01,46.43],[31.56,46.56],[32.58,46.62],[32.05,46.64],[31.76,47.21],[31.87,46.65],[30.8,46.55],[30.22,45.87],[29.63,45.72],[29.56,44.84],[28.89,44.92],[28.56,43.5],[28.13,43.4],[27.89,42.75],[27.48,42.47],[27.98,42.05],[27.99,41.86],[28.2,41.56],[29.06,41.23],[28.96,41.01],[28.78,40.97],[28.17,41.08],[27.92,40.99],[27.5,40.97],[27.43,40.84],[26.2,40.07],[26.79,40.63],[24.48,40.95],[23.76,40.75],[24.34,40.15],[23.73,40.33],[23.95,39.97],[23.43,40.26],[23.63,39.92],[22.81,40.58],[22.59,40.04],[23.23,39.36],[23.33,39.18],[23.22,39.1],[23.12,39.13],[23.16,39.26],[22.99,39.33],[22.84,39.26],[22.97,39.03],[23.07,39.04],[22.8,38.9],[22.57,38.87],[23.25,38.66],[23.37,38.53],[23.57,38.49],[23.68,38.35],[23.97,38.27],[24.06,37.82],[24.05,37.71],[23.97,37.68],[23.5,38.03],[23.03,37.88],[23.15,37.8],[23.2,37.62],[23.39,37.58],[23.49,37.44],[23.16,37.33],[23.1,37.36],[23.1,37.44],[22.94,37.52],[22.78,37.59],[22.73,37.54],[23.06,36.85],[23.04,36.64],[23.11,36.55],[22.83,36.69],[22.78,36.79],[22.72,36.79],[22.49,36.45],[22.08,37.03],[21.89,36.74],[21.58,37.08],[21.68,37.39],[21.12,37.89],[21.83,38.33],[22.24,38.19],[22.92,37.96],[22.89,38.05],[23.12,38.07],[23.18,38.13],[23.15,38.18],[22.83,38.23],[22.42,38.44],[22.23,38.35],[21.11,38.39],[20.77,38.87],[21.12,39.03],[20.3,39.33],[19.85,40.04],[19.4,40.28],[19.58,41.79],[18.65,42.44],[17.04,43.02],[17.72,42.85],[16.9,43.39],[15.99,43.52],[15.19,44.17],[15.47,44.27],[14.55,45.3],[14.31,45.34],[13.86,44.84],[13.52,45.48],[13.78,45.63],[13.63,45.77],[12.27,45.45],[12.52,44.97],[12.25,44.72],[12.4,44.22],[13.56,43.57],[14.01,42.69],[14.54,42.24],[15.17,41.93],[16.17,41.9],[15.9,41.51],[17.96,40.65],[18.48,40.1],[18.34,39.82],[17.87,40.28],[16.93,40.46],[16.52,39.75],[17.11,39.38],[17.17,39],[16.62,38.8],[16.06,37.94],[15.72,37.94],[15.64,38.18],[16.21,38.94],[15.69,39.99],[14.95,40.24],[14.77,40.67],[14.34,40.6],[14.46,40.73],[14.05,40.81],[13.86,41.13],[13.67,41.26],[13.25,41.29],[13.09,41.24],[12.85,41.41],[12.63,41.47],[12.08,41.94],[11.81,42.08],[11.64,42.29],[11.3,42.42],[11.1,42.42],[11.18,42.46],[11.17,42.53],[10.51,42.97],[10.19,43.95],[9.73,44.1],[9.29,44.32],[8.76,44.42],[8.55,44.35],[8.29,44.14],[6.72,43.37],[6.57,43.2],[6.11,43.07],[5.81,43.1],[5.41,43.23],[5.32,43.35],[5.07,43.37],[5.06,43.44],[4.71,43.37],[4.22,43.48],[4.05,43.59],[3.91,43.56],[3.16,43.08],[3.09,42.59],[3.31,42.29],[3.17,42.26],[3.15,42.16],[3.24,42.08],[3.25,41.94],[3,41.77],[2.31,41.47],[2.08,41.29],[1.03,41.06],[0.71,40.82],[0.89,40.72],[-0.33,39.52],[0.2,38.76],[-0.52,38.32],[-0.72,37.63],[-1.64,37.39],[-2.19,36.74],[-4.37,36.72],[-5.63,36.03],[-6.38,36.64],[-6.22,36.91],[-6.86,37.28],[-7.84,37.01],[-8.93,37.17],[-8.81,37.43],[-8.79,37.73],[-8.88,37.96],[-8.8,38.18],[-8.88,38.45],[-8.67,38.42],[-8.8,38.52],[-9.21,38.45],[-9.25,38.66],[-9.02,38.75],[-8.94,39],[-8.79,39.08],[-8.96,39.02],[-9.14,38.74],[-9.36,38.7],[-9.47,38.73],[-9.48,38.8],[-9.35,39.25],[-9.38,39.34],[-9.15,39.54],[-8.84,40.12],[-8.87,40.26],[-8.66,41.03],[-8.89,42.11],[-8.69,42.27],[-9.18,43.17],[-7.7,43.77],[-7.06,43.55],[-1.99,43.35],[-1.49,43.56],[-1.08,44.69],[-1.24,44.67],[-1.08,45.53],[-0.55,45],[-1.2,45.71],[-1.03,45.74],[-1.15,46.31],[-2.09,46.87],[-2.11,47.26],[-1.74,47.22],[-4.31,47.82],[-4.68,48.04],[-4.33,48.17],[-4.58,48.29],[-4.24,48.3],[-4.72,48.54],[-3.23,48.84],[-2.69,48.54],[-1.38,48.65],[-1.86,49.68],[-0.16,49.3],[0.44,49.47],[0.13,49.51],[0.19,49.7],[1.24,50],[1.59,50.25],[1.67,50.88],[3.72,51.37],[4.22,51.39],[4.01,51.44],[3.82,51.41],[3.69,51.45],[3.55,51.59],[3.89,51.57],[4.14,51.46],[4.28,51.47],[4.01,51.6],[4.18,51.61],[3.95,51.81],[4.08,51.99],[4.48,52.31],[4.77,52.94],[4.89,52.91],[5.06,52.96],[5.36,53.1],[5.53,53.27],[6.06,53.41],[7.2,53.28],[7.21,53.66],[7.63,53.7],[8.49,53.39],[8.62,53.88],[9.78,53.55],[8.65,54.29],[8.96,54.54],[8.68,54.79],[8.62,55.42],[8.13,55.6],[8.16,56.61],[9.2,56.7],[9.11,57.04],[8.77,56.72],[8.27,56.81],[10.53,57.73],[10.28,56.62],[10.9,56.36],[9.91,55.84],[9.46,55.04],[10.02,54.67],[9.87,54.47],[11.01,54.38],[10.86,54.01],[12.11,54.17],[12.58,54.47],[13.03,54.41],[13.15,54.28],[13.82,54.02],[13.87,53.85],[13.95,53.8],[14.49,53.67],[14.56,53.82],[14.17,53.87],[13.93,53.88],[13.92,54],[13.83,54.06],[14.38,53.92],[18.08,54.84],[18.76,54.68],[18.44,54.75],[18.84,54.37],[19.41,54.39],[19.97,54.92],[20.68,55.1],[21.12,55.62],[20.59,54.98],[21.19,54.93],[21.03,56.64],[21.73,57.57],[22.56,57.72],[23.65,56.97],[24.4,57.33],[24.3,57.78],[24.49,58.26],[24.55,58.3],[24.53,58.35],[24.34,58.38],[24.11,58.27],[23.77,58.36],[23.69,58.51],[23.51,58.66],[23.68,58.79],[23.5,58.79],[23.43,58.92],[23.51,59],[23.47,59.03],[23.52,59.11],[23.5,59.19],[24.08,59.29],[24.05,59.37],[24.38,59.47],[25.44,59.52],[25.52,59.56],[25.51,59.64],[27.89,59.41],[28.06,59.78],[30.17,59.96],[28.64,60.38],[28.51,60.68],[26.45,60.47],[26.21,60.41],[25.95,60.47],[26.04,60.34],[25.76,60.27],[25.66,60.33],[24.6,60.11],[24.45,60.02],[23.46,59.99],[23.18,59.84],[22.96,59.83],[23.2,60.02],[22.91,60.21],[22.46,60.03],[22.58,60.38],[21.44,60.6],[21.61,61.59],[21.12,62.69],[21.65,63.04],[21.54,63.21],[22.32,63.31],[22.53,63.65],[23.6,64.04],[24.56,64.8],[25.29,64.86],[25.35,65.48],[24.63,65.86],[22.4,65.86],[22.25,65.6],[21.41,65.32],[21.57,65.13],[21.14,64.81],[21.52,64.46],[20.76,63.87],[18.61,63.18],[18.17,62.79],[17.88,62.87],[18.04,62.6],[17.38,62.46],[17.63,62.23],[17.47,61.68],[17.13,61.57],[17.25,60.7],[17.36,60.64],[17.56,60.64],[17.66,60.54],[17.96,60.59],[18.16,60.41],[18.56,60.25],[18.53,60.15],[18.79,60.08],[18.93,59.94],[18.97,59.76],[18.28,59.44],[17.97,59.36],[18.13,59.32],[18.51,59.41],[18.62,59.33],[18.42,59.29],[18.29,59.11],[17.76,58.97],[16.98,58.65],[16.64,58.65],[16.21,58.64],[16.79,58.59],[16.93,58.49],[16.82,58.46],[16.65,58.43],[16.53,57.07],[16,56.22],[14.72,56.13],[14.26,55.89],[14.34,55.53],[14.08,55.39],[13.81,55.43],[13.32,55.35],[12.89,55.41],[12.94,55.48],[12.97,55.75],[12.47,56.29],[12.71,56.23],[12.8,56.26],[12.66,56.44],[12.86,56.45],[12.92,56.52],[12.88,56.62],[12.72,56.66],[12.42,56.91],[11.25,58.42],[11.21,58.87],[11.15,58.99],[11.19,59.08],[11.39,59.04],[11.37,59.1],[10.83,59.18],[10.64,59.39],[10.6,59.76],[10.54,59.7],[10.57,59.59],[10.4,59.52],[10.46,59.38],[10.43,59.28],[10.18,59.01],[9.84,58.96],[9.64,59.12],[9.56,59.11],[9.7,59.01],[9.62,58.95],[8.17,58.14],[7,58.02],[6.9,58.07],[6.88,58.15],[6.8,58.16],[6.73,58.07],[6.59,58.1],[6.55,58.12],[6.69,58.22],[6.66,58.26],[6.39,58.27],[6.05,58.38],[5.71,58.52],[5.52,58.73],[5.56,58.97],[5.61,59.01],[6.1,58.87],[6.36,59],[6.1,58.95],[5.89,59.1],[5.97,59.19],[5.95,59.3],[6.4,59.56],[5.56,59.29],[5.36,59.17],[5.17,59.16],[5.13,59.23],[5.19,59.45],[5.3,59.64],[5.47,59.71],[5.77,59.66],[5.87,59.73],[6.22,59.82],[5.83,59.8],[5.73,59.86],[6.07,60.08],[6.14,60.23],[6.35,60.35],[6.53,60.21],[6.53,60.15],[7,60.51],[6.35,60.42],[6.15,60.35],[5.91,60.15],[5.88,60.07],[5.7,60.01],[5.5,59.83],[5.15,59.64],[5.12,59.83],[5.22,59.98],[5.18,60.05],[5.21,60.09],[5.5,60.07],[5.69,60.12],[5.29,60.21],[5.14,60.44],[5.65,60.69],[5.12,60.64],[5.1,61.07],[6.78,61.14],[7.04,60.95],[7.61,61.21],[7.44,61.43],[7.17,61.17],[5.11,61.19],[5,61.43],[5.34,61.48],[4.93,61.88],[6.73,61.87],[5.27,61.94],[5.14,62.16],[6.69,62.47],[6.14,62.41],[6.35,62.61],[8.09,62.73],[6.73,62.72],[7.57,63.1],[8.62,62.85],[8.16,63.16],[8.63,63.34],[8.36,63.5],[8.58,63.6],[9.7,63.63],[10.02,63.39],[11.37,63.81],[11.18,63.9],[11.31,64.05],[10.06,63.51],[9.57,63.71],[11.63,64.81],[11.3,64.76],[11.49,64.98],[12.92,65.34],[12.42,65.18],[12.12,65.36],[13.03,65.96],[12.79,66.1],[14.03,66.3],[13.12,66.23],[13.21,66.64],[13.96,66.8],[13.65,66.91],[15.42,67.2],[14.44,67.27],[14.96,67.57],[15.59,67.35],[15.69,67.52],[15.25,67.6],[15.31,67.77],[14.78,67.68],[15.05,67.96],[15.62,67.95],[15.29,68.04],[16.01,68.23],[16.31,67.88],[16.21,68.32],[17.57,68.45],[16.58,68.59],[18.1,69.16],[18.26,69.47],[18.92,69.33],[18.61,69.49],[19.2,69.75],[19.72,69.78],[19.64,69.42],[20.32,69.95],[20.05,69.33],[20.74,69.52],[20.62,69.91],[21.98,69.83],[21.36,70.23],[22.69,70.37],[23.36,69.98],[23.38,70.25],[24.66,71],[25.77,70.85],[25.04,70.11],[26.51,70.91],[26.74,70.85],[26.58,70.41],[27.55,70.8],[27.33,71],[28.14,71.04],[28.38,70.87],[27.9,70.68],[28.27,70.67],[28.19,70.25],[28.83,70.86],[30.96,70.34],[28.78,70.15],[29.6,69.98],[29.69,69.74],[31.45,69.69],[31.98,69.95],[33.01,69.72],[32.09,69.63],[32.38,69.48],[33.45,69.43],[33.14,69.07],[33.68,69.31],[35.86,69.19],[40.97,67.71],[41.36,67.21],[41.19,66.83],[40.1,66.3],[38.66,66.07],[34.48,66.55],[32.93,67.09],[31.89,67.16],[33.65,66.44],[33.36,66.33],[34.69,65.95],[34.41,65.4],[35.03,64.44],[37.44,63.81],[38.06,64.09],[37.95,64.32],[37.18,64.41],[36.58,64.79],[36.88,65.17],[39.76,64.58],[40.44,64.78],[39.8,65.35],[39.82,65.6],[42.21,66.52],[43.23,66.41],[44.11,66.01],[44.43,66.94],[43.78,67.26],[44.2,68.25],[43.33,68.67],[45.89,68.48],[46.69,67.85],[45.53,67.76],[44.9,67.41],[46.49,66.8],[47.66,66.98],[47.88,67.58],[48.83,67.68],[48.75,67.9],[51.99,68.54],[52.4,68.35],[52.72,68.48],[52.34,68.61],[53.8,69],[54.49,68.99],[53.8,68.91],[53.93,68.44],[53.26,68.27],[54.86,68.2],[55.42,68.57],[57.13,68.55],[59.06,69.01],[59.37,68.74],[59.1,68.44],[59.73,68.35],[59.9,68.71],[60.93,68.99],[60.17,69.59],[60.91,69.85],[64.19,69.53],[68.5,68.35],[69.14,68.95],[68.54,68.97],[67.62,69.58],[66.9,69.55],[67.29,70.74],[66.7,70.82],[66.85,71.06],[66.64,71.08],[68.27,71.68],[69.39,72.96],[71.5,72.91],[72.81,72.69],[72.57,72.01],[71.87,71.46],[72.7,70.96],[72.47,70.28],[72.58,68.97],[73.59,68.48],[73.14,68.18],[73.07,67.77],[71.85,67.01],[71.37,66.96],[71.54,66.68],[70.72,66.52],[70.38,66.6],[70.69,66.74],[69.01,66.79],[69.98,66.4],[72.07,66.25],[73.79,66.99],[74.77,67.77],[74.39,68.42],[74.58,68.75],[75.12,68.86],[76.46,68.98],[77.24,68.47],[77.18,67.78],[78.92,67.59],[77.59,67.75],[77.67,68.19],[78,68.26],[77.65,68.9],[76,69.24],[73.78,69.2],[73.89,69.42],[73.58,69.8],[74.34,70.58],[73.09,71.44],[73.67,71.85],[74.99,72.15],[75.1,72.42],[74.79,72.81],[75.6,72.58],[75.74,72.3],[75.27,71.96],[75.5,71.65],[75.28,71.43],[75.73,71.27],[79.02,70.95],[76.43,71.55],[76.03,71.91],[78.19,71.91],[77.41,72.11],[78.48,72.4],[79.42,72.38],[81.66,71.72],[83.11,71.72],[82.98,71.45],[82.32,71.26],[82.16,70.6],[82.22,70.4],[82.59,70.89],[83.01,70.9],[82.68,70.22],[83.08,70.09],[83.74,70.55],[83.15,71.1],[83.53,71.68],[82.09,72.27],[81.1,72.39],[80.83,72.49],[80.66,72.71],[80.84,72.95],[80.76,73.03],[80.51,73.09],[80.42,73.23],[80.4,73.36],[80.6,73.47],[80.58,73.57]],[[-152.47,70.65],[-151.77,70.56],[-151.94,70.45],[-149.27,70.5],[-144.62,69.98],[-143.22,70.12],[-135.26,68.68],[-135.91,69.11],[-134.46,69.48],[-134.41,69.68],[-133.88,69.51],[-134.18,69.25],[-130.67,70.13],[-129.54,70.11],[-131.94,69.53],[-133.42,68.84],[-132.71,68.81],[-132.53,68.87],[-132.72,69.08],[-131.79,69.43],[-131.06,69.45],[-130.97,69.21],[-130.12,69.72],[-128.9,69.97],[-129.16,69.8],[-128.85,69.75],[-127.68,70.26],[-128.17,70.42],[-127.99,70.57],[-125.73,69.38],[-125.17,69.43],[-125.34,69.66],[-124.56,70.15],[-124.12,69.69],[-124.34,69.36],[-123.53,69.39],[-123.03,69.81],[-121.74,69.8],[-117.23,68.91],[-115.44,68.94],[-113.96,68.4],[-115.43,67.9],[-115.13,67.82],[-112.43,67.68],[-110.07,67.99],[-107.99,67.26],[-108.5,67.09],[-107.26,66.4],[-107.75,66.96],[-107.16,66.88],[-107.96,67.82],[-105.75,68.59],[-107.73,68.17],[-108.72,68.3],[-108.34,68.6],[-106.16,68.92],[-104.49,68.06],[-103.47,68.11],[-102.32,67.74],[-98.41,67.81],[-98.63,68.07],[-97.61,67.63],[-97.16,67.73],[-98.19,67.92],[-98.65,68.36],[-97.83,68.53],[-96.43,68.31],[-96.72,68.04],[-95.97,68.25],[-96.37,67.51],[-95.42,67.01],[-96.42,67.04],[-95.79,66.62],[-96.04,66.94],[-95.4,66.95],[-95.26,67.26],[-95.65,67.74],[-95.46,68.02],[-93.45,68.62],[-93.85,69],[-94.6,68.8],[-94.09,69.12],[-94.25,69.31],[-93.43,69.37],[-96.05,69.83],[-96.54,70.33],[-95.89,70.69],[-96.36,70.68],[-96.53,71.13],[-96.06,71.41],[-95.56,71.34],[-95.41,71.49],[-95.87,71.57],[-95.2,71.9],[-94.61,71.99],[-94.48,71.85],[-94.31,71.77],[-93.03,71.34],[-92.98,70.85],[-91.57,70.18],[-92.32,70.24],[-92.51,70.1],[-91.98,70.04],[-92.89,69.67],[-90.42,69.46],[-91.24,69.29],[-90.48,68.88],[-90.58,68.48],[-90.25,68.27],[-89.28,69.26],[-88.04,68.81],[-87.81,68.35],[-88.35,68.29],[-88.31,67.95],[-87.36,67.18],[-86.56,67.48],[-85.69,68.67],[-84.87,68.77],[-85.11,68.84],[-84.86,69.07],[-85.39,69.23],[-85.51,69.85],[-82.62,69.69],[-82.37,69.64],[-82.76,69.49],[-82.23,69.25],[-81.32,69.14],[-81.96,68.88],[-81.28,68.66],[-82.55,68.45],[-81.29,67.5],[-81.39,67.19],[-82.64,66.59],[-83.52,66.37],[-84.85,67.03],[-85.11,66.89],[-84.64,66.9],[-83.8,66.24],[-86.71,66.52],[-85.96,66.12],[-87.45,65.34],[-89.75,65.94],[-91.43,65.95],[-87,65.11],[-88.11,64.18],[-89.13,63.97],[-90.04,64.14],[-89.86,63.96],[-90.17,63.98],[-90.01,63.8],[-90.24,63.64],[-93.7,64.15],[-93.56,63.86],[-92.16,63.69],[-92.47,63.56],[-91.84,63.7],[-90.97,63.44],[-90.7,63.06],[-92.36,62.82],[-91.94,62.59],[-92.55,62.55],[-92.77,62.35],[-92.53,62.17],[-93.21,62.36],[-92.9,62.22],[-93.58,61.94],[-93.31,61.77],[-93.91,61.48],[-94.76,60.5],[-94.96,59.07],[-94.29,58.72],[-94.33,58.3],[-94.12,58.74],[-93.18,58.73],[-92.43,57.32],[-92.8,56.92],[-90.59,57.22],[-88.83,56.81],[-87.48,56.02],[-85.68,55.6],[-85.22,55.35],[-85.37,55.08],[-83.91,55.31],[-82.39,55.07],[-82.22,54.81],[-82.42,54.24],[-82.14,53.82],[-82.29,53.03],[-81.6,52.43],[-81.83,52.22],[-80.59,51.67],[-80.44,51.39],[-80.85,51.12],[-80.1,51.28],[-79.35,50.76],[-79.74,51.19],[-79.34,51.63],[-78.9,51.2],[-78.73,51.5],[-78.98,51.78],[-78.45,52.26],[-79.1,53.66],[-79.01,54.02],[-79.71,54.67],[-77.78,55.29],[-76.55,56.36],[-76.57,57.18],[-76.89,57.76],[-78.51,58.68],[-77.73,59.68],[-77.35,59.58],[-77.29,60.02],[-77.59,60.09],[-77.68,60.43],[-77.5,60.54],[-77.79,60.64],[-77.59,60.81],[-78.18,60.82],[-77.51,61.56],[-78.02,61.83],[-78.13,62.28],[-77.37,62.57],[-74.63,62.11],[-73.71,62.47],[-72.69,62.13],[-72.77,61.84],[-72.23,61.83],[-72.04,61.68],[-72.21,61.59],[-71.64,61.62],[-71.85,61.44],[-71.42,61.16],[-69.99,60.86],[-69.5,61.04],[-69.67,60.08],[-70.66,60.03],[-69.73,59.92],[-69.68,59.34],[-69.35,59.3],[-69.53,58.87],[-70.16,58.76],[-68.38,58.74],[-68.36,58.16],[-69.04,57.9],[-68.41,58.05],[-68.02,58.48],[-68.06,58.14],[-67.75,58.4],[-67.68,57.99],[-66.36,58.79],[-66,58.43],[-66.04,58.82],[-65.38,59.06],[-65.7,59.21],[-65.48,59.47],[-65.04,59.39],[-65.43,59.78],[-65.03,59.77],[-65.17,59.91],[-64.82,60.33],[-64.5,60.27],[-64.77,60.01],[-64.28,60.06],[-64.23,59.74],[-63.75,59.51],[-63.95,59.38],[-63.42,59.19],[-63.97,59.05],[-63.25,59.07],[-63.28,58.87],[-62.87,58.67],[-63.54,58.33],[-62.61,58.5],[-63.26,58.01],[-62.49,58.15],[-61.96,57.91],[-61.97,57.61],[-62.49,57.49],[-61.33,57.01],[-61.37,56.68],[-62.5,56.8],[-61.43,56.36],[-61.71,56.23],[-61.36,56.22],[-61.45,56],[-60.34,55.79],[-60.19,55.48],[-60.62,55.06],[-59.76,55.31],[-59.44,55.18],[-59.84,54.81],[-59.26,55.2],[-58.78,54.84],[-57.96,54.88],[-57.4,54.59],[-60.4,53.65],[-60.1,53.49],[-60.33,53.27],[-57.93,54.1],[-58.36,54.16],[-58.19,54.23],[-57.42,54.16],[-57.13,53.79],[-57.52,53.61],[-57.33,53.47],[-56.46,53.76],[-55.86,53.34],[-55.8,52.64],[-56.32,52.54],[-55.74,52.47],[-56.01,52.39],[-55.69,52.14],[-56.98,51.46],[-58.51,51.29],[-59.88,50.32],[-61.72,50.1],[-62.71,50.3],[-66.41,50.22],[-66.94,49.99],[-67.37,49.35],[-68.28,49.2],[-69.67,48.2],[-71.02,48.46],[-69.77,48.1],[-70.71,47.14],[-72.68,46.29],[-72.98,46.21],[-73.02,46.12],[-73.14,46.07],[-73.47,45.74],[-73.71,45.71],[-74.04,45.5],[-74.31,45.53],[-74,45.43],[-73.98,45.35],[-74.36,45.21],[-74.71,45],[-73.76,45.4],[-73.56,45.42],[-73.46,45.63],[-73.16,46.01],[-72.73,46.18],[-72.37,46.4],[-70.52,47.03],[-69.47,47.97],[-68.24,48.63],[-65.4,49.26],[-64.26,48.92],[-64.51,48.84],[-64.26,48.55],[-65.26,48.02],[-65.93,48.19],[-66.7,48.02],[-65.61,47.67],[-64.7,47.73],[-65.32,47.1],[-64.83,47.06],[-64.54,46.24],[-62.75,45.65],[-61.95,45.87],[-61.35,45.57],[-61.46,45.37],[-61.03,45.29],[-63.6,44.68],[-63.61,44.48],[-64.29,44.55],[-64.86,43.87],[-65.74,43.56],[-66.13,43.81],[-66.02,44.56],[-64.45,45.34],[-64.14,45.02],[-63.37,45.36],[-64.87,45.36],[-64.32,45.84],[-64.63,45.95],[-64.78,45.64],[-65.89,45.22],[-66.03,45.42],[-66.44,45.1],[-67.12,45.17],[-66.99,44.83],[-68.06,44.39],[-68.45,44.51],[-68.53,44.26],[-68.81,44.34],[-68.76,44.57],[-69.14,44.04],[-70.27,43.67],[-70.2,43.63],[-70.52,43.35],[-70.73,43.07],[-70.83,42.83],[-70.74,42.67],[-70.62,42.67],[-70.61,42.62],[-70.83,42.55],[-71.04,42.33],[-70.74,42.23],[-70.62,42.04],[-70.66,41.99],[-70.55,41.94],[-70.52,41.8],[-70.43,41.76],[-70.3,41.73],[-70,41.83],[-70.11,42.03],[-70.24,42.09],[-70.11,42.08],[-69.98,41.96],[-69.93,41.71],[-70.66,41.53],[-70.7,41.72],[-71.17,41.49],[-71.2,41.64],[-71.15,41.75],[-71.27,41.68],[-71.39,41.79],[-71.37,41.7],[-71.43,41.63],[-71.44,41.45],[-71.52,41.38],[-72.92,41.28],[-73.58,41.02],[-73.99,40.75],[-73.87,41.06],[-73.88,41.17],[-73.97,41.25],[-73.92,41.14],[-73.93,40.91],[-74.26,40.53],[-74.24,40.46],[-74,40.45],[-73.97,40.4],[-74.08,39.79],[-74.07,39.99],[-74.26,39.61],[-74.33,39.54],[-74.41,39.55],[-74.39,39.49],[-74.48,39.34],[-74.58,39.32],[-74.61,39.25],[-74.92,38.94],[-74.9,39.15],[-75.52,39.49],[-75.07,39.98],[-75.17,39.89],[-75.32,39.86],[-75.57,39.48],[-75.04,38.43],[-75.93,37.15],[-75.66,37.95],[-75.85,37.97],[-75.86,38.36],[-76.12,38.32],[-76.26,38.44],[-76.26,38.6],[-76,38.6],[-76.21,38.76],[-76.28,38.77],[-76.34,38.71],[-76.3,38.82],[-76.17,38.85],[-76.19,38.91],[-76.33,38.91],[-76.33,38.95],[-76.31,39.01],[-76.19,38.99],[-76.13,39.12],[-76.22,39.06],[-76.24,39.19],[-76.15,39.32],[-75.94,39.4],[-76,39.41],[-75.97,39.51],[-76.01,39.57],[-76.06,39.56],[-76.1,39.43],[-76.21,39.38],[-76.25,39.44],[-76.28,39.32],[-76.33,39.4],[-76.42,39.23],[-76.57,39.27],[-76.43,39.13],[-76.47,39.03],[-76.56,39.07],[-76.5,38.94],[-76.54,38.74],[-76.5,38.53],[-76.39,38.37],[-76.57,38.44],[-76.68,38.61],[-76.67,38.54],[-76.64,38.45],[-76.41,38.27],[-76.34,38.09],[-76.46,38.17],[-76.77,38.26],[-76.87,38.39],[-76.89,38.29],[-77,38.44],[-77.23,38.41],[-77.22,38.54],[-77.02,38.78],[-77.03,38.89],[-77.05,38.78],[-77.26,38.6],[-77.31,38.4],[-77.27,38.35],[-77.05,38.36],[-76.91,38.2],[-76.55,38.09],[-76.35,37.96],[-76.34,37.68],[-76.79,37.94],[-76.94,38.1],[-77.11,38.16],[-76.62,37.76],[-76.27,37.49],[-76.45,37.27],[-76.76,37.51],[-76.34,37.01],[-77.25,37.33],[-76.49,36.9],[-76,36.91],[-75.53,35.82],[-75.95,36.66],[-75.82,36.11],[-76.15,36.28],[-76.56,36.02],[-76.73,36.23],[-76.73,35.96],[-76.07,35.97],[-76.08,35.69],[-75.76,35.84],[-76.17,35.35],[-77.04,35.53],[-76.51,35.27],[-76.78,34.99],[-77.07,35.15],[-76.97,35.02],[-76.44,34.84],[-77.41,34.73],[-77.93,33.94],[-77.95,34.17],[-78.01,33.91],[-78.84,33.72],[-79.94,32.67],[-80.64,32.51],[-80.58,32.29],[-80.8,32.45],[-80.69,32.22],[-81.44,31.2],[-81.25,29.79],[-80.52,28.49],[-80.46,27.9],[-80.84,28.76],[-80.05,26.81],[-80.13,25.83],[-80.16,25.88],[-80.3,25.62],[-80.37,25.33],[-80.48,25.23],[-80.74,25.16],[-81.11,25.14],[-81.17,25.23],[-81.14,25.31],[-80.97,25.22],[-80.94,25.26],[-81.11,25.37],[-81.37,25.83],[-81.72,25.98],[-81.96,26.49],[-81.83,26.69],[-82.04,26.55],[-82.01,26.96],[-82.29,26.87],[-82.72,27.5],[-82.41,27.86],[-82.84,27.85],[-82.65,28.89],[-84.04,30.1],[-85.32,29.68],[-85.6,30.29],[-86.45,30.4],[-86.26,30.49],[-87.2,30.34],[-87,30.57],[-88,30.23],[-87.79,30.29],[-88.01,30.69],[-88.13,30.37],[-89.59,30.17],[-90.23,30.38],[-90.28,30.06],[-89.4,30.05],[-89.35,29.82],[-89.72,29.62],[-89.02,29.2],[-89.38,28.98],[-90.16,29.54],[-90.21,29.1],[-91.29,29.29],[-91.25,29.56],[-91.89,29.84],[-92.26,29.56],[-93.83,29.72],[-93.88,29.81],[-93.81,29.85],[-93.79,29.98],[-93.84,29.98],[-93.94,29.81],[-93.89,29.69],[-94.1,29.67],[-94.76,29.38],[-94.53,29.55],[-94.78,29.55],[-94.74,29.75],[-94.83,29.75],[-94.89,29.68],[-95.02,29.7],[-94.99,29.53],[-94.89,29.37],[-95.14,29.17],[-95.15,29.08],[-95.27,28.96],[-95.85,28.64],[-96.23,28.49],[-96.01,28.63],[-96.37,28.66],[-96.45,28.59],[-96.58,28.72],[-96.42,28.46],[-97.16,28.14],[-97.07,27.99],[-97.43,27.84],[-97.44,27.33],[-97.77,27.46],[-97.48,27.24],[-97.14,26.03],[-97.67,24.39],[-97.86,22.62],[-97.31,21.56],[-97.41,21.27],[-97.75,22.03],[-97.64,21.6],[-95.92,18.82],[-95.18,18.7],[-94.46,18.17],[-92.44,18.67],[-91.53,18.46],[-91.27,18.62],[-91.44,18.89],[-90.74,19.35],[-90.35,21.01],[-88.47,21.57],[-87.04,21.59],[-86.82,21],[-87.69,19.64],[-87.43,19.58],[-87.85,18.27],[-88.03,18.84],[-88.35,18.36],[-88.08,18.23],[-88.31,16.63],[-88.89,15.89],[-88.13,15.7],[-87.7,15.91],[-86.91,15.76],[-84.97,15.99],[-84.26,15.82],[-83.76,15.22],[-83.37,15.24],[-83.19,14.34],[-83.57,13.32],[-83.51,12.41],[-83.59,12.71],[-83.75,12.5],[-83.83,11.13],[-82.24,9.03],[-81.78,8.96],[-81.9,9.14],[-81.55,8.83],[-81.06,8.81],[-80.84,8.89],[-80.55,9.08],[-80.13,9.21],[-79.58,9.6],[-79.11,9.54],[-78.93,9.43],[-78.5,9.41],[-78.08,9.24],[-76.79,7.93],[-76.92,8.57],[-75.64,9.45],[-75.54,10.2],[-75.71,10.14],[-75.45,10.61],[-74.84,11.11],[-74.33,11],[-74.4,10.77],[-74.14,11.32],[-73.31,11.3],[-71.6,12.43],[-71.14,12.05],[-71.96,11.57],[-71.6,10.66],[-72.11,9.82],[-71.62,9.05],[-71.24,9.16],[-71.05,9.71],[-71.47,10.96],[-69.81,11.47],[-70.29,11.89],[-70,12.18],[-69.63,11.48],[-68.4,11.16],[-68.14,10.49],[-66.25,10.63],[-65.13,10.07],[-63.73,10.5],[-64.3,10.64],[-61.88,10.74],[-62.91,10.53],[-62.74,10.06],[-62.55,10.2],[-62.32,9.78],[-62.08,9.98],[-61.74,9.63],[-61.59,9.89],[-60.79,9.36],[-61.25,8.6],[-61.62,8.6],[-61.3,8.41],[-60.17,8.62],[-58.81,7.74],[-58.48,7.33],[-58.67,6.39],[-58.42,6.85],[-57.98,6.79],[-57.23,6.18],[-57.18,5.53],[-56.97,5.99],[-55.9,5.7],[-55.83,5.96],[-54.36,5.91],[-54.05,5.81],[-54.16,5.36],[-53.85,5.78],[-52.9,5.43],[-52.06,4.72],[-52,4.35],[-51.83,4.64],[-51.65,4.06],[-51.55,4.31],[-51.22,4.09],[-50.72,2.13],[-49.96,1.66],[-49.9,1.16],[-51.28,-0.08],[-51.98,-1.37],[-52.66,-1.55],[-51.95,-1.59],[-50.9,-0.94],[-50.4,-2.01],[-49.32,-1.73],[-49.64,-2.66],[-49.21,-1.92],[-48.35,-1.48],[-48.45,-1.15],[-48.12,-0.74],[-47.4,-0.63],[-45.46,-1.36],[-45.33,-1.72],[-45.08,-1.47],[-44.65,-1.75],[-44.54,-2.05],[-44.76,-2.26],[-44.44,-2.17],[-44.38,-2.37],[-44.72,-3.2],[-44.23,-2.47],[-44.19,-2.81],[-43.38,-2.38],[-42.25,-2.79],[-39.77,-2.99],[-39.02,-3.39],[-38.69,-3.65],[-38.48,-3.72],[-38.05,-4.22],[-37.63,-4.59],[-37.3,-4.71],[-36.59,-5.1],[-35.39,-5.25],[-34.83,-7.02],[-34.84,-7.97],[-35.34,-9.23],[-37.36,-11.25],[-38.02,-12.59],[-38.4,-12.97],[-38.69,-12.62],[-38.85,-12.79],[-39.09,-13.59],[-38.88,-15.86],[-39.16,-17.7],[-39.65,-18.25],[-39.78,-19.57],[-40.96,-21.24],[-41,-22],[-41.58,-22.24],[-41.98,-22.58],[-41.94,-22.79],[-42.04,-22.95],[-42.96,-22.97],[-43.08,-22.9],[-43.09,-22.72],[-43.23,-22.75],[-43.22,-22.99],[-43.9,-23.1],[-43.97,-23.06],[-43.68,-23.01],[-43.86,-22.91],[-44.15,-23.01],[-44.37,-23],[-45.21,-23.58],[-45.33,-23.6],[-45.46,-23.8],[-45.97,-23.79],[-46.87,-24.24],[-47.14,-24.49],[-47.59,-24.78],[-48.2,-25.42],[-48.73,-25.37],[-48.4,-25.6],[-48.75,-26.27],[-48.56,-27.2],[-48.8,-28.58],[-49.75,-29.36],[-50.92,-31.26],[-52.04,-32.12],[-52.06,-31.83],[-51.27,-31.48],[-50.58,-30.44],[-50.56,-30.25],[-51.03,-30.37],[-51.3,-30.04],[-51.28,-30.75],[-51.97,-31.38],[-52.65,-33.14],[-53.79,-34.38],[-54.9,-34.93],[-56.85,-34.68],[-57.17,-34.45],[-57.87,-34.45],[-58.4,-33.91],[-58.44,-33.72],[-58.36,-33.18],[-58.15,-33.07],[-58.2,-32.47],[-58.2,-33.01],[-58.25,-33.08],[-58.42,-33.11],[-58.55,-33.66],[-58.39,-34.19],[-58.52,-34.3],[-58.47,-34.46],[-58.28,-34.68],[-57.76,-34.89],[-57.3,-35.19],[-57.17,-35.36],[-57.16,-35.51],[-57.35,-35.72],[-57.26,-36.14],[-56.72,-36.39],[-56.67,-36.85],[-57.65,-38.17],[-59.83,-38.84],[-61.6,-39],[-62.34,-38.8],[-62.3,-39.24],[-62.05,-39.37],[-62.39,-40.89],[-63.62,-41.16],[-64.87,-40.74],[-65.13,-40.88],[-64.99,-42.1],[-64.42,-42.43],[-63.79,-42.11],[-63.62,-42.7],[-64.04,-42.88],[-64.49,-42.51],[-64.97,-42.67],[-64.32,-42.97],[-65.25,-43.57],[-65.29,-44.36],[-65.65,-44.66],[-65.64,-45.01],[-66.94,-45.26],[-67.6,-46.05],[-67.51,-46.44],[-66.78,-47.01],[-65.85,-47.16],[-65.77,-47.57],[-66.22,-47.83],[-65.81,-47.94],[-67.47,-48.95],[-67.91,-49.98],[-68.26,-50.1],[-68.67,-49.75],[-68.98,-50],[-68.42,-50.16],[-68.94,-50.38],[-69.36,-51.03],[-69.06,-51.55],[-69.46,-51.58],[-68.96,-51.68],[-68.4,-52.31],[-69.24,-52.21],[-70.8,-52.77],[-70.99,-53.78],[-71.3,-53.88],[-72.41,-53.35],[-71.94,-53.23],[-71.79,-53.48],[-71.23,-52.81],[-72.28,-53.13],[-72.55,-53.46],[-73.05,-53.24],[-72.73,-52.76],[-71.51,-52.61],[-72.71,-52.54],[-73.12,-53.07],[-73.64,-52.84],[-73.12,-52.49],[-74.01,-52.64],[-74.3,-52.12],[-73.83,-52.23],[-72.79,-51.95],[-72.57,-52.2],[-72.72,-52.36],[-72.52,-52.25],[-72.54,-51.71],[-73.17,-51.45],[-72.6,-51.8],[-73.52,-52.04],[-74.19,-51.68],[-73.93,-51.62],[-73.94,-51.27],[-74.81,-51.06],[-75.09,-50.68],[-74.68,-50.66],[-74.64,-50.36],[-73.81,-50.94],[-73.65,-50.49],[-73.98,-50.83],[-74.2,-50.61],[-73.95,-50.51],[-74.63,-50.19],[-73.96,-49.99],[-74.29,-49.6],[-73.83,-49.61],[-74.09,-49.43],[-73.94,-49.02],[-74.22,-49.5],[-74.37,-49.4],[-74.34,-48.6],[-74.01,-48.48],[-74.48,-48.46],[-74.58,-48],[-73.39,-48.15],[-73.72,-47.66],[-74.23,-47.97],[-74.66,-47.7],[-74.13,-47.59],[-74.48,-47.43],[-74.16,-47.18],[-74.31,-46.79],[-75,-46.74],[-75.02,-46.51],[-75.54,-46.7],[-75.43,-46.93],[-75.71,-46.77],[-74.93,-46.16],[-75.07,-45.88],[-74.16,-45.77],[-73.96,-45.4],[-74.02,-46.06],[-74.39,-46.22],[-73.97,-46.15],[-73.73,-45.81],[-73.85,-46.57],[-73.59,-45.9],[-73.73,-45.48],[-72.93,-45.45],[-73.45,-45.24],[-72.68,-44.59],[-73.27,-44.17],[-73.08,-43.32],[-72.76,-43.04],[-72.77,-42.26],[-72.41,-42.39],[-72.5,-41.98],[-72.82,-41.91],[-72.32,-41.5],[-73.73,-41.74],[-73.98,-40.97],[-73.23,-39.22],[-73.66,-37.34],[-73.22,-37.17],[-71.99,-34.29],[-72,-34.17],[-71.83,-33.82],[-71.66,-33.65],[-71.64,-33.52],[-71.7,-33.43],[-71.74,-33.09],[-71.59,-32.97],[-71.45,-32.66],[-71.42,-32.39],[-71.51,-32.21],[-71.71,-30.63],[-71.31,-29.65],[-71.52,-28.93],[-70.65,-26.33],[-70.39,-23.57],[-70.59,-23.25],[-70.09,-21.49],[-70.36,-18.4],[-71.53,-17.3],[-75.11,-15.41],[-76.29,-14.13],[-76.23,-13.37],[-76.5,-12.98],[-76.83,-12.35],[-77.15,-12.06],[-77.22,-11.66],[-77.31,-11.53],[-77.63,-11.29],[-77.74,-10.84],[-79.76,-7.07],[-81.14,-6.06],[-80.88,-5.63],[-81.34,-4.67],[-81.23,-4.23],[-79.96,-3.16],[-79.73,-2.58],[-79.84,-2.07],[-79.93,-2.55],[-80.01,-2.35],[-80.29,-2.71],[-80.96,-2.19],[-80.77,-2.08],[-80.9,-1.08],[-80.28,-0.62],[-80.48,-0.37],[-80.05,0.16],[-80.09,0.79],[-78.9,1.21],[-79.03,1.62],[-78.58,1.77],[-78.59,2.36],[-77.81,2.72],[-77.08,3.91],[-77.52,4.21],[-77.29,4.72],[-77.54,5.54],[-77.25,5.78],[-77.47,6.18],[-77.37,6.57],[-78.38,7.9],[-78.42,8.06],[-78.29,8.09],[-78.28,8.25],[-78.14,8.39],[-77.76,8.13],[-78.06,8.4],[-78.1,8.5],[-78.22,8.4],[-78.4,8.51],[-78.37,8.4],[-78.41,8.36],[-78.51,8.63],[-78.95,8.93],[-79.25,9.02],[-79.51,8.97],[-79.69,8.85],[-79.81,8.64],[-79.75,8.6],[-80.12,8.35],[-80.37,8.29],[-80.46,8.21],[-80.46,8.08],[-80.07,7.67],[-80.01,7.5],[-80.84,7.22],[-81.06,7.9],[-81.27,7.63],[-82.23,8.31],[-82.78,8.3],[-82.88,8.07],[-83.29,8.67],[-83.47,8.71],[-83.29,8.41],[-83.61,8.48],[-83.74,9.15],[-84.58,9.57],[-85.02,10.12],[-85.26,10.26],[-84.89,9.82],[-85.11,9.58],[-85.63,9.9],[-85.85,10.29],[-85.67,10.74],[-85.91,10.9],[-85.74,11.09],[-87.67,12.9],[-87.34,12.95],[-87.49,13.35],[-88.69,13.28],[-88.51,13.18],[-91.38,13.99],[-93.92,16.05],[-94.86,16.42],[-95.02,16.28],[-94.8,16.21],[-96.21,15.69],[-97.75,15.97],[-100.85,17.2],[-101.92,17.96],[-103.44,18.33],[-103.91,18.83],[-104.94,19.31],[-105.67,20.38],[-105.26,20.58],[-105.51,20.81],[-105.21,21.49],[-105.65,21.99],[-105.79,22.63],[-107.77,24.47],[-107.51,24.49],[-107.95,24.62],[-108.28,25.08],[-108.05,25.07],[-109.03,25.48],[-108.88,25.73],[-109.31,25.63],[-109.42,26.03],[-109.12,26.25],[-109.28,26.53],[-110.38,27.23],[-110.53,27.86],[-111.12,27.97],[-112.16,29.02],[-113.06,30.65],[-113.05,31.18],[-114.93,31.9],[-114.55,30.02],[-112.87,28.42],[-112.73,27.83],[-111.86,26.68],[-111.7,26.58],[-111.79,26.88],[-111.57,26.71],[-110.69,24.87],[-110.66,24.34],[-110.37,24.1],[-110.26,24.34],[-109.42,23.48],[-109.5,23.16],[-110,22.89],[-110.36,23.61],[-112.07,24.84],[-112.38,26.21],[-113.02,26.58],[-113.15,26.95],[-113.6,26.72],[-114.99,27.74],[-114.3,27.87],[-114.07,27.68],[-114.27,27.93],[-114.05,28.43],[-115.67,29.76],[-117.27,32.81],[-117.32,33.1],[-117.47,33.3],[-118.08,33.72],[-118.41,33.74],[-118.39,33.86],[-118.51,34.02],[-118.83,34.02],[-119.14,34.11],[-119.41,34.34],[-119.61,34.42],[-119.71,34.4],[-120.65,34.58],[-120.63,35.08],[-121.46,35.93],[-121.88,36.33],[-121.92,36.57],[-121.79,36.73],[-121.81,36.85],[-121.88,36.94],[-122.17,36.99],[-122.4,37.21],[-122.51,37.77],[-122.39,37.79],[-122.37,37.66],[-122.07,37.48],[-122.39,37.96],[-122.22,38.04],[-121.52,38.06],[-122.03,38.12],[-122.15,38.07],[-122.39,38.14],[-122.48,38.11],[-122.47,37.84],[-122.52,37.83],[-122.93,38.06],[-123,37.99],[-122.98,38.23],[-122.88,38.12],[-122.99,38.28],[-123.7,38.91],[-123.83,39.78],[-124.33,40.25],[-124.07,41.46],[-124.54,42.81],[-124.15,43.69],[-123.99,46.22],[-123.22,46.15],[-124.07,46.28],[-123.89,46.66],[-124.11,46.86],[-123.84,46.96],[-124.14,46.95],[-124.71,48.38],[-123.3,48.12],[-123.12,48.15],[-122.98,48.07],[-122.78,48.14],[-122.66,47.88],[-122.78,47.74],[-122.82,47.79],[-123.05,47.55],[-123.14,47.36],[-122.92,47.41],[-123.07,47.4],[-123.06,47.45],[-122.59,47.86],[-122.59,47.93],[-122.53,47.92],[-122.53,47.77],[-122.62,47.71],[-122.61,47.62],[-122.68,47.61],[-122.56,47.46],[-122.58,47.29],[-122.71,47.32],[-122.77,47.22],[-122.83,47.34],[-123.03,47.14],[-122.7,47.11],[-122.54,47.28],[-122.35,47.37],[-122.4,47.78],[-122.24,48.01],[-122.42,48.18],[-122.4,48.08],[-122.52,48.16],[-122.52,48.23],[-122.41,48.29],[-122.67,48.46],[-122.5,48.51],[-122.54,48.76],[-122.69,48.79],[-122.83,49.03],[-122.96,49.07],[-123.08,48.98],[-123.23,49.26],[-122.88,49.4],[-123.28,49.34],[-123.19,49.68],[-123.53,49.4],[-124.03,49.6],[-123.58,49.68],[-123.88,49.74],[-123.83,50.15],[-124.28,49.77],[-124.78,50.02],[-125.06,50.42],[-124.86,50.87],[-125.06,50.51],[-126.09,50.5],[-126.45,50.59],[-125.91,50.7],[-126.51,50.68],[-126.52,51.06],[-127.06,50.87],[-127.71,51.15],[-127.42,51.61],[-126.69,51.7],[-127.64,51.48],[-127.85,51.67],[-127.8,52.19],[-127.44,52.36],[-126.71,52.06],[-127.19,52.46],[-127.01,52.84],[-128.1,51.79],[-128.36,52.16],[-127.94,52.55],[-128.27,52.36],[-128.05,52.91],[-128.36,52.83],[-129.17,53.53],[-128.85,53.7],[-127.93,53.28],[-128.67,53.55],[-128.76,53.75],[-128.71,53.81],[-128.53,53.86],[-128.7,53.92],[-128.89,53.83],[-128.96,53.84],[-129.21,53.64],[-129.26,53.42],[-129.46,53.35],[-129.56,53.25],[-129.82,53.41],[-129.91,53.55],[-130.07,53.58],[-130.34,53.72],[-130.09,53.98],[-130.04,54.13],[-129.63,54.23],[-130.08,54.18],[-130.29,54.27],[-130.43,54.42],[-130.35,54.66],[-130.22,54.73],[-129.89,55.16],[-129.56,55.46],[-129.79,55.56],[-130.05,55.06],[-130.02,55.89],[-130.04,55.3],[-130.54,54.75],[-131.05,55.16],[-130.75,55.32],[-131.03,56.09],[-132.12,55.57],[-132.21,55.75],[-131.55,56.21],[-132.18,56.42],[-132.82,57.06],[-133.47,57.17],[-133.44,57.34],[-133.54,57.55],[-133.65,57.64],[-133.55,57.7],[-133.12,57.57],[-133.52,57.78],[-133.54,57.83],[-133.51,57.88],[-133.19,57.88],[-133.56,57.92],[-133.66,57.84],[-133.72,57.84],[-134.03,58.07],[-134.05,58.29],[-133.88,58.52],[-134.21,58.23],[-134.78,58.45],[-134.94,58.65],[-134.99,58.77],[-135.13,58.84],[-135.33,59.24],[-135.36,59.42],[-135.41,59.32],[-135.48,59.31],[-135.4,59.21],[-135.5,59.2],[-135.39,59.09],[-135.06,58.34],[-135.06,58.28],[-135.14,58.23],[-135.3,58.26],[-135.45,58.38],[-135.57,58.41],[-135.9,58.4],[-135.86,58.58],[-136.04,58.82],[-135.83,58.9],[-136.02,58.87],[-136.15,59.05],[-136.12,58.82],[-136.23,58.77],[-136.45,58.85],[-136.57,58.94],[-136.99,59.04],[-137.06,58.87],[-136.06,58.45],[-136.61,58.24],[-139.77,59.53],[-139.51,59.95],[-139.29,59.61],[-138.99,59.84],[-139.43,60.01],[-140.42,59.71],[-141.41,59.9],[-141.41,60.12],[-144.15,60.02],[-144.9,60.34],[-144.69,60.67],[-145.25,60.38],[-146.57,60.73],[-146.39,60.81],[-146.63,60.99],[-146.38,61.14],[-147.81,60.89],[-148.01,60.97],[-147.75,61.22],[-148.34,61.06],[-148.56,60.8],[-148.28,60.61],[-148.64,60.49],[-147.96,60.48],[-148.43,59.99],[-149.4,60.11],[-149.6,59.77],[-149.71,59.92],[-150.93,59.25],[-151.74,59.19],[-151.93,59.34],[-151.04,59.77],[-151.85,59.78],[-151.4,60.27],[-151.36,60.72],[-150.44,61.02],[-149.07,60.89],[-150.05,61.17],[-149.33,61.5],[-151.59,60.98],[-152.37,60.34],[-153.02,60.3],[-152.63,60.04],[-153.21,59.84],[-153.05,59.73],[-154.09,59.36],[-154.13,59.12],[-153.33,58.88],[-154.25,58.16],[-158.41,56.44],[-158.55,56.31],[-158.28,56.2],[-159.66,55.63],[-159.77,55.84],[-161.38,55.37],[-161.2,55.54],[-161.52,55.62],[-162.08,55.14],[-162.63,55.25],[-162.67,55],[-163.12,55.06],[-163.34,54.84],[-163.28,55.12],[-161.7,55.91],[-160.29,55.8],[-160.54,56.01],[-160.3,56.31],[-158.67,56.8],[-158.32,57.3],[-157.46,57.51],[-157.7,57.68],[-157.61,58.05],[-157.19,58.19],[-157.52,58.42],[-156.97,58.74],[-156.81,59.13],[-158.19,58.62],[-158.5,58.85],[-158.08,58.98],[-158.81,58.97],[-158.95,58.4],[-159.67,58.91],[-160.36,59.05],[-162.14,58.64],[-161.72,58.79],[-161.64,59.11],[-161.98,59.15],[-161.83,59.59],[-162.42,60.28],[-161.96,60.69],[-162.68,60.27],[-162.57,59.99],[-163.68,59.8],[-165.36,60.54],[-164.8,60.89],[-164.32,60.77],[-164.37,60.59],[-163.42,60.76],[-163.91,60.85],[-163.59,60.9],[-163.75,60.97],[-165.11,60.93],[-164.87,61.11],[-165.27,61.27],[-165.57,61.1],[-165.84,61.54],[-166.15,61.55],[-165.81,61.7],[-166.08,61.8],[-165.61,61.87],[-165.71,62.1],[-165.19,62.47],[-164.76,62.5],[-164.59,62.71],[-164.79,62.62],[-164.8,62.92],[-164.38,63.03],[-164.41,63.22],[-163.29,63.05],[-162.28,63.53],[-161.1,63.56],[-160.78,63.82],[-160.99,64.25],[-161.49,64.43],[-160.86,64.76],[-161.76,64.82],[-162.33,64.61],[-162.71,64.38],[-162.81,64.37],[-162.88,64.52],[-163.2,64.65],[-163.3,64.61],[-163.05,64.52],[-163.14,64.42],[-163.71,64.59],[-164.3,64.58],[-164.69,64.51],[-164.76,64.53],[-164.98,64.45],[-166.14,64.58],[-166.33,64.63],[-166.48,64.73],[-166.48,64.8],[-166.41,64.83],[-166.42,64.93],[-166.55,64.95],[-166.93,65.16],[-166.53,65.15],[-166.45,65.25],[-166.16,65.29],[-167.4,65.42],[-168.09,65.66],[-164.46,66.59],[-163.64,66.57],[-163.89,66.58],[-164.03,66.22],[-163.7,66.08],[-161.04,66.19],[-162.61,66.89],[-162.36,66.95],[-161.59,66.46],[-160.23,66.51],[-161.57,66.59],[-161.86,66.7],[-161.72,67.02],[-163.53,67.1],[-164.12,67.61],[-166.79,68.36],[-166.38,68.43],[-166.21,68.89],[-163.87,69.04],[-161.88,70.33],[-162.08,70.16],[-160.12,70.59],[-159.96,70.57],[-160.11,70.47],[-160.01,70.45],[-160.1,70.33],[-159.91,70.33],[-159.87,70.28],[-159.81,70.5],[-159.39,70.52],[-159.75,70.53],[-159.96,70.63],[-160.08,70.63],[-159.68,70.79],[-159.31,70.88],[-159.19,70.86],[-159.34,70.78],[-159.25,70.75],[-159,70.8],[-157.91,70.86],[-157.32,71.04],[-156.78,71.32],[-156.47,71.41],[-156.4,71.4],[-156.57,71.34],[-156.47,71.29],[-155.65,71.18],[-155.58,71.12],[-155.8,71],[-156.15,70.93],[-155.97,70.84],[-155.58,70.89],[-155.17,71.1],[-154.94,71.08],[-154.67,70.99],[-154.79,70.89],[-154.2,70.8],[-153.92,70.88],[-153.23,70.93],[-152.49,70.88],[-152.23,70.81],[-152.44,70.73]],[[143.18,-11.96],[143.75,-14.35],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.03,-18.27],[146.38,-18.98],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.21,-21.12],[149.71,-22.44],[149.98,-22.55],[150.08,-22.16],[150.54,-22.56],[150.67,-22.42],[150.84,-23.46],[151.83,-24.12],[153.03,-25.87],[153.17,-25.96],[153.08,-26.3],[153.16,-26.98],[153.12,-27.19],[153.38,-27.77],[153.45,-28.05],[153.58,-28.24],[153.6,-28.86],[152.95,-31.43],[152.21,-32.68],[152.14,-32.68],[152.19,-32.72],[152.16,-32.76],[151.81,-32.9],[151.48,-33.35],[151.43,-33.52],[151.29,-33.58],[151.28,-33.93],[151.24,-33.99],[151.12,-34.01],[151.23,-34.03],[150.96,-34.3],[150.78,-34.89],[150.81,-34.99],[150.68,-35.08],[150.71,-35.16],[150.57,-35.21],[150.2,-35.83],[149.93,-37.53],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.45,-39.11],[146.16,-38.87],[146.07,-38.83],[145.94,-38.9],[145.79,-38.67],[145.61,-38.66],[145.4,-38.54],[145.46,-38.42],[145.54,-38.39],[145.48,-38.24],[145.29,-38.24],[145.19,-38.38],[144.96,-38.5],[144.72,-38.34],[144.91,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.67,-38.21],[144.1,-38.46],[143.69,-38.77],[141.93,-38.28],[141.43,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.98,-35.62],[139.29,-35.61],[139.28,-35.38],[138.19,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.02,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.78,-32.58],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.17],[134.23,-32.55],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.01],[123.51,-33.92],[119.85,-33.97],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.51],[115.36,-33.64],[115.61,-33.37],[115.68,-33.19],[115.62,-32.67],[115.71,-32.57],[115.74,-31.89],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.18,-26.18],[113.36,-26.08],[113.58,-26.56],[113.83,-26.5],[113.45,-25.6],[113.72,-26.13],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.96,-21.94],[114.12,-21.83],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.11,-19.99],[121,-19.6],[122.35,-18.11],[122.14,-17.43],[122.33,-17.06],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.88,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.4,-16.3],[124.65,-15.87],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.36,-15.12],[125.18,-14.72],[125.63,-14.26],[125.66,-14.53],[126.02,-14.5],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.18,-14.71],[128.07,-15.33],[128.58,-14.77],[129.64,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.94,-13.5],[130.14,-13.45],[130.26,-13.3],[130.14,-13.15],[130.17,-12.96],[130.32,-12.88],[130.4,-12.69],[130.62,-12.65],[130.62,-12.43],[130.74,-12.43],[130.87,-12.56],[130.87,-12.37],[131.03,-12.34],[131.05,-12.19],[131.22,-12.18],[131.29,-12.07],[131.34,-12.21],[131.44,-12.28],[131.89,-12.23],[132.07,-12.28],[132.25,-12.19],[132.41,-12.3],[132.44,-12.18],[132.58,-12.11],[132.67,-11.65],[132.28,-11.47],[132.13,-11.5],[131.81,-11.27],[131.96,-11.18],[132.16,-11.31],[135.03,-12.19],[135.92,-11.83],[135.71,-12.21],[135.94,-12.15],[136.08,-12.42],[136.54,-11.96],[136.95,-12.35],[136.46,-13.23],[135.93,-13.3],[135.95,-13.93],[135.45,-14.92],[140.04,-17.7],[140.83,-17.41],[141.29,-16.46],[141.63,-15.06],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[142.46,-10.71],[142.78,-11.12],[142.87,-11.82],[143.07,-11.92]],[[-29.95,83.56],[-25.8,83.26],[-32.03,82.98],[-25.12,83.16],[-24.47,82.88],[-21.52,82.6],[-23.12,82.33],[-29.89,82.05],[-25.15,82],[-24.29,81.7],[-22.94,82.03],[-21.13,81.93],[-21.5,81.44],[-23.12,80.78],[-19.63,81.64],[-17.45,81.4],[-15.45,81.84],[-11.42,81.48],[-14.45,80.99],[-14.23,80.87],[-14.5,80.76],[-16.76,80.57],[-15.94,80.43],[-16.49,80.25],[-19.43,80.26],[-20.15,80.01],[-20.07,79.77],[-19.35,79.73],[-19.41,79.35],[-18.99,79.18],[-21.13,78.66],[-20.95,78.55],[-21.73,77.71],[-20.86,77.91],[-19.49,77.72],[-19.29,77.59],[-20.68,77.62],[-20.23,77.37],[-18.44,77.26],[-18.34,76.92],[-22.61,76.68],[-21.49,76.27],[-19.86,76.12],[-19.4,75.49],[-19.52,75.18],[-22.23,75.12],[-20.99,75.07],[-20.78,74.89],[-21.04,74.65],[-20.86,74.64],[-19.99,74.98],[-19.27,74.34],[-21.13,74.11],[-21.95,74.24],[-21.76,74.48],[-21.98,74.57],[-22.33,74.29],[-22.13,73.99],[-20.37,73.85],[-20.64,73.46],[-22.35,73.27],[-24.16,73.77],[-24.68,73.6],[-25.52,73.85],[-24.78,73.54],[-26.06,73.25],[-27.27,73.44],[-26.54,73.25],[-27.56,73.14],[-24.13,73.41],[-22.04,72.92],[-22.29,72.12],[-24.07,72.5],[-24.63,73.04],[-26.66,72.72],[-24.81,72.9],[-24.7,72.51],[-25.2,72.39],[-21.96,71.74],[-22.48,71.38],[-21.75,71.48],[-21.52,70.53],[-22.38,70.46],[-22.44,70.86],[-22.69,70.44],[-23.33,70.45],[-23.97,70.65],[-24.56,71.22],[-27.09,71.63],[-25.84,71.48],[-25.67,71.27],[-26.72,70.95],[-28.4,70.99],[-27.98,70.84],[-29.07,70.44],[-26.51,70.4],[-27.63,70.03],[-27.38,69.99],[-25.53,70.35],[-22.21,70.11],[-23.87,69.74],[-23.74,69.59],[-24.3,69.58],[-26.48,68.68],[-30.98,68.06],[-32.33,68.44],[-32.16,67.99],[-33.16,67.63],[-34.63,66.43],[-35.19,66.25],[-35.87,66.44],[-35.63,66.14],[-37.76,65.59],[-38,65.71],[-37.28,66.3],[-38.15,66.39],[-37.75,66.26],[-38.14,65.9],[-38.52,66.01],[-38.2,65.71],[-40.17,65.56],[-39.58,65.34],[-41.09,65.03],[-40.18,64.48],[-40.78,64.22],[-41.58,64.3],[-40.62,64.13],[-40.55,63.73],[-41.39,63.06],[-42.18,63.21],[-41.64,62.97],[-41.91,62.74],[-42.94,62.72],[-42.15,62.57],[-42.32,62.15],[-42.11,61.86],[-42.59,61.72],[-42.32,61.68],[-43.04,60.52],[-43.92,60.6],[-43.21,60.39],[-43.12,60.06],[-43.95,60.02],[-43.66,59.86],[-43.91,59.81],[-44.41,59.92],[-44.22,60.27],[-44.61,60.02],[-45.38,60.2],[-44.76,60.67],[-45.38,60.44],[-46.05,60.61],[-45.87,61.22],[-46.87,60.82],[-48.18,60.77],[-47.77,61],[-48.39,61.01],[-49.29,61.59],[-49.38,61.89],[-48.83,62.08],[-49.62,62],[-49.55,62.23],[-50.32,62.47],[-49.79,63.05],[-50.39,62.82],[-51.47,63.64],[-51.55,64.01],[-50.26,64.21],[-51.71,64.2],[-50.68,64.68],[-50.01,64.45],[-50.12,64.7],[-50.96,65.2],[-50.72,64.8],[-51.26,64.76],[-51.92,64.22],[-52.54,65.33],[-51.09,65.78],[-52.55,65.46],[-53.2,65.59],[-53.11,65.98],[-53.39,66.05],[-51.23,66.88],[-53.61,66.15],[-53.42,66.65],[-52.39,66.88],[-53.69,66.99],[-53.8,67.42],[-52.51,67.76],[-50.61,67.53],[-51.17,67.69],[-50.97,67.81],[-52.35,67.84],[-53.74,67.55],[-53.15,68.21],[-51.6,68.06],[-51.17,68.39],[-53.38,68.3],[-53.04,68.61],[-51.13,68.6],[-50.8,68.79],[-51.25,68.74],[-51.09,69.13],[-50.3,69.17],[-51.08,69.21],[-50.32,70.03],[-52.26,70.06],[-54.53,70.7],[-52.8,70.75],[-50.68,70.4],[-51.77,71.01],[-51.02,71],[-53.12,71.31],[-51.78,71.68],[-53.44,71.58],[-53.15,71.81],[-53.81,72.29],[-53.65,72.36],[-53.93,72.32],[-53.48,71.85],[-54.02,71.66],[-53.96,71.46],[-55.59,71.55],[-55.32,72.11],[-54.84,72.38],[-55.58,72.18],[-55.29,72.35],[-55.6,72.45],[-54.92,72.57],[-54.74,72.87],[-55.67,73.01],[-55.29,73.33],[-56.1,73.56],[-55.84,73.76],[-56.23,74.13],[-57.23,74.12],[-56.26,74.53],[-58.57,75.35],[-58.25,75.51],[-58.52,75.69],[-63.29,76.35],[-67.08,76.2],[-66.83,75.97],[-68.32,76.09],[-69.48,76.4],[-68.11,76.65],[-69.89,76.83],[-69.69,76.99],[-70.61,76.82],[-71.16,77.07],[-68.14,77.38],[-66.39,77.28],[-66.27,77.51],[-66.82,77.69],[-69.35,77.47],[-70.56,77.72],[-70.12,77.84],[-71.27,77.81],[-72.82,78.19],[-71.65,78.62],[-65.82,79.17],[-64.79,80],[-64.18,80.1],[-66.84,80.08],[-67.19,80.28],[-64.51,81],[-63.06,80.89],[-63.24,81.08],[-62.99,81.21],[-61.44,81.13],[-61.1,81.4],[-61.2,81.75],[-60.43,81.92],[-56.62,81.36],[-59.27,81.98],[-54.55,82.35],[-53.67,82.16],[-53.56,81.65],[-53.04,81.87],[-53.02,82.32],[-50.9,81.89],[-49.54,81.92],[-50.99,82.46],[-50.04,82.47],[-44.73,81.78],[-44.33,82.47],[-45.56,82.75],[-41.37,82.75],[-46.48,82.95],[-43.01,83.26],[-41.3,83.1],[-40.36,83.33],[-38.15,83],[-37.94,83.16],[-38.75,83.37],[-30.7,83.59]],[[-86.59,71.01],[-84.82,71.03],[-84.7,71.63],[-85.91,71.99],[-85.32,72.23],[-84.28,72.04],[-85.65,72.72],[-85.26,72.95],[-84.26,72.8],[-85.46,73.11],[-83.41,73.63],[-81.6,73.7],[-80.28,72.77],[-81.23,72.31],[-80.61,72.45],[-80.95,71.92],[-79.88,72.18],[-80.11,72.33],[-79.83,72.45],[-79,72.27],[-79.01,72.04],[-78.58,71.88],[-78.86,72.1],[-78.7,72.35],[-77.52,72.18],[-78.42,72.57],[-77.25,72.74],[-75.07,72.32],[-75.92,71.72],[-75.15,72.06],[-74.27,72.04],[-74.32,71.84],[-75.21,71.71],[-74.7,71.68],[-75,71.22],[-74.49,71.65],[-73.87,71.77],[-73.71,71.72],[-74.2,71.4],[-73.71,71.59],[-73.18,71.28],[-73.28,71.54],[-72.9,71.68],[-71.64,71.52],[-71.19,71.28],[-72.63,70.83],[-70.67,71.05],[-70.76,70.79],[-71.89,70.43],[-71.28,70.5],[-71.43,70.13],[-70.98,70.58],[-70.08,70.83],[-68.5,70.61],[-68.48,70.41],[-70.06,70.04],[-68.78,70.2],[-69.01,69.98],[-68.74,69.94],[-67.86,70.28],[-67.19,69.76],[-69.25,69.51],[-66.68,69.26],[-69.04,69.1],[-67.75,69.04],[-67.88,68.78],[-69.32,68.86],[-66.71,68.45],[-67.03,68.33],[-66.92,68.07],[-66.21,68.28],[-66.53,67.85],[-65.94,68.07],[-65.51,67.97],[-65.4,67.68],[-65.41,67.88],[-64.98,68.04],[-65.02,67.79],[-63.85,67.57],[-64.59,67.32],[-63.04,67.23],[-63.7,66.82],[-62.12,67.05],[-61.3,66.65],[-62.12,66.64],[-61.58,66.41],[-61.86,66.31],[-62.55,66.41],[-61.99,66.03],[-62.59,66.03],[-62.38,65.83],[-62.66,65.64],[-63.46,65.85],[-63.65,65.66],[-63.34,65.62],[-63.36,65.23],[-63.61,64.93],[-64.35,65.17],[-64.27,65.4],[-64.55,65.12],[-65.4,65.76],[-64.45,66.32],[-65.82,66],[-65.66,66.2],[-66.06,66.13],[-66.99,66.63],[-67.31,66.57],[-67.23,66.31],[-67.88,66.47],[-67.18,66.03],[-67.35,65.93],[-68.75,66.2],[-68.22,66.08],[-67.87,65.77],[-67.94,65.56],[-67.12,65.44],[-67.34,65.35],[-66.7,64.82],[-66.63,65],[-66.21,64.72],[-65.94,64.89],[-65.43,64.73],[-65.27,64.63],[-65.53,64.51],[-65.08,64.44],[-65.58,64.29],[-64.68,64.03],[-64.8,63.92],[-64.41,63.71],[-64.67,63.24],[-65.19,63.76],[-64.67,62.92],[-65.16,62.93],[-65.11,62.63],[-66.66,63.26],[-66.72,63.08],[-67.89,63.73],[-67.72,63.42],[-68.91,63.7],[-65.98,62.21],[-66.33,61.87],[-71.35,63.07],[-71.99,63.42],[-71.38,63.58],[-72.5,63.82],[-73.45,64.4],[-73.27,64.58],[-74.07,64.43],[-74.68,64.83],[-74.92,64.77],[-74.7,64.5],[-76.86,64.24],[-78.17,64.62],[-78.05,64.98],[-77.36,65.2],[-77.33,65.45],[-75.83,65.23],[-75.45,64.84],[-75.36,65.01],[-75.8,65.3],[-73.55,65.48],[-74.42,66.17],[-72.22,67.26],[-73.28,68.36],[-73.82,68.36],[-73.85,68.7],[-74.42,68.58],[-74.91,68.82],[-74.85,69.07],[-76.59,68.7],[-76.56,69.01],[-75.65,69.21],[-76.52,69.52],[-76.23,69.66],[-77.09,69.64],[-76.86,69.78],[-77.59,69.85],[-77.77,70.24],[-79.07,70.6],[-79.4,70.4],[-78.81,70.18],[-79.09,69.93],[-81.65,70.1],[-80.92,69.73],[-81.56,69.94],[-85.78,70.04],[-86.32,70.15],[-86.4,70.47],[-87.9,70.25],[-88.85,70.52],[-89.46,71.06],[-87.14,71.01],[-89.69,71.42],[-90.02,71.95],[-89.66,72.17],[-89.82,72.47],[-88.71,73.4],[-86.77,73.83],[-85.01,73.78],[-86.67,72.76],[-86.32,72.46],[-86.22,71.9],[-85.02,71.35],[-86.47,71.04]],[[-69.49,83.02],[-66.42,82.93],[-68.47,82.65],[-64.9,82.9],[-63.5,82.79],[-63.64,82.71],[-63.09,82.56],[-63.25,82.45],[-61.21,82.34],[-68.69,81.29],[-64.78,81.49],[-69.55,80.38],[-70.71,80.54],[-70.26,80.23],[-72.06,80.12],[-70.56,80.07],[-71.39,79.76],[-74.39,79.87],[-74.66,79.84],[-73.2,79.6],[-76.9,79.51],[-74.48,79.23],[-74.53,79.05],[-78.58,79.08],[-74.43,78.72],[-76.42,78.51],[-75.19,78.33],[-75.97,77.99],[-78.01,77.95],[-78.08,77.52],[-78.49,77.37],[-81.66,77.53],[-81.28,77.37],[-82.06,77.3],[-79.5,77.2],[-79.22,76.94],[-78,76.85],[-78.28,76.57],[-80.8,76.17],[-80.97,76.47],[-82.53,76.72],[-82.23,76.47],[-83.89,76.45],[-84.22,76.67],[-84.28,76.36],[-86.45,76.58],[-86.68,76.38],[-87.49,76.59],[-87.5,76.39],[-88.4,76.41],[-88.49,76.77],[-88.54,76.42],[-89.57,76.49],[-89.5,76.83],[-88.56,77.07],[-86.81,77.19],[-87.68,77.44],[-88.02,77.78],[-86.76,77.86],[-84.49,77.37],[-83.61,77.44],[-82.59,77.99],[-83.78,77.53],[-84.86,77.5],[-85.29,77.56],[-85.55,77.93],[-84.22,78.18],[-84.91,78.24],[-84.78,78.53],[-85.59,78.11],[-86.22,78.08],[-85.92,78.34],[-87.55,78.18],[-86.81,78.77],[-81.75,78.98],[-84.41,79],[-84.57,79.07],[-83.58,79.05],[-86.42,79.84],[-86.5,80.26],[-83.72,80.23],[-80.48,79.61],[-80.12,79.67],[-81.01,79.69],[-82.99,80.32],[-76.86,80.87],[-78.72,80.95],[-76.88,81.43],[-81.01,80.66],[-85.15,80.52],[-86.62,80.63],[-83.29,81.15],[-85.78,81.04],[-87.71,80.66],[-89.26,80.91],[-84.94,81.29],[-89.62,81.03],[-89.98,81.12],[-89.21,81.25],[-89.68,81.33],[-89.43,81.39],[-87.6,81.53],[-90.31,81.4],[-90.61,81.43],[-89.82,81.63],[-91.68,81.64],[-88.06,82.1],[-85.05,81.98],[-86.62,82.22],[-84.9,82.45],[-79.43,81.85],[-82.45,82.39],[-81.68,82.52],[-82.12,82.63],[-80.81,82.59],[-81.18,82.75],[-81.01,82.78],[-78.75,82.68],[-80.16,82.91],[-79.89,82.94],[-77.48,82.88],[-76.01,82.54],[-75.57,82.61],[-77.13,83.01],[-74.41,83.01],[-72.66,82.72],[-73.44,82.95],[-69.57,83.02]],[[133.47,-0.73],[134.11,-0.85],[134.19,-2.31],[134.46,-2.83],[134.63,-2.54],[135.09,-3.35],[135.49,-3.34],[136.39,-2.27],[137.07,-2.11],[137.12,-1.84],[137.91,-1.48],[139.79,-2.35],[144.48,-3.83],[145.77,-4.82],[145.75,-5.4],[147.42,-5.97],[147.8,-6.31],[147.81,-6.7],[146.95,-6.88],[147.26,-7.46],[148.13,-8.1],[148.58,-9.05],[149.2,-9.03],[149.26,-9.5],[150.01,-9.69],[149.76,-9.81],[149.87,-10.01],[150.85,-10.24],[150.45,-10.31],[150.65,-10.52],[150.32,-10.65],[149.75,-10.35],[147.77,-10.07],[146.03,-8.08],[144.51,-7.57],[144.14,-7.76],[143.65,-7.46],[143.94,-7.95],[143.52,-8],[143.61,-8.2],[142.21,-8.2],[143.38,-8.76],[142.65,-9.33],[141.13,-9.22],[140,-8.2],[140.12,-7.92],[139.38,-8.19],[139.25,-7.98],[138.93,-8.26],[139.09,-7.59],[138.75,-7.25],[139.18,-7.19],[138.6,-6.94],[138.87,-6.86],[138.44,-6.34],[138.34,-5.68],[138.09,-5.71],[137.28,-4.95],[135.19,-4.45],[134.68,-4.08],[134.89,-3.94],[133.97,-3.82],[133.68,-3.48],[133.84,-3.05],[133.4,-3.9],[132.97,-4.09],[132.75,-3.29],[131.97,-2.79],[132.72,-2.79],[133.19,-2.44],[133.7,-2.62],[133.92,-2.1],[132.31,-2.24],[131.93,-1.56],[131,-1.42],[131.26,-0.86],[132.39,-0.36],[133.27,-0.64]],[[116.81,6.69],[117.23,6.94],[117.69,6.35],[117.5,5.88],[118,6.05],[117.97,5.71],[118.35,5.81],[119.26,5.37],[119.13,5.1],[118.26,4.99],[118.55,4.38],[117.5,4.13],[117.78,3.69],[117.06,3.62],[118.06,2.32],[117.79,2.03],[118.99,0.98],[118.53,0.81],[117.91,1.1],[117.52,0.24],[117.56,-0.77],[116.91,-1.22],[116.74,-1.04],[116.75,-1.33],[116.28,-1.79],[116.55,-2.41],[115.96,-3.59],[114.7,-4.17],[114.34,-3.24],[113.71,-3.46],[113.04,-2.93],[112.76,-3.32],[111.86,-3.55],[111.7,-2.89],[110.26,-2.97],[109.98,-1.28],[109.29,-0.85],[109.13,-0.45],[109.26,0.03],[108.91,0.79],[109.08,1.5],[109.63,2.03],[111.22,1.4],[111.04,1.63],[111.51,2.74],[112.99,3.16],[114.01,4.57],[114.99,5.02],[115.43,4.97],[115.42,5.41],[115.88,5.61],[116.78,6.99],[116.84,6.77]],[[-114.52,72.59],[-113.58,72.65],[-113.08,73],[-111.27,72.71],[-111.89,72.36],[-111.67,72.3],[-110.21,72.66],[-110.66,73.01],[-110.01,72.98],[-108.76,72.55],[-108.19,71.72],[-107.81,71.63],[-107.3,71.9],[-107.7,72.15],[-108.24,73.15],[-107.93,73.22],[-108.03,73.35],[-106.48,73.2],[-105.41,72.79],[-104.38,71.58],[-104.51,71.06],[-103.59,70.63],[-101.09,70.14],[-100.91,69.81],[-102.24,69.84],[-102.62,69.55],[-103.43,69.67],[-103.05,69.47],[-103.12,69.2],[-102.15,69.49],[-101.79,69.18],[-102.89,68.82],[-105.1,68.92],[-105.02,69.08],[-106.14,69.16],[-106.66,69.44],[-107.44,69],[-109.47,68.68],[-113.02,68.48],[-113.55,68.77],[-113.69,69.19],[-116.51,69.43],[-117.19,70.05],[-111.63,70.31],[-113.76,70.69],[-117.59,70.63],[-118.38,70.97],[-115.3,71.49],[-117.94,71.39],[-118.23,71.47],[-117.74,71.66],[-118.99,71.76],[-118.94,71.99],[-118.21,72.26],[-118.37,72.53],[-116.57,73.06],[-114.21,73.3],[-114.08,72.91],[-114.5,72.63]],[[49.54,-12.43],[49.94,-13.07],[50.41,-15.63],[50.19,-15.96],[49.89,-15.46],[49.66,-15.52],[49.84,-16.49],[49.45,-17.24],[49.36,-18.34],[47.18,-24.79],[46.73,-25.15],[45.11,-25.54],[44.03,-25],[43.26,-22.38],[43.5,-21.36],[44.4,-19.92],[43.98,-17.39],[44.48,-16.22],[46.16,-15.74],[46.4,-15.93],[46.47,-15.51],[46.94,-15.22],[47.1,-15.43],[47.35,-14.77],[47.48,-15.01],[47.97,-14.67],[47.77,-14.37],[47.94,-13.66],[48.26,-13.72],[48.8,-13.27],[48.79,-12.47],[49.21,-12.08],[49.48,-12.35]],[[96.49,5.23],[97.55,5.21],[98.31,4.09],[99.73,3.18],[100.31,2.47],[100.53,2.19],[100.82,1.99],[100.89,1.95],[100.83,2.24],[100.94,2.29],[101.05,2.26],[101.3,2.01],[101.48,1.69],[101.79,1.62],[102.39,0.84],[102.57,0.75],[102.85,0.72],[103.03,0.58],[103.07,0.49],[102.79,0.3],[102.55,0.22],[102.78,0.24],[103.34,0.51],[103.48,0.48],[103.67,0.29],[103.79,0.05],[103.43,-0.19],[103.53,-0.75],[104.38,-1.07],[104.51,-1.82],[104.85,-2.09],[104.65,-2.59],[105.4,-2.38],[106.04,-3.11],[105.89,-5.01],[105.82,-5.68],[105.75,-5.82],[105.62,-5.8],[105.52,-5.67],[104.64,-5.52],[104.6,-5.91],[101.58,-3.17],[100.89,-2.25],[100.31,-0.83],[99.16,0.35],[98.6,1.87],[97.7,2.36],[96.97,3.58],[95.58,4.66],[95.23,5.56],[96.25,5.27]],[[-3.11,58.52],[-3.99,57.96],[-3.86,57.82],[-4.13,57.58],[-1.96,57.68],[-1.78,57.47],[-2.09,57.1],[-2.26,56.86],[-2.59,56.56],[-3.31,56.36],[-2.89,56.4],[-2.65,56.32],[-2.67,56.25],[-2.98,56.19],[-3.36,56.03],[-3.79,56.09],[-3.61,56.02],[-3.05,55.95],[-2.84,56.03],[-2.6,56.03],[-2.15,55.9],[-1.65,55.57],[-1.23,54.7],[-0.08,54.12],[0.12,53.61],[-0.66,53.72],[0.13,53.47],[0.35,53.16],[0.21,53.03],[0.05,52.91],[0.33,52.81],[0.52,52.94],[1.66,52.75],[1.75,52.47],[1.32,51.96],[1.23,51.97],[1.28,51.84],[1.19,51.8],[0.96,51.81],[0.75,51.73],[0.9,51.69],[0.89,51.57],[0.42,51.47],[0.53,51.49],[0.69,51.39],[0.89,51.36],[1.42,51.36],[1.4,51.18],[1.05,51.05],[0.96,50.93],[0.77,50.93],[0.2,50.76],[-0.2,50.82],[-0.79,50.76],[-1.42,50.9],[-1.33,50.82],[-1.52,50.75],[-3,50.72],[-3.4,50.63],[-3.68,50.24],[-3.79,50.23],[-4.2,50.39],[-4.73,50.29],[-5.01,50.16],[-5.12,50.04],[-5.23,50.02],[-5.43,50.11],[-5.62,50.05],[-5.66,50.13],[-5.34,50.25],[-4.89,50.53],[-4.58,50.78],[-4.52,50.98],[-4.3,51.03],[-4.19,51.19],[-3.84,51.23],[-3.26,51.19],[-3.04,51.25],[-2.43,51.74],[-3.29,51.39],[-3.56,51.41],[-3.89,51.59],[-4.24,51.57],[-4.09,51.66],[-4.39,51.74],[-4.6,51.74],[-4.9,51.63],[-5.12,51.71],[-5.2,51.86],[-5.26,51.88],[-5.09,52],[-4.38,52.2],[-4.15,52.33],[-4.1,52.92],[-4.68,52.84],[-3.81,53.3],[-3.32,53.35],[-3.1,53.26],[-3.17,53.39],[-3.07,53.43],[-2.92,53.3],[-2.75,53.31],[-2.91,53.35],[-3.07,53.51],[-2.93,53.73],[-3.03,53.77],[-3.03,53.91],[-2.9,53.96],[-2.87,54.18],[-3.17,54.13],[-3.57,54.47],[-3.59,54.56],[-3.47,54.77],[-3.27,54.91],[-3.04,54.95],[-3.55,54.95],[-3.96,54.78],[-4.3,54.84],[-4.91,54.69],[-5.17,54.92],[-4.68,55.5],[-4.73,55.6],[-4.87,55.87],[-4.58,55.94],[-4.67,55.97],[-4.8,56.16],[-5.23,55.89],[-5.09,56.2],[-5.77,55.36],[-5.19,56.76],[-5.65,56.53],[-6.13,56.71],[-5.59,57.1],[-5.82,57.44],[-5.58,57.55],[-5.69,57.78],[-5.16,57.88],[-5.41,58.07],[-5.01,58.26],[-4.98,58.58],[-3.06,58.59]],[[141.23,41.37],[141.45,41.4],[141.43,40.72],[141.8,40.29],[141.98,39.43],[141.47,38.4],[140.96,38.15],[141,37.11],[140.79,36.85],[140.63,36.5],[140.57,36.23],[140.62,36.06],[140.87,35.72],[140.64,35.66],[140.46,35.51],[140.36,35.18],[140.06,35.04],[139.92,34.9],[139.8,34.96],[139.84,35.01],[139.83,35.3],[140.1,35.59],[139.99,35.67],[139.83,35.66],[139.77,35.49],[139.65,35.41],[139.74,35.25],[139.68,35.15],[139.47,35.3],[139.25,35.28],[139.13,35.15],[139.09,34.84],[138.98,34.7],[138.84,34.62],[138.76,34.7],[138.8,34.97],[138.9,35.02],[138.72,35.12],[138.58,35.09],[138.35,34.85],[138.19,34.6],[137.06,34.58],[137.3,34.73],[137.1,34.76],[136.96,34.84],[136.94,34.72],[136.87,34.73],[136.85,34.98],[136.9,35.03],[136.8,35.05],[136.69,34.98],[136.53,34.68],[136.88,34.43],[136.85,34.32],[136.33,34.18],[135.92,33.56],[135.69,33.49],[135.45,33.55],[135.13,34.01],[135.1,34.29],[135.31,34.42],[135.42,34.62],[135.04,34.63],[134.74,34.77],[134.25,34.71],[133.97,34.53],[132.31,34.32],[132.14,33.84],[131.74,34.05],[130.92,33.98],[131,34.39],[131.35,34.41],[132.75,35.45],[134.21,35.54],[134.46,35.63],[135.18,35.75],[135.27,35.72],[135.23,35.59],[135.27,35.55],[135.68,35.5],[136.01,35.68],[136.09,35.77],[136.01,35.99],[136.07,36.12],[136.7,36.74],[136.84,37.38],[137.32,37.52],[136.9,37.12],[137.3,36.75],[138.32,37.22],[139.36,38.1],[140.04,39.41],[140,39.86],[139.74,39.92],[140.01,40.26],[139.92,40.6],[140.39,41.23],[140.75,40.83],[141.12,40.88],[141.25,41.21],[140.8,41.25],[140.94,41.5],[141.11,41.46]],[[-119.74,74.11],[-117.51,74.23],[-115.39,73.5],[-118.96,72.68],[-120.18,72.21],[-120.62,71.51],[-122.84,71.1],[-124.01,71.68],[-125.84,71.98],[-124.99,72.59],[-124.97,72.84],[-124.57,72.94],[-124.8,73.13],[-123.8,73.77],[-124.7,74.35],[-121.5,74.54],[-119.56,74.23],[-119.74,74.13]],[[-91.89,81.13],[-90.64,80.59],[-89.24,80.51],[-88.86,80.17],[-88.2,80.11],[-88.61,80.26],[-88.52,80.42],[-87.67,80.37],[-87.92,80.1],[-86.98,79.89],[-87.3,79.58],[-85.65,79.61],[-85.04,79.28],[-87.62,78.68],[-87.92,78.75],[-87.83,79.05],[-88.04,79],[-88.25,78.67],[-87.98,78.54],[-88.74,78.58],[-88.79,78.19],[-90.04,78.61],[-89.49,78.17],[-91.41,78.19],[-92.85,78.46],[-91.87,78.54],[-93.27,78.61],[-93.64,78.75],[-93.16,78.78],[-94.17,78.97],[-91.3,79.37],[-95.1,79.29],[-95.73,79.42],[-94.4,79.74],[-95.86,79.67],[-96.77,80.14],[-94.26,80.2],[-96.39,80.32],[-95.55,80.37],[-96.15,80.55],[-95.93,80.72],[-93.93,80.56],[-95.51,80.84],[-95.27,81],[-93.24,81.13],[-94.18,81.34],[-92,81.18]],[[-15.54,66.23],[-14.6,66.38],[-15.11,66.1],[-14.7,66.02],[-14.83,65.76],[-14.39,65.79],[-14.47,65.57],[-13.62,65.52],[-13.8,65.35],[-13.57,65.07],[-14.63,64.42],[-18.08,63.5],[-20.49,63.69],[-20.41,63.81],[-20.65,63.74],[-21.14,63.89],[-21.09,63.93],[-21.15,63.94],[-21.45,63.86],[-22.65,63.83],[-22.69,63.87],[-22.74,64.02],[-22.7,64.08],[-22.51,63.99],[-22.06,64.07],[-21.67,64.35],[-21.46,64.38],[-21.65,64.4],[-22.05,64.31],[-21.9,64.39],[-22,64.41],[-21.95,64.52],[-21.59,64.63],[-22.16,64.54],[-22.33,64.63],[-22.25,64.73],[-22.47,64.8],[-24.02,64.86],[-23.32,64.96],[-22.79,65.05],[-21.89,65.05],[-21.8,65.11],[-21.78,65.19],[-22.04,65.13],[-22.51,65.2],[-21.84,65.45],[-22.31,65.48],[-22.64,65.57],[-24.47,65.52],[-23.86,65.54],[-24.09,65.78],[-23.29,65.75],[-23.83,65.85],[-23.52,65.88],[-23.78,66.02],[-23.45,66.18],[-22.44,65.91],[-22.95,66.21],[-22.48,66.27],[-23.12,66.34],[-22.89,66.44],[-21.41,66.03],[-21.38,65.74],[-21.66,65.72],[-21.36,65.58],[-21.43,65.47],[-21.23,65.42],[-21.13,65.27],[-21.05,65.43],[-20.45,65.57],[-20.21,66.1],[-19.49,65.77],[-19.38,66.08],[-18.84,66.18],[-18.14,65.73],[-18.3,66.16],[-17.55,65.96],[-16.49,66.2],[-16.54,66.45],[-16.25,66.52],[-15.65,66.26]],[[-94.29,76.91],[-93.21,76.75],[-93.53,76.45],[-91.31,76.68],[-90.54,76.5],[-91.41,76.46],[-89.29,76.3],[-91.41,76.22],[-89.28,75.79],[-89.65,75.57],[-88.92,75.45],[-88.65,75.66],[-85.95,75.4],[-83.93,75.82],[-82.15,75.83],[-79.66,75.45],[-79.51,75.26],[-80.38,75.03],[-79.4,74.92],[-80.35,74.9],[-80.15,74.8],[-80.28,74.58],[-81.94,74.47],[-82.93,74.57],[-83.52,74.9],[-83.34,74.77],[-83.53,74.59],[-84.43,74.51],[-88.42,74.49],[-88.34,74.78],[-88.53,74.83],[-89.56,74.56],[-90.88,74.82],[-91.51,74.65],[-92.39,75.26],[-92.07,75.66],[-92.18,75.85],[-93.09,76.35],[-95.27,76.26],[-96.04,76.49],[-95.65,76.58],[-96.9,76.75],[-96.4,76.8],[-96.76,76.97],[-95.85,77.07],[-94.61,76.96]],[[173.12,-41.28],[173.95,-40.92],[173.8,-41.27],[174,-40.99],[174.3,-41.02],[174.04,-41.24],[174.37,-41.1],[174.07,-41.43],[174.21,-41.85],[172.53,-43.47],[173.1,-43.84],[172.04,-43.7],[172.18,-43.9],[171.24,-44.26],[170.78,-45.87],[169.69,-46.55],[169.1,-46.63],[168.38,-46.61],[167.54,-46.15],[166.83,-46.23],[166.92,-45.96],[166.49,-45.96],[167,-45.71],[166.73,-45.54],[166.87,-45.31],[167.16,-45.41],[167.03,-45.12],[167.91,-44.67],[168.37,-44.08],[169.18,-43.91],[171.04,-42.86],[172.27,-40.76],[172.94,-40.52],[172.7,-40.67],[173.07,-41.19]],[[16.79,79.91],[17.83,79.8],[17.67,79.39],[18.4,79.61],[18.82,79.43],[18.68,79.26],[20.61,79.11],[20.77,79.06],[20.5,78.98],[21.39,78.74],[19.15,78.38],[16.7,76.58],[14,77.51],[16.91,77.9],[14.09,77.77],[13.68,78.03],[17.17,78.42],[16.45,78.5],[16.78,78.66],[15.42,78.47],[15.38,78.77],[14.69,78.72],[14.43,78.49],[14.64,78.41],[13.15,78.24],[11.37,78.95],[12.4,78.95],[11.98,79.03],[11.98,79.29],[11.21,79.13],[10.68,79.76],[13.69,79.86],[13.92,79.76],[12.56,79.57],[13.96,79.34],[14.59,79.8],[16.34,78.98],[15.83,79.71],[16.25,80.05],[16.52,80.02]],[[67.77,76.24],[61.36,75.32],[59.67,74.61],[58.53,74.5],[58.62,74.23],[57.77,74.01],[57.76,73.77],[57.31,73.84],[57.54,73.66],[56.63,73.31],[54.3,73.35],[53.76,73.77],[55.34,74.42],[56.14,74.5],[55.58,74.63],[56.5,74.96],[55.81,75.12],[57.61,75.34],[58.88,75.86],[60.94,76.07],[61.2,76.28],[64.46,76.38],[67.53,77.01],[68.94,76.71],[68.16,76.28]],[[124.89,1],[124.43,0.47],[123.75,0.31],[120.58,0.53],[120.19,0.27],[120.06,-0.55],[120.67,-1.37],[121.15,-1.34],[121.58,-0.83],[121.97,-0.93],[123.17,-0.57],[123.43,-0.78],[123.38,-1],[122.9,-0.9],[122.25,-1.55],[121.36,-1.88],[122.29,-2.91],[122.25,-3.62],[122.85,-4.07],[122.87,-4.39],[122.12,-4.54],[122.04,-4.83],[121.59,-4.76],[121.62,-4.09],[120.89,-3.52],[121.05,-2.75],[120.65,-2.67],[120.26,-2.95],[120.43,-5.59],[119.56,-5.61],[119.36,-5.32],[119.62,-4.03],[119.47,-3.51],[118.92,-3.48],[118.78,-2.72],[119.32,-1.93],[119.51,-0.91],[119.71,-0.68],[119.84,-0.86],[119.72,-0.09],[120.27,0.97],[120.6,0.85],[121.08,1.33],[122.84,0.85],[123.85,0.84],[125.11,1.69],[125.23,1.5],[124.97,1.08]],[[-55.46,51.54],[-56.03,51.33],[-55.8,51.03],[-56.82,49.61],[-56.18,50.12],[-56.16,49.94],[-55.5,49.98],[-56.14,49.62],[-55.23,49.51],[-55.35,49.08],[-54.5,49.53],[-54.45,49.33],[-53.62,49.32],[-53.57,49.14],[-54.16,48.79],[-53.71,48.66],[-54.11,48.39],[-53.03,48.63],[-53.87,48.02],[-53.64,48.02],[-53.86,47.8],[-53.67,47.65],[-52.86,48.11],[-53.17,47.51],[-52.78,47.77],[-52.65,47.55],[-53.07,46.68],[-53.59,46.64],[-53.6,47.15],[-54.18,46.88],[-53.85,47.44],[-54.19,47.86],[-54.49,47.4],[-55.79,46.87],[-55.92,47.02],[-54.78,47.66],[-55.58,47.46],[-56.13,47.5],[-55.86,47.82],[-56.77,47.57],[-59.26,47.63],[-59.34,47.93],[-58.33,48.52],[-59.17,48.56],[-58.71,48.6],[-58.41,49.08],[-57.99,48.99],[-58.21,49.39],[-57.79,49.49],[-57.93,49.7],[-57.04,51.01],[-56.03,51.57],[-55.45,51.56]],[[-108.29,76.06],[-107.72,76],[-108.02,75.8],[-107.21,75.89],[-106.91,75.68],[-106.68,76.02],[-105.9,76.01],[-105.48,75.7],[-106.09,75.09],[-108.83,75.07],[-112.52,74.42],[-114.38,74.67],[-111.03,75.23],[-113.71,75.07],[-113.85,75.26],[-113.47,75.42],[-114.01,75.43],[-114.52,75.28],[-114.45,75.09],[-115.73,74.97],[-117.6,75.27],[-115.14,75.68],[-117.16,75.65],[-114.99,75.9],[-116.66,75.96],[-116.21,76.19],[-114.78,76.17],[-115.83,76.3],[-115,76.5],[-112.7,76.2],[-111.05,75.55],[-109.09,75.51],[-108.92,75.67],[-109.87,75.93],[-109.43,76.11],[-110.31,76.4],[-108.83,76.82],[-108.47,76.74],[-108.63,76.59],[-108.12,76.23],[-108.39,76.07]],[[173.27,-34.93],[174.37,-35.33],[174.54,-35.58],[174.51,-35.67],[174.58,-35.79],[174.39,-35.8],[174.8,-36.31],[174.75,-36.49],[174.82,-36.61],[174.72,-36.84],[174.89,-36.91],[174.95,-36.85],[175.3,-36.99],[175.38,-37.21],[175.54,-37.2],[175.49,-36.69],[175.38,-36.56],[175.46,-36.48],[175.68,-36.75],[175.77,-36.73],[175.99,-37.44],[176.12,-37.54],[176.13,-37.59],[176.03,-37.58],[176.11,-37.64],[177.27,-37.99],[178.01,-37.55],[178.53,-37.69],[177.91,-39.24],[177.08,-39.22],[176.84,-40.16],[175.98,-41.21],[175.31,-41.61],[174.87,-41.22],[174.64,-41.29],[175.21,-40.2],[173.76,-39.32],[174.57,-38.84],[174.65,-38.43],[174.84,-38.02],[174.8,-37.9],[174.93,-37.8],[174.73,-37.45],[174.77,-37.34],[174.71,-37.33],[174.59,-37.1],[174.66,-37.09],[174.73,-37.22],[174.81,-37.11],[174.93,-37.09],[174.78,-36.94],[174.6,-36.98],[174.47,-36.94],[174.38,-36.73],[174.19,-36.49],[174.4,-36.6],[174.46,-36.51],[174.36,-36.38],[174.39,-36.24],[174.27,-36.16],[174.25,-36.25],[174.03,-36.12],[173.92,-35.91],[173.92,-36.02],[174.17,-36.33],[174.15,-36.38],[174.06,-36.36],[173.41,-35.54],[173.63,-35.32],[173.31,-35.44],[172.71,-34.46],[173.04,-34.43],[173.24,-34.9]],[[-7.18,55.06],[-6.13,55.22],[-5.72,54.82],[-5.71,54.76],[-5.88,54.68],[-5.88,54.64],[-5.58,54.66],[-5.47,54.5],[-5.48,54.44],[-5.67,54.55],[-5.66,54.38],[-5.56,54.37],[-5.61,54.27],[-5.83,54.24],[-6.02,54.05],[-6.22,54.09],[-6.16,54.02],[-6.35,53.99],[-6.14,53.58],[-6.15,53.37],[-6.03,52.93],[-6.17,52.74],[-6.22,52.54],[-6.46,52.34],[-6.32,52.25],[-6.89,52.16],[-6.96,52.25],[-7.08,52.14],[-7.22,52.14],[-9.3,51.5],[-10.12,51.6],[-9.6,51.87],[-10.34,51.8],[-9.91,52.12],[-10.36,52.21],[-8.78,52.68],[-9.92,52.57],[-8.93,53.21],[-10.09,53.41],[-9.58,53.8],[-9.91,53.86],[-10.06,54.26],[-8.54,54.24],[-8.13,54.64],[-8.76,54.68],[-8.27,55.15],[-7.67,55.26],[-7.66,54.97],[-7.31,55.37],[-6.96,55.24],[-7.22,55.09]],[[107.37,-6.01],[107.56,-6.18],[108.14,-6.3],[108.29,-6.26],[108.42,-6.38],[108.78,-6.81],[110.43,-6.95],[110.84,-6.42],[112.54,-6.93],[113.01,-7.66],[114.41,-7.79],[114.58,-8.77],[113.25,-8.29],[111.51,-8.3],[107.29,-7.47],[106.53,-7.39],[106.41,-7.31],[106.52,-7.05],[105.94,-6.86],[105.48,-6.85],[105.26,-6.84],[105.34,-6.67],[105.37,-6.66],[105.4,-6.77],[105.48,-6.78],[105.66,-6.47],[105.79,-6.46],[105.87,-6.12],[106.07,-5.91],[106.83,-6.1],[107.01,-6.01],[107.05,-5.9],[107.33,-5.98]],[[142.76,54.39],[143.33,52.96],[143.19,51.95],[144.71,48.64],[144.05,49.25],[143.1,49.2],[142.56,47.74],[143.58,46.36],[143.43,46.03],[143.28,46.56],[142.58,46.7],[142.08,45.92],[141.83,46.45],[142.18,48.01],[141.86,48.75],[142.14,49.57],[142.21,51.22],[141.72,51.74],[141.66,52.27],[141.83,53.34],[142.53,53.45],[142.71,53.89],[142.34,54.28],[142.69,54.42]],[[-81.84,23.16],[-79.82,22.89],[-74.15,20.17],[-77.72,19.86],[-77.23,20.64],[-78.12,20.76],[-78.73,21.59],[-81.85,22.21],[-82.08,22.39],[-81.71,22.5],[-81.7,22.59],[-81.84,22.67],[-82.74,22.69],[-84.84,21.83],[-84.04,22.67],[-83.26,22.97],[-82.1,23.19]],[[143.82,44.12],[144.72,43.93],[145.37,44.33],[145.14,43.66],[145.34,43.3],[145.83,43.39],[143.97,42.88],[143.24,42],[141.85,42.58],[140.99,42.34],[140.48,42.56],[140.33,42.29],[141.15,41.81],[140.04,41.47],[139.86,42.58],[140.43,42.95],[140.39,43.3],[141.38,43.28],[141.76,44.48],[141.67,45.4],[141.94,45.51],[143.76,44.13]],[[121.1,18.62],[121.85,18.29],[122.27,18.46],[122.15,17.66],[122.52,17.12],[122.14,16.19],[121.69,16.02],[121.6,15.93],[121.56,15.83],[121.61,15.67],[121.39,15.32],[121.69,14.77],[121.63,14.58],[121.77,14.17],[121.91,14.02],[122.21,13.93],[122.29,14],[122.2,14.15],[122.49,14.32],[122.94,14.19],[123.1,13.75],[123.32,14.06],[123.86,13.8],[123.55,13.65],[123.79,13.11],[124.14,13.04],[124.06,12.57],[123.95,12.92],[123.31,13.04],[122.59,13.91],[122.6,13.19],[122.21,13.65],[122.07,13.79],[121.78,13.94],[121.5,13.84],[121.45,13.71],[121.34,13.65],[121.1,13.68],[120.93,13.76],[120.84,13.89],[120.73,13.9],[120.64,13.81],[120.62,14.19],[120.92,14.49],[120.94,14.65],[120.59,14.88],[120.55,14.77],[120.59,14.48],[120.44,14.45],[120.25,14.79],[120.08,14.85],[119.93,15.43],[119.77,16.25],[120.37,16.11],[120.6,18.51],[121.05,18.61]],[[-100,73.95],[-99.16,73.73],[-97.11,73.79],[-97,73.67],[-97.63,73.5],[-97.27,73.39],[-98.43,72.96],[-97.63,73.03],[-97.13,72.63],[-96.54,72.7],[-96.47,72.43],[-96.8,72.32],[-96.61,71.83],[-97.58,71.63],[-98.32,71.85],[-98.2,71.44],[-99.17,71.37],[-100.59,72.15],[-102.71,72.77],[-102.2,73.08],[-101.27,72.72],[-100.13,72.91],[-100.54,73.2],[-99.82,73.21],[-101.52,73.49],[-100.52,73.45],[-100.99,73.77],[-100.14,73.93]],[[55.32,73.31],[56.43,73.2],[56.12,72.81],[55.4,72.55],[55.52,72.22],[55.3,71.94],[56.45,71.11],[57.62,70.73],[56.26,70.71],[56.44,70.56],[53.72,70.81],[53.38,70.87],[54.16,71.12],[53.41,71.34],[53.41,71.53],[51.81,71.49],[51.44,71.78],[51.58,72.07],[52.62,72.3],[52.92,72.67],[52.55,72.77],[53.37,72.92],[53.25,73.18],[55.12,73.36]],[[-84.92,65.26],[-84.5,65.46],[-82.05,64.64],[-81.68,64.21],[-81.89,64.02],[-80.83,64.09],[-80.26,63.8],[-81.05,63.46],[-83.3,64.14],[-84.63,63.31],[-85.39,63.12],[-85.77,63.7],[-87.18,63.6],[-86.25,64.14],[-86.37,64.57],[-85.81,65.83],[-85.24,65.8],[-85.06,65.44]],[[126.01,9.32],[126.31,8.95],[126.14,8.6],[126.46,8.2],[126.58,7.25],[126.19,6.85],[126.19,6.31],[125.69,7.26],[125.38,6.69],[125.67,5.98],[125.35,5.6],[125.23,6.07],[124.93,5.88],[124.08,6.4],[123.99,6.99],[124.21,7.4],[123.67,7.82],[123.39,7.41],[122.62,7.76],[122.14,6.95],[121.9,7.07],[122.24,7.94],[122.91,8.16],[123.44,8.7],[123.85,8.43],[123.8,8.05],[124.4,8.6],[124.73,8.56],[124.87,8.97],[125.5,9.01],[125.47,9.76],[125.96,9.43]],[[140.05,75.83],[140.82,75.63],[140.99,75.96],[141.49,76.14],[145.36,75.53],[144.02,75.04],[142.82,75.27],[142.7,75.45],[142.94,75.71],[142.31,75.69],[142.09,75.66],[142.2,75.39],[143.13,74.97],[139.68,74.96],[139.1,74.66],[138.09,74.8],[136.95,75.33],[137.29,75.35],[137.27,75.75],[137.71,75.76],[137.56,75.96],[138.21,76.12],[138.92,76.2],[139.74,75.95]],[[-93.17,74.16],[-90.36,73.87],[-92.12,72.75],[-94.21,72.76],[-93.54,72.44],[-94.14,72],[-95.19,72.03],[-95.6,72.88],[-95.63,73.7],[-94.7,73.66],[-95.15,73.91],[-94.97,74.04],[-93.41,74.18]],[[145.04,-40.79],[146.32,-41.16],[148.22,-40.85],[148.34,-42.22],[148.22,-41.97],[148.02,-42.26],[147.98,-43.16],[147.3,-42.79],[146.87,-43.61],[146.04,-43.55],[146.21,-43.32],[145.49,-42.93],[145.2,-42.23],[145.52,-42.35],[144.77,-41.39],[144.72,-40.67],[144.82,-40.72]],[[20.9,80.25],[22.29,80.05],[22.45,80.4],[23.01,80.47],[23.32,80.42],[23.11,80.19],[24.4,80.36],[26.86,80.16],[27.2,79.91],[23.95,79.19],[20.13,79.49],[19.68,79.59],[20.78,79.75],[18.73,79.76],[18.25,79.93],[18.86,80.04],[17.92,80.14],[19.34,80.12],[19.54,80.16],[19.18,80.33],[19.75,80.23],[19.73,80.48],[20.69,80.3]],[[-71.95,19.72],[-69.96,19.67],[-69.74,19.3],[-69.32,19.33],[-69.23,19.27],[-69.32,19.2],[-69.61,19.21],[-69.62,19.12],[-68.36,18.54],[-68.69,18.21],[-68.93,18.41],[-69.27,18.44],[-69.77,18.44],[-70.02,18.37],[-70.18,18.25],[-70.48,18.22],[-70.64,18.34],[-71.03,18.27],[-71.11,18.07],[-71.44,17.64],[-72.06,18.23],[-73.88,18.04],[-74.39,18.62],[-72.35,18.62],[-72.7,19.44],[-73.4,19.81]],[[-69.17,-52.67],[-68.63,-52.65],[-68.24,-53.08],[-68.49,-53.26],[-67.29,-54.05],[-66.24,-54.53],[-65.18,-54.68],[-66.51,-55.03],[-71.9,-54.6],[-70.8,-54.33],[-70.31,-54.53],[-70.86,-54.11],[-70.53,-53.63],[-70.38,-53.99],[-70.63,-54],[-70.24,-54.35],[-69.05,-54.43],[-70.15,-53.89],[-69.39,-53.37],[-70.21,-53.41],[-70.46,-53.21],[-70.13,-52.94],[-70.38,-52.75],[-69.94,-52.82],[-69.5,-52.49],[-69.41,-52.49]],[[97.67,80.16],[98.02,80.02],[97.65,79.76],[98.6,80.05],[99.95,79.85],[99.68,79.32],[99.04,79.29],[99.93,78.96],[97.56,78.83],[93.07,79.5],[94.99,80.1],[97.59,80.17]],[[-115.55,77.36],[-116.33,77.14],[-115.81,76.94],[-116.25,76.9],[-115.94,76.71],[-117,76.53],[-117.23,76.28],[-117.99,76.41],[-117.88,76.8],[-118.79,76.51],[-118.62,76.37],[-118.99,76.15],[-119.58,76.33],[-119.74,76.12],[-119.54,75.98],[-119.91,75.86],[-120.41,75.83],[-120.85,76.18],[-122.4,75.94],[-122.9,76.13],[-119.09,77.3],[-116.84,77.34],[-117.04,77.46],[-116.51,77.55],[-116.01,77.46]],[[79.98,9.81],[80.71,9.37],[81.83,7.43],[81.77,6.61],[81.38,6.24],[80.73,5.98],[80.5,5.95],[80.27,6.01],[80.1,6.15],[79.86,6.83],[79.71,8.07],[79.75,8.29],[79.75,8.05],[79.81,8.05],[79.85,8.41],[80.08,9.58],[80.43,9.48],[79.97,9.79]],[[-97.7,76.47],[-97.53,76.11],[-97.89,75.76],[-97.41,75.67],[-97.34,75.42],[-97.88,75.42],[-97.66,75.15],[-98.07,75.2],[-97.99,75.05],[-100.23,75.01],[-100.48,75.19],[-100.14,75.25],[-100.73,75.35],[-99.19,75.7],[-102.8,75.6],[-102.15,75.87],[-100.97,75.8],[-101.87,76.08],[-101.56,76.24],[-102.14,76.28],[-101.79,76.45],[-99.87,75.92],[-99.69,75.96],[-100.11,76.12],[-99.54,76.15],[-100.89,76.48],[-100.07,76.63],[-98.89,76.47],[-99.02,76.61],[-98.71,76.69],[-97.72,76.5]],[[96.53,81.08],[97.86,80.7],[97.11,80.61],[97.42,80.32],[97.17,80.24],[93.87,80.01],[91.53,80.36],[92.83,80.62],[93.26,80.79],[92.61,80.81],[93.36,81.03],[95.16,81.27],[96.47,81.1]],[[-103.43,79.32],[-102.58,78.88],[-101.7,79.08],[-100.01,78.73],[-99.58,78.56],[-99.75,78.3],[-99,78],[-99.96,77.79],[-101.07,78.19],[-104.51,78.29],[-105,78.52],[-103.57,78.54],[-104.02,78.63],[-103.37,78.74],[-104.18,78.78],[-103.88,78.9],[-104.15,78.99],[-104.9,78.81],[-104.75,79.03],[-105.58,79.11],[-105.39,79.32],[-103.71,79.35]],[[102.88,79.25],[102.41,78.84],[103.8,79.15],[105.34,78.59],[104.74,78.34],[99.29,78.04],[100.42,78.75],[100.95,78.79],[101.05,79.12],[101.59,79.35],[103.1,79.3],[102.94,79.27]],[[131.18,33.6],[131.69,33.6],[131.54,33.27],[131.9,33.25],[132.01,32.92],[131.34,31.4],[131.07,31.44],[130.69,31.01],[130.78,31.71],[130.59,31.18],[130.15,31.41],[130.55,32.83],[130.24,33.18],[130.34,32.7],[129.77,32.57],[129.68,33.06],[129.99,32.85],[129.58,33.24],[130.72,33.93],[131.06,33.67]],[[-127.2,50.64],[-125.48,50.32],[-124.83,49.53],[-123.85,49.12],[-123.5,48.58],[-123.41,48.7],[-123.29,48.46],[-123.31,48.41],[-123.45,48.43],[-123.57,48.32],[-125.12,48.76],[-124.81,49.21],[-125.49,48.93],[-125.93,49.4],[-126.52,49.4],[-126.54,49.59],[-126.13,49.67],[-127.12,49.88],[-127.25,50.14],[-127.86,50.13],[-127.91,50.45],[-127.49,50.41],[-127.46,50.58],[-128.35,50.7],[-127.92,50.86],[-127.71,50.82]],[[121.01,22.62],[120.84,21.92],[120.08,23.09],[120.13,23.65],[120.63,24.48],[121.04,25.03],[121.59,25.28],[121.91,25.06],[121.93,24.97],[121.82,24.82],[121.83,24.53],[121.64,24.13],[121.52,23.67],[121.16,22.78]],[[-79.54,73.65],[-77.21,73.5],[-76.09,72.88],[-79.5,72.76],[-80.78,73.33],[-80.86,73.67],[-79.89,73.7]],[[-49.63,-0.23],[-48.39,-0.3],[-48.83,-1.39],[-49.8,-1.79],[-50.51,-1.79],[-50.79,-0.91],[-50.65,-0.27],[-50.25,-0.12]],[[110.89,19.99],[111.01,19.66],[110.02,18.42],[109.52,18.22],[108.7,18.54],[108.67,19.3],[109.26,19.88],[110.65,20.14],[110.81,20.02]],[[151.92,-4.3],[152.41,-4.34],[152.35,-4.82],[151.98,-5.07],[152.08,-5.46],[151.52,-5.55],[150.47,-6.26],[149.65,-6.29],[148.34,-5.67],[148.43,-5.47],[149.83,-5.52],[150.09,-5.01],[150.18,-5.52],[150.74,-5.51],[151.67,-4.88],[151.59,-4.2],[151.87,-4.26]],[[-97.44,69.64],[-95.27,68.83],[-96.6,68.46],[-99.56,69.03],[-98.5,69.31],[-98.55,69.57],[-98.04,69.46],[-98.3,69.67],[-98.08,69.83],[-97.47,69.67]],[[21.61,78.6],[22.04,78.58],[22.3,78.23],[23.45,78.15],[23.12,77.99],[24.9,77.76],[22.8,77.28],[22.43,77.32],[22.69,77.55],[21.05,77.44],[20.87,77.57],[21.65,77.92],[20.23,78.48],[21.45,78.6]],[[15.58,38.22],[15.1,37.46],[15.29,37.06],[15.11,36.69],[14.37,36.97],[14.14,37.1],[13.8,37.14],[12.92,37.57],[12.64,37.59],[12.44,37.82],[12.55,38.05],[12.74,38.18],[12.9,38.03],[13.16,38.19],[13.35,38.18],[13.38,38.13],[13.79,37.98],[14.05,38.04],[14.51,38.05],[14.79,38.17],[15.63,38.27]],[[9.63,40.88],[9.8,40.5],[9.56,39.17],[9.06,39.24],[8.97,38.96],[8.65,38.93],[8.42,39.21],[8.55,39.84],[8.2,40.87],[9.23,41.26],[9.57,40.91]],[[127.3,-8.42],[125.41,-9.28],[124.43,-10.15],[123.61,-10.27],[123.71,-9.62],[125.18,-8.65],[127.26,-8.39]],[[-93.54,75.03],[-93.57,74.67],[-94.54,74.64],[-96.6,75.06],[-95.95,75.44],[-94.88,75.63],[-93.91,75.42],[-93.55,75.05]],[[134.36,34.26],[134.64,34.23],[134.68,33.85],[134.74,33.82],[134.38,33.61],[134.18,33.25],[133.69,33.52],[133.29,33.36],[132.87,32.75],[132.49,32.92],[132.41,33.43],[132.03,33.34],[132.94,34.1],[133.47,33.97],[133.95,34.35],[134.07,34.36],[134.22,34.32]],[[-75.67,68.32],[-75.06,68.14],[-75.13,67.54],[-75.4,67.37],[-76.95,67.25],[-77.31,67.69],[-76.69,68.26],[-75.87,68.34]],[[-96.21,78.53],[-94.92,78.39],[-95.33,78.22],[-94.93,78.08],[-96.99,77.81],[-97.66,78.09],[-96.94,78.15],[-98.05,78.33],[-98.34,78.75],[-96.26,78.55]],[[-52.73,69.94],[-51.9,69.6],[-53.75,69.26],[-54.18,69.4],[-53.66,69.47],[-53.83,69.54],[-54.92,69.71],[-54.79,69.95],[-54.32,69.94],[-54.83,70.13],[-54.37,70.32],[-53.1,70.14]],[[-110.46,78.1],[-109.62,78.06],[-110.86,77.83],[-110.15,77.76],[-110.2,77.53],[-111.95,77.34],[-113.17,77.53],[-113.28,77.81],[-110.73,78.1]],[[146.8,75.37],[150.82,75.16],[150.58,74.92],[149.05,74.77],[146.15,75.2],[146.44,75.56],[146.75,75.43]],[[127.73,0.85],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[128.43,-0.89],[127.69,-0.24],[127.43,1.14],[127.63,1.84],[128.04,2.2],[128.01,1.33],[127.68,0.89]],[[180,71.54],[181.56,71.54],[182.5,71.22],[178.79,70.82],[178.63,71.05],[179.88,71.52]],[[142.19,73.9],[143.34,73.57],[143.49,73.25],[139.69,73.42],[141.08,73.87],[141.93,73.91]],[[-152.9,57.82],[-152.43,57.83],[-152.21,57.58],[-152.94,57.5],[-152.68,57.34],[-153.97,56.77],[-153.79,56.99],[-154.25,57.14],[-154.34,56.92],[-154.71,57.34],[-154.12,57.65],[-153.69,57.3],[-153.84,57.86],[-152.85,57.9]],[[129.75,-2.87],[130.57,-3.13],[130.81,-3.86],[129.84,-3.33],[129.47,-3.45],[128.86,-3.24],[128.52,-3.45],[128.13,-3.16],[127.9,-3.5],[128.2,-2.87],[129.6,-2.81]],[[50.28,80.93],[51.7,80.69],[48.9,80.37],[48.68,80.3],[48.98,80.16],[48.39,80.1],[46.64,80.3],[49.09,80.52],[49.24,80.82],[50.13,80.92]],[[164.2,-20.25],[165.19,-20.77],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.06,-20.14]],[[122.78,-8.61],[121.04,-8.93],[119.81,-8.7],[119.88,-8.42],[120.61,-8.24],[122.32,-8.63],[122.92,-8.1],[122.82,-8.6]],[[125.24,12.53],[125.54,12.19],[125.74,11.05],[125.03,11.34],[125,11.77],[124.44,12.15],[124.29,12.57],[125.15,12.57]],[[-105.29,72.92],[-106.95,73.51],[-105.51,73.77],[-104.59,73.58],[-104.62,73.31],[-105.2,72.95]],[[-133.57,56.34],[-133.2,56.32],[-132.17,55.48],[-132.63,55.47],[-131.98,55.21],[-132.02,54.73],[-133.12,55.33],[-133.03,55.59],[-133.68,55.79],[-133.24,55.92],[-133.74,55.96],[-133.6,56.32]],[[12.57,55.79],[12.54,55.66],[12.32,55.59],[12.22,55.47],[12.39,55.39],[12.41,55.29],[12.09,55.19],[12.05,54.81],[11.86,54.77],[11.74,54.92],[11.66,55.19],[11.29,55.2],[11.17,55.33],[11.19,55.47],[11.12,55.6],[11.01,55.64],[10.98,55.72],[11.32,55.75],[11.48,55.94],[11.63,55.96],[11.69,55.91],[11.69,55.73],[11.82,55.7],[11.94,55.9],[11.87,55.97],[12.22,56.12],[12.58,56.06],[12.61,56.03],[12.53,55.92]],[[34.46,35.59],[33.94,35.29],[34.05,34.99],[33.01,34.57],[32.32,34.95],[32.94,35.39],[34.55,35.66]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.46,70.94]],[[106.04,-1.67],[106.36,-2.46],[106.82,-2.57],[106.67,-3.07],[106,-2.83],[105.79,-2.18],[105.13,-2.04],[105.46,-1.57],[106.03,-1.59]],[[-82,62.96],[-82.12,62.65],[-83.02,62.21],[-83.7,62.16],[-83.91,62.43],[-83.38,62.9],[-82.05,62.97]],[[122.5,11.61],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.4,11.7]],[[-61.11,45.94],[-60.86,45.98],[-61.06,45.7],[-60.74,45.75],[-60.3,46.31],[-59.83,45.96],[-60.67,45.59],[-61.45,45.72],[-61.41,46.17],[-60.49,47.01],[-60.49,46.27],[-60.91,46.04]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.19,9.09]],[[-73.77,-43.35],[-74.39,-43.23],[-74.04,-41.8],[-73.53,-41.9],[-73.42,-42.19],[-73.79,-42.59],[-73.44,-42.94],[-73.74,-43.29]],[[118.24,-8.32],[118.93,-8.3],[119.13,-8.67],[116.79,-9.01],[116.83,-8.53],[117.16,-8.37],[117.97,-8.73],[118.23,-8.59],[117.76,-8.15],[118.2,-8.27]],[[62.17,80.83],[62.08,80.62],[61.05,80.42],[59.29,80.57],[59.72,80.84],[62.1,80.87]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[117.41,8.5]],[[-109.82,78.65],[-109.35,78.37],[-113.29,78.33],[-110.88,78.74],[-109.94,78.68]],[[54.72,81.12],[57.69,80.79],[55.89,80.63],[54.07,80.81],[54.63,81.11]],[[9.48,42.81],[9.56,42.16],[9.19,41.39],[8.81,41.59],[8.57,42.36],[9.32,42.71],[9.36,43.02],[9.48,42.86]],[[50.27,69.19],[48.91,68.74],[48.28,69.04],[48.42,69.35],[48.96,69.51],[50.17,69.26]],[[178.28,-17.37],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.51,-17.54],[178.25,-17.33]],[[-61.8,49.09],[-63.04,49.23],[-64.49,49.89],[-62.86,49.71],[-61.75,49.11]],[[-77.26,18.46],[-76.91,18.39],[-76.7,18.26],[-76.35,18.15],[-76.21,17.91],[-76.52,17.87],[-76.85,17.97],[-76.94,17.85],[-77.12,17.88],[-77.2,17.71],[-77.36,17.83],[-77.77,17.88],[-78.33,18.35],[-77.87,18.52]],[[-44.87,82.08],[-47.35,82.6],[-44.92,82.48],[-44.78,82.24]],[[-158.28,21.58],[-158.12,21.71],[-157.98,21.71],[-157.65,21.31],[-157.71,21.26],[-157.95,21.3],[-158.1,21.3],[-158.23,21.46]],[[-155.87,20.27],[-155.1,19.86],[-154.81,19.51],[-155.62,18.91],[-155.88,19.07],[-156.05,19.73],[-155.83,20]],[[-156.69,20.95],[-156.4,20.92],[-156,20.8],[-156,20.62],[-156.45,20.58],[-156.51,20.78],[-156.69,20.88]],[[-159.79,22.07],[-159.4,22.23],[-159.29,22.1],[-159.38,21.88],[-159.68,21.95]],[[-157.31,21.1],[-156.71,21.16],[-156.75,21.08],[-157.25,21.08]],[[144.62,13.24],[144.66,13.43],[144.79,13.53],[144.95,13.65],[144.88,13.43],[144.76,13.25],[144.7,13.23]],[[134.45,7.35],[134.48,7.28],[134.56,7.42],[134.65,7.7],[134.6,7.73],[134.52,7.55]],[[171,7.04],[171.42,7.03],[171.45,7.14],[171,7.12]],[[159.6,-9.25],[160.2,-9.4],[160.8,-9.85],[160.6,-9.95],[159.95,-9.75],[159.6,-9.5]],[[-149.62,-17.5],[-149.37,-17.53],[-149.18,-17.87],[-149.32,-17.78],[-149.6,-17.8],[-149.62,-17.66]],[[-172.07,-13.8],[-171.44,-13.79],[-171.43,-14.05],[-172,-14.04]],[[-172.78,-13.48],[-172.21,-13.58],[-172.25,-13.8],[-172.7,-13.78]],[[-170.84,-14.29],[-170.56,-14.24],[-170.56,-14.31],[-170.82,-14.36]],[[-175.36,-21.1],[-175.05,-21.13],[-175.08,-21.24],[-175.3,-21.2]],[[146.95,-9.25],[147.45,-9.2],[147.55,-9.55],[147.05,-9.65]],[[166.25,-22.1],[166.65,-22.05],[166.7,-22.4],[166.3,-22.45]],[[178.2,-17.95],[178.6,-17.95],[178.6,-18.25],[178.2,-18.25]],[[-64.89,32.25],[-64.82,32.29],[-64.7,32.36],[-64.64,32.39],[-64.67,32.35],[-64.76,32.28],[-64.85,32.23]],[[-25.86,37.9],[-25.48,37.83],[-25.13,37.83],[-25.15,37.72],[-25.5,37.71],[-25.85,37.76]],[[-27.38,38.78],[-27.05,38.76],[-27.04,38.64],[-27.35,38.66]],[[-28.55,38.55],[-28.05,38.43],[-28.1,38.39],[-28.5,38.46]],[[-28.83,38.64],[-28.6,38.62],[-28.62,38.52],[-28.8,38.53]],[[-16.92,28.37],[-16.65,28.4],[-16.13,28.58],[-16.35,28.37],[-16.5,28.06],[-16.75,28.03],[-16.88,28.2]],[[-15.8,28.15],[-15.4,28.17],[-15.36,27.9],[-15.6,27.74],[-15.82,27.9]],[[-13.85,29.22],[-13.45,29.24],[-13.47,28.88],[-13.85,28.9]],[[-14.2,28.75],[-13.84,28.72],[-13.9,28.25],[-14.5,28.06]],[[-17.92,28.85],[-17.75,28.83],[-17.83,28.46],[-17.96,28.62]],[[-17.35,28.2],[-17.1,28.2],[-17.12,28.02],[-17.32,28.03]],[[-18.15,27.8],[-17.9,27.83],[-17.95,27.65],[-18.12,27.7]],[[-23.76,15.27],[-23.47,15.33],[-23.43,15.02],[-23.52,14.91],[-23.78,15.05]],[[-24.5,15],[-24.3,15],[-24.3,14.82],[-24.5,14.82]],[[-25.08,16.9],[-24.88,16.9],[-24.88,16.78],[-25.05,16.8]],[[-25.35,17.2],[-24.98,17.1],[-25,16.98],[-25.33,17]],[[-22.98,16.84],[-22.88,16.84],[-22.88,16.6],[-22.98,16.6]],[[-22.95,16.2],[-22.7,16.15],[-22.72,15.98],[-22.93,16]],[[-5.79,-15.9],[-5.65,-15.9],[-5.63,-16],[-5.75,-16.03]],[[-65.63,18.28],[-65.6,18.22],[-65.74,18.18],[-65.94,17.97],[-66.2,17.92],[-66.77,18],[-66.93,17.93],[-67.18,17.94],[-67.15,18.2],[-67.27,18.36],[-67.1,18.52],[-66.38,18.49],[-65.62,18.39]],[[-77.48,24.99],[-77.55,25],[-77.56,25.02],[-77.55,25.04],[-77.5,25.06],[-77.34,25.08],[-77.26,25.06],[-77.38,25],[-77.44,25.01],[-77.47,24.99]],[[-61,10.7],[-61.04,10.51],[-60.96,10.33],[-61,10.14],[-61.19,10.07],[-61.93,10.06],[-61.67,10.18],[-61.63,10.25],[-61.51,10.24],[-61.46,10.28],[-61.49,10.63],[-61.67,10.71],[-61.37,10.8],[-60.95,10.85],[-60.91,10.84]],[[-59.43,13.16],[-59.43,13.13],[-59.51,13.06],[-59.62,13.09],[-59.65,13.16],[-59.65,13.32],[-59.59,13.33],[-59.54,13.23]],[[-60.81,14.46],[-61.07,14.47],[-61.11,14.52],[-61,14.57],[-61.16,14.67],[-61.22,14.85],[-60.88,14.78],[-60.94,14.67]],[[-68.78,12.1],[-68.74,12.05],[-68.81,12.04],[-68.98,12.12],[-69.16,12.29],[-69.17,12.39],[-69.07,12.34],[-69,12.22],[-68.84,12.17]],[[55.79,-21.1],[55.85,-21.16],[55.81,-21.34],[55.58,-21.37],[55.35,-21.27],[55.23,-21.03],[55.29,-20.91],[55.41,-20.86],[55.58,-20.87],[55.7,-20.94]],[[57.8,-20.22],[57.78,-20.34],[57.67,-20.48],[57.38,-20.51],[57.31,-20.44],[57.36,-20.41],[57.4,-20.2],[57.6,-19.98],[57.68,-20]],[[55.4,-4.66],[55.37,-4.64],[55.43,-4.56],[55.46,-4.57],[55.46,-4.63],[55.53,-4.68],[55.54,-4.8],[55.46,-4.76],[55.48,-4.71]],[[-130.12,-25.07],[-130.11,-25.06],[-130.1,-25.06],[-130.09,-25.07],[-130.09,-25.08],[-130.1,-25.08],[-130.11,-25.08],[-130.11,-25.07]],[[-166.29,53.73],[-167.85,53.31],[-166.8,53.63],[-167.16,53.83],[-167.02,53.96],[-166.37,54.01],[-166.22,53.91],[-166.58,53.71]],[[73.55,4.24],[73.55,4.23],[73.54,4.18],[73.51,4.16],[73.43,4.18],[73.51,4.19]]]; +// Cebu, from the same Natural Earth 1:50m land (the simplified rings had dropped it). +COAST_LL.push([[123.37,9.45],[123.33,9.42],[123.32,9.49],[123.33,9.58],[123.4,9.89],[123.39,9.97],[123.51,10.14],[123.59,10.3],[123.71,10.47],[123.73,10.56],[123.83,10.73],[123.93,10.96],[123.92,11.04],[123.95,11.08],[123.96,11.14],[123.97,11.19],[124.04,11.27],[124.06,11.22],[124.04,11.11],[124.04,11.05],[124.05,11.03],[124.05,10.93],[124.03,10.77],[124.05,10.59],[124,10.4],[123.95,10.32],[123.87,10.26],[123.79,10.22],[123.7,10.13],[123.64,10.02],[123.63,9.92],[123.49,9.59]]); const COAST=COAST_LL.map(poly=>poly.map(q=>proj(q[0],q[1]))); diff --git a/src/game/20-world/40-city-coords.js b/src/game/20-world/40-city-coords.js index 4b32a81..4304849 100644 --- a/src/game/20-world/40-city-coords.js +++ b/src/game/20-world/40-city-coords.js @@ -44,6 +44,7 @@ const CITY_LL={ "cbo":[80.0, 6.95], "cbr":[149.13,-35.28], "ccs":[-66.9,10.49], + "ceb":[123.89,10.32], "cgb":[-56.1,-15.6], "cgr":[-54.65,-20.47], "chc":[172.55,-43.53], diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index dbdb7e4..dfdb524 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -240,6 +240,8 @@ const CITIES=[ {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')}, + // The Philippines beyond Luzon + {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',P:100,ix:'GotchaFIX Cebu',dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, ]; // 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/20-world/60-cables.js b/src/game/20-world/60-cables.js index 44e1433..4e01d1e 100644 --- a/src/game/20-world/60-cables.js +++ b/src/game/20-world/60-cables.js @@ -161,6 +161,8 @@ const CABLES=[ {"id":"tw1","name":"TW1-light","price":1.1,"age":"mid","blurb":tr('cables.the_emirates_oman_and_pakistan_on'),"pairs":[["fuj","mct",[[58.25,24.25]]],["mct","khi",[[58.75,24]]]]}, {"id":"mct1","name":"MCT (Malaysia, Cambodia, Tuk-tuks)","price":0.95,"age":"new","blurb":tr('cables.malaysia_to_thailand_round_the_gulf'),"pairs":[["kul","bkk",[[101.75,2.5],[102.5,1.5],[103.5,0.75],[103.75,0.75],[104.75,1.75],[104.75,2.75],[100.5,12.75]]]]}, {"id":"kjcn","name":"KJCN (Kimchi-Japan Cable Network)","price":1,"age":"mid","blurb":tr('cables.busan_to_kyushu_the_shortest_way'),"pairs":[["icn","fuk",[[126,36.75],[126,34],[130,34]]]]}, + {"id":"pdscn","name":"Pan de Sal Cable Network","price":0.9,"age":"new","blurb":tr('cables.the_philippines_longest_domestic_cable_fresh'),"pairs":[["mnl","ceb",[[120.6,14.4],[120.45,13.95],[120.85,13.6],[121.9,12.9],[122.7,12.3],[123.6,11.6],[124.2,11.2],[124.15,10.5]]]]}, + {"id":"dfon","name":"Philippines Long Distance Relationship","price":1.1,"age":"mid","blurb":tr('cables.the_incumbent_s_own_line_south'),"pairs":[["mnl","ceb",[[121.6,13.85],[122.1,13.2],[122.9,12.45],[123.75,11.7],[124.3,11.1],[124.2,10.45]]]]}, ]; const CAB=Object.fromEntries(CABLES.map(c=>[c.id,c])); const CABLE_PAIRS=CABLES.flatMap(c=>c.pairs.map(([a,b,mid])=>{const A=CITY[a],B=CITY[b];const near=(x,ref)=>x+W*Math.round((ref-x)/W); diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index e016009..4106893 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -37,9 +37,9 @@ 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:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#D62027',pops:['mnl','hkg','sin'],ix:['hkg','mnl~3'],blurb:tr('networks.philippine_giant_peering_requests')}, - {id:'glb',name:'Snow Globe',asn:4775,type:'t2',pol:'open',share:.007,price:6,col:'#1A3D8F',pops:['mnl','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.shake_it_and_coverage_falls_gently')}, - {id:'cvg',name:'Diverge',asn:17639,type:'eye',pol:'open',share:.005,col:'#F26B21',pops:['mnl','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, + {id:'pld',name:'PLDTea Time',asn:9299,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#D62027',pops:['mnl','ceb','hkg','sin'],ix:['hkg','mnl~3'],blurb:tr('networks.philippine_giant_peering_requests')}, + {id:'glb',name:'Snow Globe',asn:4775,type:'t2',pol:'open',share:.007,price:6,col:'#1A3D8F',pops:['mnl','ceb','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.shake_it_and_coverage_falls_gently')}, + {id:'cvg',name:'Diverge',asn:17639,type:'eye',pol:'open',share:.005,col:'#F26B21',pops:['mnl','ceb','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, {id:'smt',name:'Smarty Pants',asn:10139,type:'eye',pol:'selective',up:['pld'],minIx:10,minPni:30,share:.006,col:'#00A859',pops:['mnl'],ix:[],blurb:tr('networks.pldtea_time_s_mobile_sibling_buy')}, {id:'dto',name:'Ditto',asn:139831,type:'eye',pol:'open',share:.002,col:'#B5121B',pops:['mnl'],ix:['mnl','mnl~2'],blurb:tr('networks.the_third_mobile_network_same_towers')}, {id:'rsh',name:'RISE & Shine',asn:63927,type:'eye',pol:'open',share:.002,col:'#F5A623',pops:['mnl','sin','hkg','tok','fra','ams','lon','sto','lax'],ix:['mnl','mnl~2','mnl~3','sin','sin~2','hkg','hkg~2','tok','fra','ams','lon','sto','lax'],blurb:tr('networks.up_early_in_cebu_and_already')}, diff --git a/src/game/85-incidents/30-events.js b/src/game/85-incidents/30-events.js index 60fbeba..f9c8d3c 100644 --- a/src/game/85-incidents/30-events.js +++ b/src/game/85-incidents/30-events.js @@ -6,7 +6,7 @@ function fireEvent(){ 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'); if(Object.keys(S.pops).some(c=>CITY[c].saudi))opts.push('mega'); - if(['mnl','hkg','tok','icn','sha','jkt'].some(c=>S.pops[c]))opts.push('typhoon'); + if(['mnl','ceb','hkg','tok','icn','sha','jkt'].some(c=>S.pops[c]))opts.push('typhoon'); if(S.pops.icn&&!S.krExit)opts.push('krexit');if(S.pops.icn&&!(S.ev.krroute>S.day))opts.push('krroute'); if(Object.keys(S.pops).some(cnCity)||R.gfwCross>1)opts.push('golden','gfw'); if(S.transit.some(t=>t.net==='cog'))opts.push('depeer','depeer'); @@ -32,7 +32,7 @@ function fireEvent(){ if(e==='hijack'){const nh=NETS.map(n=>n.id).filter(()=>Math.random()<0.6),old=S.ev.rpki&&S.ev.rpki.until>S.day?S.ev.rpki:null;S.ev.rpki=old?{until:Math.max(old.until,S.day+1),nets:[...new Set(old.nets.concat(nh))]}:{until:S.day+1,nets:nh};addInc({type:'hijack',ref:'rpki',until:S.day+1,msg:tr('events.a_state_owned_isp_accidentally'),cost:1500,fix:tr('events.call_everyone_you_know')});toast(tr('events.bgp_hijack_someone_else_is'),'bad');sfx('alert');return;} if(e==='landban'){const lc=[...new Set(CABLE_PAIRS.flatMap(c=>[c.a,c.b]))];const c=pick(lc);S.ev.landban={city:c,until:S.day+45};toast(tr('events.landing_permit_dispute_in_city_two',{city:CITY[c].name}),'bad');return;} if(e==='shutdown'){const ps=Object.keys(S.pops).filter(c=>c!==S.home);if(!ps.length)return;const c=pick(ps);S.pops[c].down=Math.max(S.pops[c].down||0,S.day+1);addInc({type:'shutdown',ref:c,until:S.day+1,msg:tr('events.regulators_ordered_every_network_in',{city:CITY[c].name}),cost:0});toast(tr('events.ordered_offline_in_city_a_government',{city:CITY[c].name}),'bad');sfx('alert');return;} - if(e==='typhoon'){const c=pick(['mnl','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick([tr('common.typhoon_bandwidth'),tr('common.typhoon_latency'),tr('common.typhoon_jitter'),tr('events.typhoon_packet_loss')]); + if(e==='typhoon'){const c=pick(['mnl','ceb','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick([tr('common.typhoon_bandwidth'),tr('common.typhoon_latency'),tr('common.typhoon_jitter'),tr('events.typhoon_packet_loss')]); if(p.gen){S.stats.survived++;toast(tr('events.name_hits_city_the_grid_is',{name:nm,city:CITY[c].name}),'good');sfx('alert');return;} p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');compute();return;} if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');compute();return;} diff --git a/src/i18n/en.js b/src/i18n/en.js index 12dfefd..edffb87 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -420,8 +420,10 @@ "cables.the_emirates_oman_and_pakistan_on":"The Emirates, Oman and Pakistan on one light little cable.", "cables.the_first_cable_from_south_america":"The first cable from South America to Oceania. 14,000 km of very lonely glass.", "cables.the_first_subsea_fiber_in_the":"The first subsea fiber in the American Arctic: Nome to Utqiaġvik, then over the North Slope to Anchorage. Sea ice keeps repair ships away half the year.", +"cables.the_incumbent_s_own_line_south":"The incumbent's own line south: overland to Lucena, then under the sea to Cebu. Still calls every night.", "cables.the_newest_cable_from_south_africa":"The newest cable from South Africa to Madagascar, Réunion and Mauritius, shared by the islands’ own telcos.", "cables.the_old_workhorse_s_younger_sibling":"The old workhorse’s younger sibling: Los Angeles to Sydney with a branch to Fiji.", +"cables.the_philippines_longest_domestic_cable_fresh":"The Philippines' longest domestic cable, fresh every morning. Luzon to Cebu, island by island.", "cables.the_pretty_way_around_east_asia":"The pretty way around East Asia.", "cables.the_previous_generation_still":"The previous generation. Still carries most of Pakistan, Sri Lanka and Bangladesh, held together with hope.", "cables.the_sea_stallion_blackpool_to":"The Sea Stallion: Blackpool to Denmark, galloping round the north of Scotland.", @@ -632,6 +634,7 @@ "cities.the_old_gateway_to_eastern_europe":"The old gateway to Eastern Europe. Packets still bow politely on the way through.", "cities.the_only_northeastern_capital_away":"The only northeastern capital away from the sea. Famously hot, with lightning storms that keep the surge protectors busy.", "cities.the_pacific_gateway_the_andes_sit":"The Pacific gateway. The Andes sit between it and everything else, and the ground shakes now and then.", +"cities.the_philippines_second_city_reached":"The Philippines' second city, reached only by domestic cable. Typhoons pass through on their way north.", "cities.the_prairie_gateway_between":"The prairie gateway between Vancouver and the rest of Canada. A chinook melts the snow in an afternoon, then it snows again.", "cities.the_rhine_ruhr_hub_more_carrier":"The Rhine-Ruhr hub: more carrier-neutral data centers than Hamburg or Munich, and an hour from the Dutch border, so fiber to Amsterdam is short and cheap. Order an Altbier here, never a Kölsch.", "cities.the_seychelles_capital_on_mah":"The Seychelles’ capital on Mahé: 115 islands, giant tortoises and two cables to the mainland.", diff --git a/tests/philippines.test.js b/tests/philippines.test.js index 3ef7ac0..50fea8d 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -62,3 +62,25 @@ test('Manila: RISE & Shine peers openly on all three Manila exchanges, across As assert.ok(ids(ev, `ixMembers('${x}')`).includes('rsh'), `RISE & Shine on ${x}`); assert.deepEqual(errors, []); }); + +test('Cebu: its own island, GotchaFIX Cebu, reached by two domestic cables, in the typhoon belt', () => { + const { ev, errors } = load(); + start(ev); + assert.ok(ev("isSub('ceb','mnl')"), 'Cebu is an island'); + assert.ok(ev('onLand(CITY.ceb.x,CITY.ceb.y)'), 'Cebu is drawn on land'); + assert.equal(ev('CITY.ceb.ix'), 'GotchaFIX Cebu'); + assert.equal(ev('CITY.ceb.dc'), "Magellan's Last Rack"); + assert.deepEqual(ids(ev, "cablesFor('mnl','ceb').map(p=>p.cid)").sort(), ['dfon', 'pdscn']); + for (const n of ['pld', 'glb']) assert.ok(ev(`sellsAt(NET.${n},'ceb')`), `${n} sells transit in Cebu`); + assert.ok(ev("NET.cvg.pops.includes('ceb')")); + // a subsea wave from Manila to Cebu carries traffic + for (const c of ['mnl', 'ceb']) ev(`ACT.buildPop({city:'${c}'});S.pops.${c}.rgen=3`); + ev("UI.via='pdscn';UI.route='same';openLinkModal('mnl','ceb');ACT.buildLink({tier:2});closeModal()"); + ev('compute()'); + assert.equal(ev("S.links.filter(l=>l.sub&&l.cable==='pdscn').length"), 1); + // typhoons can now hit a Cebu PoP + ev("S.pops={ceb:S.pops.ceb};delete S.pops.ceb.gen;for(let i=0;i<2000&&!(S.pops.ceb.down>S.day);i++)fireEvent()"); + assert.ok(ev("S.pops.ceb.down>S.day&&S.inc.some(i=>i.type==='power'&&i.ref==='ceb')"), 'a typhoon knocked out Cebu'); + ev('cam.z=5;cam.x=CITY.ceb.x;cam.y=CITY.ceb.y;draw(0)'); + assert.deepEqual(errors, []); +}); From becbd3de8f67382d153e557fda37db8d402a3e65 Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Thu, 29 Oct 2026 22:47:48 +1100 Subject: [PATCH 145/491] Davao: Mindanao, GotchaFIX Davao, and the trans-Pacific landings moved from Manila Davao joins the map on Mindanao, with GotchaFIX Davao and Heimdall's Hut. Mindanao's coastline is now Natural Earth 1:50m (the old simplified ring left Davao in the sea). Bi-Frosted's Philippine branch and SEA-US land at Davao, as the real cables do (Converge's Davao station and Globe's Talomo station), instead of Manila. sanitize() drops the cable tag from saved links on a pair that no longer exists, so those links keep working as plain subsea links. The Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express reach Mindanao's north coast from Cebu and run overland to Davao. PLDTea Time, Snow Globe and Diverge reach Davao. --- CHANGELOG.md | 1 + site/i18n/de.js | 2 ++ site/i18n/es.js | 4 ++- site/i18n/fr.js | 4 ++- site/i18n/it.js | 4 ++- site/i18n/pt.js | 4 ++- src/game/20-world/20-landmasses.js | 3 ++- src/game/20-world/30-coastline.js | 2 +- src/game/20-world/40-city-coords.js | 1 + src/game/20-world/50-cities.js | 1 + src/game/20-world/60-cables.js | 9 ++++--- src/game/30-networks/10-networks.js | 6 ++--- src/game/80-simulation/50-sanitize.js | 2 +- src/i18n/en.js | 4 ++- tests/philippines.test.js | 39 +++++++++++++++++++++++++++ 15 files changed, 71 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b70eef3..6838fd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. - Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe and Diverge reach Cebu, and typhoons can hit it too. +- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. ## [1.37.0] — 2026-10-28 diff --git a/site/i18n/de.js b/site/i18n/de.js index 484d4f0..a3ebbfd 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -431,6 +431,7 @@ "cables.the_sequel_singapore_to_hong_kong":"Die Fortsetzung: Singapur nach Hongkong, Taiwan, Japan und Korea, 2025 in Betrieb genommen.", "cables.the_seychelles_first_cable_to_tanzania":"Das erste Kabel der Seychellen, nach Tansania, nach Jahren mit Satellit.", "cables.the_straightest_line_across_the":"Die geradeste Linie über den Atlantik. Trader zahlen das Doppelte, um ein paar Millisekunden zu sparen.", +"cables.the_upstart_s_own_cable_from":"Das eigene Kabel des Emporkömmlings von Cebu an die Nordküste Mindanaos, dann über Land nach Davao. Verlegt mitten in der Pandemie.", "cables.tokyo_to_los_angeles_built_by":"Tokio nach Los Angeles, gebaut von einer Suchmaschine und fünf Telcos, die Händchen halten.", "cables.up_the_west_coast_of_africa":"Die Westküste Afrikas hinauf. Irgendwas daran ist immer down.", "cables.west_africa_s_first_big_cable":"Westafrikas erstes großes Kabel, von Portugal nach Kapstadt. Alt und wackelig, hält aber immer noch einiges zusammen.", @@ -563,6 +564,7 @@ "cities.mexico_s_data_center_boom_town":"Mexikos Boomtown für Rechenzentren, hoch und trocken mitten im Land. Jede Cloud will hier eine Region.", "cities.mexico_s_industrial_capital_a_few":"Mexikos Industriehauptstadt, ein paar Stunden von Texas. Fabriken, Stahl und gegrillte Ziege am Wochenende.", "cities.mexico_s_silicon_valley_home_of":"Mexikos Silicon Valley, Heimat von Mariachi und Tequila. Tagsüber Chipdesign, nachts Musik.", +"cities.mindanao_s_big_city_and_the":"Mindanaos große Stadt und das Pazifiktor der Philippinen: Hier landen die Transpazifikkabel, südlich des Taifungürtels.", "cities.morocco_s_business_capital_on_the":"Marokkos Wirtschaftshauptstadt am Atlantik, das Tor zwischen Europa und Westafrika.", "cities.most_uae_cables_land_on_this":"Die meisten Kabel der VAE landen an dieser Küste an, außerhalb der Straße von Hormus. Von hier nach Dubai heißt: beim Duopol mieten.", "cities.mountains_mines_and_more_bars_per":"Berge, Minen und mehr Kneipen pro Kopf als irgendwo sonst in Brasilien. Peering-Deals werden bei Käsebrötchen unterschrieben.", diff --git a/site/i18n/es.js b/site/i18n/es.js index e969961..b3f3601 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -273,7 +273,7 @@ "cables.a_friendly_cable_with_french_manners":"Un cable simpático con modales franceses.", "cables.a_gateway_from_europe_to_india":"Una puerta de Europa a la India, por el Mar Rojo. Se pronuncia como un cable muy sorprendido.", "cables.a_quick_hop_across_the_red":"Un salto rápido por el Mar Rojo entre Egipto y Arabia Saudí.", -"cables.a_rainbow_bridge_from_singapore_to":"Un puente arcoíris de Singapur a California, vía Yakarta y Manila.", +"cables.a_rainbow_bridge_from_singapore_to":"Un puente arcoíris de Singapur a California, vía Yakarta, Davao y Guam.", "cables.a_ring_around_the_caribbean_from":"Un anillo alrededor del Caribe, de Florida a Centroamérica, más viejo que la mayoría de sus clientes.", "cables.a_ring_round_east_asia_from":"Un anillo alrededor de Asia oriental desde 2001: Singapur, Hong Kong, Manila, Taipé, Shanghái, Seúl y Tokio.", "cables.a_short_cable_across_a_very":"Un cable corto por un estrecho muy tenso.", @@ -429,6 +429,7 @@ "cables.the_sequel_singapore_to_hong_kong":"La secuela: de Singapur a Hong Kong, Taiwán, Japón y Corea, encendido en 2025.", "cables.the_seychelles_first_cable_to_tanzania":"El primer cable de las Seychelles, hasta Tanzania, tras años de satélite.", "cables.the_straightest_line_across_the":"La línea más recta a través del Atlántico. Los traders pagan el doble por ahorrar unos milisegundos.", +"cables.the_upstart_s_own_cable_from":"El cable propio del recién llegado, de Cebú a la costa norte de Mindanao y luego por tierra hasta Davao. Tendido en plena pandemia.", "cables.tokyo_to_los_angeles_built_by":"De Tokio a Los Ángeles, construido por un buscador y cinco telcos cogidas de la mano.", "cables.up_the_west_coast_of_africa":"Costa oeste de África arriba. Siempre hay algo caído.", "cables.west_africa_s_first_big_cable":"El primer gran cable de África Occidental, de Portugal a Ciudad del Cabo. Viejo y tambaleante, pero sigue sosteniendo cosas.", @@ -561,6 +562,7 @@ "cities.mexico_s_data_center_boom_town":"La ciudad boom de centros de datos de México, alta y seca en medio del país. Todas las nubes quieren una región aquí.", "cities.mexico_s_industrial_capital_a_few":"La capital industrial de México, a pocas horas de Texas. Fábricas, acero y cabrito asado los fines de semana.", "cities.mexico_s_silicon_valley_home_of":"El Silicon Valley de México, cuna del mariachi y el tequila. Diseño de chips de día, música de noche.", +"cities.mindanao_s_big_city_and_the":"La gran ciudad de Mindanao y la puerta de Filipinas al Pacífico: los cables transpacíficos llegan aquí, al sur del cinturón de tifones.", "cities.morocco_s_business_capital_on_the":"La capital de negocios de Marruecos en el Atlántico, puerta entre Europa y África Occidental.", "cities.most_uae_cables_land_on_this":"La mayoría de los cables de los EAU llegan a tierra en esta costa, fuera del Estrecho de Ormuz. Ir de aquí a Dubái significa alquilar al duopolio.", "cities.mountains_mines_and_more_bars_per":"Montañas, minas y más bares por habitante que en cualquier otro lugar de Brasil. Los acuerdos de peering se firman con pan de queso.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 19c991a..e0e6049 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -273,7 +273,7 @@ "cables.a_friendly_cable_with_french_manners":"Un câble sympathique aux manières bien françaises.", "cables.a_gateway_from_europe_to_india":"Une passerelle de l’Europe vers l’Inde, par la mer Rouge. Se prononce comme un câble très surpris.", "cables.a_quick_hop_across_the_red":"Un saut rapide à travers la mer Rouge entre l’Égypte et l’Arabie saoudite.", -"cables.a_rainbow_bridge_from_singapore_to":"Un pont arc-en-ciel de Singapore à la Californie, via Jakarta et Manila.", +"cables.a_rainbow_bridge_from_singapore_to":"Un pont arc-en-ciel de Singapour à la Californie, via Jakarta, Davao et Guam.", "cables.a_ring_around_the_caribbean_from":"Un anneau autour des Caraïbes, de la Floride à l’Amérique centrale, plus vieux que la plupart de ses clients.", "cables.a_ring_round_east_asia_from":"Un anneau autour de l’Asie de l’Est depuis 2001 : Singapour, Hong Kong, Manila, Taipei, Shanghai, Séoul et Tokyo.", "cables.a_short_cable_across_a_very":"Un câble court à travers un détroit très tendu.", @@ -429,6 +429,7 @@ "cables.the_sequel_singapore_to_hong_kong":"La suite : de Singapour à Hong Kong, Taïwan, au Japon et en Corée, allumé en 2025.", "cables.the_seychelles_first_cable_to_tanzania":"Le premier câble des Seychelles, vers la Tanzanie, après des années de satellite.", "cables.the_straightest_line_across_the":"La ligne la plus droite à travers l’Atlantique. Les traders paient le double pour gagner quelques millisecondes.", +"cables.the_upstart_s_own_cable_from":"Le câble maison du nouveau venu, de Cebu à la côte nord de Mindanao, puis par la terre jusqu'à Davao. Posé en pleine pandémie.", "cables.tokyo_to_los_angeles_built_by":"De Tokyo à Los Angeles, construit par un moteur de recherche et cinq opérateurs qui se tiennent la main.", "cables.up_the_west_coast_of_africa":"Remonte la côte ouest de l’Afrique. Tu répares un bout, un autre tombe.", "cables.west_africa_s_first_big_cable":"Le premier grand câble d’Afrique de l’Ouest, du Portugal au Cap. Vieux et bancal, mais il tient encore tout debout.", @@ -561,6 +562,7 @@ "cities.mexico_s_data_center_boom_town":"La ville du boom des datacenters au Mexique, haute et sèche au centre du pays. Chaque cloud y veut sa région.", "cities.mexico_s_industrial_capital_a_few":"La capitale industrielle du Mexique, à quelques heures du Texas. Usines, acier et chevreau grillé le week-end.", "cities.mexico_s_silicon_valley_home_of":"La Silicon Valley du Mexique, berceau du mariachi et de la tequila. Conception de puces le jour, musique la nuit.", +"cities.mindanao_s_big_city_and_the":"La grande ville de Mindanao et la porte des Philippines sur le Pacifique : les câbles transpacifiques atterrissent ici, au sud de la ceinture des typhons.", "cities.morocco_s_business_capital_on_the":"La capitale économique du Maroc sur l’Atlantique, la porte entre l’Europe et l’Afrique de l’Ouest.", "cities.most_uae_cables_land_on_this":"La plupart des câbles des Émirats atterrissent sur cette côte, hors du détroit d’Ormuz. Aller d’ici à Dubai, c’est louer au duopole.", "cities.mountains_mines_and_more_bars_per":"Des montagnes, des mines et plus de bars par habitant que partout ailleurs au Brésil. Les accords de peering se signent autour d’un pão de queijo.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 7dad3d5..1c1a9ce 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -273,7 +273,7 @@ "cables.a_friendly_cable_with_french_manners":"Un cavo amichevole con le buone maniere francesi.", "cables.a_gateway_from_europe_to_india":"Un gateway dall’Europa all’India, attraverso il Mar Rosso. Si pronuncia come un cavo molto sorpreso.", "cables.a_quick_hop_across_the_red":"Un salto veloce attraverso il Mar Rosso tra Egitto e Arabia Saudita.", -"cables.a_rainbow_bridge_from_singapore_to":"Un ponte arcobaleno da Singapore alla California, via Jakarta e Manila.", +"cables.a_rainbow_bridge_from_singapore_to":"Un ponte arcobaleno da Singapore alla California, via Jakarta, Davao e Guam.", "cables.a_ring_around_the_caribbean_from":"Un anello intorno ai Caraibi dalla Florida all’America Centrale, più vecchio della maggior parte dei suoi clienti.", "cables.a_ring_round_east_asia_from":"Un anello intorno all’Asia orientale dal 2001: Singapore, Hong Kong, Manila, Taipei, Shanghai, Seul e Tokyo.", "cables.a_short_cable_across_a_very":"Un cavo corto attraverso uno stretto molto teso.", @@ -429,6 +429,7 @@ "cables.the_sequel_singapore_to_hong_kong":"Il sequel: da Singapore a Hong Kong, Taiwan, Giappone e Corea, acceso nel 2025.", "cables.the_seychelles_first_cable_to_tanzania":"Il primo cavo delle Seychelles, verso la Tanzania, dopo anni di satellite.", "cables.the_straightest_line_across_the":"La linea più dritta attraverso l’Atlantico. I trader pagano il doppio per risparmiare qualche millisecondo.", +"cables.the_upstart_s_own_cable_from":"Il cavo tutto suo del nuovo arrivato, da Cebu alla costa nord di Mindanao, poi via terra fino a Davao. Posato durante una pandemia.", "cables.tokyo_to_los_angeles_built_by":"Da Tokyo a Los Angeles, costruito da un motore di ricerca e cinque telco che si tengono per mano.", "cables.up_the_west_coast_of_africa":"Risale la costa ovest dell’Africa. C’è sempre qualcosa giù.", "cables.west_africa_s_first_big_cable":"Il primo grande cavo dell’Africa occidentale, dal Portogallo a Città del Capo. Vecchio e traballante, ma regge ancora tutto.", @@ -561,6 +562,7 @@ "cities.mexico_s_data_center_boom_town":"La città del boom dei data center in Messico, alta e asciutta nel centro del paese. Ogni cloud vuole una region qui.", "cities.mexico_s_industrial_capital_a_few":"La capitale industriale del Messico, a poche ore dal Texas. Fabbriche, acciaio e capretto alla griglia nel weekend.", "cities.mexico_s_silicon_valley_home_of":"La Silicon Valley del Messico, patria del mariachi e della tequila. Progettazione di chip di giorno, musica di notte.", +"cities.mindanao_s_big_city_and_the":"La grande città di Mindanao e la porta delle Filippine sul Pacifico: i cavi transpacifici approdano qui, a sud della fascia dei tifoni.", "cities.morocco_s_business_capital_on_the":"La capitale economica del Marocco sull’Atlantico, la porta tra l’Europa e l’Africa occidentale.", "cities.most_uae_cables_land_on_this":"Quasi tutti i cavi degli Emirati approdano su questa costa, fuori dallo Stretto di Hormuz. Andare da qui a Dubai vuol dire affittare dal duopolio.", "cities.mountains_mines_and_more_bars_per":"Montagne, miniere e più bar per abitante che in qualsiasi altro posto del Brasile. Gli accordi di peering si firmano davanti al pane al formaggio.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 41510d7..a54447d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -273,7 +273,7 @@ "cables.a_friendly_cable_with_french_manners":"Um cabo simpático com bons modos franceses.", "cables.a_gateway_from_europe_to_india":"Um gateway da Europa à Índia pelo Mar Vermelho. Pronuncia-se como um cabo muito surpreso.", "cables.a_quick_hop_across_the_red":"Um pulinho pelo Mar Vermelho entre o Egito e a Arábia Saudita.", -"cables.a_rainbow_bridge_from_singapore_to":"Uma ponte de arco-íris de Singapura à Califórnia, via Jakarta e Manila.", +"cables.a_rainbow_bridge_from_singapore_to":"Uma ponte de arco-íris de Singapura à Califórnia, via Jakarta, Davao e Guam.", "cables.a_ring_around_the_caribbean_from":"Um anel ao redor do Caribe, da Flórida à América Central, mais velho que a maioria dos clientes.", "cables.a_ring_round_east_asia_from":"Um anel ao redor do Leste Asiático desde 2001: Singapura, Hong Kong, Manila, Taipei, Xangai, Seul e Tóquio.", "cables.a_short_cable_across_a_very":"Um cabo curto atravessando um estreito bem tenso.", @@ -429,6 +429,7 @@ "cables.the_sequel_singapore_to_hong_kong":"A continuação: de Singapura a Hong Kong, Taiwan, Japão e Coreia, aceso em 2025.", "cables.the_seychelles_first_cable_to_tanzania":"O primeiro cabo das Seychelles, até a Tanzânia, depois de anos de satélite.", "cables.the_straightest_line_across_the":"A linha mais reta através do Atlântico. Traders pagam o dobro para economizar alguns milissegundos.", +"cables.the_upstart_s_own_cable_from":"O cabo próprio da novata, de Cebu à costa norte de Mindanao e depois por terra até Davao. Lançado numa pandemia.", "cables.tokyo_to_los_angeles_built_by":"De Tóquio a Los Angeles, construído por um buscador e cinco operadoras de mãos dadas.", "cables.up_the_west_coast_of_africa":"Sobe a costa oeste da África. Sempre tem alguma coisa fora do ar.", "cables.west_africa_s_first_big_cable":"O primeiro grande cabo da África Ocidental, de Portugal à Cidade do Cabo. Velho e bambo, mas ainda segurando as pontas.", @@ -561,6 +562,7 @@ "cities.mexico_s_data_center_boom_town":"A cidade do boom de data centers no México, alta e seca no meio do país. Toda nuvem quer uma região aqui.", "cities.mexico_s_industrial_capital_a_few":"A capital industrial do México, a poucas horas do Texas. Fábricas, aço e cabrito assado no fim de semana.", "cities.mexico_s_silicon_valley_home_of":"O Vale do Silício do México, terra do mariachi e da tequila. Projeto de chips de dia, música à noite.", +"cities.mindanao_s_big_city_and_the":"A grande cidade de Mindanao e a porta das Filipinas para o Pacífico: os cabos transpacíficos chegam aqui, ao sul do cinturão de tufões.", "cities.morocco_s_business_capital_on_the":"A capital dos negócios do Marrocos no Atlântico, a porta entre a Europa e a África Ocidental.", "cities.most_uae_cables_land_on_this":"A maioria dos cabos dos Emirados chega nesta costa, fora do Estreito de Ormuz. Ir daqui até Dubai significa alugar do duopólio.", "cities.mountains_mines_and_more_bars_per":"Montanhas, minas e mais bares por habitante do que em qualquer outro lugar do Brasil. Acordo de peering se fecha com pão de queijo.", diff --git a/src/game/20-world/20-landmasses.js b/src/game/20-world/20-landmasses.js index 38f06aa..fb62801 100644 --- a/src/game/20-world/20-landmasses.js +++ b/src/game/20-world/20-landmasses.js @@ -79,8 +79,9 @@ LANDS_LL.push( LANDS_LL.push( {id:'mv',ll:[[73.11,4.48],[73.91,4.48],[73.91,3.88],[73.11,3.88]]}, ); -// The Visayas: Cebu is its own island, reached from Luzon only by domestic cable. +// The Visayas and Mindanao: Cebu and Davao are islands of their own, reached from Luzon only by cable. LANDS_LL.push( {id:'ceb',ll:[[123.3,11.3],[124.1,11.3],[124.1,9.4],[123.3,9.4]]}, + {id:'mdn',ll:[[121.9,7],[123,8.4],[125.4,9.8],[126.6,7.5],[126.2,5.6],[125,5.6],[122,6.6]]}, ); const LANDS=LANDS_LL.map(l=>({id:l.id,hide:true,pts:l.ll.map(q=>proj(q[0],q[1]))})); diff --git a/src/game/20-world/30-coastline.js b/src/game/20-world/30-coastline.js index 594ed80..28274b1 100644 --- a/src/game/20-world/30-coastline.js +++ b/src/game/20-world/30-coastline.js @@ -1,6 +1,6 @@ // Drawn coastline: Natural Earth 1:50m land, simplified (tight around cities, looser elsewhere), lon/lat rings. Built by scripts/build-land.mjs. // LANDS above is only the coarse landmass test that decides which landmass a city sits on (subsea vs overland); it is not drawn. -const COAST_LL=[[[86.89,73.89],[85.79,73.44],[86.68,73.11],[85.91,73.39],[87.57,73.81],[86,74.32],[87.23,74.36],[85.79,74.65],[87.47,75.01],[87.01,75.17],[94.16,75.96],[92.86,75.98],[93.26,76.1],[95.58,76.14],[96.08,76.08],[95.65,75.89],[96.5,75.89],[98.66,76.24],[99.77,76.03],[99.54,75.8],[99.82,76.14],[98.8,76.48],[101.6,76.44],[100.93,76.56],[101.1,76.7],[100.91,76.9],[104.01,77.73],[106.06,77.39],[104.2,77.1],[107.43,76.93],[106.42,76.51],[111.11,76.72],[112.62,76.38],[112.66,76.05],[113.27,76.25],[113.56,75.89],[113.86,75.92],[113.57,75.57],[112.45,75.83],[113.73,75.45],[112.92,75.02],[107.27,73.62],[105.14,72.78],[110.87,73.73],[109.67,73.8],[110.26,74.02],[111.55,74.03],[111.23,73.97],[112.15,73.71],[113.03,73.91],[113.42,73.65],[113.16,73.46],[113.49,73.35],[113.16,72.77],[113.67,72.64],[113.22,72.81],[113.89,73.35],[113.51,73.5],[114.06,73.58],[118.45,73.59],[118.94,73.48],[118.46,73.46],[118.43,73.25],[119.75,72.98],[122.54,72.88],[123.62,73.19],[123.32,73.43],[123.41,73.64],[124.54,73.75],[126.55,73.33],[127.74,73.48],[129.1,73.11],[128.6,72.9],[129.25,72.7],[128.42,72.53],[129.28,72.44],[129.28,72.09],[127.73,72.41],[128.91,71.75],[129.21,71.92],[129.46,71.74],[128.84,71.66],[129.76,71.12],[131.02,70.75],[132.04,71.24],[132.65,71.93],[133.69,71.43],[136.09,71.62],[137.94,71.13],[138.32,71.33],[137.92,71.38],[138.23,71.6],[139.99,71.49],[139.72,71.89],[139.36,71.95],[140.19,72.19],[139.18,72.16],[139.14,72.33],[141.08,72.59],[140.65,72.84],[140.81,72.89],[146.25,72.44],[144.29,72.19],[146.83,72.29],[146.11,71.95],[146.23,72.14],[145.76,72.23],[145.76,71.94],[145.07,71.93],[145.19,71.7],[147.26,72.33],[149.5,72.16],[150.02,71.9],[148.92,71.71],[150.67,71.45],[150.1,71.23],[151.58,71.29],[152.09,71.02],[151.76,70.98],[152.51,70.83],[155.89,71.1],[158.7,70.94],[159.91,70.51],[159.83,69.78],[160.91,69.61],[161.34,68.9],[160.86,68.54],[161.56,68.9],[161.54,69.38],[163.2,69.72],[166.89,69.5],[167.86,69.73],[168.3,69.27],[169.31,69.08],[169.61,68.79],[170.54,68.83],[171,69.14],[170.58,69.58],[170.16,69.63],[170.49,70.11],[173.28,69.82],[175.92,69.9],[179.87,69.01],[180,68.98],[181.13,68.75],[181.94,68.27],[182.2,68.34],[181.63,68.57],[184.65,67.68],[184.63,67.36],[185.15,67.35],[185.08,66.62],[185.61,66.34],[185.91,66.47],[185.94,66.23],[186.22,66.43],[185.77,66.63],[185.91,66.94],[185.45,67.09],[186.84,67.07],[186.74,66.84],[187.48,66.95],[186.99,67.06],[188.2,66.93],[189.4,66.25],[190.27,66.06],[189.6,65.93],[189.33,65.62],[188.55,65.79],[188.83,65.5],[187.22,65.68],[187.77,65.45],[187.34,65.25],[187.79,65.05],[186.93,64.85],[187.62,64.43],[187.1,64.53],[186.84,64.28],[186.67,64.54],[186.27,64.36],[184.56,64.82],[183.91,65.47],[181.59,65.49],[181.06,66.03],[181.47,66.4],[181.08,66.18],[180.86,66.37],[180.22,66.02],[180.65,65.52],[179.45,64.82],[178.52,64.6],[176.41,65.07],[177.22,64.86],[176.06,64.96],[174.55,64.68],[175.68,64.78],[176.06,64.9],[176.25,64.84],[176.35,64.71],[176.14,64.59],[176.51,64.68],[176.84,64.63],[177.05,64.72],[177.39,64.77],[177.47,64.74],[177.41,64.57],[177.43,64.44],[177.95,64.22],[178.13,64.24],[178.23,64.36],[178.38,64.26],[178.48,64.13],[178.45,64.01],[178.65,63.97],[178.69,63.84],[178.47,63.57],[179.33,63.19],[179.57,62.77],[179.12,62.32],[177.02,62.78],[177.16,62.56],[172.86,61.47],[172.39,61.06],[170.61,60.43],[170.35,59.97],[169.23,60.6],[167.23,60.41],[166.27,59.86],[166.35,60.48],[165.09,60.1],[164.96,59.84],[163.74,60.03],[161.96,58.08],[162.39,57.72],[162.66,57.95],[163.23,57.79],[162.76,57.24],[162.8,56.81],[163.26,56.69],[163.34,56.23],[162.84,56.06],[162.63,56.23],[163.04,56.52],[162.67,56.49],[162.09,56.09],[161.72,55.5],[162.1,54.75],[160.07,54.19],[159.84,53.78],[159.96,53.55],[159.9,53.38],[160,53.27],[160.03,53.13],[159.95,53.13],[159.77,53.23],[159.59,53.24],[158.95,53.05],[158.75,52.91],[158.56,53.05],[158.47,53.03],[158.43,52.96],[158.61,52.87],[158.48,52.63],[158.49,52.38],[158.33,52.09],[158.1,51.81],[156.75,50.97],[155.56,55.2],[156.02,56.75],[156.85,57.29],[156.87,57.8],[158.27,58.01],[162.07,60.47],[163.71,60.92],[163.56,61.03],[164.01,61.34],[163.8,61.46],[164.21,62.29],[165.4,62.49],[164.42,62.71],[163.33,62.55],[163.09,61.57],[162.39,61.66],[160.17,60.64],[160.38,61.02],[159.79,60.96],[160.31,61.89],[157.09,61.68],[154.29,59.83],[154.15,59.53],[154.97,59.45],[155.16,59.19],[153.36,59.21],[152.82,58.93],[151.33,58.88],[151.12,59.08],[152.26,59.22],[149.64,59.77],[148.8,59.53],[148.96,59.37],[148.73,59.26],[146.54,59.46],[146.05,59.17],[145.55,59.41],[142.58,59.24],[140.79,58.3],[140.45,57.81],[138.66,56.97],[137.69,56.14],[135.26,54.94],[135.26,54.73],[135.85,54.58],[136.8,54.62],[136.72,53.8],[137.16,53.82],[137.14,54.18],[137.67,54.28],[137.34,54.1],[137.84,53.95],[137.25,53.55],[137.95,53.6],[138.53,53.96],[138.25,53.52],[138.45,53.54],[138.66,54.3],[139.71,54.28],[141.38,53.29],[141.18,53.01],[140.84,53.09],[141.26,52.84],[141.13,52.43],[141.49,52.18],[140.52,50.8],[140.38,48.96],[138.11,46.25],[135.13,43.53],[133.16,42.7],[133.06,42.72],[133,42.81],[132.86,42.79],[132.71,42.88],[132.3,42.88],[132.31,43.31],[132.03,43.12],[131.87,43.1],[132.01,43.28],[131.94,43.3],[131.72,43.2],[131.39,42.82],[131.16,42.63],[130.71,42.66],[130.83,42.52],[130.73,42.33],[129.76,41.71],[129.71,40.86],[127.57,39.78],[127.4,39.21],[128.33,38.68],[129.42,37.06],[129.56,35.95],[129.21,35.18],[128.51,35.1],[128.44,34.87],[127.71,34.96],[127.72,34.72],[127.4,34.82],[127.32,34.46],[127.25,34.76],[126.53,34.31],[126.27,34.67],[126.59,34.82],[126.29,35.15],[126.69,36.01],[126.54,36.17],[126.55,36.48],[126.49,36.69],[126.39,36.65],[126.18,36.69],[126.16,36.77],[126.22,36.87],[126.49,37.01],[126.78,36.95],[126.87,36.82],[126.98,36.94],[126.87,36.98],[126.74,37.19],[126.79,37.3],[126.65,37.45],[126.66,37.55],[126.56,37.72],[126.63,37.78],[126.37,37.88],[126.12,37.74],[126.05,37.87],[125.94,37.87],[125.77,37.99],[125.41,37.72],[124.99,37.93],[125.21,38.08],[124.69,38.13],[125.55,38.69],[125.17,38.81],[125.36,39.53],[124.64,39.61],[124.35,40.01],[122.84,39.6],[121.16,38.73],[121.11,38.92],[121.82,39.39],[121.27,39.55],[122.26,40.5],[121.83,40.97],[121.18,40.9],[120.48,40.23],[119.39,39.75],[118.98,39.18],[117.78,39.13],[117.65,38.42],[118.94,38.04],[119.11,37.2],[119.76,37.15],[120.75,37.83],[121.64,37.46],[122.67,37.4],[122.34,36.83],[121.93,36.96],[120.81,36.63],[120.64,36.13],[120.18,36.2],[120.29,35.98],[119.22,35.01],[119.2,34.75],[120.27,34.27],[120.86,32.66],[121.34,32.43],[121.4,32.37],[121.45,32.15],[121.68,32.05],[121.83,31.9],[121.87,31.7],[121.76,31.7],[121.35,31.86],[120.97,31.87],[120.79,32.03],[120.52,32.11],[120.07,31.96],[120.19,31.91],[120.5,32.02],[120.71,31.98],[120.79,31.82],[121.06,31.72],[121.66,31.32],[121.79,31.16],[121.88,30.92],[121.42,30.79],[121,30.56],[120.82,30.35],[120.45,30.39],[120.23,30.25],[120.5,30.3],[120.63,30.13],[120.91,30.16],[121.16,30.3],[121.26,30.3],[121.43,30.23],[121.68,29.98],[122.08,29.87],[121.91,29.78],[121.51,29.48],[121.97,29.49],[121.92,29.13],[121.45,29.13],[121.68,28.95],[121.47,28.64],[121.61,28.29],[121.15,28.33],[120.75,28.01],[120.09,26.67],[119.59,26.79],[119.88,26.33],[119.14,26.12],[119.62,26],[119.62,25.39],[119.18,25.45],[119.29,25.23],[118.98,25.21],[118.66,24.62],[117.84,24.47],[118.06,24.25],[117.37,23.59],[116.91,23.65],[116.47,22.95],[115.64,22.85],[115.5,22.72],[115.38,22.72],[115.2,22.82],[114.85,22.62],[114.75,22.63],[114.71,22.74],[114.65,22.75],[114.54,22.62],[114.55,22.53],[114.34,22.59],[114.27,22.54],[114.34,22.4],[114.27,22.3],[113.9,22.4],[114.01,22.51],[113.83,22.61],[113.62,22.86],[113.62,23.13],[113.45,23.05],[113.44,22.94],[113.33,22.91],[113.55,22.59],[113.59,22.35],[113.55,22.22],[113.15,22.08],[113.09,22.21],[113.01,22.12],[112.99,21.94],[112.9,21.88],[112.81,21.95],[112.66,21.86],[112.36,21.98],[112.3,21.74],[111.94,21.85],[111.6,21.56],[110.41,21.34],[110.16,20.94],[110.52,20.46],[110.12,20.26],[109.66,20.92],[109.93,21.48],[109.52,21.69],[109.08,21.44],[108.48,21.9],[108.5,21.63],[107.81,21.5],[107.16,20.95],[106.68,21],[106.52,20.29],[105.98,19.94],[105.62,18.97],[106.5,17.95],[106.35,17.77],[108.82,15.38],[109.3,13.86],[109.45,12.6],[109.22,12.65],[109.2,11.73],[108.99,11.34],[108.18,10.92],[108.1,10.9],[108,10.72],[107.84,10.7],[107.26,10.4],[107.09,10.5],[107.01,10.66],[106.95,10.4],[106.81,10.43],[106.73,10.54],[106.61,10.47],[106.74,10.44],[106.76,10.3],[106.47,10.3],[106.73,10.19],[106.79,10.12],[106.6,9.86],[106.14,10.22],[106.51,9.82],[106.57,9.64],[106.48,9.56],[106.38,9.56],[105.83,10],[106.16,9.59],[106.21,9.5],[106.17,9.4],[104.77,8.6],[105.03,10.07],[104.26,10.54],[103.59,10.55],[103.65,11.06],[103.15,10.91],[103.12,11.46],[102.65,12.15],[101.72,12.69],[101.44,12.62],[100.9,12.65],[100.86,12.72],[100.96,13.43],[100.6,13.57],[100.54,13.51],[100.23,13.48],[100.02,13.35],[99.99,13.24],[100.09,13.04],[99.96,12.69],[100.01,12.35],[99.16,10.32],[99.25,9.27],[99.83,9.29],[100.42,7.19],[101.5,6.86],[103.2,5.26],[103.45,4.67],[103.48,2.84],[103.81,2.58],[104.22,1.72],[104.28,1.42],[104.18,1.37],[103.98,1.62],[103.99,1.46],[103.69,1.45],[103.48,1.33],[103.36,1.55],[102.73,1.86],[102.55,2.04],[102.15,2.25],[101.78,2.57],[101.52,2.68],[101.3,2.89],[101.35,3.01],[101.3,3.25],[100.72,3.97],[100.8,4.02],[100.66,4.23],[100.26,6.18],[99.6,7.36],[98.24,8.42],[98.7,10.19],[98.56,10.03],[98.47,10.68],[98.88,11.72],[98.64,11.74],[98.57,13.16],[98.2,13.98],[98.11,13.71],[97.81,14.86],[97.58,16.02],[97.72,16.57],[97.38,16.52],[96.85,17.4],[96.77,16.71],[96.43,16.5],[96.19,16.77],[96.32,16.44],[95.39,15.72],[95.35,16.1],[95.18,15.83],[94.94,15.82],[94.89,16.18],[94.66,15.9],[94.7,16.51],[94.23,16.02],[94.59,17.57],[94.05,19.29],[93.93,18.9],[93.49,19.37],[93.83,19.24],[94,19.44],[93.71,19.91],[93.25,20.07],[93.13,19.86],[93.07,20.38],[92.83,20.18],[92.74,20.56],[92.72,20.3],[92.31,20.79],[91.86,22.35],[91.53,22.71],[91.48,22.88],[91.22,22.64],[90.95,22.6],[90.63,23.09],[90.6,23.59],[90.56,23.42],[90.27,23.46],[90.59,23.27],[90.6,23.13],[90.47,23.05],[90.55,22.91],[90.46,22.88],[90.43,22.75],[90.61,22.36],[90.55,22.22],[90.16,21.82],[90.21,22.16],[89.96,22.02],[89.89,22.31],[89.98,22.47],[89.88,22.39],[89.57,21.77],[89.48,22.28],[89.35,21.72],[89.05,22.09],[89.05,21.65],[88.75,21.58],[88.64,22.12],[88.58,21.66],[88.06,21.69],[88.2,22.14],[87.94,22.37],[88.16,22.12],[87.95,21.83],[86.86,21.24],[86.98,20.7],[86.75,20.31],[86.22,19.9],[85.25,19.76],[85.18,19.59],[85.44,19.63],[84.11,18.29],[82.36,17.1],[82.26,16.56],[81.29,16.34],[80.98,15.76],[80.38,15.79],[80.1,14.8],[80.18,14.48],[80.11,14.21],[80.31,13.49],[80.16,13.71],[80.06,13.61],[80.34,13.36],[80.23,12.69],[80.14,12.45],[79.86,11.99],[79.84,10.32],[79.31,10.26],[78.92,9.45],[79.41,9.19],[78.42,9.1],[78.06,8.38],[77.3,8.15],[76.4,9.24],[76.35,9.92],[74.94,12.56],[74.38,14.49],[73.47,16.05],[73.15,17.53],[72.87,18.64],[73.01,19.02],[72.97,19.15],[72.83,18.98],[72.8,19.08],[72.81,19.3],[72.99,19.28],[72.79,19.36],[72.75,19.45],[72.8,19.52],[72.73,19.58],[72.67,19.83],[72.9,20.67],[72.61,21.46],[73.11,21.75],[72.54,21.7],[72.7,21.97],[72.52,21.98],[72.81,22.23],[72.18,22.27],[72.04,21.82],[72.25,21.53],[72.02,21.16],[70.72,20.74],[68.97,22.29],[70.18,22.57],[70.49,23.09],[69.67,22.76],[69.24,22.85],[68.42,23.57],[68.78,23.85],[68.23,23.6],[68.16,23.86],[68.11,23.75],[68.04,23.85],[67.95,23.83],[67.86,23.9],[67.82,23.83],[67.67,23.81],[67.65,23.92],[67.56,23.88],[67.31,24.17],[67.17,24.76],[66.7,24.86],[66.7,25.23],[66.43,25.58],[66.22,25.59],[66.13,25.49],[66.36,25.51],[66.47,25.45],[66.24,25.46],[65.68,25.35],[61.41,25.1],[60.51,25.44],[59.05,25.42],[57.34,25.79],[57.21,26.04],[57.2,26.16],[56.73,27.13],[56.28,27.19],[55.42,26.77],[55.29,26.79],[54.9,26.56],[54.64,26.51],[54.52,26.59],[53.71,26.73],[52.48,27.62],[51.52,27.91],[50.07,30.2],[49.56,30.03],[49,30.51],[48.83,30.04],[47.98,30.01],[48.15,29.57],[47.72,29.39],[48.05,29.35],[48.8,27.72],[50.15,26.66],[50.15,26.1],[50.1,26.12],[50.08,25.96],[50.24,25.62],[50.46,25.42],[50.56,25.09],[50.81,24.79],[50.85,24.89],[50.76,25.45],[51,25.98],[51.26,26.15],[51.54,25.9],[51.57,25.78],[51.49,25.53],[51.61,25.05],[51.43,24.67],[51.27,24.61],[51.42,24.53],[51.31,24.34],[51.54,24.29],[51.6,24.34],[51.67,24.25],[51.77,24.25],[51.84,24.01],[52.12,23.97],[52.51,24.11],[53.03,24.15],[53.89,24.08],[54.4,24.28],[54.75,24.81],[55.1,25.04],[55.52,25.5],[55.94,25.79],[56.17,26.21],[56.31,26.24],[56.41,26.35],[56.37,25.8],[56.3,25.65],[56.36,25.57],[56.37,25.02],[56.64,24.47],[56.91,24.15],[57.22,23.92],[58.58,23.64],[59.84,22.42],[58.47,20.41],[58.17,20.59],[57.86,20.24],[57.81,19.02],[56.82,18.75],[56.38,17.99],[55.48,17.84],[55.06,17.04],[54.07,17],[52.45,16.39],[52.22,15.66],[51.6,15.34],[49.35,14.64],[48.67,14.05],[45.66,13.34],[45.04,12.82],[44.26,12.64],[43.49,12.7],[42.94,14.94],[42.66,15.23],[42.7,16.74],[41.66,18.01],[40.76,19.75],[40.08,20.27],[39.88,20.29],[39.73,20.39],[39.27,20.97],[39.09,21.31],[39.15,21.52],[38.99,21.88],[39.09,22.39],[39.01,22.77],[38.88,22.88],[38.94,22.88],[38.29,23.91],[37.54,24.29],[37.15,25.29],[35.18,28.04],[34.62,28.06],[34.97,29.55],[34.22,27.76],[33.25,28.57],[32.72,29.52],[32.56,29.97],[32.47,29.93],[32.49,29.85],[32.36,29.63],[32.4,29.53],[32.56,29.39],[32.66,28.93],[33.55,27.9],[33.96,26.65],[35.2,24.47],[35.78,23.94],[35.51,23.78],[35.7,22.95],[36.83,22.1],[37.26,21.11],[37.47,18.82],[38.57,18.07],[39.5,15.53],[39.79,15.12],[39.86,15.47],[40.2,15.01],[41.18,14.62],[43.3,12.46],[43.34,12.03],[42.54,11.51],[43.16,11.57],[44.28,10.47],[44.94,10.44],[45.82,10.84],[46.56,10.75],[47.4,11.17],[50.11,11.53],[50.79,11.98],[51.26,11.83],[51.03,10.44],[51.39,10.39],[50.93,10.34],[50.82,9.43],[47.98,4.5],[46.05,2.47],[43.72,0.86],[41.39,-1.87],[40.22,-2.69],[39.23,-4.67],[38.8,-6.07],[39.54,-7.02],[39.29,-7.52],[39.3,-8.44],[39.72,-10],[40.61,-10.66],[40.43,-12.94],[40.83,-14.79],[39.84,-16.44],[37.51,-17.57],[36.41,-18.77],[34.95,-19.81],[34.65,-19.7],[35.31,-22.4],[35.45,-22.12],[35.54,-22.3],[35.44,-24.17],[34.99,-24.65],[32.79,-25.64],[32.59,-26],[32.85,-26.27],[32.96,-26.08],[32.89,-26.83],[32.38,-28.5],[31.34,-29.38],[29.97,-31.32],[27.86,-33.05],[26.61,-33.71],[25.81,-33.74],[25.57,-34.04],[22.55,-34.01],[21.79,-34.37],[19.64,-34.75],[19.39,-34.6],[19.3,-34.62],[19.33,-34.49],[19.24,-34.41],[19.15,-34.42],[19.1,-34.35],[18.83,-34.36],[18.81,-34.11],[18.75,-34.08],[18.53,-34.09],[18.46,-34.17],[18.46,-34.35],[18.41,-34.3],[18.33,-34.07],[18.35,-33.94],[18.47,-33.89],[18.43,-33.72],[18.26,-33.42],[18.16,-33.36],[17.88,-32.96],[17.85,-32.83],[17.89,-32.75],[17.97,-32.71],[18.04,-32.78],[18.12,-32.75],[18.25,-32.65],[18.33,-32.5],[18.21,-31.74],[16.74,-29.01],[15.29,-27.28],[14.5,-24.2],[14.46,-22.45],[11.78,-18],[11.75,-15.83],[12.55,-13.44],[13.79,-11.81],[13.83,-10.93],[13,-9.05],[13.38,-8.37],[12.28,-6.12],[13.07,-5.87],[12.45,-6],[12.24,-5.81],[11.78,-4.57],[9.72,-2.47],[10.06,-2.55],[9.62,-2.37],[9.04,-1.31],[9.5,-1.55],[9.06,-1.3],[8.7,-0.59],[8.95,-0.69],[9.3,-0.35],[9.35,0.34],[9.8,0.04],[10,0.2],[9.33,0.55],[9.62,0.58],[9.6,1.05],[9.39,1.14],[9.81,1.93],[9.95,3.08],[9.56,3.8],[9.69,4.06],[9,4.09],[8.92,4.55],[8.57,4.53],[8.25,4.92],[8.29,4.56],[7.08,4.72],[6.92,4.39],[6.77,4.72],[6.86,4.37],[6.08,4.29],[5.49,4.84],[5.37,5.34],[5.55,5.47],[5.2,5.53],[5.46,5.61],[5.11,5.64],[4.86,6.03],[4.43,6.35],[4.13,6.41],[3.45,6.43],[3.75,6.58],[3.72,6.6],[3.43,6.52],[3.34,6.4],[1.82,6.26],[-2,4.76],[-3.25,5.11],[-3.02,5.13],[-3.2,5.35],[-3.35,5.13],[-5.28,5.21],[-5.06,5.13],[-7.54,4.35],[-8.26,4.59],[-11.73,7.09],[-12.49,7.39],[-12.48,7.75],[-12.85,7.82],[-13.27,8.43],[-12.89,8.63],[-13.18,8.58],[-13.06,8.88],[-13.69,9.54],[-13.69,9.93],[-14.43,10.25],[-14.59,10.77],[-14.89,10.97],[-15.01,10.8],[-15.05,11.14],[-15.39,11.22],[-15.43,11.5],[-15.07,11.6],[-15.5,11.78],[-15.08,11.97],[-15.94,11.79],[-16.79,12.47],[-16.44,12.61],[-16.77,12.63],[-16.75,13.43],[-16.41,13.27],[-15.43,13.47],[-16.44,13.35],[-16.77,13.9],[-16.62,14.04],[-17.53,14.75],[-16.57,15.73],[-16.08,17.55],[-16.09,18.52],[-16.52,19.36],[-16.21,20.23],[-16.88,21.09],[-17.1,20.86],[-16.93,21.9],[-16.36,22.59],[-15.9,23.84],[-14.91,24.72],[-14.47,26.16],[-13.58,26.74],[-12.95,27.91],[-11.55,28.31],[-10.2,29.38],[-9.67,30.11],[-9.81,31.42],[-9.25,32.57],[-8.51,33.25],[-6.9,33.97],[-5.92,35.79],[-5.28,35.9],[-5.25,35.61],[-4.63,35.21],[-2.97,35.41],[-2.84,35.13],[-1.91,35.09],[1.26,36.52],[3.78,36.9],[5.29,36.65],[6.49,37.09],[7.91,36.86],[9.69,37.34],[9.83,37.14],[10.2,37.21],[10.41,36.73],[10.95,37.06],[11.13,36.87],[10.49,36.26],[11.12,35.24],[10.06,34.21],[10.31,33.73],[10.96,33.63],[11.2,33.25],[12.28,32.86],[13.28,32.92],[15.18,32.39],[15.71,31.43],[17.83,30.93],[18.94,30.29],[19.59,30.41],[20.01,30.8],[19.93,31.82],[20.12,32.22],[21.63,32.94],[23.09,32.62],[23.29,32.21],[24.88,31.98],[25.23,31.53],[26.77,31.47],[29.07,30.83],[30.22,31.26],[30.57,31.47],[30.92,31.57],[30.56,31.42],[31,31.46],[31.08,31.6],[32.14,31.34],[31.89,31.48],[31.77,31.29],[32.01,31.22],[32.1,31.09],[32.28,31.2],[32.21,31.29],[32.6,31.07],[33.67,31.13],[34.48,31.59],[35.98,34.55],[35.81,36.31],[36.18,36.81],[35.39,36.57],[34.7,36.82],[33.69,36.18],[32.79,36.04],[31.24,36.82],[30.65,36.87],[30.45,36.27],[29.69,36.16],[28.97,36.72],[27.46,36.71],[28.24,37.03],[27.26,36.98],[27.53,37.16],[27.07,37.66],[27.23,37.98],[26.29,38.28],[26.44,38.64],[26.67,38.34],[27.14,38.45],[26.76,38.71],[27.01,38.89],[26.68,39.29],[26.9,39.55],[26.09,39.52],[26.18,39.99],[26.74,40.4],[27.73,40.33],[27.85,40.38],[27.73,40.48],[27.99,40.49],[27.93,40.38],[27.96,40.37],[29.01,40.39],[29.05,40.42],[28.79,40.53],[29.05,40.65],[29.85,40.74],[29.36,40.81],[29.12,40.94],[29.05,41.01],[29.15,41.22],[29.92,41.15],[30.35,41.2],[31.25,41.11],[33.28,42],[35,42.06],[35.3,41.73],[36.05,41.68],[36.41,41.27],[38.38,40.93],[39.43,41.11],[40.13,40.94],[41.41,41.42],[41.76,41.97],[41.42,42.74],[38.72,44.29],[36.63,45.15],[36.87,45.43],[37.65,45.38],[37.93,46],[38.49,46.09],[37.77,46.64],[38.5,46.66],[38.44,46.81],[39.27,47.04],[39.02,47.27],[35.83,46.62],[35.02,46.11],[35.23,46.44],[34.85,46.19],[35.02,45.7],[35.46,45.32],[36.57,45.39],[36.39,45.07],[35.47,45.1],[33.91,44.39],[33.45,44.55],[33.55,45.1],[32.51,45.4],[33.67,45.95],[33.59,46.1],[31.83,46.28],[32.01,46.43],[31.56,46.56],[32.58,46.62],[32.05,46.64],[31.76,47.21],[31.87,46.65],[30.8,46.55],[30.22,45.87],[29.63,45.72],[29.56,44.84],[28.89,44.92],[28.56,43.5],[28.13,43.4],[27.89,42.75],[27.48,42.47],[27.98,42.05],[27.99,41.86],[28.2,41.56],[29.06,41.23],[28.96,41.01],[28.78,40.97],[28.17,41.08],[27.92,40.99],[27.5,40.97],[27.43,40.84],[26.2,40.07],[26.79,40.63],[24.48,40.95],[23.76,40.75],[24.34,40.15],[23.73,40.33],[23.95,39.97],[23.43,40.26],[23.63,39.92],[22.81,40.58],[22.59,40.04],[23.23,39.36],[23.33,39.18],[23.22,39.1],[23.12,39.13],[23.16,39.26],[22.99,39.33],[22.84,39.26],[22.97,39.03],[23.07,39.04],[22.8,38.9],[22.57,38.87],[23.25,38.66],[23.37,38.53],[23.57,38.49],[23.68,38.35],[23.97,38.27],[24.06,37.82],[24.05,37.71],[23.97,37.68],[23.5,38.03],[23.03,37.88],[23.15,37.8],[23.2,37.62],[23.39,37.58],[23.49,37.44],[23.16,37.33],[23.1,37.36],[23.1,37.44],[22.94,37.52],[22.78,37.59],[22.73,37.54],[23.06,36.85],[23.04,36.64],[23.11,36.55],[22.83,36.69],[22.78,36.79],[22.72,36.79],[22.49,36.45],[22.08,37.03],[21.89,36.74],[21.58,37.08],[21.68,37.39],[21.12,37.89],[21.83,38.33],[22.24,38.19],[22.92,37.96],[22.89,38.05],[23.12,38.07],[23.18,38.13],[23.15,38.18],[22.83,38.23],[22.42,38.44],[22.23,38.35],[21.11,38.39],[20.77,38.87],[21.12,39.03],[20.3,39.33],[19.85,40.04],[19.4,40.28],[19.58,41.79],[18.65,42.44],[17.04,43.02],[17.72,42.85],[16.9,43.39],[15.99,43.52],[15.19,44.17],[15.47,44.27],[14.55,45.3],[14.31,45.34],[13.86,44.84],[13.52,45.48],[13.78,45.63],[13.63,45.77],[12.27,45.45],[12.52,44.97],[12.25,44.72],[12.4,44.22],[13.56,43.57],[14.01,42.69],[14.54,42.24],[15.17,41.93],[16.17,41.9],[15.9,41.51],[17.96,40.65],[18.48,40.1],[18.34,39.82],[17.87,40.28],[16.93,40.46],[16.52,39.75],[17.11,39.38],[17.17,39],[16.62,38.8],[16.06,37.94],[15.72,37.94],[15.64,38.18],[16.21,38.94],[15.69,39.99],[14.95,40.24],[14.77,40.67],[14.34,40.6],[14.46,40.73],[14.05,40.81],[13.86,41.13],[13.67,41.26],[13.25,41.29],[13.09,41.24],[12.85,41.41],[12.63,41.47],[12.08,41.94],[11.81,42.08],[11.64,42.29],[11.3,42.42],[11.1,42.42],[11.18,42.46],[11.17,42.53],[10.51,42.97],[10.19,43.95],[9.73,44.1],[9.29,44.32],[8.76,44.42],[8.55,44.35],[8.29,44.14],[6.72,43.37],[6.57,43.2],[6.11,43.07],[5.81,43.1],[5.41,43.23],[5.32,43.35],[5.07,43.37],[5.06,43.44],[4.71,43.37],[4.22,43.48],[4.05,43.59],[3.91,43.56],[3.16,43.08],[3.09,42.59],[3.31,42.29],[3.17,42.26],[3.15,42.16],[3.24,42.08],[3.25,41.94],[3,41.77],[2.31,41.47],[2.08,41.29],[1.03,41.06],[0.71,40.82],[0.89,40.72],[-0.33,39.52],[0.2,38.76],[-0.52,38.32],[-0.72,37.63],[-1.64,37.39],[-2.19,36.74],[-4.37,36.72],[-5.63,36.03],[-6.38,36.64],[-6.22,36.91],[-6.86,37.28],[-7.84,37.01],[-8.93,37.17],[-8.81,37.43],[-8.79,37.73],[-8.88,37.96],[-8.8,38.18],[-8.88,38.45],[-8.67,38.42],[-8.8,38.52],[-9.21,38.45],[-9.25,38.66],[-9.02,38.75],[-8.94,39],[-8.79,39.08],[-8.96,39.02],[-9.14,38.74],[-9.36,38.7],[-9.47,38.73],[-9.48,38.8],[-9.35,39.25],[-9.38,39.34],[-9.15,39.54],[-8.84,40.12],[-8.87,40.26],[-8.66,41.03],[-8.89,42.11],[-8.69,42.27],[-9.18,43.17],[-7.7,43.77],[-7.06,43.55],[-1.99,43.35],[-1.49,43.56],[-1.08,44.69],[-1.24,44.67],[-1.08,45.53],[-0.55,45],[-1.2,45.71],[-1.03,45.74],[-1.15,46.31],[-2.09,46.87],[-2.11,47.26],[-1.74,47.22],[-4.31,47.82],[-4.68,48.04],[-4.33,48.17],[-4.58,48.29],[-4.24,48.3],[-4.72,48.54],[-3.23,48.84],[-2.69,48.54],[-1.38,48.65],[-1.86,49.68],[-0.16,49.3],[0.44,49.47],[0.13,49.51],[0.19,49.7],[1.24,50],[1.59,50.25],[1.67,50.88],[3.72,51.37],[4.22,51.39],[4.01,51.44],[3.82,51.41],[3.69,51.45],[3.55,51.59],[3.89,51.57],[4.14,51.46],[4.28,51.47],[4.01,51.6],[4.18,51.61],[3.95,51.81],[4.08,51.99],[4.48,52.31],[4.77,52.94],[4.89,52.91],[5.06,52.96],[5.36,53.1],[5.53,53.27],[6.06,53.41],[7.2,53.28],[7.21,53.66],[7.63,53.7],[8.49,53.39],[8.62,53.88],[9.78,53.55],[8.65,54.29],[8.96,54.54],[8.68,54.79],[8.62,55.42],[8.13,55.6],[8.16,56.61],[9.2,56.7],[9.11,57.04],[8.77,56.72],[8.27,56.81],[10.53,57.73],[10.28,56.62],[10.9,56.36],[9.91,55.84],[9.46,55.04],[10.02,54.67],[9.87,54.47],[11.01,54.38],[10.86,54.01],[12.11,54.17],[12.58,54.47],[13.03,54.41],[13.15,54.28],[13.82,54.02],[13.87,53.85],[13.95,53.8],[14.49,53.67],[14.56,53.82],[14.17,53.87],[13.93,53.88],[13.92,54],[13.83,54.06],[14.38,53.92],[18.08,54.84],[18.76,54.68],[18.44,54.75],[18.84,54.37],[19.41,54.39],[19.97,54.92],[20.68,55.1],[21.12,55.62],[20.59,54.98],[21.19,54.93],[21.03,56.64],[21.73,57.57],[22.56,57.72],[23.65,56.97],[24.4,57.33],[24.3,57.78],[24.49,58.26],[24.55,58.3],[24.53,58.35],[24.34,58.38],[24.11,58.27],[23.77,58.36],[23.69,58.51],[23.51,58.66],[23.68,58.79],[23.5,58.79],[23.43,58.92],[23.51,59],[23.47,59.03],[23.52,59.11],[23.5,59.19],[24.08,59.29],[24.05,59.37],[24.38,59.47],[25.44,59.52],[25.52,59.56],[25.51,59.64],[27.89,59.41],[28.06,59.78],[30.17,59.96],[28.64,60.38],[28.51,60.68],[26.45,60.47],[26.21,60.41],[25.95,60.47],[26.04,60.34],[25.76,60.27],[25.66,60.33],[24.6,60.11],[24.45,60.02],[23.46,59.99],[23.18,59.84],[22.96,59.83],[23.2,60.02],[22.91,60.21],[22.46,60.03],[22.58,60.38],[21.44,60.6],[21.61,61.59],[21.12,62.69],[21.65,63.04],[21.54,63.21],[22.32,63.31],[22.53,63.65],[23.6,64.04],[24.56,64.8],[25.29,64.86],[25.35,65.48],[24.63,65.86],[22.4,65.86],[22.25,65.6],[21.41,65.32],[21.57,65.13],[21.14,64.81],[21.52,64.46],[20.76,63.87],[18.61,63.18],[18.17,62.79],[17.88,62.87],[18.04,62.6],[17.38,62.46],[17.63,62.23],[17.47,61.68],[17.13,61.57],[17.25,60.7],[17.36,60.64],[17.56,60.64],[17.66,60.54],[17.96,60.59],[18.16,60.41],[18.56,60.25],[18.53,60.15],[18.79,60.08],[18.93,59.94],[18.97,59.76],[18.28,59.44],[17.97,59.36],[18.13,59.32],[18.51,59.41],[18.62,59.33],[18.42,59.29],[18.29,59.11],[17.76,58.97],[16.98,58.65],[16.64,58.65],[16.21,58.64],[16.79,58.59],[16.93,58.49],[16.82,58.46],[16.65,58.43],[16.53,57.07],[16,56.22],[14.72,56.13],[14.26,55.89],[14.34,55.53],[14.08,55.39],[13.81,55.43],[13.32,55.35],[12.89,55.41],[12.94,55.48],[12.97,55.75],[12.47,56.29],[12.71,56.23],[12.8,56.26],[12.66,56.44],[12.86,56.45],[12.92,56.52],[12.88,56.62],[12.72,56.66],[12.42,56.91],[11.25,58.42],[11.21,58.87],[11.15,58.99],[11.19,59.08],[11.39,59.04],[11.37,59.1],[10.83,59.18],[10.64,59.39],[10.6,59.76],[10.54,59.7],[10.57,59.59],[10.4,59.52],[10.46,59.38],[10.43,59.28],[10.18,59.01],[9.84,58.96],[9.64,59.12],[9.56,59.11],[9.7,59.01],[9.62,58.95],[8.17,58.14],[7,58.02],[6.9,58.07],[6.88,58.15],[6.8,58.16],[6.73,58.07],[6.59,58.1],[6.55,58.12],[6.69,58.22],[6.66,58.26],[6.39,58.27],[6.05,58.38],[5.71,58.52],[5.52,58.73],[5.56,58.97],[5.61,59.01],[6.1,58.87],[6.36,59],[6.1,58.95],[5.89,59.1],[5.97,59.19],[5.95,59.3],[6.4,59.56],[5.56,59.29],[5.36,59.17],[5.17,59.16],[5.13,59.23],[5.19,59.45],[5.3,59.64],[5.47,59.71],[5.77,59.66],[5.87,59.73],[6.22,59.82],[5.83,59.8],[5.73,59.86],[6.07,60.08],[6.14,60.23],[6.35,60.35],[6.53,60.21],[6.53,60.15],[7,60.51],[6.35,60.42],[6.15,60.35],[5.91,60.15],[5.88,60.07],[5.7,60.01],[5.5,59.83],[5.15,59.64],[5.12,59.83],[5.22,59.98],[5.18,60.05],[5.21,60.09],[5.5,60.07],[5.69,60.12],[5.29,60.21],[5.14,60.44],[5.65,60.69],[5.12,60.64],[5.1,61.07],[6.78,61.14],[7.04,60.95],[7.61,61.21],[7.44,61.43],[7.17,61.17],[5.11,61.19],[5,61.43],[5.34,61.48],[4.93,61.88],[6.73,61.87],[5.27,61.94],[5.14,62.16],[6.69,62.47],[6.14,62.41],[6.35,62.61],[8.09,62.73],[6.73,62.72],[7.57,63.1],[8.62,62.85],[8.16,63.16],[8.63,63.34],[8.36,63.5],[8.58,63.6],[9.7,63.63],[10.02,63.39],[11.37,63.81],[11.18,63.9],[11.31,64.05],[10.06,63.51],[9.57,63.71],[11.63,64.81],[11.3,64.76],[11.49,64.98],[12.92,65.34],[12.42,65.18],[12.12,65.36],[13.03,65.96],[12.79,66.1],[14.03,66.3],[13.12,66.23],[13.21,66.64],[13.96,66.8],[13.65,66.91],[15.42,67.2],[14.44,67.27],[14.96,67.57],[15.59,67.35],[15.69,67.52],[15.25,67.6],[15.31,67.77],[14.78,67.68],[15.05,67.96],[15.62,67.95],[15.29,68.04],[16.01,68.23],[16.31,67.88],[16.21,68.32],[17.57,68.45],[16.58,68.59],[18.1,69.16],[18.26,69.47],[18.92,69.33],[18.61,69.49],[19.2,69.75],[19.72,69.78],[19.64,69.42],[20.32,69.95],[20.05,69.33],[20.74,69.52],[20.62,69.91],[21.98,69.83],[21.36,70.23],[22.69,70.37],[23.36,69.98],[23.38,70.25],[24.66,71],[25.77,70.85],[25.04,70.11],[26.51,70.91],[26.74,70.85],[26.58,70.41],[27.55,70.8],[27.33,71],[28.14,71.04],[28.38,70.87],[27.9,70.68],[28.27,70.67],[28.19,70.25],[28.83,70.86],[30.96,70.34],[28.78,70.15],[29.6,69.98],[29.69,69.74],[31.45,69.69],[31.98,69.95],[33.01,69.72],[32.09,69.63],[32.38,69.48],[33.45,69.43],[33.14,69.07],[33.68,69.31],[35.86,69.19],[40.97,67.71],[41.36,67.21],[41.19,66.83],[40.1,66.3],[38.66,66.07],[34.48,66.55],[32.93,67.09],[31.89,67.16],[33.65,66.44],[33.36,66.33],[34.69,65.95],[34.41,65.4],[35.03,64.44],[37.44,63.81],[38.06,64.09],[37.95,64.32],[37.18,64.41],[36.58,64.79],[36.88,65.17],[39.76,64.58],[40.44,64.78],[39.8,65.35],[39.82,65.6],[42.21,66.52],[43.23,66.41],[44.11,66.01],[44.43,66.94],[43.78,67.26],[44.2,68.25],[43.33,68.67],[45.89,68.48],[46.69,67.85],[45.53,67.76],[44.9,67.41],[46.49,66.8],[47.66,66.98],[47.88,67.58],[48.83,67.68],[48.75,67.9],[51.99,68.54],[52.4,68.35],[52.72,68.48],[52.34,68.61],[53.8,69],[54.49,68.99],[53.8,68.91],[53.93,68.44],[53.26,68.27],[54.86,68.2],[55.42,68.57],[57.13,68.55],[59.06,69.01],[59.37,68.74],[59.1,68.44],[59.73,68.35],[59.9,68.71],[60.93,68.99],[60.17,69.59],[60.91,69.85],[64.19,69.53],[68.5,68.35],[69.14,68.95],[68.54,68.97],[67.62,69.58],[66.9,69.55],[67.29,70.74],[66.7,70.82],[66.85,71.06],[66.64,71.08],[68.27,71.68],[69.39,72.96],[71.5,72.91],[72.81,72.69],[72.57,72.01],[71.87,71.46],[72.7,70.96],[72.47,70.28],[72.58,68.97],[73.59,68.48],[73.14,68.18],[73.07,67.77],[71.85,67.01],[71.37,66.96],[71.54,66.68],[70.72,66.52],[70.38,66.6],[70.69,66.74],[69.01,66.79],[69.98,66.4],[72.07,66.25],[73.79,66.99],[74.77,67.77],[74.39,68.42],[74.58,68.75],[75.12,68.86],[76.46,68.98],[77.24,68.47],[77.18,67.78],[78.92,67.59],[77.59,67.75],[77.67,68.19],[78,68.26],[77.65,68.9],[76,69.24],[73.78,69.2],[73.89,69.42],[73.58,69.8],[74.34,70.58],[73.09,71.44],[73.67,71.85],[74.99,72.15],[75.1,72.42],[74.79,72.81],[75.6,72.58],[75.74,72.3],[75.27,71.96],[75.5,71.65],[75.28,71.43],[75.73,71.27],[79.02,70.95],[76.43,71.55],[76.03,71.91],[78.19,71.91],[77.41,72.11],[78.48,72.4],[79.42,72.38],[81.66,71.72],[83.11,71.72],[82.98,71.45],[82.32,71.26],[82.16,70.6],[82.22,70.4],[82.59,70.89],[83.01,70.9],[82.68,70.22],[83.08,70.09],[83.74,70.55],[83.15,71.1],[83.53,71.68],[82.09,72.27],[81.1,72.39],[80.83,72.49],[80.66,72.71],[80.84,72.95],[80.76,73.03],[80.51,73.09],[80.42,73.23],[80.4,73.36],[80.6,73.47],[80.58,73.57]],[[-152.47,70.65],[-151.77,70.56],[-151.94,70.45],[-149.27,70.5],[-144.62,69.98],[-143.22,70.12],[-135.26,68.68],[-135.91,69.11],[-134.46,69.48],[-134.41,69.68],[-133.88,69.51],[-134.18,69.25],[-130.67,70.13],[-129.54,70.11],[-131.94,69.53],[-133.42,68.84],[-132.71,68.81],[-132.53,68.87],[-132.72,69.08],[-131.79,69.43],[-131.06,69.45],[-130.97,69.21],[-130.12,69.72],[-128.9,69.97],[-129.16,69.8],[-128.85,69.75],[-127.68,70.26],[-128.17,70.42],[-127.99,70.57],[-125.73,69.38],[-125.17,69.43],[-125.34,69.66],[-124.56,70.15],[-124.12,69.69],[-124.34,69.36],[-123.53,69.39],[-123.03,69.81],[-121.74,69.8],[-117.23,68.91],[-115.44,68.94],[-113.96,68.4],[-115.43,67.9],[-115.13,67.82],[-112.43,67.68],[-110.07,67.99],[-107.99,67.26],[-108.5,67.09],[-107.26,66.4],[-107.75,66.96],[-107.16,66.88],[-107.96,67.82],[-105.75,68.59],[-107.73,68.17],[-108.72,68.3],[-108.34,68.6],[-106.16,68.92],[-104.49,68.06],[-103.47,68.11],[-102.32,67.74],[-98.41,67.81],[-98.63,68.07],[-97.61,67.63],[-97.16,67.73],[-98.19,67.92],[-98.65,68.36],[-97.83,68.53],[-96.43,68.31],[-96.72,68.04],[-95.97,68.25],[-96.37,67.51],[-95.42,67.01],[-96.42,67.04],[-95.79,66.62],[-96.04,66.94],[-95.4,66.95],[-95.26,67.26],[-95.65,67.74],[-95.46,68.02],[-93.45,68.62],[-93.85,69],[-94.6,68.8],[-94.09,69.12],[-94.25,69.31],[-93.43,69.37],[-96.05,69.83],[-96.54,70.33],[-95.89,70.69],[-96.36,70.68],[-96.53,71.13],[-96.06,71.41],[-95.56,71.34],[-95.41,71.49],[-95.87,71.57],[-95.2,71.9],[-94.61,71.99],[-94.48,71.85],[-94.31,71.77],[-93.03,71.34],[-92.98,70.85],[-91.57,70.18],[-92.32,70.24],[-92.51,70.1],[-91.98,70.04],[-92.89,69.67],[-90.42,69.46],[-91.24,69.29],[-90.48,68.88],[-90.58,68.48],[-90.25,68.27],[-89.28,69.26],[-88.04,68.81],[-87.81,68.35],[-88.35,68.29],[-88.31,67.95],[-87.36,67.18],[-86.56,67.48],[-85.69,68.67],[-84.87,68.77],[-85.11,68.84],[-84.86,69.07],[-85.39,69.23],[-85.51,69.85],[-82.62,69.69],[-82.37,69.64],[-82.76,69.49],[-82.23,69.25],[-81.32,69.14],[-81.96,68.88],[-81.28,68.66],[-82.55,68.45],[-81.29,67.5],[-81.39,67.19],[-82.64,66.59],[-83.52,66.37],[-84.85,67.03],[-85.11,66.89],[-84.64,66.9],[-83.8,66.24],[-86.71,66.52],[-85.96,66.12],[-87.45,65.34],[-89.75,65.94],[-91.43,65.95],[-87,65.11],[-88.11,64.18],[-89.13,63.97],[-90.04,64.14],[-89.86,63.96],[-90.17,63.98],[-90.01,63.8],[-90.24,63.64],[-93.7,64.15],[-93.56,63.86],[-92.16,63.69],[-92.47,63.56],[-91.84,63.7],[-90.97,63.44],[-90.7,63.06],[-92.36,62.82],[-91.94,62.59],[-92.55,62.55],[-92.77,62.35],[-92.53,62.17],[-93.21,62.36],[-92.9,62.22],[-93.58,61.94],[-93.31,61.77],[-93.91,61.48],[-94.76,60.5],[-94.96,59.07],[-94.29,58.72],[-94.33,58.3],[-94.12,58.74],[-93.18,58.73],[-92.43,57.32],[-92.8,56.92],[-90.59,57.22],[-88.83,56.81],[-87.48,56.02],[-85.68,55.6],[-85.22,55.35],[-85.37,55.08],[-83.91,55.31],[-82.39,55.07],[-82.22,54.81],[-82.42,54.24],[-82.14,53.82],[-82.29,53.03],[-81.6,52.43],[-81.83,52.22],[-80.59,51.67],[-80.44,51.39],[-80.85,51.12],[-80.1,51.28],[-79.35,50.76],[-79.74,51.19],[-79.34,51.63],[-78.9,51.2],[-78.73,51.5],[-78.98,51.78],[-78.45,52.26],[-79.1,53.66],[-79.01,54.02],[-79.71,54.67],[-77.78,55.29],[-76.55,56.36],[-76.57,57.18],[-76.89,57.76],[-78.51,58.68],[-77.73,59.68],[-77.35,59.58],[-77.29,60.02],[-77.59,60.09],[-77.68,60.43],[-77.5,60.54],[-77.79,60.64],[-77.59,60.81],[-78.18,60.82],[-77.51,61.56],[-78.02,61.83],[-78.13,62.28],[-77.37,62.57],[-74.63,62.11],[-73.71,62.47],[-72.69,62.13],[-72.77,61.84],[-72.23,61.83],[-72.04,61.68],[-72.21,61.59],[-71.64,61.62],[-71.85,61.44],[-71.42,61.16],[-69.99,60.86],[-69.5,61.04],[-69.67,60.08],[-70.66,60.03],[-69.73,59.92],[-69.68,59.34],[-69.35,59.3],[-69.53,58.87],[-70.16,58.76],[-68.38,58.74],[-68.36,58.16],[-69.04,57.9],[-68.41,58.05],[-68.02,58.48],[-68.06,58.14],[-67.75,58.4],[-67.68,57.99],[-66.36,58.79],[-66,58.43],[-66.04,58.82],[-65.38,59.06],[-65.7,59.21],[-65.48,59.47],[-65.04,59.39],[-65.43,59.78],[-65.03,59.77],[-65.17,59.91],[-64.82,60.33],[-64.5,60.27],[-64.77,60.01],[-64.28,60.06],[-64.23,59.74],[-63.75,59.51],[-63.95,59.38],[-63.42,59.19],[-63.97,59.05],[-63.25,59.07],[-63.28,58.87],[-62.87,58.67],[-63.54,58.33],[-62.61,58.5],[-63.26,58.01],[-62.49,58.15],[-61.96,57.91],[-61.97,57.61],[-62.49,57.49],[-61.33,57.01],[-61.37,56.68],[-62.5,56.8],[-61.43,56.36],[-61.71,56.23],[-61.36,56.22],[-61.45,56],[-60.34,55.79],[-60.19,55.48],[-60.62,55.06],[-59.76,55.31],[-59.44,55.18],[-59.84,54.81],[-59.26,55.2],[-58.78,54.84],[-57.96,54.88],[-57.4,54.59],[-60.4,53.65],[-60.1,53.49],[-60.33,53.27],[-57.93,54.1],[-58.36,54.16],[-58.19,54.23],[-57.42,54.16],[-57.13,53.79],[-57.52,53.61],[-57.33,53.47],[-56.46,53.76],[-55.86,53.34],[-55.8,52.64],[-56.32,52.54],[-55.74,52.47],[-56.01,52.39],[-55.69,52.14],[-56.98,51.46],[-58.51,51.29],[-59.88,50.32],[-61.72,50.1],[-62.71,50.3],[-66.41,50.22],[-66.94,49.99],[-67.37,49.35],[-68.28,49.2],[-69.67,48.2],[-71.02,48.46],[-69.77,48.1],[-70.71,47.14],[-72.68,46.29],[-72.98,46.21],[-73.02,46.12],[-73.14,46.07],[-73.47,45.74],[-73.71,45.71],[-74.04,45.5],[-74.31,45.53],[-74,45.43],[-73.98,45.35],[-74.36,45.21],[-74.71,45],[-73.76,45.4],[-73.56,45.42],[-73.46,45.63],[-73.16,46.01],[-72.73,46.18],[-72.37,46.4],[-70.52,47.03],[-69.47,47.97],[-68.24,48.63],[-65.4,49.26],[-64.26,48.92],[-64.51,48.84],[-64.26,48.55],[-65.26,48.02],[-65.93,48.19],[-66.7,48.02],[-65.61,47.67],[-64.7,47.73],[-65.32,47.1],[-64.83,47.06],[-64.54,46.24],[-62.75,45.65],[-61.95,45.87],[-61.35,45.57],[-61.46,45.37],[-61.03,45.29],[-63.6,44.68],[-63.61,44.48],[-64.29,44.55],[-64.86,43.87],[-65.74,43.56],[-66.13,43.81],[-66.02,44.56],[-64.45,45.34],[-64.14,45.02],[-63.37,45.36],[-64.87,45.36],[-64.32,45.84],[-64.63,45.95],[-64.78,45.64],[-65.89,45.22],[-66.03,45.42],[-66.44,45.1],[-67.12,45.17],[-66.99,44.83],[-68.06,44.39],[-68.45,44.51],[-68.53,44.26],[-68.81,44.34],[-68.76,44.57],[-69.14,44.04],[-70.27,43.67],[-70.2,43.63],[-70.52,43.35],[-70.73,43.07],[-70.83,42.83],[-70.74,42.67],[-70.62,42.67],[-70.61,42.62],[-70.83,42.55],[-71.04,42.33],[-70.74,42.23],[-70.62,42.04],[-70.66,41.99],[-70.55,41.94],[-70.52,41.8],[-70.43,41.76],[-70.3,41.73],[-70,41.83],[-70.11,42.03],[-70.24,42.09],[-70.11,42.08],[-69.98,41.96],[-69.93,41.71],[-70.66,41.53],[-70.7,41.72],[-71.17,41.49],[-71.2,41.64],[-71.15,41.75],[-71.27,41.68],[-71.39,41.79],[-71.37,41.7],[-71.43,41.63],[-71.44,41.45],[-71.52,41.38],[-72.92,41.28],[-73.58,41.02],[-73.99,40.75],[-73.87,41.06],[-73.88,41.17],[-73.97,41.25],[-73.92,41.14],[-73.93,40.91],[-74.26,40.53],[-74.24,40.46],[-74,40.45],[-73.97,40.4],[-74.08,39.79],[-74.07,39.99],[-74.26,39.61],[-74.33,39.54],[-74.41,39.55],[-74.39,39.49],[-74.48,39.34],[-74.58,39.32],[-74.61,39.25],[-74.92,38.94],[-74.9,39.15],[-75.52,39.49],[-75.07,39.98],[-75.17,39.89],[-75.32,39.86],[-75.57,39.48],[-75.04,38.43],[-75.93,37.15],[-75.66,37.95],[-75.85,37.97],[-75.86,38.36],[-76.12,38.32],[-76.26,38.44],[-76.26,38.6],[-76,38.6],[-76.21,38.76],[-76.28,38.77],[-76.34,38.71],[-76.3,38.82],[-76.17,38.85],[-76.19,38.91],[-76.33,38.91],[-76.33,38.95],[-76.31,39.01],[-76.19,38.99],[-76.13,39.12],[-76.22,39.06],[-76.24,39.19],[-76.15,39.32],[-75.94,39.4],[-76,39.41],[-75.97,39.51],[-76.01,39.57],[-76.06,39.56],[-76.1,39.43],[-76.21,39.38],[-76.25,39.44],[-76.28,39.32],[-76.33,39.4],[-76.42,39.23],[-76.57,39.27],[-76.43,39.13],[-76.47,39.03],[-76.56,39.07],[-76.5,38.94],[-76.54,38.74],[-76.5,38.53],[-76.39,38.37],[-76.57,38.44],[-76.68,38.61],[-76.67,38.54],[-76.64,38.45],[-76.41,38.27],[-76.34,38.09],[-76.46,38.17],[-76.77,38.26],[-76.87,38.39],[-76.89,38.29],[-77,38.44],[-77.23,38.41],[-77.22,38.54],[-77.02,38.78],[-77.03,38.89],[-77.05,38.78],[-77.26,38.6],[-77.31,38.4],[-77.27,38.35],[-77.05,38.36],[-76.91,38.2],[-76.55,38.09],[-76.35,37.96],[-76.34,37.68],[-76.79,37.94],[-76.94,38.1],[-77.11,38.16],[-76.62,37.76],[-76.27,37.49],[-76.45,37.27],[-76.76,37.51],[-76.34,37.01],[-77.25,37.33],[-76.49,36.9],[-76,36.91],[-75.53,35.82],[-75.95,36.66],[-75.82,36.11],[-76.15,36.28],[-76.56,36.02],[-76.73,36.23],[-76.73,35.96],[-76.07,35.97],[-76.08,35.69],[-75.76,35.84],[-76.17,35.35],[-77.04,35.53],[-76.51,35.27],[-76.78,34.99],[-77.07,35.15],[-76.97,35.02],[-76.44,34.84],[-77.41,34.73],[-77.93,33.94],[-77.95,34.17],[-78.01,33.91],[-78.84,33.72],[-79.94,32.67],[-80.64,32.51],[-80.58,32.29],[-80.8,32.45],[-80.69,32.22],[-81.44,31.2],[-81.25,29.79],[-80.52,28.49],[-80.46,27.9],[-80.84,28.76],[-80.05,26.81],[-80.13,25.83],[-80.16,25.88],[-80.3,25.62],[-80.37,25.33],[-80.48,25.23],[-80.74,25.16],[-81.11,25.14],[-81.17,25.23],[-81.14,25.31],[-80.97,25.22],[-80.94,25.26],[-81.11,25.37],[-81.37,25.83],[-81.72,25.98],[-81.96,26.49],[-81.83,26.69],[-82.04,26.55],[-82.01,26.96],[-82.29,26.87],[-82.72,27.5],[-82.41,27.86],[-82.84,27.85],[-82.65,28.89],[-84.04,30.1],[-85.32,29.68],[-85.6,30.29],[-86.45,30.4],[-86.26,30.49],[-87.2,30.34],[-87,30.57],[-88,30.23],[-87.79,30.29],[-88.01,30.69],[-88.13,30.37],[-89.59,30.17],[-90.23,30.38],[-90.28,30.06],[-89.4,30.05],[-89.35,29.82],[-89.72,29.62],[-89.02,29.2],[-89.38,28.98],[-90.16,29.54],[-90.21,29.1],[-91.29,29.29],[-91.25,29.56],[-91.89,29.84],[-92.26,29.56],[-93.83,29.72],[-93.88,29.81],[-93.81,29.85],[-93.79,29.98],[-93.84,29.98],[-93.94,29.81],[-93.89,29.69],[-94.1,29.67],[-94.76,29.38],[-94.53,29.55],[-94.78,29.55],[-94.74,29.75],[-94.83,29.75],[-94.89,29.68],[-95.02,29.7],[-94.99,29.53],[-94.89,29.37],[-95.14,29.17],[-95.15,29.08],[-95.27,28.96],[-95.85,28.64],[-96.23,28.49],[-96.01,28.63],[-96.37,28.66],[-96.45,28.59],[-96.58,28.72],[-96.42,28.46],[-97.16,28.14],[-97.07,27.99],[-97.43,27.84],[-97.44,27.33],[-97.77,27.46],[-97.48,27.24],[-97.14,26.03],[-97.67,24.39],[-97.86,22.62],[-97.31,21.56],[-97.41,21.27],[-97.75,22.03],[-97.64,21.6],[-95.92,18.82],[-95.18,18.7],[-94.46,18.17],[-92.44,18.67],[-91.53,18.46],[-91.27,18.62],[-91.44,18.89],[-90.74,19.35],[-90.35,21.01],[-88.47,21.57],[-87.04,21.59],[-86.82,21],[-87.69,19.64],[-87.43,19.58],[-87.85,18.27],[-88.03,18.84],[-88.35,18.36],[-88.08,18.23],[-88.31,16.63],[-88.89,15.89],[-88.13,15.7],[-87.7,15.91],[-86.91,15.76],[-84.97,15.99],[-84.26,15.82],[-83.76,15.22],[-83.37,15.24],[-83.19,14.34],[-83.57,13.32],[-83.51,12.41],[-83.59,12.71],[-83.75,12.5],[-83.83,11.13],[-82.24,9.03],[-81.78,8.96],[-81.9,9.14],[-81.55,8.83],[-81.06,8.81],[-80.84,8.89],[-80.55,9.08],[-80.13,9.21],[-79.58,9.6],[-79.11,9.54],[-78.93,9.43],[-78.5,9.41],[-78.08,9.24],[-76.79,7.93],[-76.92,8.57],[-75.64,9.45],[-75.54,10.2],[-75.71,10.14],[-75.45,10.61],[-74.84,11.11],[-74.33,11],[-74.4,10.77],[-74.14,11.32],[-73.31,11.3],[-71.6,12.43],[-71.14,12.05],[-71.96,11.57],[-71.6,10.66],[-72.11,9.82],[-71.62,9.05],[-71.24,9.16],[-71.05,9.71],[-71.47,10.96],[-69.81,11.47],[-70.29,11.89],[-70,12.18],[-69.63,11.48],[-68.4,11.16],[-68.14,10.49],[-66.25,10.63],[-65.13,10.07],[-63.73,10.5],[-64.3,10.64],[-61.88,10.74],[-62.91,10.53],[-62.74,10.06],[-62.55,10.2],[-62.32,9.78],[-62.08,9.98],[-61.74,9.63],[-61.59,9.89],[-60.79,9.36],[-61.25,8.6],[-61.62,8.6],[-61.3,8.41],[-60.17,8.62],[-58.81,7.74],[-58.48,7.33],[-58.67,6.39],[-58.42,6.85],[-57.98,6.79],[-57.23,6.18],[-57.18,5.53],[-56.97,5.99],[-55.9,5.7],[-55.83,5.96],[-54.36,5.91],[-54.05,5.81],[-54.16,5.36],[-53.85,5.78],[-52.9,5.43],[-52.06,4.72],[-52,4.35],[-51.83,4.64],[-51.65,4.06],[-51.55,4.31],[-51.22,4.09],[-50.72,2.13],[-49.96,1.66],[-49.9,1.16],[-51.28,-0.08],[-51.98,-1.37],[-52.66,-1.55],[-51.95,-1.59],[-50.9,-0.94],[-50.4,-2.01],[-49.32,-1.73],[-49.64,-2.66],[-49.21,-1.92],[-48.35,-1.48],[-48.45,-1.15],[-48.12,-0.74],[-47.4,-0.63],[-45.46,-1.36],[-45.33,-1.72],[-45.08,-1.47],[-44.65,-1.75],[-44.54,-2.05],[-44.76,-2.26],[-44.44,-2.17],[-44.38,-2.37],[-44.72,-3.2],[-44.23,-2.47],[-44.19,-2.81],[-43.38,-2.38],[-42.25,-2.79],[-39.77,-2.99],[-39.02,-3.39],[-38.69,-3.65],[-38.48,-3.72],[-38.05,-4.22],[-37.63,-4.59],[-37.3,-4.71],[-36.59,-5.1],[-35.39,-5.25],[-34.83,-7.02],[-34.84,-7.97],[-35.34,-9.23],[-37.36,-11.25],[-38.02,-12.59],[-38.4,-12.97],[-38.69,-12.62],[-38.85,-12.79],[-39.09,-13.59],[-38.88,-15.86],[-39.16,-17.7],[-39.65,-18.25],[-39.78,-19.57],[-40.96,-21.24],[-41,-22],[-41.58,-22.24],[-41.98,-22.58],[-41.94,-22.79],[-42.04,-22.95],[-42.96,-22.97],[-43.08,-22.9],[-43.09,-22.72],[-43.23,-22.75],[-43.22,-22.99],[-43.9,-23.1],[-43.97,-23.06],[-43.68,-23.01],[-43.86,-22.91],[-44.15,-23.01],[-44.37,-23],[-45.21,-23.58],[-45.33,-23.6],[-45.46,-23.8],[-45.97,-23.79],[-46.87,-24.24],[-47.14,-24.49],[-47.59,-24.78],[-48.2,-25.42],[-48.73,-25.37],[-48.4,-25.6],[-48.75,-26.27],[-48.56,-27.2],[-48.8,-28.58],[-49.75,-29.36],[-50.92,-31.26],[-52.04,-32.12],[-52.06,-31.83],[-51.27,-31.48],[-50.58,-30.44],[-50.56,-30.25],[-51.03,-30.37],[-51.3,-30.04],[-51.28,-30.75],[-51.97,-31.38],[-52.65,-33.14],[-53.79,-34.38],[-54.9,-34.93],[-56.85,-34.68],[-57.17,-34.45],[-57.87,-34.45],[-58.4,-33.91],[-58.44,-33.72],[-58.36,-33.18],[-58.15,-33.07],[-58.2,-32.47],[-58.2,-33.01],[-58.25,-33.08],[-58.42,-33.11],[-58.55,-33.66],[-58.39,-34.19],[-58.52,-34.3],[-58.47,-34.46],[-58.28,-34.68],[-57.76,-34.89],[-57.3,-35.19],[-57.17,-35.36],[-57.16,-35.51],[-57.35,-35.72],[-57.26,-36.14],[-56.72,-36.39],[-56.67,-36.85],[-57.65,-38.17],[-59.83,-38.84],[-61.6,-39],[-62.34,-38.8],[-62.3,-39.24],[-62.05,-39.37],[-62.39,-40.89],[-63.62,-41.16],[-64.87,-40.74],[-65.13,-40.88],[-64.99,-42.1],[-64.42,-42.43],[-63.79,-42.11],[-63.62,-42.7],[-64.04,-42.88],[-64.49,-42.51],[-64.97,-42.67],[-64.32,-42.97],[-65.25,-43.57],[-65.29,-44.36],[-65.65,-44.66],[-65.64,-45.01],[-66.94,-45.26],[-67.6,-46.05],[-67.51,-46.44],[-66.78,-47.01],[-65.85,-47.16],[-65.77,-47.57],[-66.22,-47.83],[-65.81,-47.94],[-67.47,-48.95],[-67.91,-49.98],[-68.26,-50.1],[-68.67,-49.75],[-68.98,-50],[-68.42,-50.16],[-68.94,-50.38],[-69.36,-51.03],[-69.06,-51.55],[-69.46,-51.58],[-68.96,-51.68],[-68.4,-52.31],[-69.24,-52.21],[-70.8,-52.77],[-70.99,-53.78],[-71.3,-53.88],[-72.41,-53.35],[-71.94,-53.23],[-71.79,-53.48],[-71.23,-52.81],[-72.28,-53.13],[-72.55,-53.46],[-73.05,-53.24],[-72.73,-52.76],[-71.51,-52.61],[-72.71,-52.54],[-73.12,-53.07],[-73.64,-52.84],[-73.12,-52.49],[-74.01,-52.64],[-74.3,-52.12],[-73.83,-52.23],[-72.79,-51.95],[-72.57,-52.2],[-72.72,-52.36],[-72.52,-52.25],[-72.54,-51.71],[-73.17,-51.45],[-72.6,-51.8],[-73.52,-52.04],[-74.19,-51.68],[-73.93,-51.62],[-73.94,-51.27],[-74.81,-51.06],[-75.09,-50.68],[-74.68,-50.66],[-74.64,-50.36],[-73.81,-50.94],[-73.65,-50.49],[-73.98,-50.83],[-74.2,-50.61],[-73.95,-50.51],[-74.63,-50.19],[-73.96,-49.99],[-74.29,-49.6],[-73.83,-49.61],[-74.09,-49.43],[-73.94,-49.02],[-74.22,-49.5],[-74.37,-49.4],[-74.34,-48.6],[-74.01,-48.48],[-74.48,-48.46],[-74.58,-48],[-73.39,-48.15],[-73.72,-47.66],[-74.23,-47.97],[-74.66,-47.7],[-74.13,-47.59],[-74.48,-47.43],[-74.16,-47.18],[-74.31,-46.79],[-75,-46.74],[-75.02,-46.51],[-75.54,-46.7],[-75.43,-46.93],[-75.71,-46.77],[-74.93,-46.16],[-75.07,-45.88],[-74.16,-45.77],[-73.96,-45.4],[-74.02,-46.06],[-74.39,-46.22],[-73.97,-46.15],[-73.73,-45.81],[-73.85,-46.57],[-73.59,-45.9],[-73.73,-45.48],[-72.93,-45.45],[-73.45,-45.24],[-72.68,-44.59],[-73.27,-44.17],[-73.08,-43.32],[-72.76,-43.04],[-72.77,-42.26],[-72.41,-42.39],[-72.5,-41.98],[-72.82,-41.91],[-72.32,-41.5],[-73.73,-41.74],[-73.98,-40.97],[-73.23,-39.22],[-73.66,-37.34],[-73.22,-37.17],[-71.99,-34.29],[-72,-34.17],[-71.83,-33.82],[-71.66,-33.65],[-71.64,-33.52],[-71.7,-33.43],[-71.74,-33.09],[-71.59,-32.97],[-71.45,-32.66],[-71.42,-32.39],[-71.51,-32.21],[-71.71,-30.63],[-71.31,-29.65],[-71.52,-28.93],[-70.65,-26.33],[-70.39,-23.57],[-70.59,-23.25],[-70.09,-21.49],[-70.36,-18.4],[-71.53,-17.3],[-75.11,-15.41],[-76.29,-14.13],[-76.23,-13.37],[-76.5,-12.98],[-76.83,-12.35],[-77.15,-12.06],[-77.22,-11.66],[-77.31,-11.53],[-77.63,-11.29],[-77.74,-10.84],[-79.76,-7.07],[-81.14,-6.06],[-80.88,-5.63],[-81.34,-4.67],[-81.23,-4.23],[-79.96,-3.16],[-79.73,-2.58],[-79.84,-2.07],[-79.93,-2.55],[-80.01,-2.35],[-80.29,-2.71],[-80.96,-2.19],[-80.77,-2.08],[-80.9,-1.08],[-80.28,-0.62],[-80.48,-0.37],[-80.05,0.16],[-80.09,0.79],[-78.9,1.21],[-79.03,1.62],[-78.58,1.77],[-78.59,2.36],[-77.81,2.72],[-77.08,3.91],[-77.52,4.21],[-77.29,4.72],[-77.54,5.54],[-77.25,5.78],[-77.47,6.18],[-77.37,6.57],[-78.38,7.9],[-78.42,8.06],[-78.29,8.09],[-78.28,8.25],[-78.14,8.39],[-77.76,8.13],[-78.06,8.4],[-78.1,8.5],[-78.22,8.4],[-78.4,8.51],[-78.37,8.4],[-78.41,8.36],[-78.51,8.63],[-78.95,8.93],[-79.25,9.02],[-79.51,8.97],[-79.69,8.85],[-79.81,8.64],[-79.75,8.6],[-80.12,8.35],[-80.37,8.29],[-80.46,8.21],[-80.46,8.08],[-80.07,7.67],[-80.01,7.5],[-80.84,7.22],[-81.06,7.9],[-81.27,7.63],[-82.23,8.31],[-82.78,8.3],[-82.88,8.07],[-83.29,8.67],[-83.47,8.71],[-83.29,8.41],[-83.61,8.48],[-83.74,9.15],[-84.58,9.57],[-85.02,10.12],[-85.26,10.26],[-84.89,9.82],[-85.11,9.58],[-85.63,9.9],[-85.85,10.29],[-85.67,10.74],[-85.91,10.9],[-85.74,11.09],[-87.67,12.9],[-87.34,12.95],[-87.49,13.35],[-88.69,13.28],[-88.51,13.18],[-91.38,13.99],[-93.92,16.05],[-94.86,16.42],[-95.02,16.28],[-94.8,16.21],[-96.21,15.69],[-97.75,15.97],[-100.85,17.2],[-101.92,17.96],[-103.44,18.33],[-103.91,18.83],[-104.94,19.31],[-105.67,20.38],[-105.26,20.58],[-105.51,20.81],[-105.21,21.49],[-105.65,21.99],[-105.79,22.63],[-107.77,24.47],[-107.51,24.49],[-107.95,24.62],[-108.28,25.08],[-108.05,25.07],[-109.03,25.48],[-108.88,25.73],[-109.31,25.63],[-109.42,26.03],[-109.12,26.25],[-109.28,26.53],[-110.38,27.23],[-110.53,27.86],[-111.12,27.97],[-112.16,29.02],[-113.06,30.65],[-113.05,31.18],[-114.93,31.9],[-114.55,30.02],[-112.87,28.42],[-112.73,27.83],[-111.86,26.68],[-111.7,26.58],[-111.79,26.88],[-111.57,26.71],[-110.69,24.87],[-110.66,24.34],[-110.37,24.1],[-110.26,24.34],[-109.42,23.48],[-109.5,23.16],[-110,22.89],[-110.36,23.61],[-112.07,24.84],[-112.38,26.21],[-113.02,26.58],[-113.15,26.95],[-113.6,26.72],[-114.99,27.74],[-114.3,27.87],[-114.07,27.68],[-114.27,27.93],[-114.05,28.43],[-115.67,29.76],[-117.27,32.81],[-117.32,33.1],[-117.47,33.3],[-118.08,33.72],[-118.41,33.74],[-118.39,33.86],[-118.51,34.02],[-118.83,34.02],[-119.14,34.11],[-119.41,34.34],[-119.61,34.42],[-119.71,34.4],[-120.65,34.58],[-120.63,35.08],[-121.46,35.93],[-121.88,36.33],[-121.92,36.57],[-121.79,36.73],[-121.81,36.85],[-121.88,36.94],[-122.17,36.99],[-122.4,37.21],[-122.51,37.77],[-122.39,37.79],[-122.37,37.66],[-122.07,37.48],[-122.39,37.96],[-122.22,38.04],[-121.52,38.06],[-122.03,38.12],[-122.15,38.07],[-122.39,38.14],[-122.48,38.11],[-122.47,37.84],[-122.52,37.83],[-122.93,38.06],[-123,37.99],[-122.98,38.23],[-122.88,38.12],[-122.99,38.28],[-123.7,38.91],[-123.83,39.78],[-124.33,40.25],[-124.07,41.46],[-124.54,42.81],[-124.15,43.69],[-123.99,46.22],[-123.22,46.15],[-124.07,46.28],[-123.89,46.66],[-124.11,46.86],[-123.84,46.96],[-124.14,46.95],[-124.71,48.38],[-123.3,48.12],[-123.12,48.15],[-122.98,48.07],[-122.78,48.14],[-122.66,47.88],[-122.78,47.74],[-122.82,47.79],[-123.05,47.55],[-123.14,47.36],[-122.92,47.41],[-123.07,47.4],[-123.06,47.45],[-122.59,47.86],[-122.59,47.93],[-122.53,47.92],[-122.53,47.77],[-122.62,47.71],[-122.61,47.62],[-122.68,47.61],[-122.56,47.46],[-122.58,47.29],[-122.71,47.32],[-122.77,47.22],[-122.83,47.34],[-123.03,47.14],[-122.7,47.11],[-122.54,47.28],[-122.35,47.37],[-122.4,47.78],[-122.24,48.01],[-122.42,48.18],[-122.4,48.08],[-122.52,48.16],[-122.52,48.23],[-122.41,48.29],[-122.67,48.46],[-122.5,48.51],[-122.54,48.76],[-122.69,48.79],[-122.83,49.03],[-122.96,49.07],[-123.08,48.98],[-123.23,49.26],[-122.88,49.4],[-123.28,49.34],[-123.19,49.68],[-123.53,49.4],[-124.03,49.6],[-123.58,49.68],[-123.88,49.74],[-123.83,50.15],[-124.28,49.77],[-124.78,50.02],[-125.06,50.42],[-124.86,50.87],[-125.06,50.51],[-126.09,50.5],[-126.45,50.59],[-125.91,50.7],[-126.51,50.68],[-126.52,51.06],[-127.06,50.87],[-127.71,51.15],[-127.42,51.61],[-126.69,51.7],[-127.64,51.48],[-127.85,51.67],[-127.8,52.19],[-127.44,52.36],[-126.71,52.06],[-127.19,52.46],[-127.01,52.84],[-128.1,51.79],[-128.36,52.16],[-127.94,52.55],[-128.27,52.36],[-128.05,52.91],[-128.36,52.83],[-129.17,53.53],[-128.85,53.7],[-127.93,53.28],[-128.67,53.55],[-128.76,53.75],[-128.71,53.81],[-128.53,53.86],[-128.7,53.92],[-128.89,53.83],[-128.96,53.84],[-129.21,53.64],[-129.26,53.42],[-129.46,53.35],[-129.56,53.25],[-129.82,53.41],[-129.91,53.55],[-130.07,53.58],[-130.34,53.72],[-130.09,53.98],[-130.04,54.13],[-129.63,54.23],[-130.08,54.18],[-130.29,54.27],[-130.43,54.42],[-130.35,54.66],[-130.22,54.73],[-129.89,55.16],[-129.56,55.46],[-129.79,55.56],[-130.05,55.06],[-130.02,55.89],[-130.04,55.3],[-130.54,54.75],[-131.05,55.16],[-130.75,55.32],[-131.03,56.09],[-132.12,55.57],[-132.21,55.75],[-131.55,56.21],[-132.18,56.42],[-132.82,57.06],[-133.47,57.17],[-133.44,57.34],[-133.54,57.55],[-133.65,57.64],[-133.55,57.7],[-133.12,57.57],[-133.52,57.78],[-133.54,57.83],[-133.51,57.88],[-133.19,57.88],[-133.56,57.92],[-133.66,57.84],[-133.72,57.84],[-134.03,58.07],[-134.05,58.29],[-133.88,58.52],[-134.21,58.23],[-134.78,58.45],[-134.94,58.65],[-134.99,58.77],[-135.13,58.84],[-135.33,59.24],[-135.36,59.42],[-135.41,59.32],[-135.48,59.31],[-135.4,59.21],[-135.5,59.2],[-135.39,59.09],[-135.06,58.34],[-135.06,58.28],[-135.14,58.23],[-135.3,58.26],[-135.45,58.38],[-135.57,58.41],[-135.9,58.4],[-135.86,58.58],[-136.04,58.82],[-135.83,58.9],[-136.02,58.87],[-136.15,59.05],[-136.12,58.82],[-136.23,58.77],[-136.45,58.85],[-136.57,58.94],[-136.99,59.04],[-137.06,58.87],[-136.06,58.45],[-136.61,58.24],[-139.77,59.53],[-139.51,59.95],[-139.29,59.61],[-138.99,59.84],[-139.43,60.01],[-140.42,59.71],[-141.41,59.9],[-141.41,60.12],[-144.15,60.02],[-144.9,60.34],[-144.69,60.67],[-145.25,60.38],[-146.57,60.73],[-146.39,60.81],[-146.63,60.99],[-146.38,61.14],[-147.81,60.89],[-148.01,60.97],[-147.75,61.22],[-148.34,61.06],[-148.56,60.8],[-148.28,60.61],[-148.64,60.49],[-147.96,60.48],[-148.43,59.99],[-149.4,60.11],[-149.6,59.77],[-149.71,59.92],[-150.93,59.25],[-151.74,59.19],[-151.93,59.34],[-151.04,59.77],[-151.85,59.78],[-151.4,60.27],[-151.36,60.72],[-150.44,61.02],[-149.07,60.89],[-150.05,61.17],[-149.33,61.5],[-151.59,60.98],[-152.37,60.34],[-153.02,60.3],[-152.63,60.04],[-153.21,59.84],[-153.05,59.73],[-154.09,59.36],[-154.13,59.12],[-153.33,58.88],[-154.25,58.16],[-158.41,56.44],[-158.55,56.31],[-158.28,56.2],[-159.66,55.63],[-159.77,55.84],[-161.38,55.37],[-161.2,55.54],[-161.52,55.62],[-162.08,55.14],[-162.63,55.25],[-162.67,55],[-163.12,55.06],[-163.34,54.84],[-163.28,55.12],[-161.7,55.91],[-160.29,55.8],[-160.54,56.01],[-160.3,56.31],[-158.67,56.8],[-158.32,57.3],[-157.46,57.51],[-157.7,57.68],[-157.61,58.05],[-157.19,58.19],[-157.52,58.42],[-156.97,58.74],[-156.81,59.13],[-158.19,58.62],[-158.5,58.85],[-158.08,58.98],[-158.81,58.97],[-158.95,58.4],[-159.67,58.91],[-160.36,59.05],[-162.14,58.64],[-161.72,58.79],[-161.64,59.11],[-161.98,59.15],[-161.83,59.59],[-162.42,60.28],[-161.96,60.69],[-162.68,60.27],[-162.57,59.99],[-163.68,59.8],[-165.36,60.54],[-164.8,60.89],[-164.32,60.77],[-164.37,60.59],[-163.42,60.76],[-163.91,60.85],[-163.59,60.9],[-163.75,60.97],[-165.11,60.93],[-164.87,61.11],[-165.27,61.27],[-165.57,61.1],[-165.84,61.54],[-166.15,61.55],[-165.81,61.7],[-166.08,61.8],[-165.61,61.87],[-165.71,62.1],[-165.19,62.47],[-164.76,62.5],[-164.59,62.71],[-164.79,62.62],[-164.8,62.92],[-164.38,63.03],[-164.41,63.22],[-163.29,63.05],[-162.28,63.53],[-161.1,63.56],[-160.78,63.82],[-160.99,64.25],[-161.49,64.43],[-160.86,64.76],[-161.76,64.82],[-162.33,64.61],[-162.71,64.38],[-162.81,64.37],[-162.88,64.52],[-163.2,64.65],[-163.3,64.61],[-163.05,64.52],[-163.14,64.42],[-163.71,64.59],[-164.3,64.58],[-164.69,64.51],[-164.76,64.53],[-164.98,64.45],[-166.14,64.58],[-166.33,64.63],[-166.48,64.73],[-166.48,64.8],[-166.41,64.83],[-166.42,64.93],[-166.55,64.95],[-166.93,65.16],[-166.53,65.15],[-166.45,65.25],[-166.16,65.29],[-167.4,65.42],[-168.09,65.66],[-164.46,66.59],[-163.64,66.57],[-163.89,66.58],[-164.03,66.22],[-163.7,66.08],[-161.04,66.19],[-162.61,66.89],[-162.36,66.95],[-161.59,66.46],[-160.23,66.51],[-161.57,66.59],[-161.86,66.7],[-161.72,67.02],[-163.53,67.1],[-164.12,67.61],[-166.79,68.36],[-166.38,68.43],[-166.21,68.89],[-163.87,69.04],[-161.88,70.33],[-162.08,70.16],[-160.12,70.59],[-159.96,70.57],[-160.11,70.47],[-160.01,70.45],[-160.1,70.33],[-159.91,70.33],[-159.87,70.28],[-159.81,70.5],[-159.39,70.52],[-159.75,70.53],[-159.96,70.63],[-160.08,70.63],[-159.68,70.79],[-159.31,70.88],[-159.19,70.86],[-159.34,70.78],[-159.25,70.75],[-159,70.8],[-157.91,70.86],[-157.32,71.04],[-156.78,71.32],[-156.47,71.41],[-156.4,71.4],[-156.57,71.34],[-156.47,71.29],[-155.65,71.18],[-155.58,71.12],[-155.8,71],[-156.15,70.93],[-155.97,70.84],[-155.58,70.89],[-155.17,71.1],[-154.94,71.08],[-154.67,70.99],[-154.79,70.89],[-154.2,70.8],[-153.92,70.88],[-153.23,70.93],[-152.49,70.88],[-152.23,70.81],[-152.44,70.73]],[[143.18,-11.96],[143.75,-14.35],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.03,-18.27],[146.38,-18.98],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.21,-21.12],[149.71,-22.44],[149.98,-22.55],[150.08,-22.16],[150.54,-22.56],[150.67,-22.42],[150.84,-23.46],[151.83,-24.12],[153.03,-25.87],[153.17,-25.96],[153.08,-26.3],[153.16,-26.98],[153.12,-27.19],[153.38,-27.77],[153.45,-28.05],[153.58,-28.24],[153.6,-28.86],[152.95,-31.43],[152.21,-32.68],[152.14,-32.68],[152.19,-32.72],[152.16,-32.76],[151.81,-32.9],[151.48,-33.35],[151.43,-33.52],[151.29,-33.58],[151.28,-33.93],[151.24,-33.99],[151.12,-34.01],[151.23,-34.03],[150.96,-34.3],[150.78,-34.89],[150.81,-34.99],[150.68,-35.08],[150.71,-35.16],[150.57,-35.21],[150.2,-35.83],[149.93,-37.53],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.45,-39.11],[146.16,-38.87],[146.07,-38.83],[145.94,-38.9],[145.79,-38.67],[145.61,-38.66],[145.4,-38.54],[145.46,-38.42],[145.54,-38.39],[145.48,-38.24],[145.29,-38.24],[145.19,-38.38],[144.96,-38.5],[144.72,-38.34],[144.91,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.67,-38.21],[144.1,-38.46],[143.69,-38.77],[141.93,-38.28],[141.43,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.98,-35.62],[139.29,-35.61],[139.28,-35.38],[138.19,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.02,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.78,-32.58],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.17],[134.23,-32.55],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.01],[123.51,-33.92],[119.85,-33.97],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.51],[115.36,-33.64],[115.61,-33.37],[115.68,-33.19],[115.62,-32.67],[115.71,-32.57],[115.74,-31.89],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.18,-26.18],[113.36,-26.08],[113.58,-26.56],[113.83,-26.5],[113.45,-25.6],[113.72,-26.13],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.96,-21.94],[114.12,-21.83],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.11,-19.99],[121,-19.6],[122.35,-18.11],[122.14,-17.43],[122.33,-17.06],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.88,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.4,-16.3],[124.65,-15.87],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.36,-15.12],[125.18,-14.72],[125.63,-14.26],[125.66,-14.53],[126.02,-14.5],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.18,-14.71],[128.07,-15.33],[128.58,-14.77],[129.64,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.94,-13.5],[130.14,-13.45],[130.26,-13.3],[130.14,-13.15],[130.17,-12.96],[130.32,-12.88],[130.4,-12.69],[130.62,-12.65],[130.62,-12.43],[130.74,-12.43],[130.87,-12.56],[130.87,-12.37],[131.03,-12.34],[131.05,-12.19],[131.22,-12.18],[131.29,-12.07],[131.34,-12.21],[131.44,-12.28],[131.89,-12.23],[132.07,-12.28],[132.25,-12.19],[132.41,-12.3],[132.44,-12.18],[132.58,-12.11],[132.67,-11.65],[132.28,-11.47],[132.13,-11.5],[131.81,-11.27],[131.96,-11.18],[132.16,-11.31],[135.03,-12.19],[135.92,-11.83],[135.71,-12.21],[135.94,-12.15],[136.08,-12.42],[136.54,-11.96],[136.95,-12.35],[136.46,-13.23],[135.93,-13.3],[135.95,-13.93],[135.45,-14.92],[140.04,-17.7],[140.83,-17.41],[141.29,-16.46],[141.63,-15.06],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[142.46,-10.71],[142.78,-11.12],[142.87,-11.82],[143.07,-11.92]],[[-29.95,83.56],[-25.8,83.26],[-32.03,82.98],[-25.12,83.16],[-24.47,82.88],[-21.52,82.6],[-23.12,82.33],[-29.89,82.05],[-25.15,82],[-24.29,81.7],[-22.94,82.03],[-21.13,81.93],[-21.5,81.44],[-23.12,80.78],[-19.63,81.64],[-17.45,81.4],[-15.45,81.84],[-11.42,81.48],[-14.45,80.99],[-14.23,80.87],[-14.5,80.76],[-16.76,80.57],[-15.94,80.43],[-16.49,80.25],[-19.43,80.26],[-20.15,80.01],[-20.07,79.77],[-19.35,79.73],[-19.41,79.35],[-18.99,79.18],[-21.13,78.66],[-20.95,78.55],[-21.73,77.71],[-20.86,77.91],[-19.49,77.72],[-19.29,77.59],[-20.68,77.62],[-20.23,77.37],[-18.44,77.26],[-18.34,76.92],[-22.61,76.68],[-21.49,76.27],[-19.86,76.12],[-19.4,75.49],[-19.52,75.18],[-22.23,75.12],[-20.99,75.07],[-20.78,74.89],[-21.04,74.65],[-20.86,74.64],[-19.99,74.98],[-19.27,74.34],[-21.13,74.11],[-21.95,74.24],[-21.76,74.48],[-21.98,74.57],[-22.33,74.29],[-22.13,73.99],[-20.37,73.85],[-20.64,73.46],[-22.35,73.27],[-24.16,73.77],[-24.68,73.6],[-25.52,73.85],[-24.78,73.54],[-26.06,73.25],[-27.27,73.44],[-26.54,73.25],[-27.56,73.14],[-24.13,73.41],[-22.04,72.92],[-22.29,72.12],[-24.07,72.5],[-24.63,73.04],[-26.66,72.72],[-24.81,72.9],[-24.7,72.51],[-25.2,72.39],[-21.96,71.74],[-22.48,71.38],[-21.75,71.48],[-21.52,70.53],[-22.38,70.46],[-22.44,70.86],[-22.69,70.44],[-23.33,70.45],[-23.97,70.65],[-24.56,71.22],[-27.09,71.63],[-25.84,71.48],[-25.67,71.27],[-26.72,70.95],[-28.4,70.99],[-27.98,70.84],[-29.07,70.44],[-26.51,70.4],[-27.63,70.03],[-27.38,69.99],[-25.53,70.35],[-22.21,70.11],[-23.87,69.74],[-23.74,69.59],[-24.3,69.58],[-26.48,68.68],[-30.98,68.06],[-32.33,68.44],[-32.16,67.99],[-33.16,67.63],[-34.63,66.43],[-35.19,66.25],[-35.87,66.44],[-35.63,66.14],[-37.76,65.59],[-38,65.71],[-37.28,66.3],[-38.15,66.39],[-37.75,66.26],[-38.14,65.9],[-38.52,66.01],[-38.2,65.71],[-40.17,65.56],[-39.58,65.34],[-41.09,65.03],[-40.18,64.48],[-40.78,64.22],[-41.58,64.3],[-40.62,64.13],[-40.55,63.73],[-41.39,63.06],[-42.18,63.21],[-41.64,62.97],[-41.91,62.74],[-42.94,62.72],[-42.15,62.57],[-42.32,62.15],[-42.11,61.86],[-42.59,61.72],[-42.32,61.68],[-43.04,60.52],[-43.92,60.6],[-43.21,60.39],[-43.12,60.06],[-43.95,60.02],[-43.66,59.86],[-43.91,59.81],[-44.41,59.92],[-44.22,60.27],[-44.61,60.02],[-45.38,60.2],[-44.76,60.67],[-45.38,60.44],[-46.05,60.61],[-45.87,61.22],[-46.87,60.82],[-48.18,60.77],[-47.77,61],[-48.39,61.01],[-49.29,61.59],[-49.38,61.89],[-48.83,62.08],[-49.62,62],[-49.55,62.23],[-50.32,62.47],[-49.79,63.05],[-50.39,62.82],[-51.47,63.64],[-51.55,64.01],[-50.26,64.21],[-51.71,64.2],[-50.68,64.68],[-50.01,64.45],[-50.12,64.7],[-50.96,65.2],[-50.72,64.8],[-51.26,64.76],[-51.92,64.22],[-52.54,65.33],[-51.09,65.78],[-52.55,65.46],[-53.2,65.59],[-53.11,65.98],[-53.39,66.05],[-51.23,66.88],[-53.61,66.15],[-53.42,66.65],[-52.39,66.88],[-53.69,66.99],[-53.8,67.42],[-52.51,67.76],[-50.61,67.53],[-51.17,67.69],[-50.97,67.81],[-52.35,67.84],[-53.74,67.55],[-53.15,68.21],[-51.6,68.06],[-51.17,68.39],[-53.38,68.3],[-53.04,68.61],[-51.13,68.6],[-50.8,68.79],[-51.25,68.74],[-51.09,69.13],[-50.3,69.17],[-51.08,69.21],[-50.32,70.03],[-52.26,70.06],[-54.53,70.7],[-52.8,70.75],[-50.68,70.4],[-51.77,71.01],[-51.02,71],[-53.12,71.31],[-51.78,71.68],[-53.44,71.58],[-53.15,71.81],[-53.81,72.29],[-53.65,72.36],[-53.93,72.32],[-53.48,71.85],[-54.02,71.66],[-53.96,71.46],[-55.59,71.55],[-55.32,72.11],[-54.84,72.38],[-55.58,72.18],[-55.29,72.35],[-55.6,72.45],[-54.92,72.57],[-54.74,72.87],[-55.67,73.01],[-55.29,73.33],[-56.1,73.56],[-55.84,73.76],[-56.23,74.13],[-57.23,74.12],[-56.26,74.53],[-58.57,75.35],[-58.25,75.51],[-58.52,75.69],[-63.29,76.35],[-67.08,76.2],[-66.83,75.97],[-68.32,76.09],[-69.48,76.4],[-68.11,76.65],[-69.89,76.83],[-69.69,76.99],[-70.61,76.82],[-71.16,77.07],[-68.14,77.38],[-66.39,77.28],[-66.27,77.51],[-66.82,77.69],[-69.35,77.47],[-70.56,77.72],[-70.12,77.84],[-71.27,77.81],[-72.82,78.19],[-71.65,78.62],[-65.82,79.17],[-64.79,80],[-64.18,80.1],[-66.84,80.08],[-67.19,80.28],[-64.51,81],[-63.06,80.89],[-63.24,81.08],[-62.99,81.21],[-61.44,81.13],[-61.1,81.4],[-61.2,81.75],[-60.43,81.92],[-56.62,81.36],[-59.27,81.98],[-54.55,82.35],[-53.67,82.16],[-53.56,81.65],[-53.04,81.87],[-53.02,82.32],[-50.9,81.89],[-49.54,81.92],[-50.99,82.46],[-50.04,82.47],[-44.73,81.78],[-44.33,82.47],[-45.56,82.75],[-41.37,82.75],[-46.48,82.95],[-43.01,83.26],[-41.3,83.1],[-40.36,83.33],[-38.15,83],[-37.94,83.16],[-38.75,83.37],[-30.7,83.59]],[[-86.59,71.01],[-84.82,71.03],[-84.7,71.63],[-85.91,71.99],[-85.32,72.23],[-84.28,72.04],[-85.65,72.72],[-85.26,72.95],[-84.26,72.8],[-85.46,73.11],[-83.41,73.63],[-81.6,73.7],[-80.28,72.77],[-81.23,72.31],[-80.61,72.45],[-80.95,71.92],[-79.88,72.18],[-80.11,72.33],[-79.83,72.45],[-79,72.27],[-79.01,72.04],[-78.58,71.88],[-78.86,72.1],[-78.7,72.35],[-77.52,72.18],[-78.42,72.57],[-77.25,72.74],[-75.07,72.32],[-75.92,71.72],[-75.15,72.06],[-74.27,72.04],[-74.32,71.84],[-75.21,71.71],[-74.7,71.68],[-75,71.22],[-74.49,71.65],[-73.87,71.77],[-73.71,71.72],[-74.2,71.4],[-73.71,71.59],[-73.18,71.28],[-73.28,71.54],[-72.9,71.68],[-71.64,71.52],[-71.19,71.28],[-72.63,70.83],[-70.67,71.05],[-70.76,70.79],[-71.89,70.43],[-71.28,70.5],[-71.43,70.13],[-70.98,70.58],[-70.08,70.83],[-68.5,70.61],[-68.48,70.41],[-70.06,70.04],[-68.78,70.2],[-69.01,69.98],[-68.74,69.94],[-67.86,70.28],[-67.19,69.76],[-69.25,69.51],[-66.68,69.26],[-69.04,69.1],[-67.75,69.04],[-67.88,68.78],[-69.32,68.86],[-66.71,68.45],[-67.03,68.33],[-66.92,68.07],[-66.21,68.28],[-66.53,67.85],[-65.94,68.07],[-65.51,67.97],[-65.4,67.68],[-65.41,67.88],[-64.98,68.04],[-65.02,67.79],[-63.85,67.57],[-64.59,67.32],[-63.04,67.23],[-63.7,66.82],[-62.12,67.05],[-61.3,66.65],[-62.12,66.64],[-61.58,66.41],[-61.86,66.31],[-62.55,66.41],[-61.99,66.03],[-62.59,66.03],[-62.38,65.83],[-62.66,65.64],[-63.46,65.85],[-63.65,65.66],[-63.34,65.62],[-63.36,65.23],[-63.61,64.93],[-64.35,65.17],[-64.27,65.4],[-64.55,65.12],[-65.4,65.76],[-64.45,66.32],[-65.82,66],[-65.66,66.2],[-66.06,66.13],[-66.99,66.63],[-67.31,66.57],[-67.23,66.31],[-67.88,66.47],[-67.18,66.03],[-67.35,65.93],[-68.75,66.2],[-68.22,66.08],[-67.87,65.77],[-67.94,65.56],[-67.12,65.44],[-67.34,65.35],[-66.7,64.82],[-66.63,65],[-66.21,64.72],[-65.94,64.89],[-65.43,64.73],[-65.27,64.63],[-65.53,64.51],[-65.08,64.44],[-65.58,64.29],[-64.68,64.03],[-64.8,63.92],[-64.41,63.71],[-64.67,63.24],[-65.19,63.76],[-64.67,62.92],[-65.16,62.93],[-65.11,62.63],[-66.66,63.26],[-66.72,63.08],[-67.89,63.73],[-67.72,63.42],[-68.91,63.7],[-65.98,62.21],[-66.33,61.87],[-71.35,63.07],[-71.99,63.42],[-71.38,63.58],[-72.5,63.82],[-73.45,64.4],[-73.27,64.58],[-74.07,64.43],[-74.68,64.83],[-74.92,64.77],[-74.7,64.5],[-76.86,64.24],[-78.17,64.62],[-78.05,64.98],[-77.36,65.2],[-77.33,65.45],[-75.83,65.23],[-75.45,64.84],[-75.36,65.01],[-75.8,65.3],[-73.55,65.48],[-74.42,66.17],[-72.22,67.26],[-73.28,68.36],[-73.82,68.36],[-73.85,68.7],[-74.42,68.58],[-74.91,68.82],[-74.85,69.07],[-76.59,68.7],[-76.56,69.01],[-75.65,69.21],[-76.52,69.52],[-76.23,69.66],[-77.09,69.64],[-76.86,69.78],[-77.59,69.85],[-77.77,70.24],[-79.07,70.6],[-79.4,70.4],[-78.81,70.18],[-79.09,69.93],[-81.65,70.1],[-80.92,69.73],[-81.56,69.94],[-85.78,70.04],[-86.32,70.15],[-86.4,70.47],[-87.9,70.25],[-88.85,70.52],[-89.46,71.06],[-87.14,71.01],[-89.69,71.42],[-90.02,71.95],[-89.66,72.17],[-89.82,72.47],[-88.71,73.4],[-86.77,73.83],[-85.01,73.78],[-86.67,72.76],[-86.32,72.46],[-86.22,71.9],[-85.02,71.35],[-86.47,71.04]],[[-69.49,83.02],[-66.42,82.93],[-68.47,82.65],[-64.9,82.9],[-63.5,82.79],[-63.64,82.71],[-63.09,82.56],[-63.25,82.45],[-61.21,82.34],[-68.69,81.29],[-64.78,81.49],[-69.55,80.38],[-70.71,80.54],[-70.26,80.23],[-72.06,80.12],[-70.56,80.07],[-71.39,79.76],[-74.39,79.87],[-74.66,79.84],[-73.2,79.6],[-76.9,79.51],[-74.48,79.23],[-74.53,79.05],[-78.58,79.08],[-74.43,78.72],[-76.42,78.51],[-75.19,78.33],[-75.97,77.99],[-78.01,77.95],[-78.08,77.52],[-78.49,77.37],[-81.66,77.53],[-81.28,77.37],[-82.06,77.3],[-79.5,77.2],[-79.22,76.94],[-78,76.85],[-78.28,76.57],[-80.8,76.17],[-80.97,76.47],[-82.53,76.72],[-82.23,76.47],[-83.89,76.45],[-84.22,76.67],[-84.28,76.36],[-86.45,76.58],[-86.68,76.38],[-87.49,76.59],[-87.5,76.39],[-88.4,76.41],[-88.49,76.77],[-88.54,76.42],[-89.57,76.49],[-89.5,76.83],[-88.56,77.07],[-86.81,77.19],[-87.68,77.44],[-88.02,77.78],[-86.76,77.86],[-84.49,77.37],[-83.61,77.44],[-82.59,77.99],[-83.78,77.53],[-84.86,77.5],[-85.29,77.56],[-85.55,77.93],[-84.22,78.18],[-84.91,78.24],[-84.78,78.53],[-85.59,78.11],[-86.22,78.08],[-85.92,78.34],[-87.55,78.18],[-86.81,78.77],[-81.75,78.98],[-84.41,79],[-84.57,79.07],[-83.58,79.05],[-86.42,79.84],[-86.5,80.26],[-83.72,80.23],[-80.48,79.61],[-80.12,79.67],[-81.01,79.69],[-82.99,80.32],[-76.86,80.87],[-78.72,80.95],[-76.88,81.43],[-81.01,80.66],[-85.15,80.52],[-86.62,80.63],[-83.29,81.15],[-85.78,81.04],[-87.71,80.66],[-89.26,80.91],[-84.94,81.29],[-89.62,81.03],[-89.98,81.12],[-89.21,81.25],[-89.68,81.33],[-89.43,81.39],[-87.6,81.53],[-90.31,81.4],[-90.61,81.43],[-89.82,81.63],[-91.68,81.64],[-88.06,82.1],[-85.05,81.98],[-86.62,82.22],[-84.9,82.45],[-79.43,81.85],[-82.45,82.39],[-81.68,82.52],[-82.12,82.63],[-80.81,82.59],[-81.18,82.75],[-81.01,82.78],[-78.75,82.68],[-80.16,82.91],[-79.89,82.94],[-77.48,82.88],[-76.01,82.54],[-75.57,82.61],[-77.13,83.01],[-74.41,83.01],[-72.66,82.72],[-73.44,82.95],[-69.57,83.02]],[[133.47,-0.73],[134.11,-0.85],[134.19,-2.31],[134.46,-2.83],[134.63,-2.54],[135.09,-3.35],[135.49,-3.34],[136.39,-2.27],[137.07,-2.11],[137.12,-1.84],[137.91,-1.48],[139.79,-2.35],[144.48,-3.83],[145.77,-4.82],[145.75,-5.4],[147.42,-5.97],[147.8,-6.31],[147.81,-6.7],[146.95,-6.88],[147.26,-7.46],[148.13,-8.1],[148.58,-9.05],[149.2,-9.03],[149.26,-9.5],[150.01,-9.69],[149.76,-9.81],[149.87,-10.01],[150.85,-10.24],[150.45,-10.31],[150.65,-10.52],[150.32,-10.65],[149.75,-10.35],[147.77,-10.07],[146.03,-8.08],[144.51,-7.57],[144.14,-7.76],[143.65,-7.46],[143.94,-7.95],[143.52,-8],[143.61,-8.2],[142.21,-8.2],[143.38,-8.76],[142.65,-9.33],[141.13,-9.22],[140,-8.2],[140.12,-7.92],[139.38,-8.19],[139.25,-7.98],[138.93,-8.26],[139.09,-7.59],[138.75,-7.25],[139.18,-7.19],[138.6,-6.94],[138.87,-6.86],[138.44,-6.34],[138.34,-5.68],[138.09,-5.71],[137.28,-4.95],[135.19,-4.45],[134.68,-4.08],[134.89,-3.94],[133.97,-3.82],[133.68,-3.48],[133.84,-3.05],[133.4,-3.9],[132.97,-4.09],[132.75,-3.29],[131.97,-2.79],[132.72,-2.79],[133.19,-2.44],[133.7,-2.62],[133.92,-2.1],[132.31,-2.24],[131.93,-1.56],[131,-1.42],[131.26,-0.86],[132.39,-0.36],[133.27,-0.64]],[[116.81,6.69],[117.23,6.94],[117.69,6.35],[117.5,5.88],[118,6.05],[117.97,5.71],[118.35,5.81],[119.26,5.37],[119.13,5.1],[118.26,4.99],[118.55,4.38],[117.5,4.13],[117.78,3.69],[117.06,3.62],[118.06,2.32],[117.79,2.03],[118.99,0.98],[118.53,0.81],[117.91,1.1],[117.52,0.24],[117.56,-0.77],[116.91,-1.22],[116.74,-1.04],[116.75,-1.33],[116.28,-1.79],[116.55,-2.41],[115.96,-3.59],[114.7,-4.17],[114.34,-3.24],[113.71,-3.46],[113.04,-2.93],[112.76,-3.32],[111.86,-3.55],[111.7,-2.89],[110.26,-2.97],[109.98,-1.28],[109.29,-0.85],[109.13,-0.45],[109.26,0.03],[108.91,0.79],[109.08,1.5],[109.63,2.03],[111.22,1.4],[111.04,1.63],[111.51,2.74],[112.99,3.16],[114.01,4.57],[114.99,5.02],[115.43,4.97],[115.42,5.41],[115.88,5.61],[116.78,6.99],[116.84,6.77]],[[-114.52,72.59],[-113.58,72.65],[-113.08,73],[-111.27,72.71],[-111.89,72.36],[-111.67,72.3],[-110.21,72.66],[-110.66,73.01],[-110.01,72.98],[-108.76,72.55],[-108.19,71.72],[-107.81,71.63],[-107.3,71.9],[-107.7,72.15],[-108.24,73.15],[-107.93,73.22],[-108.03,73.35],[-106.48,73.2],[-105.41,72.79],[-104.38,71.58],[-104.51,71.06],[-103.59,70.63],[-101.09,70.14],[-100.91,69.81],[-102.24,69.84],[-102.62,69.55],[-103.43,69.67],[-103.05,69.47],[-103.12,69.2],[-102.15,69.49],[-101.79,69.18],[-102.89,68.82],[-105.1,68.92],[-105.02,69.08],[-106.14,69.16],[-106.66,69.44],[-107.44,69],[-109.47,68.68],[-113.02,68.48],[-113.55,68.77],[-113.69,69.19],[-116.51,69.43],[-117.19,70.05],[-111.63,70.31],[-113.76,70.69],[-117.59,70.63],[-118.38,70.97],[-115.3,71.49],[-117.94,71.39],[-118.23,71.47],[-117.74,71.66],[-118.99,71.76],[-118.94,71.99],[-118.21,72.26],[-118.37,72.53],[-116.57,73.06],[-114.21,73.3],[-114.08,72.91],[-114.5,72.63]],[[49.54,-12.43],[49.94,-13.07],[50.41,-15.63],[50.19,-15.96],[49.89,-15.46],[49.66,-15.52],[49.84,-16.49],[49.45,-17.24],[49.36,-18.34],[47.18,-24.79],[46.73,-25.15],[45.11,-25.54],[44.03,-25],[43.26,-22.38],[43.5,-21.36],[44.4,-19.92],[43.98,-17.39],[44.48,-16.22],[46.16,-15.74],[46.4,-15.93],[46.47,-15.51],[46.94,-15.22],[47.1,-15.43],[47.35,-14.77],[47.48,-15.01],[47.97,-14.67],[47.77,-14.37],[47.94,-13.66],[48.26,-13.72],[48.8,-13.27],[48.79,-12.47],[49.21,-12.08],[49.48,-12.35]],[[96.49,5.23],[97.55,5.21],[98.31,4.09],[99.73,3.18],[100.31,2.47],[100.53,2.19],[100.82,1.99],[100.89,1.95],[100.83,2.24],[100.94,2.29],[101.05,2.26],[101.3,2.01],[101.48,1.69],[101.79,1.62],[102.39,0.84],[102.57,0.75],[102.85,0.72],[103.03,0.58],[103.07,0.49],[102.79,0.3],[102.55,0.22],[102.78,0.24],[103.34,0.51],[103.48,0.48],[103.67,0.29],[103.79,0.05],[103.43,-0.19],[103.53,-0.75],[104.38,-1.07],[104.51,-1.82],[104.85,-2.09],[104.65,-2.59],[105.4,-2.38],[106.04,-3.11],[105.89,-5.01],[105.82,-5.68],[105.75,-5.82],[105.62,-5.8],[105.52,-5.67],[104.64,-5.52],[104.6,-5.91],[101.58,-3.17],[100.89,-2.25],[100.31,-0.83],[99.16,0.35],[98.6,1.87],[97.7,2.36],[96.97,3.58],[95.58,4.66],[95.23,5.56],[96.25,5.27]],[[-3.11,58.52],[-3.99,57.96],[-3.86,57.82],[-4.13,57.58],[-1.96,57.68],[-1.78,57.47],[-2.09,57.1],[-2.26,56.86],[-2.59,56.56],[-3.31,56.36],[-2.89,56.4],[-2.65,56.32],[-2.67,56.25],[-2.98,56.19],[-3.36,56.03],[-3.79,56.09],[-3.61,56.02],[-3.05,55.95],[-2.84,56.03],[-2.6,56.03],[-2.15,55.9],[-1.65,55.57],[-1.23,54.7],[-0.08,54.12],[0.12,53.61],[-0.66,53.72],[0.13,53.47],[0.35,53.16],[0.21,53.03],[0.05,52.91],[0.33,52.81],[0.52,52.94],[1.66,52.75],[1.75,52.47],[1.32,51.96],[1.23,51.97],[1.28,51.84],[1.19,51.8],[0.96,51.81],[0.75,51.73],[0.9,51.69],[0.89,51.57],[0.42,51.47],[0.53,51.49],[0.69,51.39],[0.89,51.36],[1.42,51.36],[1.4,51.18],[1.05,51.05],[0.96,50.93],[0.77,50.93],[0.2,50.76],[-0.2,50.82],[-0.79,50.76],[-1.42,50.9],[-1.33,50.82],[-1.52,50.75],[-3,50.72],[-3.4,50.63],[-3.68,50.24],[-3.79,50.23],[-4.2,50.39],[-4.73,50.29],[-5.01,50.16],[-5.12,50.04],[-5.23,50.02],[-5.43,50.11],[-5.62,50.05],[-5.66,50.13],[-5.34,50.25],[-4.89,50.53],[-4.58,50.78],[-4.52,50.98],[-4.3,51.03],[-4.19,51.19],[-3.84,51.23],[-3.26,51.19],[-3.04,51.25],[-2.43,51.74],[-3.29,51.39],[-3.56,51.41],[-3.89,51.59],[-4.24,51.57],[-4.09,51.66],[-4.39,51.74],[-4.6,51.74],[-4.9,51.63],[-5.12,51.71],[-5.2,51.86],[-5.26,51.88],[-5.09,52],[-4.38,52.2],[-4.15,52.33],[-4.1,52.92],[-4.68,52.84],[-3.81,53.3],[-3.32,53.35],[-3.1,53.26],[-3.17,53.39],[-3.07,53.43],[-2.92,53.3],[-2.75,53.31],[-2.91,53.35],[-3.07,53.51],[-2.93,53.73],[-3.03,53.77],[-3.03,53.91],[-2.9,53.96],[-2.87,54.18],[-3.17,54.13],[-3.57,54.47],[-3.59,54.56],[-3.47,54.77],[-3.27,54.91],[-3.04,54.95],[-3.55,54.95],[-3.96,54.78],[-4.3,54.84],[-4.91,54.69],[-5.17,54.92],[-4.68,55.5],[-4.73,55.6],[-4.87,55.87],[-4.58,55.94],[-4.67,55.97],[-4.8,56.16],[-5.23,55.89],[-5.09,56.2],[-5.77,55.36],[-5.19,56.76],[-5.65,56.53],[-6.13,56.71],[-5.59,57.1],[-5.82,57.44],[-5.58,57.55],[-5.69,57.78],[-5.16,57.88],[-5.41,58.07],[-5.01,58.26],[-4.98,58.58],[-3.06,58.59]],[[141.23,41.37],[141.45,41.4],[141.43,40.72],[141.8,40.29],[141.98,39.43],[141.47,38.4],[140.96,38.15],[141,37.11],[140.79,36.85],[140.63,36.5],[140.57,36.23],[140.62,36.06],[140.87,35.72],[140.64,35.66],[140.46,35.51],[140.36,35.18],[140.06,35.04],[139.92,34.9],[139.8,34.96],[139.84,35.01],[139.83,35.3],[140.1,35.59],[139.99,35.67],[139.83,35.66],[139.77,35.49],[139.65,35.41],[139.74,35.25],[139.68,35.15],[139.47,35.3],[139.25,35.28],[139.13,35.15],[139.09,34.84],[138.98,34.7],[138.84,34.62],[138.76,34.7],[138.8,34.97],[138.9,35.02],[138.72,35.12],[138.58,35.09],[138.35,34.85],[138.19,34.6],[137.06,34.58],[137.3,34.73],[137.1,34.76],[136.96,34.84],[136.94,34.72],[136.87,34.73],[136.85,34.98],[136.9,35.03],[136.8,35.05],[136.69,34.98],[136.53,34.68],[136.88,34.43],[136.85,34.32],[136.33,34.18],[135.92,33.56],[135.69,33.49],[135.45,33.55],[135.13,34.01],[135.1,34.29],[135.31,34.42],[135.42,34.62],[135.04,34.63],[134.74,34.77],[134.25,34.71],[133.97,34.53],[132.31,34.32],[132.14,33.84],[131.74,34.05],[130.92,33.98],[131,34.39],[131.35,34.41],[132.75,35.45],[134.21,35.54],[134.46,35.63],[135.18,35.75],[135.27,35.72],[135.23,35.59],[135.27,35.55],[135.68,35.5],[136.01,35.68],[136.09,35.77],[136.01,35.99],[136.07,36.12],[136.7,36.74],[136.84,37.38],[137.32,37.52],[136.9,37.12],[137.3,36.75],[138.32,37.22],[139.36,38.1],[140.04,39.41],[140,39.86],[139.74,39.92],[140.01,40.26],[139.92,40.6],[140.39,41.23],[140.75,40.83],[141.12,40.88],[141.25,41.21],[140.8,41.25],[140.94,41.5],[141.11,41.46]],[[-119.74,74.11],[-117.51,74.23],[-115.39,73.5],[-118.96,72.68],[-120.18,72.21],[-120.62,71.51],[-122.84,71.1],[-124.01,71.68],[-125.84,71.98],[-124.99,72.59],[-124.97,72.84],[-124.57,72.94],[-124.8,73.13],[-123.8,73.77],[-124.7,74.35],[-121.5,74.54],[-119.56,74.23],[-119.74,74.13]],[[-91.89,81.13],[-90.64,80.59],[-89.24,80.51],[-88.86,80.17],[-88.2,80.11],[-88.61,80.26],[-88.52,80.42],[-87.67,80.37],[-87.92,80.1],[-86.98,79.89],[-87.3,79.58],[-85.65,79.61],[-85.04,79.28],[-87.62,78.68],[-87.92,78.75],[-87.83,79.05],[-88.04,79],[-88.25,78.67],[-87.98,78.54],[-88.74,78.58],[-88.79,78.19],[-90.04,78.61],[-89.49,78.17],[-91.41,78.19],[-92.85,78.46],[-91.87,78.54],[-93.27,78.61],[-93.64,78.75],[-93.16,78.78],[-94.17,78.97],[-91.3,79.37],[-95.1,79.29],[-95.73,79.42],[-94.4,79.74],[-95.86,79.67],[-96.77,80.14],[-94.26,80.2],[-96.39,80.32],[-95.55,80.37],[-96.15,80.55],[-95.93,80.72],[-93.93,80.56],[-95.51,80.84],[-95.27,81],[-93.24,81.13],[-94.18,81.34],[-92,81.18]],[[-15.54,66.23],[-14.6,66.38],[-15.11,66.1],[-14.7,66.02],[-14.83,65.76],[-14.39,65.79],[-14.47,65.57],[-13.62,65.52],[-13.8,65.35],[-13.57,65.07],[-14.63,64.42],[-18.08,63.5],[-20.49,63.69],[-20.41,63.81],[-20.65,63.74],[-21.14,63.89],[-21.09,63.93],[-21.15,63.94],[-21.45,63.86],[-22.65,63.83],[-22.69,63.87],[-22.74,64.02],[-22.7,64.08],[-22.51,63.99],[-22.06,64.07],[-21.67,64.35],[-21.46,64.38],[-21.65,64.4],[-22.05,64.31],[-21.9,64.39],[-22,64.41],[-21.95,64.52],[-21.59,64.63],[-22.16,64.54],[-22.33,64.63],[-22.25,64.73],[-22.47,64.8],[-24.02,64.86],[-23.32,64.96],[-22.79,65.05],[-21.89,65.05],[-21.8,65.11],[-21.78,65.19],[-22.04,65.13],[-22.51,65.2],[-21.84,65.45],[-22.31,65.48],[-22.64,65.57],[-24.47,65.52],[-23.86,65.54],[-24.09,65.78],[-23.29,65.75],[-23.83,65.85],[-23.52,65.88],[-23.78,66.02],[-23.45,66.18],[-22.44,65.91],[-22.95,66.21],[-22.48,66.27],[-23.12,66.34],[-22.89,66.44],[-21.41,66.03],[-21.38,65.74],[-21.66,65.72],[-21.36,65.58],[-21.43,65.47],[-21.23,65.42],[-21.13,65.27],[-21.05,65.43],[-20.45,65.57],[-20.21,66.1],[-19.49,65.77],[-19.38,66.08],[-18.84,66.18],[-18.14,65.73],[-18.3,66.16],[-17.55,65.96],[-16.49,66.2],[-16.54,66.45],[-16.25,66.52],[-15.65,66.26]],[[-94.29,76.91],[-93.21,76.75],[-93.53,76.45],[-91.31,76.68],[-90.54,76.5],[-91.41,76.46],[-89.29,76.3],[-91.41,76.22],[-89.28,75.79],[-89.65,75.57],[-88.92,75.45],[-88.65,75.66],[-85.95,75.4],[-83.93,75.82],[-82.15,75.83],[-79.66,75.45],[-79.51,75.26],[-80.38,75.03],[-79.4,74.92],[-80.35,74.9],[-80.15,74.8],[-80.28,74.58],[-81.94,74.47],[-82.93,74.57],[-83.52,74.9],[-83.34,74.77],[-83.53,74.59],[-84.43,74.51],[-88.42,74.49],[-88.34,74.78],[-88.53,74.83],[-89.56,74.56],[-90.88,74.82],[-91.51,74.65],[-92.39,75.26],[-92.07,75.66],[-92.18,75.85],[-93.09,76.35],[-95.27,76.26],[-96.04,76.49],[-95.65,76.58],[-96.9,76.75],[-96.4,76.8],[-96.76,76.97],[-95.85,77.07],[-94.61,76.96]],[[173.12,-41.28],[173.95,-40.92],[173.8,-41.27],[174,-40.99],[174.3,-41.02],[174.04,-41.24],[174.37,-41.1],[174.07,-41.43],[174.21,-41.85],[172.53,-43.47],[173.1,-43.84],[172.04,-43.7],[172.18,-43.9],[171.24,-44.26],[170.78,-45.87],[169.69,-46.55],[169.1,-46.63],[168.38,-46.61],[167.54,-46.15],[166.83,-46.23],[166.92,-45.96],[166.49,-45.96],[167,-45.71],[166.73,-45.54],[166.87,-45.31],[167.16,-45.41],[167.03,-45.12],[167.91,-44.67],[168.37,-44.08],[169.18,-43.91],[171.04,-42.86],[172.27,-40.76],[172.94,-40.52],[172.7,-40.67],[173.07,-41.19]],[[16.79,79.91],[17.83,79.8],[17.67,79.39],[18.4,79.61],[18.82,79.43],[18.68,79.26],[20.61,79.11],[20.77,79.06],[20.5,78.98],[21.39,78.74],[19.15,78.38],[16.7,76.58],[14,77.51],[16.91,77.9],[14.09,77.77],[13.68,78.03],[17.17,78.42],[16.45,78.5],[16.78,78.66],[15.42,78.47],[15.38,78.77],[14.69,78.72],[14.43,78.49],[14.64,78.41],[13.15,78.24],[11.37,78.95],[12.4,78.95],[11.98,79.03],[11.98,79.29],[11.21,79.13],[10.68,79.76],[13.69,79.86],[13.92,79.76],[12.56,79.57],[13.96,79.34],[14.59,79.8],[16.34,78.98],[15.83,79.71],[16.25,80.05],[16.52,80.02]],[[67.77,76.24],[61.36,75.32],[59.67,74.61],[58.53,74.5],[58.62,74.23],[57.77,74.01],[57.76,73.77],[57.31,73.84],[57.54,73.66],[56.63,73.31],[54.3,73.35],[53.76,73.77],[55.34,74.42],[56.14,74.5],[55.58,74.63],[56.5,74.96],[55.81,75.12],[57.61,75.34],[58.88,75.86],[60.94,76.07],[61.2,76.28],[64.46,76.38],[67.53,77.01],[68.94,76.71],[68.16,76.28]],[[124.89,1],[124.43,0.47],[123.75,0.31],[120.58,0.53],[120.19,0.27],[120.06,-0.55],[120.67,-1.37],[121.15,-1.34],[121.58,-0.83],[121.97,-0.93],[123.17,-0.57],[123.43,-0.78],[123.38,-1],[122.9,-0.9],[122.25,-1.55],[121.36,-1.88],[122.29,-2.91],[122.25,-3.62],[122.85,-4.07],[122.87,-4.39],[122.12,-4.54],[122.04,-4.83],[121.59,-4.76],[121.62,-4.09],[120.89,-3.52],[121.05,-2.75],[120.65,-2.67],[120.26,-2.95],[120.43,-5.59],[119.56,-5.61],[119.36,-5.32],[119.62,-4.03],[119.47,-3.51],[118.92,-3.48],[118.78,-2.72],[119.32,-1.93],[119.51,-0.91],[119.71,-0.68],[119.84,-0.86],[119.72,-0.09],[120.27,0.97],[120.6,0.85],[121.08,1.33],[122.84,0.85],[123.85,0.84],[125.11,1.69],[125.23,1.5],[124.97,1.08]],[[-55.46,51.54],[-56.03,51.33],[-55.8,51.03],[-56.82,49.61],[-56.18,50.12],[-56.16,49.94],[-55.5,49.98],[-56.14,49.62],[-55.23,49.51],[-55.35,49.08],[-54.5,49.53],[-54.45,49.33],[-53.62,49.32],[-53.57,49.14],[-54.16,48.79],[-53.71,48.66],[-54.11,48.39],[-53.03,48.63],[-53.87,48.02],[-53.64,48.02],[-53.86,47.8],[-53.67,47.65],[-52.86,48.11],[-53.17,47.51],[-52.78,47.77],[-52.65,47.55],[-53.07,46.68],[-53.59,46.64],[-53.6,47.15],[-54.18,46.88],[-53.85,47.44],[-54.19,47.86],[-54.49,47.4],[-55.79,46.87],[-55.92,47.02],[-54.78,47.66],[-55.58,47.46],[-56.13,47.5],[-55.86,47.82],[-56.77,47.57],[-59.26,47.63],[-59.34,47.93],[-58.33,48.52],[-59.17,48.56],[-58.71,48.6],[-58.41,49.08],[-57.99,48.99],[-58.21,49.39],[-57.79,49.49],[-57.93,49.7],[-57.04,51.01],[-56.03,51.57],[-55.45,51.56]],[[-108.29,76.06],[-107.72,76],[-108.02,75.8],[-107.21,75.89],[-106.91,75.68],[-106.68,76.02],[-105.9,76.01],[-105.48,75.7],[-106.09,75.09],[-108.83,75.07],[-112.52,74.42],[-114.38,74.67],[-111.03,75.23],[-113.71,75.07],[-113.85,75.26],[-113.47,75.42],[-114.01,75.43],[-114.52,75.28],[-114.45,75.09],[-115.73,74.97],[-117.6,75.27],[-115.14,75.68],[-117.16,75.65],[-114.99,75.9],[-116.66,75.96],[-116.21,76.19],[-114.78,76.17],[-115.83,76.3],[-115,76.5],[-112.7,76.2],[-111.05,75.55],[-109.09,75.51],[-108.92,75.67],[-109.87,75.93],[-109.43,76.11],[-110.31,76.4],[-108.83,76.82],[-108.47,76.74],[-108.63,76.59],[-108.12,76.23],[-108.39,76.07]],[[173.27,-34.93],[174.37,-35.33],[174.54,-35.58],[174.51,-35.67],[174.58,-35.79],[174.39,-35.8],[174.8,-36.31],[174.75,-36.49],[174.82,-36.61],[174.72,-36.84],[174.89,-36.91],[174.95,-36.85],[175.3,-36.99],[175.38,-37.21],[175.54,-37.2],[175.49,-36.69],[175.38,-36.56],[175.46,-36.48],[175.68,-36.75],[175.77,-36.73],[175.99,-37.44],[176.12,-37.54],[176.13,-37.59],[176.03,-37.58],[176.11,-37.64],[177.27,-37.99],[178.01,-37.55],[178.53,-37.69],[177.91,-39.24],[177.08,-39.22],[176.84,-40.16],[175.98,-41.21],[175.31,-41.61],[174.87,-41.22],[174.64,-41.29],[175.21,-40.2],[173.76,-39.32],[174.57,-38.84],[174.65,-38.43],[174.84,-38.02],[174.8,-37.9],[174.93,-37.8],[174.73,-37.45],[174.77,-37.34],[174.71,-37.33],[174.59,-37.1],[174.66,-37.09],[174.73,-37.22],[174.81,-37.11],[174.93,-37.09],[174.78,-36.94],[174.6,-36.98],[174.47,-36.94],[174.38,-36.73],[174.19,-36.49],[174.4,-36.6],[174.46,-36.51],[174.36,-36.38],[174.39,-36.24],[174.27,-36.16],[174.25,-36.25],[174.03,-36.12],[173.92,-35.91],[173.92,-36.02],[174.17,-36.33],[174.15,-36.38],[174.06,-36.36],[173.41,-35.54],[173.63,-35.32],[173.31,-35.44],[172.71,-34.46],[173.04,-34.43],[173.24,-34.9]],[[-7.18,55.06],[-6.13,55.22],[-5.72,54.82],[-5.71,54.76],[-5.88,54.68],[-5.88,54.64],[-5.58,54.66],[-5.47,54.5],[-5.48,54.44],[-5.67,54.55],[-5.66,54.38],[-5.56,54.37],[-5.61,54.27],[-5.83,54.24],[-6.02,54.05],[-6.22,54.09],[-6.16,54.02],[-6.35,53.99],[-6.14,53.58],[-6.15,53.37],[-6.03,52.93],[-6.17,52.74],[-6.22,52.54],[-6.46,52.34],[-6.32,52.25],[-6.89,52.16],[-6.96,52.25],[-7.08,52.14],[-7.22,52.14],[-9.3,51.5],[-10.12,51.6],[-9.6,51.87],[-10.34,51.8],[-9.91,52.12],[-10.36,52.21],[-8.78,52.68],[-9.92,52.57],[-8.93,53.21],[-10.09,53.41],[-9.58,53.8],[-9.91,53.86],[-10.06,54.26],[-8.54,54.24],[-8.13,54.64],[-8.76,54.68],[-8.27,55.15],[-7.67,55.26],[-7.66,54.97],[-7.31,55.37],[-6.96,55.24],[-7.22,55.09]],[[107.37,-6.01],[107.56,-6.18],[108.14,-6.3],[108.29,-6.26],[108.42,-6.38],[108.78,-6.81],[110.43,-6.95],[110.84,-6.42],[112.54,-6.93],[113.01,-7.66],[114.41,-7.79],[114.58,-8.77],[113.25,-8.29],[111.51,-8.3],[107.29,-7.47],[106.53,-7.39],[106.41,-7.31],[106.52,-7.05],[105.94,-6.86],[105.48,-6.85],[105.26,-6.84],[105.34,-6.67],[105.37,-6.66],[105.4,-6.77],[105.48,-6.78],[105.66,-6.47],[105.79,-6.46],[105.87,-6.12],[106.07,-5.91],[106.83,-6.1],[107.01,-6.01],[107.05,-5.9],[107.33,-5.98]],[[142.76,54.39],[143.33,52.96],[143.19,51.95],[144.71,48.64],[144.05,49.25],[143.1,49.2],[142.56,47.74],[143.58,46.36],[143.43,46.03],[143.28,46.56],[142.58,46.7],[142.08,45.92],[141.83,46.45],[142.18,48.01],[141.86,48.75],[142.14,49.57],[142.21,51.22],[141.72,51.74],[141.66,52.27],[141.83,53.34],[142.53,53.45],[142.71,53.89],[142.34,54.28],[142.69,54.42]],[[-81.84,23.16],[-79.82,22.89],[-74.15,20.17],[-77.72,19.86],[-77.23,20.64],[-78.12,20.76],[-78.73,21.59],[-81.85,22.21],[-82.08,22.39],[-81.71,22.5],[-81.7,22.59],[-81.84,22.67],[-82.74,22.69],[-84.84,21.83],[-84.04,22.67],[-83.26,22.97],[-82.1,23.19]],[[143.82,44.12],[144.72,43.93],[145.37,44.33],[145.14,43.66],[145.34,43.3],[145.83,43.39],[143.97,42.88],[143.24,42],[141.85,42.58],[140.99,42.34],[140.48,42.56],[140.33,42.29],[141.15,41.81],[140.04,41.47],[139.86,42.58],[140.43,42.95],[140.39,43.3],[141.38,43.28],[141.76,44.48],[141.67,45.4],[141.94,45.51],[143.76,44.13]],[[121.1,18.62],[121.85,18.29],[122.27,18.46],[122.15,17.66],[122.52,17.12],[122.14,16.19],[121.69,16.02],[121.6,15.93],[121.56,15.83],[121.61,15.67],[121.39,15.32],[121.69,14.77],[121.63,14.58],[121.77,14.17],[121.91,14.02],[122.21,13.93],[122.29,14],[122.2,14.15],[122.49,14.32],[122.94,14.19],[123.1,13.75],[123.32,14.06],[123.86,13.8],[123.55,13.65],[123.79,13.11],[124.14,13.04],[124.06,12.57],[123.95,12.92],[123.31,13.04],[122.59,13.91],[122.6,13.19],[122.21,13.65],[122.07,13.79],[121.78,13.94],[121.5,13.84],[121.45,13.71],[121.34,13.65],[121.1,13.68],[120.93,13.76],[120.84,13.89],[120.73,13.9],[120.64,13.81],[120.62,14.19],[120.92,14.49],[120.94,14.65],[120.59,14.88],[120.55,14.77],[120.59,14.48],[120.44,14.45],[120.25,14.79],[120.08,14.85],[119.93,15.43],[119.77,16.25],[120.37,16.11],[120.6,18.51],[121.05,18.61]],[[-100,73.95],[-99.16,73.73],[-97.11,73.79],[-97,73.67],[-97.63,73.5],[-97.27,73.39],[-98.43,72.96],[-97.63,73.03],[-97.13,72.63],[-96.54,72.7],[-96.47,72.43],[-96.8,72.32],[-96.61,71.83],[-97.58,71.63],[-98.32,71.85],[-98.2,71.44],[-99.17,71.37],[-100.59,72.15],[-102.71,72.77],[-102.2,73.08],[-101.27,72.72],[-100.13,72.91],[-100.54,73.2],[-99.82,73.21],[-101.52,73.49],[-100.52,73.45],[-100.99,73.77],[-100.14,73.93]],[[55.32,73.31],[56.43,73.2],[56.12,72.81],[55.4,72.55],[55.52,72.22],[55.3,71.94],[56.45,71.11],[57.62,70.73],[56.26,70.71],[56.44,70.56],[53.72,70.81],[53.38,70.87],[54.16,71.12],[53.41,71.34],[53.41,71.53],[51.81,71.49],[51.44,71.78],[51.58,72.07],[52.62,72.3],[52.92,72.67],[52.55,72.77],[53.37,72.92],[53.25,73.18],[55.12,73.36]],[[-84.92,65.26],[-84.5,65.46],[-82.05,64.64],[-81.68,64.21],[-81.89,64.02],[-80.83,64.09],[-80.26,63.8],[-81.05,63.46],[-83.3,64.14],[-84.63,63.31],[-85.39,63.12],[-85.77,63.7],[-87.18,63.6],[-86.25,64.14],[-86.37,64.57],[-85.81,65.83],[-85.24,65.8],[-85.06,65.44]],[[126.01,9.32],[126.31,8.95],[126.14,8.6],[126.46,8.2],[126.58,7.25],[126.19,6.85],[126.19,6.31],[125.69,7.26],[125.38,6.69],[125.67,5.98],[125.35,5.6],[125.23,6.07],[124.93,5.88],[124.08,6.4],[123.99,6.99],[124.21,7.4],[123.67,7.82],[123.39,7.41],[122.62,7.76],[122.14,6.95],[121.9,7.07],[122.24,7.94],[122.91,8.16],[123.44,8.7],[123.85,8.43],[123.8,8.05],[124.4,8.6],[124.73,8.56],[124.87,8.97],[125.5,9.01],[125.47,9.76],[125.96,9.43]],[[140.05,75.83],[140.82,75.63],[140.99,75.96],[141.49,76.14],[145.36,75.53],[144.02,75.04],[142.82,75.27],[142.7,75.45],[142.94,75.71],[142.31,75.69],[142.09,75.66],[142.2,75.39],[143.13,74.97],[139.68,74.96],[139.1,74.66],[138.09,74.8],[136.95,75.33],[137.29,75.35],[137.27,75.75],[137.71,75.76],[137.56,75.96],[138.21,76.12],[138.92,76.2],[139.74,75.95]],[[-93.17,74.16],[-90.36,73.87],[-92.12,72.75],[-94.21,72.76],[-93.54,72.44],[-94.14,72],[-95.19,72.03],[-95.6,72.88],[-95.63,73.7],[-94.7,73.66],[-95.15,73.91],[-94.97,74.04],[-93.41,74.18]],[[145.04,-40.79],[146.32,-41.16],[148.22,-40.85],[148.34,-42.22],[148.22,-41.97],[148.02,-42.26],[147.98,-43.16],[147.3,-42.79],[146.87,-43.61],[146.04,-43.55],[146.21,-43.32],[145.49,-42.93],[145.2,-42.23],[145.52,-42.35],[144.77,-41.39],[144.72,-40.67],[144.82,-40.72]],[[20.9,80.25],[22.29,80.05],[22.45,80.4],[23.01,80.47],[23.32,80.42],[23.11,80.19],[24.4,80.36],[26.86,80.16],[27.2,79.91],[23.95,79.19],[20.13,79.49],[19.68,79.59],[20.78,79.75],[18.73,79.76],[18.25,79.93],[18.86,80.04],[17.92,80.14],[19.34,80.12],[19.54,80.16],[19.18,80.33],[19.75,80.23],[19.73,80.48],[20.69,80.3]],[[-71.95,19.72],[-69.96,19.67],[-69.74,19.3],[-69.32,19.33],[-69.23,19.27],[-69.32,19.2],[-69.61,19.21],[-69.62,19.12],[-68.36,18.54],[-68.69,18.21],[-68.93,18.41],[-69.27,18.44],[-69.77,18.44],[-70.02,18.37],[-70.18,18.25],[-70.48,18.22],[-70.64,18.34],[-71.03,18.27],[-71.11,18.07],[-71.44,17.64],[-72.06,18.23],[-73.88,18.04],[-74.39,18.62],[-72.35,18.62],[-72.7,19.44],[-73.4,19.81]],[[-69.17,-52.67],[-68.63,-52.65],[-68.24,-53.08],[-68.49,-53.26],[-67.29,-54.05],[-66.24,-54.53],[-65.18,-54.68],[-66.51,-55.03],[-71.9,-54.6],[-70.8,-54.33],[-70.31,-54.53],[-70.86,-54.11],[-70.53,-53.63],[-70.38,-53.99],[-70.63,-54],[-70.24,-54.35],[-69.05,-54.43],[-70.15,-53.89],[-69.39,-53.37],[-70.21,-53.41],[-70.46,-53.21],[-70.13,-52.94],[-70.38,-52.75],[-69.94,-52.82],[-69.5,-52.49],[-69.41,-52.49]],[[97.67,80.16],[98.02,80.02],[97.65,79.76],[98.6,80.05],[99.95,79.85],[99.68,79.32],[99.04,79.29],[99.93,78.96],[97.56,78.83],[93.07,79.5],[94.99,80.1],[97.59,80.17]],[[-115.55,77.36],[-116.33,77.14],[-115.81,76.94],[-116.25,76.9],[-115.94,76.71],[-117,76.53],[-117.23,76.28],[-117.99,76.41],[-117.88,76.8],[-118.79,76.51],[-118.62,76.37],[-118.99,76.15],[-119.58,76.33],[-119.74,76.12],[-119.54,75.98],[-119.91,75.86],[-120.41,75.83],[-120.85,76.18],[-122.4,75.94],[-122.9,76.13],[-119.09,77.3],[-116.84,77.34],[-117.04,77.46],[-116.51,77.55],[-116.01,77.46]],[[79.98,9.81],[80.71,9.37],[81.83,7.43],[81.77,6.61],[81.38,6.24],[80.73,5.98],[80.5,5.95],[80.27,6.01],[80.1,6.15],[79.86,6.83],[79.71,8.07],[79.75,8.29],[79.75,8.05],[79.81,8.05],[79.85,8.41],[80.08,9.58],[80.43,9.48],[79.97,9.79]],[[-97.7,76.47],[-97.53,76.11],[-97.89,75.76],[-97.41,75.67],[-97.34,75.42],[-97.88,75.42],[-97.66,75.15],[-98.07,75.2],[-97.99,75.05],[-100.23,75.01],[-100.48,75.19],[-100.14,75.25],[-100.73,75.35],[-99.19,75.7],[-102.8,75.6],[-102.15,75.87],[-100.97,75.8],[-101.87,76.08],[-101.56,76.24],[-102.14,76.28],[-101.79,76.45],[-99.87,75.92],[-99.69,75.96],[-100.11,76.12],[-99.54,76.15],[-100.89,76.48],[-100.07,76.63],[-98.89,76.47],[-99.02,76.61],[-98.71,76.69],[-97.72,76.5]],[[96.53,81.08],[97.86,80.7],[97.11,80.61],[97.42,80.32],[97.17,80.24],[93.87,80.01],[91.53,80.36],[92.83,80.62],[93.26,80.79],[92.61,80.81],[93.36,81.03],[95.16,81.27],[96.47,81.1]],[[-103.43,79.32],[-102.58,78.88],[-101.7,79.08],[-100.01,78.73],[-99.58,78.56],[-99.75,78.3],[-99,78],[-99.96,77.79],[-101.07,78.19],[-104.51,78.29],[-105,78.52],[-103.57,78.54],[-104.02,78.63],[-103.37,78.74],[-104.18,78.78],[-103.88,78.9],[-104.15,78.99],[-104.9,78.81],[-104.75,79.03],[-105.58,79.11],[-105.39,79.32],[-103.71,79.35]],[[102.88,79.25],[102.41,78.84],[103.8,79.15],[105.34,78.59],[104.74,78.34],[99.29,78.04],[100.42,78.75],[100.95,78.79],[101.05,79.12],[101.59,79.35],[103.1,79.3],[102.94,79.27]],[[131.18,33.6],[131.69,33.6],[131.54,33.27],[131.9,33.25],[132.01,32.92],[131.34,31.4],[131.07,31.44],[130.69,31.01],[130.78,31.71],[130.59,31.18],[130.15,31.41],[130.55,32.83],[130.24,33.18],[130.34,32.7],[129.77,32.57],[129.68,33.06],[129.99,32.85],[129.58,33.24],[130.72,33.93],[131.06,33.67]],[[-127.2,50.64],[-125.48,50.32],[-124.83,49.53],[-123.85,49.12],[-123.5,48.58],[-123.41,48.7],[-123.29,48.46],[-123.31,48.41],[-123.45,48.43],[-123.57,48.32],[-125.12,48.76],[-124.81,49.21],[-125.49,48.93],[-125.93,49.4],[-126.52,49.4],[-126.54,49.59],[-126.13,49.67],[-127.12,49.88],[-127.25,50.14],[-127.86,50.13],[-127.91,50.45],[-127.49,50.41],[-127.46,50.58],[-128.35,50.7],[-127.92,50.86],[-127.71,50.82]],[[121.01,22.62],[120.84,21.92],[120.08,23.09],[120.13,23.65],[120.63,24.48],[121.04,25.03],[121.59,25.28],[121.91,25.06],[121.93,24.97],[121.82,24.82],[121.83,24.53],[121.64,24.13],[121.52,23.67],[121.16,22.78]],[[-79.54,73.65],[-77.21,73.5],[-76.09,72.88],[-79.5,72.76],[-80.78,73.33],[-80.86,73.67],[-79.89,73.7]],[[-49.63,-0.23],[-48.39,-0.3],[-48.83,-1.39],[-49.8,-1.79],[-50.51,-1.79],[-50.79,-0.91],[-50.65,-0.27],[-50.25,-0.12]],[[110.89,19.99],[111.01,19.66],[110.02,18.42],[109.52,18.22],[108.7,18.54],[108.67,19.3],[109.26,19.88],[110.65,20.14],[110.81,20.02]],[[151.92,-4.3],[152.41,-4.34],[152.35,-4.82],[151.98,-5.07],[152.08,-5.46],[151.52,-5.55],[150.47,-6.26],[149.65,-6.29],[148.34,-5.67],[148.43,-5.47],[149.83,-5.52],[150.09,-5.01],[150.18,-5.52],[150.74,-5.51],[151.67,-4.88],[151.59,-4.2],[151.87,-4.26]],[[-97.44,69.64],[-95.27,68.83],[-96.6,68.46],[-99.56,69.03],[-98.5,69.31],[-98.55,69.57],[-98.04,69.46],[-98.3,69.67],[-98.08,69.83],[-97.47,69.67]],[[21.61,78.6],[22.04,78.58],[22.3,78.23],[23.45,78.15],[23.12,77.99],[24.9,77.76],[22.8,77.28],[22.43,77.32],[22.69,77.55],[21.05,77.44],[20.87,77.57],[21.65,77.92],[20.23,78.48],[21.45,78.6]],[[15.58,38.22],[15.1,37.46],[15.29,37.06],[15.11,36.69],[14.37,36.97],[14.14,37.1],[13.8,37.14],[12.92,37.57],[12.64,37.59],[12.44,37.82],[12.55,38.05],[12.74,38.18],[12.9,38.03],[13.16,38.19],[13.35,38.18],[13.38,38.13],[13.79,37.98],[14.05,38.04],[14.51,38.05],[14.79,38.17],[15.63,38.27]],[[9.63,40.88],[9.8,40.5],[9.56,39.17],[9.06,39.24],[8.97,38.96],[8.65,38.93],[8.42,39.21],[8.55,39.84],[8.2,40.87],[9.23,41.26],[9.57,40.91]],[[127.3,-8.42],[125.41,-9.28],[124.43,-10.15],[123.61,-10.27],[123.71,-9.62],[125.18,-8.65],[127.26,-8.39]],[[-93.54,75.03],[-93.57,74.67],[-94.54,74.64],[-96.6,75.06],[-95.95,75.44],[-94.88,75.63],[-93.91,75.42],[-93.55,75.05]],[[134.36,34.26],[134.64,34.23],[134.68,33.85],[134.74,33.82],[134.38,33.61],[134.18,33.25],[133.69,33.52],[133.29,33.36],[132.87,32.75],[132.49,32.92],[132.41,33.43],[132.03,33.34],[132.94,34.1],[133.47,33.97],[133.95,34.35],[134.07,34.36],[134.22,34.32]],[[-75.67,68.32],[-75.06,68.14],[-75.13,67.54],[-75.4,67.37],[-76.95,67.25],[-77.31,67.69],[-76.69,68.26],[-75.87,68.34]],[[-96.21,78.53],[-94.92,78.39],[-95.33,78.22],[-94.93,78.08],[-96.99,77.81],[-97.66,78.09],[-96.94,78.15],[-98.05,78.33],[-98.34,78.75],[-96.26,78.55]],[[-52.73,69.94],[-51.9,69.6],[-53.75,69.26],[-54.18,69.4],[-53.66,69.47],[-53.83,69.54],[-54.92,69.71],[-54.79,69.95],[-54.32,69.94],[-54.83,70.13],[-54.37,70.32],[-53.1,70.14]],[[-110.46,78.1],[-109.62,78.06],[-110.86,77.83],[-110.15,77.76],[-110.2,77.53],[-111.95,77.34],[-113.17,77.53],[-113.28,77.81],[-110.73,78.1]],[[146.8,75.37],[150.82,75.16],[150.58,74.92],[149.05,74.77],[146.15,75.2],[146.44,75.56],[146.75,75.43]],[[127.73,0.85],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[128.43,-0.89],[127.69,-0.24],[127.43,1.14],[127.63,1.84],[128.04,2.2],[128.01,1.33],[127.68,0.89]],[[180,71.54],[181.56,71.54],[182.5,71.22],[178.79,70.82],[178.63,71.05],[179.88,71.52]],[[142.19,73.9],[143.34,73.57],[143.49,73.25],[139.69,73.42],[141.08,73.87],[141.93,73.91]],[[-152.9,57.82],[-152.43,57.83],[-152.21,57.58],[-152.94,57.5],[-152.68,57.34],[-153.97,56.77],[-153.79,56.99],[-154.25,57.14],[-154.34,56.92],[-154.71,57.34],[-154.12,57.65],[-153.69,57.3],[-153.84,57.86],[-152.85,57.9]],[[129.75,-2.87],[130.57,-3.13],[130.81,-3.86],[129.84,-3.33],[129.47,-3.45],[128.86,-3.24],[128.52,-3.45],[128.13,-3.16],[127.9,-3.5],[128.2,-2.87],[129.6,-2.81]],[[50.28,80.93],[51.7,80.69],[48.9,80.37],[48.68,80.3],[48.98,80.16],[48.39,80.1],[46.64,80.3],[49.09,80.52],[49.24,80.82],[50.13,80.92]],[[164.2,-20.25],[165.19,-20.77],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.06,-20.14]],[[122.78,-8.61],[121.04,-8.93],[119.81,-8.7],[119.88,-8.42],[120.61,-8.24],[122.32,-8.63],[122.92,-8.1],[122.82,-8.6]],[[125.24,12.53],[125.54,12.19],[125.74,11.05],[125.03,11.34],[125,11.77],[124.44,12.15],[124.29,12.57],[125.15,12.57]],[[-105.29,72.92],[-106.95,73.51],[-105.51,73.77],[-104.59,73.58],[-104.62,73.31],[-105.2,72.95]],[[-133.57,56.34],[-133.2,56.32],[-132.17,55.48],[-132.63,55.47],[-131.98,55.21],[-132.02,54.73],[-133.12,55.33],[-133.03,55.59],[-133.68,55.79],[-133.24,55.92],[-133.74,55.96],[-133.6,56.32]],[[12.57,55.79],[12.54,55.66],[12.32,55.59],[12.22,55.47],[12.39,55.39],[12.41,55.29],[12.09,55.19],[12.05,54.81],[11.86,54.77],[11.74,54.92],[11.66,55.19],[11.29,55.2],[11.17,55.33],[11.19,55.47],[11.12,55.6],[11.01,55.64],[10.98,55.72],[11.32,55.75],[11.48,55.94],[11.63,55.96],[11.69,55.91],[11.69,55.73],[11.82,55.7],[11.94,55.9],[11.87,55.97],[12.22,56.12],[12.58,56.06],[12.61,56.03],[12.53,55.92]],[[34.46,35.59],[33.94,35.29],[34.05,34.99],[33.01,34.57],[32.32,34.95],[32.94,35.39],[34.55,35.66]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.46,70.94]],[[106.04,-1.67],[106.36,-2.46],[106.82,-2.57],[106.67,-3.07],[106,-2.83],[105.79,-2.18],[105.13,-2.04],[105.46,-1.57],[106.03,-1.59]],[[-82,62.96],[-82.12,62.65],[-83.02,62.21],[-83.7,62.16],[-83.91,62.43],[-83.38,62.9],[-82.05,62.97]],[[122.5,11.61],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.4,11.7]],[[-61.11,45.94],[-60.86,45.98],[-61.06,45.7],[-60.74,45.75],[-60.3,46.31],[-59.83,45.96],[-60.67,45.59],[-61.45,45.72],[-61.41,46.17],[-60.49,47.01],[-60.49,46.27],[-60.91,46.04]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.19,9.09]],[[-73.77,-43.35],[-74.39,-43.23],[-74.04,-41.8],[-73.53,-41.9],[-73.42,-42.19],[-73.79,-42.59],[-73.44,-42.94],[-73.74,-43.29]],[[118.24,-8.32],[118.93,-8.3],[119.13,-8.67],[116.79,-9.01],[116.83,-8.53],[117.16,-8.37],[117.97,-8.73],[118.23,-8.59],[117.76,-8.15],[118.2,-8.27]],[[62.17,80.83],[62.08,80.62],[61.05,80.42],[59.29,80.57],[59.72,80.84],[62.1,80.87]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[117.41,8.5]],[[-109.82,78.65],[-109.35,78.37],[-113.29,78.33],[-110.88,78.74],[-109.94,78.68]],[[54.72,81.12],[57.69,80.79],[55.89,80.63],[54.07,80.81],[54.63,81.11]],[[9.48,42.81],[9.56,42.16],[9.19,41.39],[8.81,41.59],[8.57,42.36],[9.32,42.71],[9.36,43.02],[9.48,42.86]],[[50.27,69.19],[48.91,68.74],[48.28,69.04],[48.42,69.35],[48.96,69.51],[50.17,69.26]],[[178.28,-17.37],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.51,-17.54],[178.25,-17.33]],[[-61.8,49.09],[-63.04,49.23],[-64.49,49.89],[-62.86,49.71],[-61.75,49.11]],[[-77.26,18.46],[-76.91,18.39],[-76.7,18.26],[-76.35,18.15],[-76.21,17.91],[-76.52,17.87],[-76.85,17.97],[-76.94,17.85],[-77.12,17.88],[-77.2,17.71],[-77.36,17.83],[-77.77,17.88],[-78.33,18.35],[-77.87,18.52]],[[-44.87,82.08],[-47.35,82.6],[-44.92,82.48],[-44.78,82.24]],[[-158.28,21.58],[-158.12,21.71],[-157.98,21.71],[-157.65,21.31],[-157.71,21.26],[-157.95,21.3],[-158.1,21.3],[-158.23,21.46]],[[-155.87,20.27],[-155.1,19.86],[-154.81,19.51],[-155.62,18.91],[-155.88,19.07],[-156.05,19.73],[-155.83,20]],[[-156.69,20.95],[-156.4,20.92],[-156,20.8],[-156,20.62],[-156.45,20.58],[-156.51,20.78],[-156.69,20.88]],[[-159.79,22.07],[-159.4,22.23],[-159.29,22.1],[-159.38,21.88],[-159.68,21.95]],[[-157.31,21.1],[-156.71,21.16],[-156.75,21.08],[-157.25,21.08]],[[144.62,13.24],[144.66,13.43],[144.79,13.53],[144.95,13.65],[144.88,13.43],[144.76,13.25],[144.7,13.23]],[[134.45,7.35],[134.48,7.28],[134.56,7.42],[134.65,7.7],[134.6,7.73],[134.52,7.55]],[[171,7.04],[171.42,7.03],[171.45,7.14],[171,7.12]],[[159.6,-9.25],[160.2,-9.4],[160.8,-9.85],[160.6,-9.95],[159.95,-9.75],[159.6,-9.5]],[[-149.62,-17.5],[-149.37,-17.53],[-149.18,-17.87],[-149.32,-17.78],[-149.6,-17.8],[-149.62,-17.66]],[[-172.07,-13.8],[-171.44,-13.79],[-171.43,-14.05],[-172,-14.04]],[[-172.78,-13.48],[-172.21,-13.58],[-172.25,-13.8],[-172.7,-13.78]],[[-170.84,-14.29],[-170.56,-14.24],[-170.56,-14.31],[-170.82,-14.36]],[[-175.36,-21.1],[-175.05,-21.13],[-175.08,-21.24],[-175.3,-21.2]],[[146.95,-9.25],[147.45,-9.2],[147.55,-9.55],[147.05,-9.65]],[[166.25,-22.1],[166.65,-22.05],[166.7,-22.4],[166.3,-22.45]],[[178.2,-17.95],[178.6,-17.95],[178.6,-18.25],[178.2,-18.25]],[[-64.89,32.25],[-64.82,32.29],[-64.7,32.36],[-64.64,32.39],[-64.67,32.35],[-64.76,32.28],[-64.85,32.23]],[[-25.86,37.9],[-25.48,37.83],[-25.13,37.83],[-25.15,37.72],[-25.5,37.71],[-25.85,37.76]],[[-27.38,38.78],[-27.05,38.76],[-27.04,38.64],[-27.35,38.66]],[[-28.55,38.55],[-28.05,38.43],[-28.1,38.39],[-28.5,38.46]],[[-28.83,38.64],[-28.6,38.62],[-28.62,38.52],[-28.8,38.53]],[[-16.92,28.37],[-16.65,28.4],[-16.13,28.58],[-16.35,28.37],[-16.5,28.06],[-16.75,28.03],[-16.88,28.2]],[[-15.8,28.15],[-15.4,28.17],[-15.36,27.9],[-15.6,27.74],[-15.82,27.9]],[[-13.85,29.22],[-13.45,29.24],[-13.47,28.88],[-13.85,28.9]],[[-14.2,28.75],[-13.84,28.72],[-13.9,28.25],[-14.5,28.06]],[[-17.92,28.85],[-17.75,28.83],[-17.83,28.46],[-17.96,28.62]],[[-17.35,28.2],[-17.1,28.2],[-17.12,28.02],[-17.32,28.03]],[[-18.15,27.8],[-17.9,27.83],[-17.95,27.65],[-18.12,27.7]],[[-23.76,15.27],[-23.47,15.33],[-23.43,15.02],[-23.52,14.91],[-23.78,15.05]],[[-24.5,15],[-24.3,15],[-24.3,14.82],[-24.5,14.82]],[[-25.08,16.9],[-24.88,16.9],[-24.88,16.78],[-25.05,16.8]],[[-25.35,17.2],[-24.98,17.1],[-25,16.98],[-25.33,17]],[[-22.98,16.84],[-22.88,16.84],[-22.88,16.6],[-22.98,16.6]],[[-22.95,16.2],[-22.7,16.15],[-22.72,15.98],[-22.93,16]],[[-5.79,-15.9],[-5.65,-15.9],[-5.63,-16],[-5.75,-16.03]],[[-65.63,18.28],[-65.6,18.22],[-65.74,18.18],[-65.94,17.97],[-66.2,17.92],[-66.77,18],[-66.93,17.93],[-67.18,17.94],[-67.15,18.2],[-67.27,18.36],[-67.1,18.52],[-66.38,18.49],[-65.62,18.39]],[[-77.48,24.99],[-77.55,25],[-77.56,25.02],[-77.55,25.04],[-77.5,25.06],[-77.34,25.08],[-77.26,25.06],[-77.38,25],[-77.44,25.01],[-77.47,24.99]],[[-61,10.7],[-61.04,10.51],[-60.96,10.33],[-61,10.14],[-61.19,10.07],[-61.93,10.06],[-61.67,10.18],[-61.63,10.25],[-61.51,10.24],[-61.46,10.28],[-61.49,10.63],[-61.67,10.71],[-61.37,10.8],[-60.95,10.85],[-60.91,10.84]],[[-59.43,13.16],[-59.43,13.13],[-59.51,13.06],[-59.62,13.09],[-59.65,13.16],[-59.65,13.32],[-59.59,13.33],[-59.54,13.23]],[[-60.81,14.46],[-61.07,14.47],[-61.11,14.52],[-61,14.57],[-61.16,14.67],[-61.22,14.85],[-60.88,14.78],[-60.94,14.67]],[[-68.78,12.1],[-68.74,12.05],[-68.81,12.04],[-68.98,12.12],[-69.16,12.29],[-69.17,12.39],[-69.07,12.34],[-69,12.22],[-68.84,12.17]],[[55.79,-21.1],[55.85,-21.16],[55.81,-21.34],[55.58,-21.37],[55.35,-21.27],[55.23,-21.03],[55.29,-20.91],[55.41,-20.86],[55.58,-20.87],[55.7,-20.94]],[[57.8,-20.22],[57.78,-20.34],[57.67,-20.48],[57.38,-20.51],[57.31,-20.44],[57.36,-20.41],[57.4,-20.2],[57.6,-19.98],[57.68,-20]],[[55.4,-4.66],[55.37,-4.64],[55.43,-4.56],[55.46,-4.57],[55.46,-4.63],[55.53,-4.68],[55.54,-4.8],[55.46,-4.76],[55.48,-4.71]],[[-130.12,-25.07],[-130.11,-25.06],[-130.1,-25.06],[-130.09,-25.07],[-130.09,-25.08],[-130.1,-25.08],[-130.11,-25.08],[-130.11,-25.07]],[[-166.29,53.73],[-167.85,53.31],[-166.8,53.63],[-167.16,53.83],[-167.02,53.96],[-166.37,54.01],[-166.22,53.91],[-166.58,53.71]],[[73.55,4.24],[73.55,4.23],[73.54,4.18],[73.51,4.16],[73.43,4.18],[73.51,4.19]]]; +const COAST_LL=[[[86.89,73.89],[85.79,73.44],[86.68,73.11],[85.91,73.39],[87.57,73.81],[86,74.32],[87.23,74.36],[85.79,74.65],[87.47,75.01],[87.01,75.17],[94.16,75.96],[92.86,75.98],[93.26,76.1],[95.58,76.14],[96.08,76.08],[95.65,75.89],[96.5,75.89],[98.66,76.24],[99.77,76.03],[99.54,75.8],[99.82,76.14],[98.8,76.48],[101.6,76.44],[100.93,76.56],[101.1,76.7],[100.91,76.9],[104.01,77.73],[106.06,77.39],[104.2,77.1],[107.43,76.93],[106.42,76.51],[111.11,76.72],[112.62,76.38],[112.66,76.05],[113.27,76.25],[113.56,75.89],[113.86,75.92],[113.57,75.57],[112.45,75.83],[113.73,75.45],[112.92,75.02],[107.27,73.62],[105.14,72.78],[110.87,73.73],[109.67,73.8],[110.26,74.02],[111.55,74.03],[111.23,73.97],[112.15,73.71],[113.03,73.91],[113.42,73.65],[113.16,73.46],[113.49,73.35],[113.16,72.77],[113.67,72.64],[113.22,72.81],[113.89,73.35],[113.51,73.5],[114.06,73.58],[118.45,73.59],[118.94,73.48],[118.46,73.46],[118.43,73.25],[119.75,72.98],[122.54,72.88],[123.62,73.19],[123.32,73.43],[123.41,73.64],[124.54,73.75],[126.55,73.33],[127.74,73.48],[129.1,73.11],[128.6,72.9],[129.25,72.7],[128.42,72.53],[129.28,72.44],[129.28,72.09],[127.73,72.41],[128.91,71.75],[129.21,71.92],[129.46,71.74],[128.84,71.66],[129.76,71.12],[131.02,70.75],[132.04,71.24],[132.65,71.93],[133.69,71.43],[136.09,71.62],[137.94,71.13],[138.32,71.33],[137.92,71.38],[138.23,71.6],[139.99,71.49],[139.72,71.89],[139.36,71.95],[140.19,72.19],[139.18,72.16],[139.14,72.33],[141.08,72.59],[140.65,72.84],[140.81,72.89],[146.25,72.44],[144.29,72.19],[146.83,72.29],[146.11,71.95],[146.23,72.14],[145.76,72.23],[145.76,71.94],[145.07,71.93],[145.19,71.7],[147.26,72.33],[149.5,72.16],[150.02,71.9],[148.92,71.71],[150.67,71.45],[150.1,71.23],[151.58,71.29],[152.09,71.02],[151.76,70.98],[152.51,70.83],[155.89,71.1],[158.7,70.94],[159.91,70.51],[159.83,69.78],[160.91,69.61],[161.34,68.9],[160.86,68.54],[161.56,68.9],[161.54,69.38],[163.2,69.72],[166.89,69.5],[167.86,69.73],[168.3,69.27],[169.31,69.08],[169.61,68.79],[170.54,68.83],[171,69.14],[170.58,69.58],[170.16,69.63],[170.49,70.11],[173.28,69.82],[175.92,69.9],[179.87,69.01],[180,68.98],[181.13,68.75],[181.94,68.27],[182.2,68.34],[181.63,68.57],[184.65,67.68],[184.63,67.36],[185.15,67.35],[185.08,66.62],[185.61,66.34],[185.91,66.47],[185.94,66.23],[186.22,66.43],[185.77,66.63],[185.91,66.94],[185.45,67.09],[186.84,67.07],[186.74,66.84],[187.48,66.95],[186.99,67.06],[188.2,66.93],[189.4,66.25],[190.27,66.06],[189.6,65.93],[189.33,65.62],[188.55,65.79],[188.83,65.5],[187.22,65.68],[187.77,65.45],[187.34,65.25],[187.79,65.05],[186.93,64.85],[187.62,64.43],[187.1,64.53],[186.84,64.28],[186.67,64.54],[186.27,64.36],[184.56,64.82],[183.91,65.47],[181.59,65.49],[181.06,66.03],[181.47,66.4],[181.08,66.18],[180.86,66.37],[180.22,66.02],[180.65,65.52],[179.45,64.82],[178.52,64.6],[176.41,65.07],[177.22,64.86],[176.06,64.96],[174.55,64.68],[175.68,64.78],[176.06,64.9],[176.25,64.84],[176.35,64.71],[176.14,64.59],[176.51,64.68],[176.84,64.63],[177.05,64.72],[177.39,64.77],[177.47,64.74],[177.41,64.57],[177.43,64.44],[177.95,64.22],[178.13,64.24],[178.23,64.36],[178.38,64.26],[178.48,64.13],[178.45,64.01],[178.65,63.97],[178.69,63.84],[178.47,63.57],[179.33,63.19],[179.57,62.77],[179.12,62.32],[177.02,62.78],[177.16,62.56],[172.86,61.47],[172.39,61.06],[170.61,60.43],[170.35,59.97],[169.23,60.6],[167.23,60.41],[166.27,59.86],[166.35,60.48],[165.09,60.1],[164.96,59.84],[163.74,60.03],[161.96,58.08],[162.39,57.72],[162.66,57.95],[163.23,57.79],[162.76,57.24],[162.8,56.81],[163.26,56.69],[163.34,56.23],[162.84,56.06],[162.63,56.23],[163.04,56.52],[162.67,56.49],[162.09,56.09],[161.72,55.5],[162.1,54.75],[160.07,54.19],[159.84,53.78],[159.96,53.55],[159.9,53.38],[160,53.27],[160.03,53.13],[159.95,53.13],[159.77,53.23],[159.59,53.24],[158.95,53.05],[158.75,52.91],[158.56,53.05],[158.47,53.03],[158.43,52.96],[158.61,52.87],[158.48,52.63],[158.49,52.38],[158.33,52.09],[158.1,51.81],[156.75,50.97],[155.56,55.2],[156.02,56.75],[156.85,57.29],[156.87,57.8],[158.27,58.01],[162.07,60.47],[163.71,60.92],[163.56,61.03],[164.01,61.34],[163.8,61.46],[164.21,62.29],[165.4,62.49],[164.42,62.71],[163.33,62.55],[163.09,61.57],[162.39,61.66],[160.17,60.64],[160.38,61.02],[159.79,60.96],[160.31,61.89],[157.09,61.68],[154.29,59.83],[154.15,59.53],[154.97,59.45],[155.16,59.19],[153.36,59.21],[152.82,58.93],[151.33,58.88],[151.12,59.08],[152.26,59.22],[149.64,59.77],[148.8,59.53],[148.96,59.37],[148.73,59.26],[146.54,59.46],[146.05,59.17],[145.55,59.41],[142.58,59.24],[140.79,58.3],[140.45,57.81],[138.66,56.97],[137.69,56.14],[135.26,54.94],[135.26,54.73],[135.85,54.58],[136.8,54.62],[136.72,53.8],[137.16,53.82],[137.14,54.18],[137.67,54.28],[137.34,54.1],[137.84,53.95],[137.25,53.55],[137.95,53.6],[138.53,53.96],[138.25,53.52],[138.45,53.54],[138.66,54.3],[139.71,54.28],[141.38,53.29],[141.18,53.01],[140.84,53.09],[141.26,52.84],[141.13,52.43],[141.49,52.18],[140.52,50.8],[140.38,48.96],[138.11,46.25],[135.13,43.53],[133.16,42.7],[133.06,42.72],[133,42.81],[132.86,42.79],[132.71,42.88],[132.3,42.88],[132.31,43.31],[132.03,43.12],[131.87,43.1],[132.01,43.28],[131.94,43.3],[131.72,43.2],[131.39,42.82],[131.16,42.63],[130.71,42.66],[130.83,42.52],[130.73,42.33],[129.76,41.71],[129.71,40.86],[127.57,39.78],[127.4,39.21],[128.33,38.68],[129.42,37.06],[129.56,35.95],[129.21,35.18],[128.51,35.1],[128.44,34.87],[127.71,34.96],[127.72,34.72],[127.4,34.82],[127.32,34.46],[127.25,34.76],[126.53,34.31],[126.27,34.67],[126.59,34.82],[126.29,35.15],[126.69,36.01],[126.54,36.17],[126.55,36.48],[126.49,36.69],[126.39,36.65],[126.18,36.69],[126.16,36.77],[126.22,36.87],[126.49,37.01],[126.78,36.95],[126.87,36.82],[126.98,36.94],[126.87,36.98],[126.74,37.19],[126.79,37.3],[126.65,37.45],[126.66,37.55],[126.56,37.72],[126.63,37.78],[126.37,37.88],[126.12,37.74],[126.05,37.87],[125.94,37.87],[125.77,37.99],[125.41,37.72],[124.99,37.93],[125.21,38.08],[124.69,38.13],[125.55,38.69],[125.17,38.81],[125.36,39.53],[124.64,39.61],[124.35,40.01],[122.84,39.6],[121.16,38.73],[121.11,38.92],[121.82,39.39],[121.27,39.55],[122.26,40.5],[121.83,40.97],[121.18,40.9],[120.48,40.23],[119.39,39.75],[118.98,39.18],[117.78,39.13],[117.65,38.42],[118.94,38.04],[119.11,37.2],[119.76,37.15],[120.75,37.83],[121.64,37.46],[122.67,37.4],[122.34,36.83],[121.93,36.96],[120.81,36.63],[120.64,36.13],[120.18,36.2],[120.29,35.98],[119.22,35.01],[119.2,34.75],[120.27,34.27],[120.86,32.66],[121.34,32.43],[121.4,32.37],[121.45,32.15],[121.68,32.05],[121.83,31.9],[121.87,31.7],[121.76,31.7],[121.35,31.86],[120.97,31.87],[120.79,32.03],[120.52,32.11],[120.07,31.96],[120.19,31.91],[120.5,32.02],[120.71,31.98],[120.79,31.82],[121.06,31.72],[121.66,31.32],[121.79,31.16],[121.88,30.92],[121.42,30.79],[121,30.56],[120.82,30.35],[120.45,30.39],[120.23,30.25],[120.5,30.3],[120.63,30.13],[120.91,30.16],[121.16,30.3],[121.26,30.3],[121.43,30.23],[121.68,29.98],[122.08,29.87],[121.91,29.78],[121.51,29.48],[121.97,29.49],[121.92,29.13],[121.45,29.13],[121.68,28.95],[121.47,28.64],[121.61,28.29],[121.15,28.33],[120.75,28.01],[120.09,26.67],[119.59,26.79],[119.88,26.33],[119.14,26.12],[119.62,26],[119.62,25.39],[119.18,25.45],[119.29,25.23],[118.98,25.21],[118.66,24.62],[117.84,24.47],[118.06,24.25],[117.37,23.59],[116.91,23.65],[116.47,22.95],[115.64,22.85],[115.5,22.72],[115.38,22.72],[115.2,22.82],[114.85,22.62],[114.75,22.63],[114.71,22.74],[114.65,22.75],[114.54,22.62],[114.55,22.53],[114.34,22.59],[114.27,22.54],[114.34,22.4],[114.27,22.3],[113.9,22.4],[114.01,22.51],[113.83,22.61],[113.62,22.86],[113.62,23.13],[113.45,23.05],[113.44,22.94],[113.33,22.91],[113.55,22.59],[113.59,22.35],[113.55,22.22],[113.15,22.08],[113.09,22.21],[113.01,22.12],[112.99,21.94],[112.9,21.88],[112.81,21.95],[112.66,21.86],[112.36,21.98],[112.3,21.74],[111.94,21.85],[111.6,21.56],[110.41,21.34],[110.16,20.94],[110.52,20.46],[110.12,20.26],[109.66,20.92],[109.93,21.48],[109.52,21.69],[109.08,21.44],[108.48,21.9],[108.5,21.63],[107.81,21.5],[107.16,20.95],[106.68,21],[106.52,20.29],[105.98,19.94],[105.62,18.97],[106.5,17.95],[106.35,17.77],[108.82,15.38],[109.3,13.86],[109.45,12.6],[109.22,12.65],[109.2,11.73],[108.99,11.34],[108.18,10.92],[108.1,10.9],[108,10.72],[107.84,10.7],[107.26,10.4],[107.09,10.5],[107.01,10.66],[106.95,10.4],[106.81,10.43],[106.73,10.54],[106.61,10.47],[106.74,10.44],[106.76,10.3],[106.47,10.3],[106.73,10.19],[106.79,10.12],[106.6,9.86],[106.14,10.22],[106.51,9.82],[106.57,9.64],[106.48,9.56],[106.38,9.56],[105.83,10],[106.16,9.59],[106.21,9.5],[106.17,9.4],[104.77,8.6],[105.03,10.07],[104.26,10.54],[103.59,10.55],[103.65,11.06],[103.15,10.91],[103.12,11.46],[102.65,12.15],[101.72,12.69],[101.44,12.62],[100.9,12.65],[100.86,12.72],[100.96,13.43],[100.6,13.57],[100.54,13.51],[100.23,13.48],[100.02,13.35],[99.99,13.24],[100.09,13.04],[99.96,12.69],[100.01,12.35],[99.16,10.32],[99.25,9.27],[99.83,9.29],[100.42,7.19],[101.5,6.86],[103.2,5.26],[103.45,4.67],[103.48,2.84],[103.81,2.58],[104.22,1.72],[104.28,1.42],[104.18,1.37],[103.98,1.62],[103.99,1.46],[103.69,1.45],[103.48,1.33],[103.36,1.55],[102.73,1.86],[102.55,2.04],[102.15,2.25],[101.78,2.57],[101.52,2.68],[101.3,2.89],[101.35,3.01],[101.3,3.25],[100.72,3.97],[100.8,4.02],[100.66,4.23],[100.26,6.18],[99.6,7.36],[98.24,8.42],[98.7,10.19],[98.56,10.03],[98.47,10.68],[98.88,11.72],[98.64,11.74],[98.57,13.16],[98.2,13.98],[98.11,13.71],[97.81,14.86],[97.58,16.02],[97.72,16.57],[97.38,16.52],[96.85,17.4],[96.77,16.71],[96.43,16.5],[96.19,16.77],[96.32,16.44],[95.39,15.72],[95.35,16.1],[95.18,15.83],[94.94,15.82],[94.89,16.18],[94.66,15.9],[94.7,16.51],[94.23,16.02],[94.59,17.57],[94.05,19.29],[93.93,18.9],[93.49,19.37],[93.83,19.24],[94,19.44],[93.71,19.91],[93.25,20.07],[93.13,19.86],[93.07,20.38],[92.83,20.18],[92.74,20.56],[92.72,20.3],[92.31,20.79],[91.86,22.35],[91.53,22.71],[91.48,22.88],[91.22,22.64],[90.95,22.6],[90.63,23.09],[90.6,23.59],[90.56,23.42],[90.27,23.46],[90.59,23.27],[90.6,23.13],[90.47,23.05],[90.55,22.91],[90.46,22.88],[90.43,22.75],[90.61,22.36],[90.55,22.22],[90.16,21.82],[90.21,22.16],[89.96,22.02],[89.89,22.31],[89.98,22.47],[89.88,22.39],[89.57,21.77],[89.48,22.28],[89.35,21.72],[89.05,22.09],[89.05,21.65],[88.75,21.58],[88.64,22.12],[88.58,21.66],[88.06,21.69],[88.2,22.14],[87.94,22.37],[88.16,22.12],[87.95,21.83],[86.86,21.24],[86.98,20.7],[86.75,20.31],[86.22,19.9],[85.25,19.76],[85.18,19.59],[85.44,19.63],[84.11,18.29],[82.36,17.1],[82.26,16.56],[81.29,16.34],[80.98,15.76],[80.38,15.79],[80.1,14.8],[80.18,14.48],[80.11,14.21],[80.31,13.49],[80.16,13.71],[80.06,13.61],[80.34,13.36],[80.23,12.69],[80.14,12.45],[79.86,11.99],[79.84,10.32],[79.31,10.26],[78.92,9.45],[79.41,9.19],[78.42,9.1],[78.06,8.38],[77.3,8.15],[76.4,9.24],[76.35,9.92],[74.94,12.56],[74.38,14.49],[73.47,16.05],[73.15,17.53],[72.87,18.64],[73.01,19.02],[72.97,19.15],[72.83,18.98],[72.8,19.08],[72.81,19.3],[72.99,19.28],[72.79,19.36],[72.75,19.45],[72.8,19.52],[72.73,19.58],[72.67,19.83],[72.9,20.67],[72.61,21.46],[73.11,21.75],[72.54,21.7],[72.7,21.97],[72.52,21.98],[72.81,22.23],[72.18,22.27],[72.04,21.82],[72.25,21.53],[72.02,21.16],[70.72,20.74],[68.97,22.29],[70.18,22.57],[70.49,23.09],[69.67,22.76],[69.24,22.85],[68.42,23.57],[68.78,23.85],[68.23,23.6],[68.16,23.86],[68.11,23.75],[68.04,23.85],[67.95,23.83],[67.86,23.9],[67.82,23.83],[67.67,23.81],[67.65,23.92],[67.56,23.88],[67.31,24.17],[67.17,24.76],[66.7,24.86],[66.7,25.23],[66.43,25.58],[66.22,25.59],[66.13,25.49],[66.36,25.51],[66.47,25.45],[66.24,25.46],[65.68,25.35],[61.41,25.1],[60.51,25.44],[59.05,25.42],[57.34,25.79],[57.21,26.04],[57.2,26.16],[56.73,27.13],[56.28,27.19],[55.42,26.77],[55.29,26.79],[54.9,26.56],[54.64,26.51],[54.52,26.59],[53.71,26.73],[52.48,27.62],[51.52,27.91],[50.07,30.2],[49.56,30.03],[49,30.51],[48.83,30.04],[47.98,30.01],[48.15,29.57],[47.72,29.39],[48.05,29.35],[48.8,27.72],[50.15,26.66],[50.15,26.1],[50.1,26.12],[50.08,25.96],[50.24,25.62],[50.46,25.42],[50.56,25.09],[50.81,24.79],[50.85,24.89],[50.76,25.45],[51,25.98],[51.26,26.15],[51.54,25.9],[51.57,25.78],[51.49,25.53],[51.61,25.05],[51.43,24.67],[51.27,24.61],[51.42,24.53],[51.31,24.34],[51.54,24.29],[51.6,24.34],[51.67,24.25],[51.77,24.25],[51.84,24.01],[52.12,23.97],[52.51,24.11],[53.03,24.15],[53.89,24.08],[54.4,24.28],[54.75,24.81],[55.1,25.04],[55.52,25.5],[55.94,25.79],[56.17,26.21],[56.31,26.24],[56.41,26.35],[56.37,25.8],[56.3,25.65],[56.36,25.57],[56.37,25.02],[56.64,24.47],[56.91,24.15],[57.22,23.92],[58.58,23.64],[59.84,22.42],[58.47,20.41],[58.17,20.59],[57.86,20.24],[57.81,19.02],[56.82,18.75],[56.38,17.99],[55.48,17.84],[55.06,17.04],[54.07,17],[52.45,16.39],[52.22,15.66],[51.6,15.34],[49.35,14.64],[48.67,14.05],[45.66,13.34],[45.04,12.82],[44.26,12.64],[43.49,12.7],[42.94,14.94],[42.66,15.23],[42.7,16.74],[41.66,18.01],[40.76,19.75],[40.08,20.27],[39.88,20.29],[39.73,20.39],[39.27,20.97],[39.09,21.31],[39.15,21.52],[38.99,21.88],[39.09,22.39],[39.01,22.77],[38.88,22.88],[38.94,22.88],[38.29,23.91],[37.54,24.29],[37.15,25.29],[35.18,28.04],[34.62,28.06],[34.97,29.55],[34.22,27.76],[33.25,28.57],[32.72,29.52],[32.56,29.97],[32.47,29.93],[32.49,29.85],[32.36,29.63],[32.4,29.53],[32.56,29.39],[32.66,28.93],[33.55,27.9],[33.96,26.65],[35.2,24.47],[35.78,23.94],[35.51,23.78],[35.7,22.95],[36.83,22.1],[37.26,21.11],[37.47,18.82],[38.57,18.07],[39.5,15.53],[39.79,15.12],[39.86,15.47],[40.2,15.01],[41.18,14.62],[43.3,12.46],[43.34,12.03],[42.54,11.51],[43.16,11.57],[44.28,10.47],[44.94,10.44],[45.82,10.84],[46.56,10.75],[47.4,11.17],[50.11,11.53],[50.79,11.98],[51.26,11.83],[51.03,10.44],[51.39,10.39],[50.93,10.34],[50.82,9.43],[47.98,4.5],[46.05,2.47],[43.72,0.86],[41.39,-1.87],[40.22,-2.69],[39.23,-4.67],[38.8,-6.07],[39.54,-7.02],[39.29,-7.52],[39.3,-8.44],[39.72,-10],[40.61,-10.66],[40.43,-12.94],[40.83,-14.79],[39.84,-16.44],[37.51,-17.57],[36.41,-18.77],[34.95,-19.81],[34.65,-19.7],[35.31,-22.4],[35.45,-22.12],[35.54,-22.3],[35.44,-24.17],[34.99,-24.65],[32.79,-25.64],[32.59,-26],[32.85,-26.27],[32.96,-26.08],[32.89,-26.83],[32.38,-28.5],[31.34,-29.38],[29.97,-31.32],[27.86,-33.05],[26.61,-33.71],[25.81,-33.74],[25.57,-34.04],[22.55,-34.01],[21.79,-34.37],[19.64,-34.75],[19.39,-34.6],[19.3,-34.62],[19.33,-34.49],[19.24,-34.41],[19.15,-34.42],[19.1,-34.35],[18.83,-34.36],[18.81,-34.11],[18.75,-34.08],[18.53,-34.09],[18.46,-34.17],[18.46,-34.35],[18.41,-34.3],[18.33,-34.07],[18.35,-33.94],[18.47,-33.89],[18.43,-33.72],[18.26,-33.42],[18.16,-33.36],[17.88,-32.96],[17.85,-32.83],[17.89,-32.75],[17.97,-32.71],[18.04,-32.78],[18.12,-32.75],[18.25,-32.65],[18.33,-32.5],[18.21,-31.74],[16.74,-29.01],[15.29,-27.28],[14.5,-24.2],[14.46,-22.45],[11.78,-18],[11.75,-15.83],[12.55,-13.44],[13.79,-11.81],[13.83,-10.93],[13,-9.05],[13.38,-8.37],[12.28,-6.12],[13.07,-5.87],[12.45,-6],[12.24,-5.81],[11.78,-4.57],[9.72,-2.47],[10.06,-2.55],[9.62,-2.37],[9.04,-1.31],[9.5,-1.55],[9.06,-1.3],[8.7,-0.59],[8.95,-0.69],[9.3,-0.35],[9.35,0.34],[9.8,0.04],[10,0.2],[9.33,0.55],[9.62,0.58],[9.6,1.05],[9.39,1.14],[9.81,1.93],[9.95,3.08],[9.56,3.8],[9.69,4.06],[9,4.09],[8.92,4.55],[8.57,4.53],[8.25,4.92],[8.29,4.56],[7.08,4.72],[6.92,4.39],[6.77,4.72],[6.86,4.37],[6.08,4.29],[5.49,4.84],[5.37,5.34],[5.55,5.47],[5.2,5.53],[5.46,5.61],[5.11,5.64],[4.86,6.03],[4.43,6.35],[4.13,6.41],[3.45,6.43],[3.75,6.58],[3.72,6.6],[3.43,6.52],[3.34,6.4],[1.82,6.26],[-2,4.76],[-3.25,5.11],[-3.02,5.13],[-3.2,5.35],[-3.35,5.13],[-5.28,5.21],[-5.06,5.13],[-7.54,4.35],[-8.26,4.59],[-11.73,7.09],[-12.49,7.39],[-12.48,7.75],[-12.85,7.82],[-13.27,8.43],[-12.89,8.63],[-13.18,8.58],[-13.06,8.88],[-13.69,9.54],[-13.69,9.93],[-14.43,10.25],[-14.59,10.77],[-14.89,10.97],[-15.01,10.8],[-15.05,11.14],[-15.39,11.22],[-15.43,11.5],[-15.07,11.6],[-15.5,11.78],[-15.08,11.97],[-15.94,11.79],[-16.79,12.47],[-16.44,12.61],[-16.77,12.63],[-16.75,13.43],[-16.41,13.27],[-15.43,13.47],[-16.44,13.35],[-16.77,13.9],[-16.62,14.04],[-17.53,14.75],[-16.57,15.73],[-16.08,17.55],[-16.09,18.52],[-16.52,19.36],[-16.21,20.23],[-16.88,21.09],[-17.1,20.86],[-16.93,21.9],[-16.36,22.59],[-15.9,23.84],[-14.91,24.72],[-14.47,26.16],[-13.58,26.74],[-12.95,27.91],[-11.55,28.31],[-10.2,29.38],[-9.67,30.11],[-9.81,31.42],[-9.25,32.57],[-8.51,33.25],[-6.9,33.97],[-5.92,35.79],[-5.28,35.9],[-5.25,35.61],[-4.63,35.21],[-2.97,35.41],[-2.84,35.13],[-1.91,35.09],[1.26,36.52],[3.78,36.9],[5.29,36.65],[6.49,37.09],[7.91,36.86],[9.69,37.34],[9.83,37.14],[10.2,37.21],[10.41,36.73],[10.95,37.06],[11.13,36.87],[10.49,36.26],[11.12,35.24],[10.06,34.21],[10.31,33.73],[10.96,33.63],[11.2,33.25],[12.28,32.86],[13.28,32.92],[15.18,32.39],[15.71,31.43],[17.83,30.93],[18.94,30.29],[19.59,30.41],[20.01,30.8],[19.93,31.82],[20.12,32.22],[21.63,32.94],[23.09,32.62],[23.29,32.21],[24.88,31.98],[25.23,31.53],[26.77,31.47],[29.07,30.83],[30.22,31.26],[30.57,31.47],[30.92,31.57],[30.56,31.42],[31,31.46],[31.08,31.6],[32.14,31.34],[31.89,31.48],[31.77,31.29],[32.01,31.22],[32.1,31.09],[32.28,31.2],[32.21,31.29],[32.6,31.07],[33.67,31.13],[34.48,31.59],[35.98,34.55],[35.81,36.31],[36.18,36.81],[35.39,36.57],[34.7,36.82],[33.69,36.18],[32.79,36.04],[31.24,36.82],[30.65,36.87],[30.45,36.27],[29.69,36.16],[28.97,36.72],[27.46,36.71],[28.24,37.03],[27.26,36.98],[27.53,37.16],[27.07,37.66],[27.23,37.98],[26.29,38.28],[26.44,38.64],[26.67,38.34],[27.14,38.45],[26.76,38.71],[27.01,38.89],[26.68,39.29],[26.9,39.55],[26.09,39.52],[26.18,39.99],[26.74,40.4],[27.73,40.33],[27.85,40.38],[27.73,40.48],[27.99,40.49],[27.93,40.38],[27.96,40.37],[29.01,40.39],[29.05,40.42],[28.79,40.53],[29.05,40.65],[29.85,40.74],[29.36,40.81],[29.12,40.94],[29.05,41.01],[29.15,41.22],[29.92,41.15],[30.35,41.2],[31.25,41.11],[33.28,42],[35,42.06],[35.3,41.73],[36.05,41.68],[36.41,41.27],[38.38,40.93],[39.43,41.11],[40.13,40.94],[41.41,41.42],[41.76,41.97],[41.42,42.74],[38.72,44.29],[36.63,45.15],[36.87,45.43],[37.65,45.38],[37.93,46],[38.49,46.09],[37.77,46.64],[38.5,46.66],[38.44,46.81],[39.27,47.04],[39.02,47.27],[35.83,46.62],[35.02,46.11],[35.23,46.44],[34.85,46.19],[35.02,45.7],[35.46,45.32],[36.57,45.39],[36.39,45.07],[35.47,45.1],[33.91,44.39],[33.45,44.55],[33.55,45.1],[32.51,45.4],[33.67,45.95],[33.59,46.1],[31.83,46.28],[32.01,46.43],[31.56,46.56],[32.58,46.62],[32.05,46.64],[31.76,47.21],[31.87,46.65],[30.8,46.55],[30.22,45.87],[29.63,45.72],[29.56,44.84],[28.89,44.92],[28.56,43.5],[28.13,43.4],[27.89,42.75],[27.48,42.47],[27.98,42.05],[27.99,41.86],[28.2,41.56],[29.06,41.23],[28.96,41.01],[28.78,40.97],[28.17,41.08],[27.92,40.99],[27.5,40.97],[27.43,40.84],[26.2,40.07],[26.79,40.63],[24.48,40.95],[23.76,40.75],[24.34,40.15],[23.73,40.33],[23.95,39.97],[23.43,40.26],[23.63,39.92],[22.81,40.58],[22.59,40.04],[23.23,39.36],[23.33,39.18],[23.22,39.1],[23.12,39.13],[23.16,39.26],[22.99,39.33],[22.84,39.26],[22.97,39.03],[23.07,39.04],[22.8,38.9],[22.57,38.87],[23.25,38.66],[23.37,38.53],[23.57,38.49],[23.68,38.35],[23.97,38.27],[24.06,37.82],[24.05,37.71],[23.97,37.68],[23.5,38.03],[23.03,37.88],[23.15,37.8],[23.2,37.62],[23.39,37.58],[23.49,37.44],[23.16,37.33],[23.1,37.36],[23.1,37.44],[22.94,37.52],[22.78,37.59],[22.73,37.54],[23.06,36.85],[23.04,36.64],[23.11,36.55],[22.83,36.69],[22.78,36.79],[22.72,36.79],[22.49,36.45],[22.08,37.03],[21.89,36.74],[21.58,37.08],[21.68,37.39],[21.12,37.89],[21.83,38.33],[22.24,38.19],[22.92,37.96],[22.89,38.05],[23.12,38.07],[23.18,38.13],[23.15,38.18],[22.83,38.23],[22.42,38.44],[22.23,38.35],[21.11,38.39],[20.77,38.87],[21.12,39.03],[20.3,39.33],[19.85,40.04],[19.4,40.28],[19.58,41.79],[18.65,42.44],[17.04,43.02],[17.72,42.85],[16.9,43.39],[15.99,43.52],[15.19,44.17],[15.47,44.27],[14.55,45.3],[14.31,45.34],[13.86,44.84],[13.52,45.48],[13.78,45.63],[13.63,45.77],[12.27,45.45],[12.52,44.97],[12.25,44.72],[12.4,44.22],[13.56,43.57],[14.01,42.69],[14.54,42.24],[15.17,41.93],[16.17,41.9],[15.9,41.51],[17.96,40.65],[18.48,40.1],[18.34,39.82],[17.87,40.28],[16.93,40.46],[16.52,39.75],[17.11,39.38],[17.17,39],[16.62,38.8],[16.06,37.94],[15.72,37.94],[15.64,38.18],[16.21,38.94],[15.69,39.99],[14.95,40.24],[14.77,40.67],[14.34,40.6],[14.46,40.73],[14.05,40.81],[13.86,41.13],[13.67,41.26],[13.25,41.29],[13.09,41.24],[12.85,41.41],[12.63,41.47],[12.08,41.94],[11.81,42.08],[11.64,42.29],[11.3,42.42],[11.1,42.42],[11.18,42.46],[11.17,42.53],[10.51,42.97],[10.19,43.95],[9.73,44.1],[9.29,44.32],[8.76,44.42],[8.55,44.35],[8.29,44.14],[6.72,43.37],[6.57,43.2],[6.11,43.07],[5.81,43.1],[5.41,43.23],[5.32,43.35],[5.07,43.37],[5.06,43.44],[4.71,43.37],[4.22,43.48],[4.05,43.59],[3.91,43.56],[3.16,43.08],[3.09,42.59],[3.31,42.29],[3.17,42.26],[3.15,42.16],[3.24,42.08],[3.25,41.94],[3,41.77],[2.31,41.47],[2.08,41.29],[1.03,41.06],[0.71,40.82],[0.89,40.72],[-0.33,39.52],[0.2,38.76],[-0.52,38.32],[-0.72,37.63],[-1.64,37.39],[-2.19,36.74],[-4.37,36.72],[-5.63,36.03],[-6.38,36.64],[-6.22,36.91],[-6.86,37.28],[-7.84,37.01],[-8.93,37.17],[-8.81,37.43],[-8.79,37.73],[-8.88,37.96],[-8.8,38.18],[-8.88,38.45],[-8.67,38.42],[-8.8,38.52],[-9.21,38.45],[-9.25,38.66],[-9.02,38.75],[-8.94,39],[-8.79,39.08],[-8.96,39.02],[-9.14,38.74],[-9.36,38.7],[-9.47,38.73],[-9.48,38.8],[-9.35,39.25],[-9.38,39.34],[-9.15,39.54],[-8.84,40.12],[-8.87,40.26],[-8.66,41.03],[-8.89,42.11],[-8.69,42.27],[-9.18,43.17],[-7.7,43.77],[-7.06,43.55],[-1.99,43.35],[-1.49,43.56],[-1.08,44.69],[-1.24,44.67],[-1.08,45.53],[-0.55,45],[-1.2,45.71],[-1.03,45.74],[-1.15,46.31],[-2.09,46.87],[-2.11,47.26],[-1.74,47.22],[-4.31,47.82],[-4.68,48.04],[-4.33,48.17],[-4.58,48.29],[-4.24,48.3],[-4.72,48.54],[-3.23,48.84],[-2.69,48.54],[-1.38,48.65],[-1.86,49.68],[-0.16,49.3],[0.44,49.47],[0.13,49.51],[0.19,49.7],[1.24,50],[1.59,50.25],[1.67,50.88],[3.72,51.37],[4.22,51.39],[4.01,51.44],[3.82,51.41],[3.69,51.45],[3.55,51.59],[3.89,51.57],[4.14,51.46],[4.28,51.47],[4.01,51.6],[4.18,51.61],[3.95,51.81],[4.08,51.99],[4.48,52.31],[4.77,52.94],[4.89,52.91],[5.06,52.96],[5.36,53.1],[5.53,53.27],[6.06,53.41],[7.2,53.28],[7.21,53.66],[7.63,53.7],[8.49,53.39],[8.62,53.88],[9.78,53.55],[8.65,54.29],[8.96,54.54],[8.68,54.79],[8.62,55.42],[8.13,55.6],[8.16,56.61],[9.2,56.7],[9.11,57.04],[8.77,56.72],[8.27,56.81],[10.53,57.73],[10.28,56.62],[10.9,56.36],[9.91,55.84],[9.46,55.04],[10.02,54.67],[9.87,54.47],[11.01,54.38],[10.86,54.01],[12.11,54.17],[12.58,54.47],[13.03,54.41],[13.15,54.28],[13.82,54.02],[13.87,53.85],[13.95,53.8],[14.49,53.67],[14.56,53.82],[14.17,53.87],[13.93,53.88],[13.92,54],[13.83,54.06],[14.38,53.92],[18.08,54.84],[18.76,54.68],[18.44,54.75],[18.84,54.37],[19.41,54.39],[19.97,54.92],[20.68,55.1],[21.12,55.62],[20.59,54.98],[21.19,54.93],[21.03,56.64],[21.73,57.57],[22.56,57.72],[23.65,56.97],[24.4,57.33],[24.3,57.78],[24.49,58.26],[24.55,58.3],[24.53,58.35],[24.34,58.38],[24.11,58.27],[23.77,58.36],[23.69,58.51],[23.51,58.66],[23.68,58.79],[23.5,58.79],[23.43,58.92],[23.51,59],[23.47,59.03],[23.52,59.11],[23.5,59.19],[24.08,59.29],[24.05,59.37],[24.38,59.47],[25.44,59.52],[25.52,59.56],[25.51,59.64],[27.89,59.41],[28.06,59.78],[30.17,59.96],[28.64,60.38],[28.51,60.68],[26.45,60.47],[26.21,60.41],[25.95,60.47],[26.04,60.34],[25.76,60.27],[25.66,60.33],[24.6,60.11],[24.45,60.02],[23.46,59.99],[23.18,59.84],[22.96,59.83],[23.2,60.02],[22.91,60.21],[22.46,60.03],[22.58,60.38],[21.44,60.6],[21.61,61.59],[21.12,62.69],[21.65,63.04],[21.54,63.21],[22.32,63.31],[22.53,63.65],[23.6,64.04],[24.56,64.8],[25.29,64.86],[25.35,65.48],[24.63,65.86],[22.4,65.86],[22.25,65.6],[21.41,65.32],[21.57,65.13],[21.14,64.81],[21.52,64.46],[20.76,63.87],[18.61,63.18],[18.17,62.79],[17.88,62.87],[18.04,62.6],[17.38,62.46],[17.63,62.23],[17.47,61.68],[17.13,61.57],[17.25,60.7],[17.36,60.64],[17.56,60.64],[17.66,60.54],[17.96,60.59],[18.16,60.41],[18.56,60.25],[18.53,60.15],[18.79,60.08],[18.93,59.94],[18.97,59.76],[18.28,59.44],[17.97,59.36],[18.13,59.32],[18.51,59.41],[18.62,59.33],[18.42,59.29],[18.29,59.11],[17.76,58.97],[16.98,58.65],[16.64,58.65],[16.21,58.64],[16.79,58.59],[16.93,58.49],[16.82,58.46],[16.65,58.43],[16.53,57.07],[16,56.22],[14.72,56.13],[14.26,55.89],[14.34,55.53],[14.08,55.39],[13.81,55.43],[13.32,55.35],[12.89,55.41],[12.94,55.48],[12.97,55.75],[12.47,56.29],[12.71,56.23],[12.8,56.26],[12.66,56.44],[12.86,56.45],[12.92,56.52],[12.88,56.62],[12.72,56.66],[12.42,56.91],[11.25,58.42],[11.21,58.87],[11.15,58.99],[11.19,59.08],[11.39,59.04],[11.37,59.1],[10.83,59.18],[10.64,59.39],[10.6,59.76],[10.54,59.7],[10.57,59.59],[10.4,59.52],[10.46,59.38],[10.43,59.28],[10.18,59.01],[9.84,58.96],[9.64,59.12],[9.56,59.11],[9.7,59.01],[9.62,58.95],[8.17,58.14],[7,58.02],[6.9,58.07],[6.88,58.15],[6.8,58.16],[6.73,58.07],[6.59,58.1],[6.55,58.12],[6.69,58.22],[6.66,58.26],[6.39,58.27],[6.05,58.38],[5.71,58.52],[5.52,58.73],[5.56,58.97],[5.61,59.01],[6.1,58.87],[6.36,59],[6.1,58.95],[5.89,59.1],[5.97,59.19],[5.95,59.3],[6.4,59.56],[5.56,59.29],[5.36,59.17],[5.17,59.16],[5.13,59.23],[5.19,59.45],[5.3,59.64],[5.47,59.71],[5.77,59.66],[5.87,59.73],[6.22,59.82],[5.83,59.8],[5.73,59.86],[6.07,60.08],[6.14,60.23],[6.35,60.35],[6.53,60.21],[6.53,60.15],[7,60.51],[6.35,60.42],[6.15,60.35],[5.91,60.15],[5.88,60.07],[5.7,60.01],[5.5,59.83],[5.15,59.64],[5.12,59.83],[5.22,59.98],[5.18,60.05],[5.21,60.09],[5.5,60.07],[5.69,60.12],[5.29,60.21],[5.14,60.44],[5.65,60.69],[5.12,60.64],[5.1,61.07],[6.78,61.14],[7.04,60.95],[7.61,61.21],[7.44,61.43],[7.17,61.17],[5.11,61.19],[5,61.43],[5.34,61.48],[4.93,61.88],[6.73,61.87],[5.27,61.94],[5.14,62.16],[6.69,62.47],[6.14,62.41],[6.35,62.61],[8.09,62.73],[6.73,62.72],[7.57,63.1],[8.62,62.85],[8.16,63.16],[8.63,63.34],[8.36,63.5],[8.58,63.6],[9.7,63.63],[10.02,63.39],[11.37,63.81],[11.18,63.9],[11.31,64.05],[10.06,63.51],[9.57,63.71],[11.63,64.81],[11.3,64.76],[11.49,64.98],[12.92,65.34],[12.42,65.18],[12.12,65.36],[13.03,65.96],[12.79,66.1],[14.03,66.3],[13.12,66.23],[13.21,66.64],[13.96,66.8],[13.65,66.91],[15.42,67.2],[14.44,67.27],[14.96,67.57],[15.59,67.35],[15.69,67.52],[15.25,67.6],[15.31,67.77],[14.78,67.68],[15.05,67.96],[15.62,67.95],[15.29,68.04],[16.01,68.23],[16.31,67.88],[16.21,68.32],[17.57,68.45],[16.58,68.59],[18.1,69.16],[18.26,69.47],[18.92,69.33],[18.61,69.49],[19.2,69.75],[19.72,69.78],[19.64,69.42],[20.32,69.95],[20.05,69.33],[20.74,69.52],[20.62,69.91],[21.98,69.83],[21.36,70.23],[22.69,70.37],[23.36,69.98],[23.38,70.25],[24.66,71],[25.77,70.85],[25.04,70.11],[26.51,70.91],[26.74,70.85],[26.58,70.41],[27.55,70.8],[27.33,71],[28.14,71.04],[28.38,70.87],[27.9,70.68],[28.27,70.67],[28.19,70.25],[28.83,70.86],[30.96,70.34],[28.78,70.15],[29.6,69.98],[29.69,69.74],[31.45,69.69],[31.98,69.95],[33.01,69.72],[32.09,69.63],[32.38,69.48],[33.45,69.43],[33.14,69.07],[33.68,69.31],[35.86,69.19],[40.97,67.71],[41.36,67.21],[41.19,66.83],[40.1,66.3],[38.66,66.07],[34.48,66.55],[32.93,67.09],[31.89,67.16],[33.65,66.44],[33.36,66.33],[34.69,65.95],[34.41,65.4],[35.03,64.44],[37.44,63.81],[38.06,64.09],[37.95,64.32],[37.18,64.41],[36.58,64.79],[36.88,65.17],[39.76,64.58],[40.44,64.78],[39.8,65.35],[39.82,65.6],[42.21,66.52],[43.23,66.41],[44.11,66.01],[44.43,66.94],[43.78,67.26],[44.2,68.25],[43.33,68.67],[45.89,68.48],[46.69,67.85],[45.53,67.76],[44.9,67.41],[46.49,66.8],[47.66,66.98],[47.88,67.58],[48.83,67.68],[48.75,67.9],[51.99,68.54],[52.4,68.35],[52.72,68.48],[52.34,68.61],[53.8,69],[54.49,68.99],[53.8,68.91],[53.93,68.44],[53.26,68.27],[54.86,68.2],[55.42,68.57],[57.13,68.55],[59.06,69.01],[59.37,68.74],[59.1,68.44],[59.73,68.35],[59.9,68.71],[60.93,68.99],[60.17,69.59],[60.91,69.85],[64.19,69.53],[68.5,68.35],[69.14,68.95],[68.54,68.97],[67.62,69.58],[66.9,69.55],[67.29,70.74],[66.7,70.82],[66.85,71.06],[66.64,71.08],[68.27,71.68],[69.39,72.96],[71.5,72.91],[72.81,72.69],[72.57,72.01],[71.87,71.46],[72.7,70.96],[72.47,70.28],[72.58,68.97],[73.59,68.48],[73.14,68.18],[73.07,67.77],[71.85,67.01],[71.37,66.96],[71.54,66.68],[70.72,66.52],[70.38,66.6],[70.69,66.74],[69.01,66.79],[69.98,66.4],[72.07,66.25],[73.79,66.99],[74.77,67.77],[74.39,68.42],[74.58,68.75],[75.12,68.86],[76.46,68.98],[77.24,68.47],[77.18,67.78],[78.92,67.59],[77.59,67.75],[77.67,68.19],[78,68.26],[77.65,68.9],[76,69.24],[73.78,69.2],[73.89,69.42],[73.58,69.8],[74.34,70.58],[73.09,71.44],[73.67,71.85],[74.99,72.15],[75.1,72.42],[74.79,72.81],[75.6,72.58],[75.74,72.3],[75.27,71.96],[75.5,71.65],[75.28,71.43],[75.73,71.27],[79.02,70.95],[76.43,71.55],[76.03,71.91],[78.19,71.91],[77.41,72.11],[78.48,72.4],[79.42,72.38],[81.66,71.72],[83.11,71.72],[82.98,71.45],[82.32,71.26],[82.16,70.6],[82.22,70.4],[82.59,70.89],[83.01,70.9],[82.68,70.22],[83.08,70.09],[83.74,70.55],[83.15,71.1],[83.53,71.68],[82.09,72.27],[81.1,72.39],[80.83,72.49],[80.66,72.71],[80.84,72.95],[80.76,73.03],[80.51,73.09],[80.42,73.23],[80.4,73.36],[80.6,73.47],[80.58,73.57]],[[-152.47,70.65],[-151.77,70.56],[-151.94,70.45],[-149.27,70.5],[-144.62,69.98],[-143.22,70.12],[-135.26,68.68],[-135.91,69.11],[-134.46,69.48],[-134.41,69.68],[-133.88,69.51],[-134.18,69.25],[-130.67,70.13],[-129.54,70.11],[-131.94,69.53],[-133.42,68.84],[-132.71,68.81],[-132.53,68.87],[-132.72,69.08],[-131.79,69.43],[-131.06,69.45],[-130.97,69.21],[-130.12,69.72],[-128.9,69.97],[-129.16,69.8],[-128.85,69.75],[-127.68,70.26],[-128.17,70.42],[-127.99,70.57],[-125.73,69.38],[-125.17,69.43],[-125.34,69.66],[-124.56,70.15],[-124.12,69.69],[-124.34,69.36],[-123.53,69.39],[-123.03,69.81],[-121.74,69.8],[-117.23,68.91],[-115.44,68.94],[-113.96,68.4],[-115.43,67.9],[-115.13,67.82],[-112.43,67.68],[-110.07,67.99],[-107.99,67.26],[-108.5,67.09],[-107.26,66.4],[-107.75,66.96],[-107.16,66.88],[-107.96,67.82],[-105.75,68.59],[-107.73,68.17],[-108.72,68.3],[-108.34,68.6],[-106.16,68.92],[-104.49,68.06],[-103.47,68.11],[-102.32,67.74],[-98.41,67.81],[-98.63,68.07],[-97.61,67.63],[-97.16,67.73],[-98.19,67.92],[-98.65,68.36],[-97.83,68.53],[-96.43,68.31],[-96.72,68.04],[-95.97,68.25],[-96.37,67.51],[-95.42,67.01],[-96.42,67.04],[-95.79,66.62],[-96.04,66.94],[-95.4,66.95],[-95.26,67.26],[-95.65,67.74],[-95.46,68.02],[-93.45,68.62],[-93.85,69],[-94.6,68.8],[-94.09,69.12],[-94.25,69.31],[-93.43,69.37],[-96.05,69.83],[-96.54,70.33],[-95.89,70.69],[-96.36,70.68],[-96.53,71.13],[-96.06,71.41],[-95.56,71.34],[-95.41,71.49],[-95.87,71.57],[-95.2,71.9],[-94.61,71.99],[-94.48,71.85],[-94.31,71.77],[-93.03,71.34],[-92.98,70.85],[-91.57,70.18],[-92.32,70.24],[-92.51,70.1],[-91.98,70.04],[-92.89,69.67],[-90.42,69.46],[-91.24,69.29],[-90.48,68.88],[-90.58,68.48],[-90.25,68.27],[-89.28,69.26],[-88.04,68.81],[-87.81,68.35],[-88.35,68.29],[-88.31,67.95],[-87.36,67.18],[-86.56,67.48],[-85.69,68.67],[-84.87,68.77],[-85.11,68.84],[-84.86,69.07],[-85.39,69.23],[-85.51,69.85],[-82.62,69.69],[-82.37,69.64],[-82.76,69.49],[-82.23,69.25],[-81.32,69.14],[-81.96,68.88],[-81.28,68.66],[-82.55,68.45],[-81.29,67.5],[-81.39,67.19],[-82.64,66.59],[-83.52,66.37],[-84.85,67.03],[-85.11,66.89],[-84.64,66.9],[-83.8,66.24],[-86.71,66.52],[-85.96,66.12],[-87.45,65.34],[-89.75,65.94],[-91.43,65.95],[-87,65.11],[-88.11,64.18],[-89.13,63.97],[-90.04,64.14],[-89.86,63.96],[-90.17,63.98],[-90.01,63.8],[-90.24,63.64],[-93.7,64.15],[-93.56,63.86],[-92.16,63.69],[-92.47,63.56],[-91.84,63.7],[-90.97,63.44],[-90.7,63.06],[-92.36,62.82],[-91.94,62.59],[-92.55,62.55],[-92.77,62.35],[-92.53,62.17],[-93.21,62.36],[-92.9,62.22],[-93.58,61.94],[-93.31,61.77],[-93.91,61.48],[-94.76,60.5],[-94.96,59.07],[-94.29,58.72],[-94.33,58.3],[-94.12,58.74],[-93.18,58.73],[-92.43,57.32],[-92.8,56.92],[-90.59,57.22],[-88.83,56.81],[-87.48,56.02],[-85.68,55.6],[-85.22,55.35],[-85.37,55.08],[-83.91,55.31],[-82.39,55.07],[-82.22,54.81],[-82.42,54.24],[-82.14,53.82],[-82.29,53.03],[-81.6,52.43],[-81.83,52.22],[-80.59,51.67],[-80.44,51.39],[-80.85,51.12],[-80.1,51.28],[-79.35,50.76],[-79.74,51.19],[-79.34,51.63],[-78.9,51.2],[-78.73,51.5],[-78.98,51.78],[-78.45,52.26],[-79.1,53.66],[-79.01,54.02],[-79.71,54.67],[-77.78,55.29],[-76.55,56.36],[-76.57,57.18],[-76.89,57.76],[-78.51,58.68],[-77.73,59.68],[-77.35,59.58],[-77.29,60.02],[-77.59,60.09],[-77.68,60.43],[-77.5,60.54],[-77.79,60.64],[-77.59,60.81],[-78.18,60.82],[-77.51,61.56],[-78.02,61.83],[-78.13,62.28],[-77.37,62.57],[-74.63,62.11],[-73.71,62.47],[-72.69,62.13],[-72.77,61.84],[-72.23,61.83],[-72.04,61.68],[-72.21,61.59],[-71.64,61.62],[-71.85,61.44],[-71.42,61.16],[-69.99,60.86],[-69.5,61.04],[-69.67,60.08],[-70.66,60.03],[-69.73,59.92],[-69.68,59.34],[-69.35,59.3],[-69.53,58.87],[-70.16,58.76],[-68.38,58.74],[-68.36,58.16],[-69.04,57.9],[-68.41,58.05],[-68.02,58.48],[-68.06,58.14],[-67.75,58.4],[-67.68,57.99],[-66.36,58.79],[-66,58.43],[-66.04,58.82],[-65.38,59.06],[-65.7,59.21],[-65.48,59.47],[-65.04,59.39],[-65.43,59.78],[-65.03,59.77],[-65.17,59.91],[-64.82,60.33],[-64.5,60.27],[-64.77,60.01],[-64.28,60.06],[-64.23,59.74],[-63.75,59.51],[-63.95,59.38],[-63.42,59.19],[-63.97,59.05],[-63.25,59.07],[-63.28,58.87],[-62.87,58.67],[-63.54,58.33],[-62.61,58.5],[-63.26,58.01],[-62.49,58.15],[-61.96,57.91],[-61.97,57.61],[-62.49,57.49],[-61.33,57.01],[-61.37,56.68],[-62.5,56.8],[-61.43,56.36],[-61.71,56.23],[-61.36,56.22],[-61.45,56],[-60.34,55.79],[-60.19,55.48],[-60.62,55.06],[-59.76,55.31],[-59.44,55.18],[-59.84,54.81],[-59.26,55.2],[-58.78,54.84],[-57.96,54.88],[-57.4,54.59],[-60.4,53.65],[-60.1,53.49],[-60.33,53.27],[-57.93,54.1],[-58.36,54.16],[-58.19,54.23],[-57.42,54.16],[-57.13,53.79],[-57.52,53.61],[-57.33,53.47],[-56.46,53.76],[-55.86,53.34],[-55.8,52.64],[-56.32,52.54],[-55.74,52.47],[-56.01,52.39],[-55.69,52.14],[-56.98,51.46],[-58.51,51.29],[-59.88,50.32],[-61.72,50.1],[-62.71,50.3],[-66.41,50.22],[-66.94,49.99],[-67.37,49.35],[-68.28,49.2],[-69.67,48.2],[-71.02,48.46],[-69.77,48.1],[-70.71,47.14],[-72.68,46.29],[-72.98,46.21],[-73.02,46.12],[-73.14,46.07],[-73.47,45.74],[-73.71,45.71],[-74.04,45.5],[-74.31,45.53],[-74,45.43],[-73.98,45.35],[-74.36,45.21],[-74.71,45],[-73.76,45.4],[-73.56,45.42],[-73.46,45.63],[-73.16,46.01],[-72.73,46.18],[-72.37,46.4],[-70.52,47.03],[-69.47,47.97],[-68.24,48.63],[-65.4,49.26],[-64.26,48.92],[-64.51,48.84],[-64.26,48.55],[-65.26,48.02],[-65.93,48.19],[-66.7,48.02],[-65.61,47.67],[-64.7,47.73],[-65.32,47.1],[-64.83,47.06],[-64.54,46.24],[-62.75,45.65],[-61.95,45.87],[-61.35,45.57],[-61.46,45.37],[-61.03,45.29],[-63.6,44.68],[-63.61,44.48],[-64.29,44.55],[-64.86,43.87],[-65.74,43.56],[-66.13,43.81],[-66.02,44.56],[-64.45,45.34],[-64.14,45.02],[-63.37,45.36],[-64.87,45.36],[-64.32,45.84],[-64.63,45.95],[-64.78,45.64],[-65.89,45.22],[-66.03,45.42],[-66.44,45.1],[-67.12,45.17],[-66.99,44.83],[-68.06,44.39],[-68.45,44.51],[-68.53,44.26],[-68.81,44.34],[-68.76,44.57],[-69.14,44.04],[-70.27,43.67],[-70.2,43.63],[-70.52,43.35],[-70.73,43.07],[-70.83,42.83],[-70.74,42.67],[-70.62,42.67],[-70.61,42.62],[-70.83,42.55],[-71.04,42.33],[-70.74,42.23],[-70.62,42.04],[-70.66,41.99],[-70.55,41.94],[-70.52,41.8],[-70.43,41.76],[-70.3,41.73],[-70,41.83],[-70.11,42.03],[-70.24,42.09],[-70.11,42.08],[-69.98,41.96],[-69.93,41.71],[-70.66,41.53],[-70.7,41.72],[-71.17,41.49],[-71.2,41.64],[-71.15,41.75],[-71.27,41.68],[-71.39,41.79],[-71.37,41.7],[-71.43,41.63],[-71.44,41.45],[-71.52,41.38],[-72.92,41.28],[-73.58,41.02],[-73.99,40.75],[-73.87,41.06],[-73.88,41.17],[-73.97,41.25],[-73.92,41.14],[-73.93,40.91],[-74.26,40.53],[-74.24,40.46],[-74,40.45],[-73.97,40.4],[-74.08,39.79],[-74.07,39.99],[-74.26,39.61],[-74.33,39.54],[-74.41,39.55],[-74.39,39.49],[-74.48,39.34],[-74.58,39.32],[-74.61,39.25],[-74.92,38.94],[-74.9,39.15],[-75.52,39.49],[-75.07,39.98],[-75.17,39.89],[-75.32,39.86],[-75.57,39.48],[-75.04,38.43],[-75.93,37.15],[-75.66,37.95],[-75.85,37.97],[-75.86,38.36],[-76.12,38.32],[-76.26,38.44],[-76.26,38.6],[-76,38.6],[-76.21,38.76],[-76.28,38.77],[-76.34,38.71],[-76.3,38.82],[-76.17,38.85],[-76.19,38.91],[-76.33,38.91],[-76.33,38.95],[-76.31,39.01],[-76.19,38.99],[-76.13,39.12],[-76.22,39.06],[-76.24,39.19],[-76.15,39.32],[-75.94,39.4],[-76,39.41],[-75.97,39.51],[-76.01,39.57],[-76.06,39.56],[-76.1,39.43],[-76.21,39.38],[-76.25,39.44],[-76.28,39.32],[-76.33,39.4],[-76.42,39.23],[-76.57,39.27],[-76.43,39.13],[-76.47,39.03],[-76.56,39.07],[-76.5,38.94],[-76.54,38.74],[-76.5,38.53],[-76.39,38.37],[-76.57,38.44],[-76.68,38.61],[-76.67,38.54],[-76.64,38.45],[-76.41,38.27],[-76.34,38.09],[-76.46,38.17],[-76.77,38.26],[-76.87,38.39],[-76.89,38.29],[-77,38.44],[-77.23,38.41],[-77.22,38.54],[-77.02,38.78],[-77.03,38.89],[-77.05,38.78],[-77.26,38.6],[-77.31,38.4],[-77.27,38.35],[-77.05,38.36],[-76.91,38.2],[-76.55,38.09],[-76.35,37.96],[-76.34,37.68],[-76.79,37.94],[-76.94,38.1],[-77.11,38.16],[-76.62,37.76],[-76.27,37.49],[-76.45,37.27],[-76.76,37.51],[-76.34,37.01],[-77.25,37.33],[-76.49,36.9],[-76,36.91],[-75.53,35.82],[-75.95,36.66],[-75.82,36.11],[-76.15,36.28],[-76.56,36.02],[-76.73,36.23],[-76.73,35.96],[-76.07,35.97],[-76.08,35.69],[-75.76,35.84],[-76.17,35.35],[-77.04,35.53],[-76.51,35.27],[-76.78,34.99],[-77.07,35.15],[-76.97,35.02],[-76.44,34.84],[-77.41,34.73],[-77.93,33.94],[-77.95,34.17],[-78.01,33.91],[-78.84,33.72],[-79.94,32.67],[-80.64,32.51],[-80.58,32.29],[-80.8,32.45],[-80.69,32.22],[-81.44,31.2],[-81.25,29.79],[-80.52,28.49],[-80.46,27.9],[-80.84,28.76],[-80.05,26.81],[-80.13,25.83],[-80.16,25.88],[-80.3,25.62],[-80.37,25.33],[-80.48,25.23],[-80.74,25.16],[-81.11,25.14],[-81.17,25.23],[-81.14,25.31],[-80.97,25.22],[-80.94,25.26],[-81.11,25.37],[-81.37,25.83],[-81.72,25.98],[-81.96,26.49],[-81.83,26.69],[-82.04,26.55],[-82.01,26.96],[-82.29,26.87],[-82.72,27.5],[-82.41,27.86],[-82.84,27.85],[-82.65,28.89],[-84.04,30.1],[-85.32,29.68],[-85.6,30.29],[-86.45,30.4],[-86.26,30.49],[-87.2,30.34],[-87,30.57],[-88,30.23],[-87.79,30.29],[-88.01,30.69],[-88.13,30.37],[-89.59,30.17],[-90.23,30.38],[-90.28,30.06],[-89.4,30.05],[-89.35,29.82],[-89.72,29.62],[-89.02,29.2],[-89.38,28.98],[-90.16,29.54],[-90.21,29.1],[-91.29,29.29],[-91.25,29.56],[-91.89,29.84],[-92.26,29.56],[-93.83,29.72],[-93.88,29.81],[-93.81,29.85],[-93.79,29.98],[-93.84,29.98],[-93.94,29.81],[-93.89,29.69],[-94.1,29.67],[-94.76,29.38],[-94.53,29.55],[-94.78,29.55],[-94.74,29.75],[-94.83,29.75],[-94.89,29.68],[-95.02,29.7],[-94.99,29.53],[-94.89,29.37],[-95.14,29.17],[-95.15,29.08],[-95.27,28.96],[-95.85,28.64],[-96.23,28.49],[-96.01,28.63],[-96.37,28.66],[-96.45,28.59],[-96.58,28.72],[-96.42,28.46],[-97.16,28.14],[-97.07,27.99],[-97.43,27.84],[-97.44,27.33],[-97.77,27.46],[-97.48,27.24],[-97.14,26.03],[-97.67,24.39],[-97.86,22.62],[-97.31,21.56],[-97.41,21.27],[-97.75,22.03],[-97.64,21.6],[-95.92,18.82],[-95.18,18.7],[-94.46,18.17],[-92.44,18.67],[-91.53,18.46],[-91.27,18.62],[-91.44,18.89],[-90.74,19.35],[-90.35,21.01],[-88.47,21.57],[-87.04,21.59],[-86.82,21],[-87.69,19.64],[-87.43,19.58],[-87.85,18.27],[-88.03,18.84],[-88.35,18.36],[-88.08,18.23],[-88.31,16.63],[-88.89,15.89],[-88.13,15.7],[-87.7,15.91],[-86.91,15.76],[-84.97,15.99],[-84.26,15.82],[-83.76,15.22],[-83.37,15.24],[-83.19,14.34],[-83.57,13.32],[-83.51,12.41],[-83.59,12.71],[-83.75,12.5],[-83.83,11.13],[-82.24,9.03],[-81.78,8.96],[-81.9,9.14],[-81.55,8.83],[-81.06,8.81],[-80.84,8.89],[-80.55,9.08],[-80.13,9.21],[-79.58,9.6],[-79.11,9.54],[-78.93,9.43],[-78.5,9.41],[-78.08,9.24],[-76.79,7.93],[-76.92,8.57],[-75.64,9.45],[-75.54,10.2],[-75.71,10.14],[-75.45,10.61],[-74.84,11.11],[-74.33,11],[-74.4,10.77],[-74.14,11.32],[-73.31,11.3],[-71.6,12.43],[-71.14,12.05],[-71.96,11.57],[-71.6,10.66],[-72.11,9.82],[-71.62,9.05],[-71.24,9.16],[-71.05,9.71],[-71.47,10.96],[-69.81,11.47],[-70.29,11.89],[-70,12.18],[-69.63,11.48],[-68.4,11.16],[-68.14,10.49],[-66.25,10.63],[-65.13,10.07],[-63.73,10.5],[-64.3,10.64],[-61.88,10.74],[-62.91,10.53],[-62.74,10.06],[-62.55,10.2],[-62.32,9.78],[-62.08,9.98],[-61.74,9.63],[-61.59,9.89],[-60.79,9.36],[-61.25,8.6],[-61.62,8.6],[-61.3,8.41],[-60.17,8.62],[-58.81,7.74],[-58.48,7.33],[-58.67,6.39],[-58.42,6.85],[-57.98,6.79],[-57.23,6.18],[-57.18,5.53],[-56.97,5.99],[-55.9,5.7],[-55.83,5.96],[-54.36,5.91],[-54.05,5.81],[-54.16,5.36],[-53.85,5.78],[-52.9,5.43],[-52.06,4.72],[-52,4.35],[-51.83,4.64],[-51.65,4.06],[-51.55,4.31],[-51.22,4.09],[-50.72,2.13],[-49.96,1.66],[-49.9,1.16],[-51.28,-0.08],[-51.98,-1.37],[-52.66,-1.55],[-51.95,-1.59],[-50.9,-0.94],[-50.4,-2.01],[-49.32,-1.73],[-49.64,-2.66],[-49.21,-1.92],[-48.35,-1.48],[-48.45,-1.15],[-48.12,-0.74],[-47.4,-0.63],[-45.46,-1.36],[-45.33,-1.72],[-45.08,-1.47],[-44.65,-1.75],[-44.54,-2.05],[-44.76,-2.26],[-44.44,-2.17],[-44.38,-2.37],[-44.72,-3.2],[-44.23,-2.47],[-44.19,-2.81],[-43.38,-2.38],[-42.25,-2.79],[-39.77,-2.99],[-39.02,-3.39],[-38.69,-3.65],[-38.48,-3.72],[-38.05,-4.22],[-37.63,-4.59],[-37.3,-4.71],[-36.59,-5.1],[-35.39,-5.25],[-34.83,-7.02],[-34.84,-7.97],[-35.34,-9.23],[-37.36,-11.25],[-38.02,-12.59],[-38.4,-12.97],[-38.69,-12.62],[-38.85,-12.79],[-39.09,-13.59],[-38.88,-15.86],[-39.16,-17.7],[-39.65,-18.25],[-39.78,-19.57],[-40.96,-21.24],[-41,-22],[-41.58,-22.24],[-41.98,-22.58],[-41.94,-22.79],[-42.04,-22.95],[-42.96,-22.97],[-43.08,-22.9],[-43.09,-22.72],[-43.23,-22.75],[-43.22,-22.99],[-43.9,-23.1],[-43.97,-23.06],[-43.68,-23.01],[-43.86,-22.91],[-44.15,-23.01],[-44.37,-23],[-45.21,-23.58],[-45.33,-23.6],[-45.46,-23.8],[-45.97,-23.79],[-46.87,-24.24],[-47.14,-24.49],[-47.59,-24.78],[-48.2,-25.42],[-48.73,-25.37],[-48.4,-25.6],[-48.75,-26.27],[-48.56,-27.2],[-48.8,-28.58],[-49.75,-29.36],[-50.92,-31.26],[-52.04,-32.12],[-52.06,-31.83],[-51.27,-31.48],[-50.58,-30.44],[-50.56,-30.25],[-51.03,-30.37],[-51.3,-30.04],[-51.28,-30.75],[-51.97,-31.38],[-52.65,-33.14],[-53.79,-34.38],[-54.9,-34.93],[-56.85,-34.68],[-57.17,-34.45],[-57.87,-34.45],[-58.4,-33.91],[-58.44,-33.72],[-58.36,-33.18],[-58.15,-33.07],[-58.2,-32.47],[-58.2,-33.01],[-58.25,-33.08],[-58.42,-33.11],[-58.55,-33.66],[-58.39,-34.19],[-58.52,-34.3],[-58.47,-34.46],[-58.28,-34.68],[-57.76,-34.89],[-57.3,-35.19],[-57.17,-35.36],[-57.16,-35.51],[-57.35,-35.72],[-57.26,-36.14],[-56.72,-36.39],[-56.67,-36.85],[-57.65,-38.17],[-59.83,-38.84],[-61.6,-39],[-62.34,-38.8],[-62.3,-39.24],[-62.05,-39.37],[-62.39,-40.89],[-63.62,-41.16],[-64.87,-40.74],[-65.13,-40.88],[-64.99,-42.1],[-64.42,-42.43],[-63.79,-42.11],[-63.62,-42.7],[-64.04,-42.88],[-64.49,-42.51],[-64.97,-42.67],[-64.32,-42.97],[-65.25,-43.57],[-65.29,-44.36],[-65.65,-44.66],[-65.64,-45.01],[-66.94,-45.26],[-67.6,-46.05],[-67.51,-46.44],[-66.78,-47.01],[-65.85,-47.16],[-65.77,-47.57],[-66.22,-47.83],[-65.81,-47.94],[-67.47,-48.95],[-67.91,-49.98],[-68.26,-50.1],[-68.67,-49.75],[-68.98,-50],[-68.42,-50.16],[-68.94,-50.38],[-69.36,-51.03],[-69.06,-51.55],[-69.46,-51.58],[-68.96,-51.68],[-68.4,-52.31],[-69.24,-52.21],[-70.8,-52.77],[-70.99,-53.78],[-71.3,-53.88],[-72.41,-53.35],[-71.94,-53.23],[-71.79,-53.48],[-71.23,-52.81],[-72.28,-53.13],[-72.55,-53.46],[-73.05,-53.24],[-72.73,-52.76],[-71.51,-52.61],[-72.71,-52.54],[-73.12,-53.07],[-73.64,-52.84],[-73.12,-52.49],[-74.01,-52.64],[-74.3,-52.12],[-73.83,-52.23],[-72.79,-51.95],[-72.57,-52.2],[-72.72,-52.36],[-72.52,-52.25],[-72.54,-51.71],[-73.17,-51.45],[-72.6,-51.8],[-73.52,-52.04],[-74.19,-51.68],[-73.93,-51.62],[-73.94,-51.27],[-74.81,-51.06],[-75.09,-50.68],[-74.68,-50.66],[-74.64,-50.36],[-73.81,-50.94],[-73.65,-50.49],[-73.98,-50.83],[-74.2,-50.61],[-73.95,-50.51],[-74.63,-50.19],[-73.96,-49.99],[-74.29,-49.6],[-73.83,-49.61],[-74.09,-49.43],[-73.94,-49.02],[-74.22,-49.5],[-74.37,-49.4],[-74.34,-48.6],[-74.01,-48.48],[-74.48,-48.46],[-74.58,-48],[-73.39,-48.15],[-73.72,-47.66],[-74.23,-47.97],[-74.66,-47.7],[-74.13,-47.59],[-74.48,-47.43],[-74.16,-47.18],[-74.31,-46.79],[-75,-46.74],[-75.02,-46.51],[-75.54,-46.7],[-75.43,-46.93],[-75.71,-46.77],[-74.93,-46.16],[-75.07,-45.88],[-74.16,-45.77],[-73.96,-45.4],[-74.02,-46.06],[-74.39,-46.22],[-73.97,-46.15],[-73.73,-45.81],[-73.85,-46.57],[-73.59,-45.9],[-73.73,-45.48],[-72.93,-45.45],[-73.45,-45.24],[-72.68,-44.59],[-73.27,-44.17],[-73.08,-43.32],[-72.76,-43.04],[-72.77,-42.26],[-72.41,-42.39],[-72.5,-41.98],[-72.82,-41.91],[-72.32,-41.5],[-73.73,-41.74],[-73.98,-40.97],[-73.23,-39.22],[-73.66,-37.34],[-73.22,-37.17],[-71.99,-34.29],[-72,-34.17],[-71.83,-33.82],[-71.66,-33.65],[-71.64,-33.52],[-71.7,-33.43],[-71.74,-33.09],[-71.59,-32.97],[-71.45,-32.66],[-71.42,-32.39],[-71.51,-32.21],[-71.71,-30.63],[-71.31,-29.65],[-71.52,-28.93],[-70.65,-26.33],[-70.39,-23.57],[-70.59,-23.25],[-70.09,-21.49],[-70.36,-18.4],[-71.53,-17.3],[-75.11,-15.41],[-76.29,-14.13],[-76.23,-13.37],[-76.5,-12.98],[-76.83,-12.35],[-77.15,-12.06],[-77.22,-11.66],[-77.31,-11.53],[-77.63,-11.29],[-77.74,-10.84],[-79.76,-7.07],[-81.14,-6.06],[-80.88,-5.63],[-81.34,-4.67],[-81.23,-4.23],[-79.96,-3.16],[-79.73,-2.58],[-79.84,-2.07],[-79.93,-2.55],[-80.01,-2.35],[-80.29,-2.71],[-80.96,-2.19],[-80.77,-2.08],[-80.9,-1.08],[-80.28,-0.62],[-80.48,-0.37],[-80.05,0.16],[-80.09,0.79],[-78.9,1.21],[-79.03,1.62],[-78.58,1.77],[-78.59,2.36],[-77.81,2.72],[-77.08,3.91],[-77.52,4.21],[-77.29,4.72],[-77.54,5.54],[-77.25,5.78],[-77.47,6.18],[-77.37,6.57],[-78.38,7.9],[-78.42,8.06],[-78.29,8.09],[-78.28,8.25],[-78.14,8.39],[-77.76,8.13],[-78.06,8.4],[-78.1,8.5],[-78.22,8.4],[-78.4,8.51],[-78.37,8.4],[-78.41,8.36],[-78.51,8.63],[-78.95,8.93],[-79.25,9.02],[-79.51,8.97],[-79.69,8.85],[-79.81,8.64],[-79.75,8.6],[-80.12,8.35],[-80.37,8.29],[-80.46,8.21],[-80.46,8.08],[-80.07,7.67],[-80.01,7.5],[-80.84,7.22],[-81.06,7.9],[-81.27,7.63],[-82.23,8.31],[-82.78,8.3],[-82.88,8.07],[-83.29,8.67],[-83.47,8.71],[-83.29,8.41],[-83.61,8.48],[-83.74,9.15],[-84.58,9.57],[-85.02,10.12],[-85.26,10.26],[-84.89,9.82],[-85.11,9.58],[-85.63,9.9],[-85.85,10.29],[-85.67,10.74],[-85.91,10.9],[-85.74,11.09],[-87.67,12.9],[-87.34,12.95],[-87.49,13.35],[-88.69,13.28],[-88.51,13.18],[-91.38,13.99],[-93.92,16.05],[-94.86,16.42],[-95.02,16.28],[-94.8,16.21],[-96.21,15.69],[-97.75,15.97],[-100.85,17.2],[-101.92,17.96],[-103.44,18.33],[-103.91,18.83],[-104.94,19.31],[-105.67,20.38],[-105.26,20.58],[-105.51,20.81],[-105.21,21.49],[-105.65,21.99],[-105.79,22.63],[-107.77,24.47],[-107.51,24.49],[-107.95,24.62],[-108.28,25.08],[-108.05,25.07],[-109.03,25.48],[-108.88,25.73],[-109.31,25.63],[-109.42,26.03],[-109.12,26.25],[-109.28,26.53],[-110.38,27.23],[-110.53,27.86],[-111.12,27.97],[-112.16,29.02],[-113.06,30.65],[-113.05,31.18],[-114.93,31.9],[-114.55,30.02],[-112.87,28.42],[-112.73,27.83],[-111.86,26.68],[-111.7,26.58],[-111.79,26.88],[-111.57,26.71],[-110.69,24.87],[-110.66,24.34],[-110.37,24.1],[-110.26,24.34],[-109.42,23.48],[-109.5,23.16],[-110,22.89],[-110.36,23.61],[-112.07,24.84],[-112.38,26.21],[-113.02,26.58],[-113.15,26.95],[-113.6,26.72],[-114.99,27.74],[-114.3,27.87],[-114.07,27.68],[-114.27,27.93],[-114.05,28.43],[-115.67,29.76],[-117.27,32.81],[-117.32,33.1],[-117.47,33.3],[-118.08,33.72],[-118.41,33.74],[-118.39,33.86],[-118.51,34.02],[-118.83,34.02],[-119.14,34.11],[-119.41,34.34],[-119.61,34.42],[-119.71,34.4],[-120.65,34.58],[-120.63,35.08],[-121.46,35.93],[-121.88,36.33],[-121.92,36.57],[-121.79,36.73],[-121.81,36.85],[-121.88,36.94],[-122.17,36.99],[-122.4,37.21],[-122.51,37.77],[-122.39,37.79],[-122.37,37.66],[-122.07,37.48],[-122.39,37.96],[-122.22,38.04],[-121.52,38.06],[-122.03,38.12],[-122.15,38.07],[-122.39,38.14],[-122.48,38.11],[-122.47,37.84],[-122.52,37.83],[-122.93,38.06],[-123,37.99],[-122.98,38.23],[-122.88,38.12],[-122.99,38.28],[-123.7,38.91],[-123.83,39.78],[-124.33,40.25],[-124.07,41.46],[-124.54,42.81],[-124.15,43.69],[-123.99,46.22],[-123.22,46.15],[-124.07,46.28],[-123.89,46.66],[-124.11,46.86],[-123.84,46.96],[-124.14,46.95],[-124.71,48.38],[-123.3,48.12],[-123.12,48.15],[-122.98,48.07],[-122.78,48.14],[-122.66,47.88],[-122.78,47.74],[-122.82,47.79],[-123.05,47.55],[-123.14,47.36],[-122.92,47.41],[-123.07,47.4],[-123.06,47.45],[-122.59,47.86],[-122.59,47.93],[-122.53,47.92],[-122.53,47.77],[-122.62,47.71],[-122.61,47.62],[-122.68,47.61],[-122.56,47.46],[-122.58,47.29],[-122.71,47.32],[-122.77,47.22],[-122.83,47.34],[-123.03,47.14],[-122.7,47.11],[-122.54,47.28],[-122.35,47.37],[-122.4,47.78],[-122.24,48.01],[-122.42,48.18],[-122.4,48.08],[-122.52,48.16],[-122.52,48.23],[-122.41,48.29],[-122.67,48.46],[-122.5,48.51],[-122.54,48.76],[-122.69,48.79],[-122.83,49.03],[-122.96,49.07],[-123.08,48.98],[-123.23,49.26],[-122.88,49.4],[-123.28,49.34],[-123.19,49.68],[-123.53,49.4],[-124.03,49.6],[-123.58,49.68],[-123.88,49.74],[-123.83,50.15],[-124.28,49.77],[-124.78,50.02],[-125.06,50.42],[-124.86,50.87],[-125.06,50.51],[-126.09,50.5],[-126.45,50.59],[-125.91,50.7],[-126.51,50.68],[-126.52,51.06],[-127.06,50.87],[-127.71,51.15],[-127.42,51.61],[-126.69,51.7],[-127.64,51.48],[-127.85,51.67],[-127.8,52.19],[-127.44,52.36],[-126.71,52.06],[-127.19,52.46],[-127.01,52.84],[-128.1,51.79],[-128.36,52.16],[-127.94,52.55],[-128.27,52.36],[-128.05,52.91],[-128.36,52.83],[-129.17,53.53],[-128.85,53.7],[-127.93,53.28],[-128.67,53.55],[-128.76,53.75],[-128.71,53.81],[-128.53,53.86],[-128.7,53.92],[-128.89,53.83],[-128.96,53.84],[-129.21,53.64],[-129.26,53.42],[-129.46,53.35],[-129.56,53.25],[-129.82,53.41],[-129.91,53.55],[-130.07,53.58],[-130.34,53.72],[-130.09,53.98],[-130.04,54.13],[-129.63,54.23],[-130.08,54.18],[-130.29,54.27],[-130.43,54.42],[-130.35,54.66],[-130.22,54.73],[-129.89,55.16],[-129.56,55.46],[-129.79,55.56],[-130.05,55.06],[-130.02,55.89],[-130.04,55.3],[-130.54,54.75],[-131.05,55.16],[-130.75,55.32],[-131.03,56.09],[-132.12,55.57],[-132.21,55.75],[-131.55,56.21],[-132.18,56.42],[-132.82,57.06],[-133.47,57.17],[-133.44,57.34],[-133.54,57.55],[-133.65,57.64],[-133.55,57.7],[-133.12,57.57],[-133.52,57.78],[-133.54,57.83],[-133.51,57.88],[-133.19,57.88],[-133.56,57.92],[-133.66,57.84],[-133.72,57.84],[-134.03,58.07],[-134.05,58.29],[-133.88,58.52],[-134.21,58.23],[-134.78,58.45],[-134.94,58.65],[-134.99,58.77],[-135.13,58.84],[-135.33,59.24],[-135.36,59.42],[-135.41,59.32],[-135.48,59.31],[-135.4,59.21],[-135.5,59.2],[-135.39,59.09],[-135.06,58.34],[-135.06,58.28],[-135.14,58.23],[-135.3,58.26],[-135.45,58.38],[-135.57,58.41],[-135.9,58.4],[-135.86,58.58],[-136.04,58.82],[-135.83,58.9],[-136.02,58.87],[-136.15,59.05],[-136.12,58.82],[-136.23,58.77],[-136.45,58.85],[-136.57,58.94],[-136.99,59.04],[-137.06,58.87],[-136.06,58.45],[-136.61,58.24],[-139.77,59.53],[-139.51,59.95],[-139.29,59.61],[-138.99,59.84],[-139.43,60.01],[-140.42,59.71],[-141.41,59.9],[-141.41,60.12],[-144.15,60.02],[-144.9,60.34],[-144.69,60.67],[-145.25,60.38],[-146.57,60.73],[-146.39,60.81],[-146.63,60.99],[-146.38,61.14],[-147.81,60.89],[-148.01,60.97],[-147.75,61.22],[-148.34,61.06],[-148.56,60.8],[-148.28,60.61],[-148.64,60.49],[-147.96,60.48],[-148.43,59.99],[-149.4,60.11],[-149.6,59.77],[-149.71,59.92],[-150.93,59.25],[-151.74,59.19],[-151.93,59.34],[-151.04,59.77],[-151.85,59.78],[-151.4,60.27],[-151.36,60.72],[-150.44,61.02],[-149.07,60.89],[-150.05,61.17],[-149.33,61.5],[-151.59,60.98],[-152.37,60.34],[-153.02,60.3],[-152.63,60.04],[-153.21,59.84],[-153.05,59.73],[-154.09,59.36],[-154.13,59.12],[-153.33,58.88],[-154.25,58.16],[-158.41,56.44],[-158.55,56.31],[-158.28,56.2],[-159.66,55.63],[-159.77,55.84],[-161.38,55.37],[-161.2,55.54],[-161.52,55.62],[-162.08,55.14],[-162.63,55.25],[-162.67,55],[-163.12,55.06],[-163.34,54.84],[-163.28,55.12],[-161.7,55.91],[-160.29,55.8],[-160.54,56.01],[-160.3,56.31],[-158.67,56.8],[-158.32,57.3],[-157.46,57.51],[-157.7,57.68],[-157.61,58.05],[-157.19,58.19],[-157.52,58.42],[-156.97,58.74],[-156.81,59.13],[-158.19,58.62],[-158.5,58.85],[-158.08,58.98],[-158.81,58.97],[-158.95,58.4],[-159.67,58.91],[-160.36,59.05],[-162.14,58.64],[-161.72,58.79],[-161.64,59.11],[-161.98,59.15],[-161.83,59.59],[-162.42,60.28],[-161.96,60.69],[-162.68,60.27],[-162.57,59.99],[-163.68,59.8],[-165.36,60.54],[-164.8,60.89],[-164.32,60.77],[-164.37,60.59],[-163.42,60.76],[-163.91,60.85],[-163.59,60.9],[-163.75,60.97],[-165.11,60.93],[-164.87,61.11],[-165.27,61.27],[-165.57,61.1],[-165.84,61.54],[-166.15,61.55],[-165.81,61.7],[-166.08,61.8],[-165.61,61.87],[-165.71,62.1],[-165.19,62.47],[-164.76,62.5],[-164.59,62.71],[-164.79,62.62],[-164.8,62.92],[-164.38,63.03],[-164.41,63.22],[-163.29,63.05],[-162.28,63.53],[-161.1,63.56],[-160.78,63.82],[-160.99,64.25],[-161.49,64.43],[-160.86,64.76],[-161.76,64.82],[-162.33,64.61],[-162.71,64.38],[-162.81,64.37],[-162.88,64.52],[-163.2,64.65],[-163.3,64.61],[-163.05,64.52],[-163.14,64.42],[-163.71,64.59],[-164.3,64.58],[-164.69,64.51],[-164.76,64.53],[-164.98,64.45],[-166.14,64.58],[-166.33,64.63],[-166.48,64.73],[-166.48,64.8],[-166.41,64.83],[-166.42,64.93],[-166.55,64.95],[-166.93,65.16],[-166.53,65.15],[-166.45,65.25],[-166.16,65.29],[-167.4,65.42],[-168.09,65.66],[-164.46,66.59],[-163.64,66.57],[-163.89,66.58],[-164.03,66.22],[-163.7,66.08],[-161.04,66.19],[-162.61,66.89],[-162.36,66.95],[-161.59,66.46],[-160.23,66.51],[-161.57,66.59],[-161.86,66.7],[-161.72,67.02],[-163.53,67.1],[-164.12,67.61],[-166.79,68.36],[-166.38,68.43],[-166.21,68.89],[-163.87,69.04],[-161.88,70.33],[-162.08,70.16],[-160.12,70.59],[-159.96,70.57],[-160.11,70.47],[-160.01,70.45],[-160.1,70.33],[-159.91,70.33],[-159.87,70.28],[-159.81,70.5],[-159.39,70.52],[-159.75,70.53],[-159.96,70.63],[-160.08,70.63],[-159.68,70.79],[-159.31,70.88],[-159.19,70.86],[-159.34,70.78],[-159.25,70.75],[-159,70.8],[-157.91,70.86],[-157.32,71.04],[-156.78,71.32],[-156.47,71.41],[-156.4,71.4],[-156.57,71.34],[-156.47,71.29],[-155.65,71.18],[-155.58,71.12],[-155.8,71],[-156.15,70.93],[-155.97,70.84],[-155.58,70.89],[-155.17,71.1],[-154.94,71.08],[-154.67,70.99],[-154.79,70.89],[-154.2,70.8],[-153.92,70.88],[-153.23,70.93],[-152.49,70.88],[-152.23,70.81],[-152.44,70.73]],[[143.18,-11.96],[143.75,-14.35],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.03,-18.27],[146.38,-18.98],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.21,-21.12],[149.71,-22.44],[149.98,-22.55],[150.08,-22.16],[150.54,-22.56],[150.67,-22.42],[150.84,-23.46],[151.83,-24.12],[153.03,-25.87],[153.17,-25.96],[153.08,-26.3],[153.16,-26.98],[153.12,-27.19],[153.38,-27.77],[153.45,-28.05],[153.58,-28.24],[153.6,-28.86],[152.95,-31.43],[152.21,-32.68],[152.14,-32.68],[152.19,-32.72],[152.16,-32.76],[151.81,-32.9],[151.48,-33.35],[151.43,-33.52],[151.29,-33.58],[151.28,-33.93],[151.24,-33.99],[151.12,-34.01],[151.23,-34.03],[150.96,-34.3],[150.78,-34.89],[150.81,-34.99],[150.68,-35.08],[150.71,-35.16],[150.57,-35.21],[150.2,-35.83],[149.93,-37.53],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.45,-39.11],[146.16,-38.87],[146.07,-38.83],[145.94,-38.9],[145.79,-38.67],[145.61,-38.66],[145.4,-38.54],[145.46,-38.42],[145.54,-38.39],[145.48,-38.24],[145.29,-38.24],[145.19,-38.38],[144.96,-38.5],[144.72,-38.34],[144.91,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.67,-38.21],[144.1,-38.46],[143.69,-38.77],[141.93,-38.28],[141.43,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.98,-35.62],[139.29,-35.61],[139.28,-35.38],[138.19,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.02,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.78,-32.58],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.17],[134.23,-32.55],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.01],[123.51,-33.92],[119.85,-33.97],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.51],[115.36,-33.64],[115.61,-33.37],[115.68,-33.19],[115.62,-32.67],[115.71,-32.57],[115.74,-31.89],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.18,-26.18],[113.36,-26.08],[113.58,-26.56],[113.83,-26.5],[113.45,-25.6],[113.72,-26.13],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.96,-21.94],[114.12,-21.83],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.11,-19.99],[121,-19.6],[122.35,-18.11],[122.14,-17.43],[122.33,-17.06],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.88,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.4,-16.3],[124.65,-15.87],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.36,-15.12],[125.18,-14.72],[125.63,-14.26],[125.66,-14.53],[126.02,-14.5],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.18,-14.71],[128.07,-15.33],[128.58,-14.77],[129.64,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.94,-13.5],[130.14,-13.45],[130.26,-13.3],[130.14,-13.15],[130.17,-12.96],[130.32,-12.88],[130.4,-12.69],[130.62,-12.65],[130.62,-12.43],[130.74,-12.43],[130.87,-12.56],[130.87,-12.37],[131.03,-12.34],[131.05,-12.19],[131.22,-12.18],[131.29,-12.07],[131.34,-12.21],[131.44,-12.28],[131.89,-12.23],[132.07,-12.28],[132.25,-12.19],[132.41,-12.3],[132.44,-12.18],[132.58,-12.11],[132.67,-11.65],[132.28,-11.47],[132.13,-11.5],[131.81,-11.27],[131.96,-11.18],[132.16,-11.31],[135.03,-12.19],[135.92,-11.83],[135.71,-12.21],[135.94,-12.15],[136.08,-12.42],[136.54,-11.96],[136.95,-12.35],[136.46,-13.23],[135.93,-13.3],[135.95,-13.93],[135.45,-14.92],[140.04,-17.7],[140.83,-17.41],[141.29,-16.46],[141.63,-15.06],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[142.46,-10.71],[142.78,-11.12],[142.87,-11.82],[143.07,-11.92]],[[-29.95,83.56],[-25.8,83.26],[-32.03,82.98],[-25.12,83.16],[-24.47,82.88],[-21.52,82.6],[-23.12,82.33],[-29.89,82.05],[-25.15,82],[-24.29,81.7],[-22.94,82.03],[-21.13,81.93],[-21.5,81.44],[-23.12,80.78],[-19.63,81.64],[-17.45,81.4],[-15.45,81.84],[-11.42,81.48],[-14.45,80.99],[-14.23,80.87],[-14.5,80.76],[-16.76,80.57],[-15.94,80.43],[-16.49,80.25],[-19.43,80.26],[-20.15,80.01],[-20.07,79.77],[-19.35,79.73],[-19.41,79.35],[-18.99,79.18],[-21.13,78.66],[-20.95,78.55],[-21.73,77.71],[-20.86,77.91],[-19.49,77.72],[-19.29,77.59],[-20.68,77.62],[-20.23,77.37],[-18.44,77.26],[-18.34,76.92],[-22.61,76.68],[-21.49,76.27],[-19.86,76.12],[-19.4,75.49],[-19.52,75.18],[-22.23,75.12],[-20.99,75.07],[-20.78,74.89],[-21.04,74.65],[-20.86,74.64],[-19.99,74.98],[-19.27,74.34],[-21.13,74.11],[-21.95,74.24],[-21.76,74.48],[-21.98,74.57],[-22.33,74.29],[-22.13,73.99],[-20.37,73.85],[-20.64,73.46],[-22.35,73.27],[-24.16,73.77],[-24.68,73.6],[-25.52,73.85],[-24.78,73.54],[-26.06,73.25],[-27.27,73.44],[-26.54,73.25],[-27.56,73.14],[-24.13,73.41],[-22.04,72.92],[-22.29,72.12],[-24.07,72.5],[-24.63,73.04],[-26.66,72.72],[-24.81,72.9],[-24.7,72.51],[-25.2,72.39],[-21.96,71.74],[-22.48,71.38],[-21.75,71.48],[-21.52,70.53],[-22.38,70.46],[-22.44,70.86],[-22.69,70.44],[-23.33,70.45],[-23.97,70.65],[-24.56,71.22],[-27.09,71.63],[-25.84,71.48],[-25.67,71.27],[-26.72,70.95],[-28.4,70.99],[-27.98,70.84],[-29.07,70.44],[-26.51,70.4],[-27.63,70.03],[-27.38,69.99],[-25.53,70.35],[-22.21,70.11],[-23.87,69.74],[-23.74,69.59],[-24.3,69.58],[-26.48,68.68],[-30.98,68.06],[-32.33,68.44],[-32.16,67.99],[-33.16,67.63],[-34.63,66.43],[-35.19,66.25],[-35.87,66.44],[-35.63,66.14],[-37.76,65.59],[-38,65.71],[-37.28,66.3],[-38.15,66.39],[-37.75,66.26],[-38.14,65.9],[-38.52,66.01],[-38.2,65.71],[-40.17,65.56],[-39.58,65.34],[-41.09,65.03],[-40.18,64.48],[-40.78,64.22],[-41.58,64.3],[-40.62,64.13],[-40.55,63.73],[-41.39,63.06],[-42.18,63.21],[-41.64,62.97],[-41.91,62.74],[-42.94,62.72],[-42.15,62.57],[-42.32,62.15],[-42.11,61.86],[-42.59,61.72],[-42.32,61.68],[-43.04,60.52],[-43.92,60.6],[-43.21,60.39],[-43.12,60.06],[-43.95,60.02],[-43.66,59.86],[-43.91,59.81],[-44.41,59.92],[-44.22,60.27],[-44.61,60.02],[-45.38,60.2],[-44.76,60.67],[-45.38,60.44],[-46.05,60.61],[-45.87,61.22],[-46.87,60.82],[-48.18,60.77],[-47.77,61],[-48.39,61.01],[-49.29,61.59],[-49.38,61.89],[-48.83,62.08],[-49.62,62],[-49.55,62.23],[-50.32,62.47],[-49.79,63.05],[-50.39,62.82],[-51.47,63.64],[-51.55,64.01],[-50.26,64.21],[-51.71,64.2],[-50.68,64.68],[-50.01,64.45],[-50.12,64.7],[-50.96,65.2],[-50.72,64.8],[-51.26,64.76],[-51.92,64.22],[-52.54,65.33],[-51.09,65.78],[-52.55,65.46],[-53.2,65.59],[-53.11,65.98],[-53.39,66.05],[-51.23,66.88],[-53.61,66.15],[-53.42,66.65],[-52.39,66.88],[-53.69,66.99],[-53.8,67.42],[-52.51,67.76],[-50.61,67.53],[-51.17,67.69],[-50.97,67.81],[-52.35,67.84],[-53.74,67.55],[-53.15,68.21],[-51.6,68.06],[-51.17,68.39],[-53.38,68.3],[-53.04,68.61],[-51.13,68.6],[-50.8,68.79],[-51.25,68.74],[-51.09,69.13],[-50.3,69.17],[-51.08,69.21],[-50.32,70.03],[-52.26,70.06],[-54.53,70.7],[-52.8,70.75],[-50.68,70.4],[-51.77,71.01],[-51.02,71],[-53.12,71.31],[-51.78,71.68],[-53.44,71.58],[-53.15,71.81],[-53.81,72.29],[-53.65,72.36],[-53.93,72.32],[-53.48,71.85],[-54.02,71.66],[-53.96,71.46],[-55.59,71.55],[-55.32,72.11],[-54.84,72.38],[-55.58,72.18],[-55.29,72.35],[-55.6,72.45],[-54.92,72.57],[-54.74,72.87],[-55.67,73.01],[-55.29,73.33],[-56.1,73.56],[-55.84,73.76],[-56.23,74.13],[-57.23,74.12],[-56.26,74.53],[-58.57,75.35],[-58.25,75.51],[-58.52,75.69],[-63.29,76.35],[-67.08,76.2],[-66.83,75.97],[-68.32,76.09],[-69.48,76.4],[-68.11,76.65],[-69.89,76.83],[-69.69,76.99],[-70.61,76.82],[-71.16,77.07],[-68.14,77.38],[-66.39,77.28],[-66.27,77.51],[-66.82,77.69],[-69.35,77.47],[-70.56,77.72],[-70.12,77.84],[-71.27,77.81],[-72.82,78.19],[-71.65,78.62],[-65.82,79.17],[-64.79,80],[-64.18,80.1],[-66.84,80.08],[-67.19,80.28],[-64.51,81],[-63.06,80.89],[-63.24,81.08],[-62.99,81.21],[-61.44,81.13],[-61.1,81.4],[-61.2,81.75],[-60.43,81.92],[-56.62,81.36],[-59.27,81.98],[-54.55,82.35],[-53.67,82.16],[-53.56,81.65],[-53.04,81.87],[-53.02,82.32],[-50.9,81.89],[-49.54,81.92],[-50.99,82.46],[-50.04,82.47],[-44.73,81.78],[-44.33,82.47],[-45.56,82.75],[-41.37,82.75],[-46.48,82.95],[-43.01,83.26],[-41.3,83.1],[-40.36,83.33],[-38.15,83],[-37.94,83.16],[-38.75,83.37],[-30.7,83.59]],[[-86.59,71.01],[-84.82,71.03],[-84.7,71.63],[-85.91,71.99],[-85.32,72.23],[-84.28,72.04],[-85.65,72.72],[-85.26,72.95],[-84.26,72.8],[-85.46,73.11],[-83.41,73.63],[-81.6,73.7],[-80.28,72.77],[-81.23,72.31],[-80.61,72.45],[-80.95,71.92],[-79.88,72.18],[-80.11,72.33],[-79.83,72.45],[-79,72.27],[-79.01,72.04],[-78.58,71.88],[-78.86,72.1],[-78.7,72.35],[-77.52,72.18],[-78.42,72.57],[-77.25,72.74],[-75.07,72.32],[-75.92,71.72],[-75.15,72.06],[-74.27,72.04],[-74.32,71.84],[-75.21,71.71],[-74.7,71.68],[-75,71.22],[-74.49,71.65],[-73.87,71.77],[-73.71,71.72],[-74.2,71.4],[-73.71,71.59],[-73.18,71.28],[-73.28,71.54],[-72.9,71.68],[-71.64,71.52],[-71.19,71.28],[-72.63,70.83],[-70.67,71.05],[-70.76,70.79],[-71.89,70.43],[-71.28,70.5],[-71.43,70.13],[-70.98,70.58],[-70.08,70.83],[-68.5,70.61],[-68.48,70.41],[-70.06,70.04],[-68.78,70.2],[-69.01,69.98],[-68.74,69.94],[-67.86,70.28],[-67.19,69.76],[-69.25,69.51],[-66.68,69.26],[-69.04,69.1],[-67.75,69.04],[-67.88,68.78],[-69.32,68.86],[-66.71,68.45],[-67.03,68.33],[-66.92,68.07],[-66.21,68.28],[-66.53,67.85],[-65.94,68.07],[-65.51,67.97],[-65.4,67.68],[-65.41,67.88],[-64.98,68.04],[-65.02,67.79],[-63.85,67.57],[-64.59,67.32],[-63.04,67.23],[-63.7,66.82],[-62.12,67.05],[-61.3,66.65],[-62.12,66.64],[-61.58,66.41],[-61.86,66.31],[-62.55,66.41],[-61.99,66.03],[-62.59,66.03],[-62.38,65.83],[-62.66,65.64],[-63.46,65.85],[-63.65,65.66],[-63.34,65.62],[-63.36,65.23],[-63.61,64.93],[-64.35,65.17],[-64.27,65.4],[-64.55,65.12],[-65.4,65.76],[-64.45,66.32],[-65.82,66],[-65.66,66.2],[-66.06,66.13],[-66.99,66.63],[-67.31,66.57],[-67.23,66.31],[-67.88,66.47],[-67.18,66.03],[-67.35,65.93],[-68.75,66.2],[-68.22,66.08],[-67.87,65.77],[-67.94,65.56],[-67.12,65.44],[-67.34,65.35],[-66.7,64.82],[-66.63,65],[-66.21,64.72],[-65.94,64.89],[-65.43,64.73],[-65.27,64.63],[-65.53,64.51],[-65.08,64.44],[-65.58,64.29],[-64.68,64.03],[-64.8,63.92],[-64.41,63.71],[-64.67,63.24],[-65.19,63.76],[-64.67,62.92],[-65.16,62.93],[-65.11,62.63],[-66.66,63.26],[-66.72,63.08],[-67.89,63.73],[-67.72,63.42],[-68.91,63.7],[-65.98,62.21],[-66.33,61.87],[-71.35,63.07],[-71.99,63.42],[-71.38,63.58],[-72.5,63.82],[-73.45,64.4],[-73.27,64.58],[-74.07,64.43],[-74.68,64.83],[-74.92,64.77],[-74.7,64.5],[-76.86,64.24],[-78.17,64.62],[-78.05,64.98],[-77.36,65.2],[-77.33,65.45],[-75.83,65.23],[-75.45,64.84],[-75.36,65.01],[-75.8,65.3],[-73.55,65.48],[-74.42,66.17],[-72.22,67.26],[-73.28,68.36],[-73.82,68.36],[-73.85,68.7],[-74.42,68.58],[-74.91,68.82],[-74.85,69.07],[-76.59,68.7],[-76.56,69.01],[-75.65,69.21],[-76.52,69.52],[-76.23,69.66],[-77.09,69.64],[-76.86,69.78],[-77.59,69.85],[-77.77,70.24],[-79.07,70.6],[-79.4,70.4],[-78.81,70.18],[-79.09,69.93],[-81.65,70.1],[-80.92,69.73],[-81.56,69.94],[-85.78,70.04],[-86.32,70.15],[-86.4,70.47],[-87.9,70.25],[-88.85,70.52],[-89.46,71.06],[-87.14,71.01],[-89.69,71.42],[-90.02,71.95],[-89.66,72.17],[-89.82,72.47],[-88.71,73.4],[-86.77,73.83],[-85.01,73.78],[-86.67,72.76],[-86.32,72.46],[-86.22,71.9],[-85.02,71.35],[-86.47,71.04]],[[-69.49,83.02],[-66.42,82.93],[-68.47,82.65],[-64.9,82.9],[-63.5,82.79],[-63.64,82.71],[-63.09,82.56],[-63.25,82.45],[-61.21,82.34],[-68.69,81.29],[-64.78,81.49],[-69.55,80.38],[-70.71,80.54],[-70.26,80.23],[-72.06,80.12],[-70.56,80.07],[-71.39,79.76],[-74.39,79.87],[-74.66,79.84],[-73.2,79.6],[-76.9,79.51],[-74.48,79.23],[-74.53,79.05],[-78.58,79.08],[-74.43,78.72],[-76.42,78.51],[-75.19,78.33],[-75.97,77.99],[-78.01,77.95],[-78.08,77.52],[-78.49,77.37],[-81.66,77.53],[-81.28,77.37],[-82.06,77.3],[-79.5,77.2],[-79.22,76.94],[-78,76.85],[-78.28,76.57],[-80.8,76.17],[-80.97,76.47],[-82.53,76.72],[-82.23,76.47],[-83.89,76.45],[-84.22,76.67],[-84.28,76.36],[-86.45,76.58],[-86.68,76.38],[-87.49,76.59],[-87.5,76.39],[-88.4,76.41],[-88.49,76.77],[-88.54,76.42],[-89.57,76.49],[-89.5,76.83],[-88.56,77.07],[-86.81,77.19],[-87.68,77.44],[-88.02,77.78],[-86.76,77.86],[-84.49,77.37],[-83.61,77.44],[-82.59,77.99],[-83.78,77.53],[-84.86,77.5],[-85.29,77.56],[-85.55,77.93],[-84.22,78.18],[-84.91,78.24],[-84.78,78.53],[-85.59,78.11],[-86.22,78.08],[-85.92,78.34],[-87.55,78.18],[-86.81,78.77],[-81.75,78.98],[-84.41,79],[-84.57,79.07],[-83.58,79.05],[-86.42,79.84],[-86.5,80.26],[-83.72,80.23],[-80.48,79.61],[-80.12,79.67],[-81.01,79.69],[-82.99,80.32],[-76.86,80.87],[-78.72,80.95],[-76.88,81.43],[-81.01,80.66],[-85.15,80.52],[-86.62,80.63],[-83.29,81.15],[-85.78,81.04],[-87.71,80.66],[-89.26,80.91],[-84.94,81.29],[-89.62,81.03],[-89.98,81.12],[-89.21,81.25],[-89.68,81.33],[-89.43,81.39],[-87.6,81.53],[-90.31,81.4],[-90.61,81.43],[-89.82,81.63],[-91.68,81.64],[-88.06,82.1],[-85.05,81.98],[-86.62,82.22],[-84.9,82.45],[-79.43,81.85],[-82.45,82.39],[-81.68,82.52],[-82.12,82.63],[-80.81,82.59],[-81.18,82.75],[-81.01,82.78],[-78.75,82.68],[-80.16,82.91],[-79.89,82.94],[-77.48,82.88],[-76.01,82.54],[-75.57,82.61],[-77.13,83.01],[-74.41,83.01],[-72.66,82.72],[-73.44,82.95],[-69.57,83.02]],[[133.47,-0.73],[134.11,-0.85],[134.19,-2.31],[134.46,-2.83],[134.63,-2.54],[135.09,-3.35],[135.49,-3.34],[136.39,-2.27],[137.07,-2.11],[137.12,-1.84],[137.91,-1.48],[139.79,-2.35],[144.48,-3.83],[145.77,-4.82],[145.75,-5.4],[147.42,-5.97],[147.8,-6.31],[147.81,-6.7],[146.95,-6.88],[147.26,-7.46],[148.13,-8.1],[148.58,-9.05],[149.2,-9.03],[149.26,-9.5],[150.01,-9.69],[149.76,-9.81],[149.87,-10.01],[150.85,-10.24],[150.45,-10.31],[150.65,-10.52],[150.32,-10.65],[149.75,-10.35],[147.77,-10.07],[146.03,-8.08],[144.51,-7.57],[144.14,-7.76],[143.65,-7.46],[143.94,-7.95],[143.52,-8],[143.61,-8.2],[142.21,-8.2],[143.38,-8.76],[142.65,-9.33],[141.13,-9.22],[140,-8.2],[140.12,-7.92],[139.38,-8.19],[139.25,-7.98],[138.93,-8.26],[139.09,-7.59],[138.75,-7.25],[139.18,-7.19],[138.6,-6.94],[138.87,-6.86],[138.44,-6.34],[138.34,-5.68],[138.09,-5.71],[137.28,-4.95],[135.19,-4.45],[134.68,-4.08],[134.89,-3.94],[133.97,-3.82],[133.68,-3.48],[133.84,-3.05],[133.4,-3.9],[132.97,-4.09],[132.75,-3.29],[131.97,-2.79],[132.72,-2.79],[133.19,-2.44],[133.7,-2.62],[133.92,-2.1],[132.31,-2.24],[131.93,-1.56],[131,-1.42],[131.26,-0.86],[132.39,-0.36],[133.27,-0.64]],[[116.81,6.69],[117.23,6.94],[117.69,6.35],[117.5,5.88],[118,6.05],[117.97,5.71],[118.35,5.81],[119.26,5.37],[119.13,5.1],[118.26,4.99],[118.55,4.38],[117.5,4.13],[117.78,3.69],[117.06,3.62],[118.06,2.32],[117.79,2.03],[118.99,0.98],[118.53,0.81],[117.91,1.1],[117.52,0.24],[117.56,-0.77],[116.91,-1.22],[116.74,-1.04],[116.75,-1.33],[116.28,-1.79],[116.55,-2.41],[115.96,-3.59],[114.7,-4.17],[114.34,-3.24],[113.71,-3.46],[113.04,-2.93],[112.76,-3.32],[111.86,-3.55],[111.7,-2.89],[110.26,-2.97],[109.98,-1.28],[109.29,-0.85],[109.13,-0.45],[109.26,0.03],[108.91,0.79],[109.08,1.5],[109.63,2.03],[111.22,1.4],[111.04,1.63],[111.51,2.74],[112.99,3.16],[114.01,4.57],[114.99,5.02],[115.43,4.97],[115.42,5.41],[115.88,5.61],[116.78,6.99],[116.84,6.77]],[[-114.52,72.59],[-113.58,72.65],[-113.08,73],[-111.27,72.71],[-111.89,72.36],[-111.67,72.3],[-110.21,72.66],[-110.66,73.01],[-110.01,72.98],[-108.76,72.55],[-108.19,71.72],[-107.81,71.63],[-107.3,71.9],[-107.7,72.15],[-108.24,73.15],[-107.93,73.22],[-108.03,73.35],[-106.48,73.2],[-105.41,72.79],[-104.38,71.58],[-104.51,71.06],[-103.59,70.63],[-101.09,70.14],[-100.91,69.81],[-102.24,69.84],[-102.62,69.55],[-103.43,69.67],[-103.05,69.47],[-103.12,69.2],[-102.15,69.49],[-101.79,69.18],[-102.89,68.82],[-105.1,68.92],[-105.02,69.08],[-106.14,69.16],[-106.66,69.44],[-107.44,69],[-109.47,68.68],[-113.02,68.48],[-113.55,68.77],[-113.69,69.19],[-116.51,69.43],[-117.19,70.05],[-111.63,70.31],[-113.76,70.69],[-117.59,70.63],[-118.38,70.97],[-115.3,71.49],[-117.94,71.39],[-118.23,71.47],[-117.74,71.66],[-118.99,71.76],[-118.94,71.99],[-118.21,72.26],[-118.37,72.53],[-116.57,73.06],[-114.21,73.3],[-114.08,72.91],[-114.5,72.63]],[[49.54,-12.43],[49.94,-13.07],[50.41,-15.63],[50.19,-15.96],[49.89,-15.46],[49.66,-15.52],[49.84,-16.49],[49.45,-17.24],[49.36,-18.34],[47.18,-24.79],[46.73,-25.15],[45.11,-25.54],[44.03,-25],[43.26,-22.38],[43.5,-21.36],[44.4,-19.92],[43.98,-17.39],[44.48,-16.22],[46.16,-15.74],[46.4,-15.93],[46.47,-15.51],[46.94,-15.22],[47.1,-15.43],[47.35,-14.77],[47.48,-15.01],[47.97,-14.67],[47.77,-14.37],[47.94,-13.66],[48.26,-13.72],[48.8,-13.27],[48.79,-12.47],[49.21,-12.08],[49.48,-12.35]],[[96.49,5.23],[97.55,5.21],[98.31,4.09],[99.73,3.18],[100.31,2.47],[100.53,2.19],[100.82,1.99],[100.89,1.95],[100.83,2.24],[100.94,2.29],[101.05,2.26],[101.3,2.01],[101.48,1.69],[101.79,1.62],[102.39,0.84],[102.57,0.75],[102.85,0.72],[103.03,0.58],[103.07,0.49],[102.79,0.3],[102.55,0.22],[102.78,0.24],[103.34,0.51],[103.48,0.48],[103.67,0.29],[103.79,0.05],[103.43,-0.19],[103.53,-0.75],[104.38,-1.07],[104.51,-1.82],[104.85,-2.09],[104.65,-2.59],[105.4,-2.38],[106.04,-3.11],[105.89,-5.01],[105.82,-5.68],[105.75,-5.82],[105.62,-5.8],[105.52,-5.67],[104.64,-5.52],[104.6,-5.91],[101.58,-3.17],[100.89,-2.25],[100.31,-0.83],[99.16,0.35],[98.6,1.87],[97.7,2.36],[96.97,3.58],[95.58,4.66],[95.23,5.56],[96.25,5.27]],[[-3.11,58.52],[-3.99,57.96],[-3.86,57.82],[-4.13,57.58],[-1.96,57.68],[-1.78,57.47],[-2.09,57.1],[-2.26,56.86],[-2.59,56.56],[-3.31,56.36],[-2.89,56.4],[-2.65,56.32],[-2.67,56.25],[-2.98,56.19],[-3.36,56.03],[-3.79,56.09],[-3.61,56.02],[-3.05,55.95],[-2.84,56.03],[-2.6,56.03],[-2.15,55.9],[-1.65,55.57],[-1.23,54.7],[-0.08,54.12],[0.12,53.61],[-0.66,53.72],[0.13,53.47],[0.35,53.16],[0.21,53.03],[0.05,52.91],[0.33,52.81],[0.52,52.94],[1.66,52.75],[1.75,52.47],[1.32,51.96],[1.23,51.97],[1.28,51.84],[1.19,51.8],[0.96,51.81],[0.75,51.73],[0.9,51.69],[0.89,51.57],[0.42,51.47],[0.53,51.49],[0.69,51.39],[0.89,51.36],[1.42,51.36],[1.4,51.18],[1.05,51.05],[0.96,50.93],[0.77,50.93],[0.2,50.76],[-0.2,50.82],[-0.79,50.76],[-1.42,50.9],[-1.33,50.82],[-1.52,50.75],[-3,50.72],[-3.4,50.63],[-3.68,50.24],[-3.79,50.23],[-4.2,50.39],[-4.73,50.29],[-5.01,50.16],[-5.12,50.04],[-5.23,50.02],[-5.43,50.11],[-5.62,50.05],[-5.66,50.13],[-5.34,50.25],[-4.89,50.53],[-4.58,50.78],[-4.52,50.98],[-4.3,51.03],[-4.19,51.19],[-3.84,51.23],[-3.26,51.19],[-3.04,51.25],[-2.43,51.74],[-3.29,51.39],[-3.56,51.41],[-3.89,51.59],[-4.24,51.57],[-4.09,51.66],[-4.39,51.74],[-4.6,51.74],[-4.9,51.63],[-5.12,51.71],[-5.2,51.86],[-5.26,51.88],[-5.09,52],[-4.38,52.2],[-4.15,52.33],[-4.1,52.92],[-4.68,52.84],[-3.81,53.3],[-3.32,53.35],[-3.1,53.26],[-3.17,53.39],[-3.07,53.43],[-2.92,53.3],[-2.75,53.31],[-2.91,53.35],[-3.07,53.51],[-2.93,53.73],[-3.03,53.77],[-3.03,53.91],[-2.9,53.96],[-2.87,54.18],[-3.17,54.13],[-3.57,54.47],[-3.59,54.56],[-3.47,54.77],[-3.27,54.91],[-3.04,54.95],[-3.55,54.95],[-3.96,54.78],[-4.3,54.84],[-4.91,54.69],[-5.17,54.92],[-4.68,55.5],[-4.73,55.6],[-4.87,55.87],[-4.58,55.94],[-4.67,55.97],[-4.8,56.16],[-5.23,55.89],[-5.09,56.2],[-5.77,55.36],[-5.19,56.76],[-5.65,56.53],[-6.13,56.71],[-5.59,57.1],[-5.82,57.44],[-5.58,57.55],[-5.69,57.78],[-5.16,57.88],[-5.41,58.07],[-5.01,58.26],[-4.98,58.58],[-3.06,58.59]],[[141.23,41.37],[141.45,41.4],[141.43,40.72],[141.8,40.29],[141.98,39.43],[141.47,38.4],[140.96,38.15],[141,37.11],[140.79,36.85],[140.63,36.5],[140.57,36.23],[140.62,36.06],[140.87,35.72],[140.64,35.66],[140.46,35.51],[140.36,35.18],[140.06,35.04],[139.92,34.9],[139.8,34.96],[139.84,35.01],[139.83,35.3],[140.1,35.59],[139.99,35.67],[139.83,35.66],[139.77,35.49],[139.65,35.41],[139.74,35.25],[139.68,35.15],[139.47,35.3],[139.25,35.28],[139.13,35.15],[139.09,34.84],[138.98,34.7],[138.84,34.62],[138.76,34.7],[138.8,34.97],[138.9,35.02],[138.72,35.12],[138.58,35.09],[138.35,34.85],[138.19,34.6],[137.06,34.58],[137.3,34.73],[137.1,34.76],[136.96,34.84],[136.94,34.72],[136.87,34.73],[136.85,34.98],[136.9,35.03],[136.8,35.05],[136.69,34.98],[136.53,34.68],[136.88,34.43],[136.85,34.32],[136.33,34.18],[135.92,33.56],[135.69,33.49],[135.45,33.55],[135.13,34.01],[135.1,34.29],[135.31,34.42],[135.42,34.62],[135.04,34.63],[134.74,34.77],[134.25,34.71],[133.97,34.53],[132.31,34.32],[132.14,33.84],[131.74,34.05],[130.92,33.98],[131,34.39],[131.35,34.41],[132.75,35.45],[134.21,35.54],[134.46,35.63],[135.18,35.75],[135.27,35.72],[135.23,35.59],[135.27,35.55],[135.68,35.5],[136.01,35.68],[136.09,35.77],[136.01,35.99],[136.07,36.12],[136.7,36.74],[136.84,37.38],[137.32,37.52],[136.9,37.12],[137.3,36.75],[138.32,37.22],[139.36,38.1],[140.04,39.41],[140,39.86],[139.74,39.92],[140.01,40.26],[139.92,40.6],[140.39,41.23],[140.75,40.83],[141.12,40.88],[141.25,41.21],[140.8,41.25],[140.94,41.5],[141.11,41.46]],[[-119.74,74.11],[-117.51,74.23],[-115.39,73.5],[-118.96,72.68],[-120.18,72.21],[-120.62,71.51],[-122.84,71.1],[-124.01,71.68],[-125.84,71.98],[-124.99,72.59],[-124.97,72.84],[-124.57,72.94],[-124.8,73.13],[-123.8,73.77],[-124.7,74.35],[-121.5,74.54],[-119.56,74.23],[-119.74,74.13]],[[-91.89,81.13],[-90.64,80.59],[-89.24,80.51],[-88.86,80.17],[-88.2,80.11],[-88.61,80.26],[-88.52,80.42],[-87.67,80.37],[-87.92,80.1],[-86.98,79.89],[-87.3,79.58],[-85.65,79.61],[-85.04,79.28],[-87.62,78.68],[-87.92,78.75],[-87.83,79.05],[-88.04,79],[-88.25,78.67],[-87.98,78.54],[-88.74,78.58],[-88.79,78.19],[-90.04,78.61],[-89.49,78.17],[-91.41,78.19],[-92.85,78.46],[-91.87,78.54],[-93.27,78.61],[-93.64,78.75],[-93.16,78.78],[-94.17,78.97],[-91.3,79.37],[-95.1,79.29],[-95.73,79.42],[-94.4,79.74],[-95.86,79.67],[-96.77,80.14],[-94.26,80.2],[-96.39,80.32],[-95.55,80.37],[-96.15,80.55],[-95.93,80.72],[-93.93,80.56],[-95.51,80.84],[-95.27,81],[-93.24,81.13],[-94.18,81.34],[-92,81.18]],[[-15.54,66.23],[-14.6,66.38],[-15.11,66.1],[-14.7,66.02],[-14.83,65.76],[-14.39,65.79],[-14.47,65.57],[-13.62,65.52],[-13.8,65.35],[-13.57,65.07],[-14.63,64.42],[-18.08,63.5],[-20.49,63.69],[-20.41,63.81],[-20.65,63.74],[-21.14,63.89],[-21.09,63.93],[-21.15,63.94],[-21.45,63.86],[-22.65,63.83],[-22.69,63.87],[-22.74,64.02],[-22.7,64.08],[-22.51,63.99],[-22.06,64.07],[-21.67,64.35],[-21.46,64.38],[-21.65,64.4],[-22.05,64.31],[-21.9,64.39],[-22,64.41],[-21.95,64.52],[-21.59,64.63],[-22.16,64.54],[-22.33,64.63],[-22.25,64.73],[-22.47,64.8],[-24.02,64.86],[-23.32,64.96],[-22.79,65.05],[-21.89,65.05],[-21.8,65.11],[-21.78,65.19],[-22.04,65.13],[-22.51,65.2],[-21.84,65.45],[-22.31,65.48],[-22.64,65.57],[-24.47,65.52],[-23.86,65.54],[-24.09,65.78],[-23.29,65.75],[-23.83,65.85],[-23.52,65.88],[-23.78,66.02],[-23.45,66.18],[-22.44,65.91],[-22.95,66.21],[-22.48,66.27],[-23.12,66.34],[-22.89,66.44],[-21.41,66.03],[-21.38,65.74],[-21.66,65.72],[-21.36,65.58],[-21.43,65.47],[-21.23,65.42],[-21.13,65.27],[-21.05,65.43],[-20.45,65.57],[-20.21,66.1],[-19.49,65.77],[-19.38,66.08],[-18.84,66.18],[-18.14,65.73],[-18.3,66.16],[-17.55,65.96],[-16.49,66.2],[-16.54,66.45],[-16.25,66.52],[-15.65,66.26]],[[-94.29,76.91],[-93.21,76.75],[-93.53,76.45],[-91.31,76.68],[-90.54,76.5],[-91.41,76.46],[-89.29,76.3],[-91.41,76.22],[-89.28,75.79],[-89.65,75.57],[-88.92,75.45],[-88.65,75.66],[-85.95,75.4],[-83.93,75.82],[-82.15,75.83],[-79.66,75.45],[-79.51,75.26],[-80.38,75.03],[-79.4,74.92],[-80.35,74.9],[-80.15,74.8],[-80.28,74.58],[-81.94,74.47],[-82.93,74.57],[-83.52,74.9],[-83.34,74.77],[-83.53,74.59],[-84.43,74.51],[-88.42,74.49],[-88.34,74.78],[-88.53,74.83],[-89.56,74.56],[-90.88,74.82],[-91.51,74.65],[-92.39,75.26],[-92.07,75.66],[-92.18,75.85],[-93.09,76.35],[-95.27,76.26],[-96.04,76.49],[-95.65,76.58],[-96.9,76.75],[-96.4,76.8],[-96.76,76.97],[-95.85,77.07],[-94.61,76.96]],[[173.12,-41.28],[173.95,-40.92],[173.8,-41.27],[174,-40.99],[174.3,-41.02],[174.04,-41.24],[174.37,-41.1],[174.07,-41.43],[174.21,-41.85],[172.53,-43.47],[173.1,-43.84],[172.04,-43.7],[172.18,-43.9],[171.24,-44.26],[170.78,-45.87],[169.69,-46.55],[169.1,-46.63],[168.38,-46.61],[167.54,-46.15],[166.83,-46.23],[166.92,-45.96],[166.49,-45.96],[167,-45.71],[166.73,-45.54],[166.87,-45.31],[167.16,-45.41],[167.03,-45.12],[167.91,-44.67],[168.37,-44.08],[169.18,-43.91],[171.04,-42.86],[172.27,-40.76],[172.94,-40.52],[172.7,-40.67],[173.07,-41.19]],[[16.79,79.91],[17.83,79.8],[17.67,79.39],[18.4,79.61],[18.82,79.43],[18.68,79.26],[20.61,79.11],[20.77,79.06],[20.5,78.98],[21.39,78.74],[19.15,78.38],[16.7,76.58],[14,77.51],[16.91,77.9],[14.09,77.77],[13.68,78.03],[17.17,78.42],[16.45,78.5],[16.78,78.66],[15.42,78.47],[15.38,78.77],[14.69,78.72],[14.43,78.49],[14.64,78.41],[13.15,78.24],[11.37,78.95],[12.4,78.95],[11.98,79.03],[11.98,79.29],[11.21,79.13],[10.68,79.76],[13.69,79.86],[13.92,79.76],[12.56,79.57],[13.96,79.34],[14.59,79.8],[16.34,78.98],[15.83,79.71],[16.25,80.05],[16.52,80.02]],[[67.77,76.24],[61.36,75.32],[59.67,74.61],[58.53,74.5],[58.62,74.23],[57.77,74.01],[57.76,73.77],[57.31,73.84],[57.54,73.66],[56.63,73.31],[54.3,73.35],[53.76,73.77],[55.34,74.42],[56.14,74.5],[55.58,74.63],[56.5,74.96],[55.81,75.12],[57.61,75.34],[58.88,75.86],[60.94,76.07],[61.2,76.28],[64.46,76.38],[67.53,77.01],[68.94,76.71],[68.16,76.28]],[[124.89,1],[124.43,0.47],[123.75,0.31],[120.58,0.53],[120.19,0.27],[120.06,-0.55],[120.67,-1.37],[121.15,-1.34],[121.58,-0.83],[121.97,-0.93],[123.17,-0.57],[123.43,-0.78],[123.38,-1],[122.9,-0.9],[122.25,-1.55],[121.36,-1.88],[122.29,-2.91],[122.25,-3.62],[122.85,-4.07],[122.87,-4.39],[122.12,-4.54],[122.04,-4.83],[121.59,-4.76],[121.62,-4.09],[120.89,-3.52],[121.05,-2.75],[120.65,-2.67],[120.26,-2.95],[120.43,-5.59],[119.56,-5.61],[119.36,-5.32],[119.62,-4.03],[119.47,-3.51],[118.92,-3.48],[118.78,-2.72],[119.32,-1.93],[119.51,-0.91],[119.71,-0.68],[119.84,-0.86],[119.72,-0.09],[120.27,0.97],[120.6,0.85],[121.08,1.33],[122.84,0.85],[123.85,0.84],[125.11,1.69],[125.23,1.5],[124.97,1.08]],[[-55.46,51.54],[-56.03,51.33],[-55.8,51.03],[-56.82,49.61],[-56.18,50.12],[-56.16,49.94],[-55.5,49.98],[-56.14,49.62],[-55.23,49.51],[-55.35,49.08],[-54.5,49.53],[-54.45,49.33],[-53.62,49.32],[-53.57,49.14],[-54.16,48.79],[-53.71,48.66],[-54.11,48.39],[-53.03,48.63],[-53.87,48.02],[-53.64,48.02],[-53.86,47.8],[-53.67,47.65],[-52.86,48.11],[-53.17,47.51],[-52.78,47.77],[-52.65,47.55],[-53.07,46.68],[-53.59,46.64],[-53.6,47.15],[-54.18,46.88],[-53.85,47.44],[-54.19,47.86],[-54.49,47.4],[-55.79,46.87],[-55.92,47.02],[-54.78,47.66],[-55.58,47.46],[-56.13,47.5],[-55.86,47.82],[-56.77,47.57],[-59.26,47.63],[-59.34,47.93],[-58.33,48.52],[-59.17,48.56],[-58.71,48.6],[-58.41,49.08],[-57.99,48.99],[-58.21,49.39],[-57.79,49.49],[-57.93,49.7],[-57.04,51.01],[-56.03,51.57],[-55.45,51.56]],[[-108.29,76.06],[-107.72,76],[-108.02,75.8],[-107.21,75.89],[-106.91,75.68],[-106.68,76.02],[-105.9,76.01],[-105.48,75.7],[-106.09,75.09],[-108.83,75.07],[-112.52,74.42],[-114.38,74.67],[-111.03,75.23],[-113.71,75.07],[-113.85,75.26],[-113.47,75.42],[-114.01,75.43],[-114.52,75.28],[-114.45,75.09],[-115.73,74.97],[-117.6,75.27],[-115.14,75.68],[-117.16,75.65],[-114.99,75.9],[-116.66,75.96],[-116.21,76.19],[-114.78,76.17],[-115.83,76.3],[-115,76.5],[-112.7,76.2],[-111.05,75.55],[-109.09,75.51],[-108.92,75.67],[-109.87,75.93],[-109.43,76.11],[-110.31,76.4],[-108.83,76.82],[-108.47,76.74],[-108.63,76.59],[-108.12,76.23],[-108.39,76.07]],[[173.27,-34.93],[174.37,-35.33],[174.54,-35.58],[174.51,-35.67],[174.58,-35.79],[174.39,-35.8],[174.8,-36.31],[174.75,-36.49],[174.82,-36.61],[174.72,-36.84],[174.89,-36.91],[174.95,-36.85],[175.3,-36.99],[175.38,-37.21],[175.54,-37.2],[175.49,-36.69],[175.38,-36.56],[175.46,-36.48],[175.68,-36.75],[175.77,-36.73],[175.99,-37.44],[176.12,-37.54],[176.13,-37.59],[176.03,-37.58],[176.11,-37.64],[177.27,-37.99],[178.01,-37.55],[178.53,-37.69],[177.91,-39.24],[177.08,-39.22],[176.84,-40.16],[175.98,-41.21],[175.31,-41.61],[174.87,-41.22],[174.64,-41.29],[175.21,-40.2],[173.76,-39.32],[174.57,-38.84],[174.65,-38.43],[174.84,-38.02],[174.8,-37.9],[174.93,-37.8],[174.73,-37.45],[174.77,-37.34],[174.71,-37.33],[174.59,-37.1],[174.66,-37.09],[174.73,-37.22],[174.81,-37.11],[174.93,-37.09],[174.78,-36.94],[174.6,-36.98],[174.47,-36.94],[174.38,-36.73],[174.19,-36.49],[174.4,-36.6],[174.46,-36.51],[174.36,-36.38],[174.39,-36.24],[174.27,-36.16],[174.25,-36.25],[174.03,-36.12],[173.92,-35.91],[173.92,-36.02],[174.17,-36.33],[174.15,-36.38],[174.06,-36.36],[173.41,-35.54],[173.63,-35.32],[173.31,-35.44],[172.71,-34.46],[173.04,-34.43],[173.24,-34.9]],[[-7.18,55.06],[-6.13,55.22],[-5.72,54.82],[-5.71,54.76],[-5.88,54.68],[-5.88,54.64],[-5.58,54.66],[-5.47,54.5],[-5.48,54.44],[-5.67,54.55],[-5.66,54.38],[-5.56,54.37],[-5.61,54.27],[-5.83,54.24],[-6.02,54.05],[-6.22,54.09],[-6.16,54.02],[-6.35,53.99],[-6.14,53.58],[-6.15,53.37],[-6.03,52.93],[-6.17,52.74],[-6.22,52.54],[-6.46,52.34],[-6.32,52.25],[-6.89,52.16],[-6.96,52.25],[-7.08,52.14],[-7.22,52.14],[-9.3,51.5],[-10.12,51.6],[-9.6,51.87],[-10.34,51.8],[-9.91,52.12],[-10.36,52.21],[-8.78,52.68],[-9.92,52.57],[-8.93,53.21],[-10.09,53.41],[-9.58,53.8],[-9.91,53.86],[-10.06,54.26],[-8.54,54.24],[-8.13,54.64],[-8.76,54.68],[-8.27,55.15],[-7.67,55.26],[-7.66,54.97],[-7.31,55.37],[-6.96,55.24],[-7.22,55.09]],[[107.37,-6.01],[107.56,-6.18],[108.14,-6.3],[108.29,-6.26],[108.42,-6.38],[108.78,-6.81],[110.43,-6.95],[110.84,-6.42],[112.54,-6.93],[113.01,-7.66],[114.41,-7.79],[114.58,-8.77],[113.25,-8.29],[111.51,-8.3],[107.29,-7.47],[106.53,-7.39],[106.41,-7.31],[106.52,-7.05],[105.94,-6.86],[105.48,-6.85],[105.26,-6.84],[105.34,-6.67],[105.37,-6.66],[105.4,-6.77],[105.48,-6.78],[105.66,-6.47],[105.79,-6.46],[105.87,-6.12],[106.07,-5.91],[106.83,-6.1],[107.01,-6.01],[107.05,-5.9],[107.33,-5.98]],[[142.76,54.39],[143.33,52.96],[143.19,51.95],[144.71,48.64],[144.05,49.25],[143.1,49.2],[142.56,47.74],[143.58,46.36],[143.43,46.03],[143.28,46.56],[142.58,46.7],[142.08,45.92],[141.83,46.45],[142.18,48.01],[141.86,48.75],[142.14,49.57],[142.21,51.22],[141.72,51.74],[141.66,52.27],[141.83,53.34],[142.53,53.45],[142.71,53.89],[142.34,54.28],[142.69,54.42]],[[-81.84,23.16],[-79.82,22.89],[-74.15,20.17],[-77.72,19.86],[-77.23,20.64],[-78.12,20.76],[-78.73,21.59],[-81.85,22.21],[-82.08,22.39],[-81.71,22.5],[-81.7,22.59],[-81.84,22.67],[-82.74,22.69],[-84.84,21.83],[-84.04,22.67],[-83.26,22.97],[-82.1,23.19]],[[143.82,44.12],[144.72,43.93],[145.37,44.33],[145.14,43.66],[145.34,43.3],[145.83,43.39],[143.97,42.88],[143.24,42],[141.85,42.58],[140.99,42.34],[140.48,42.56],[140.33,42.29],[141.15,41.81],[140.04,41.47],[139.86,42.58],[140.43,42.95],[140.39,43.3],[141.38,43.28],[141.76,44.48],[141.67,45.4],[141.94,45.51],[143.76,44.13]],[[121.1,18.62],[121.85,18.29],[122.27,18.46],[122.15,17.66],[122.52,17.12],[122.14,16.19],[121.69,16.02],[121.6,15.93],[121.56,15.83],[121.61,15.67],[121.39,15.32],[121.69,14.77],[121.63,14.58],[121.77,14.17],[121.91,14.02],[122.21,13.93],[122.29,14],[122.2,14.15],[122.49,14.32],[122.94,14.19],[123.1,13.75],[123.32,14.06],[123.86,13.8],[123.55,13.65],[123.79,13.11],[124.14,13.04],[124.06,12.57],[123.95,12.92],[123.31,13.04],[122.59,13.91],[122.6,13.19],[122.21,13.65],[122.07,13.79],[121.78,13.94],[121.5,13.84],[121.45,13.71],[121.34,13.65],[121.1,13.68],[120.93,13.76],[120.84,13.89],[120.73,13.9],[120.64,13.81],[120.62,14.19],[120.92,14.49],[120.94,14.65],[120.59,14.88],[120.55,14.77],[120.59,14.48],[120.44,14.45],[120.25,14.79],[120.08,14.85],[119.93,15.43],[119.77,16.25],[120.37,16.11],[120.6,18.51],[121.05,18.61]],[[-100,73.95],[-99.16,73.73],[-97.11,73.79],[-97,73.67],[-97.63,73.5],[-97.27,73.39],[-98.43,72.96],[-97.63,73.03],[-97.13,72.63],[-96.54,72.7],[-96.47,72.43],[-96.8,72.32],[-96.61,71.83],[-97.58,71.63],[-98.32,71.85],[-98.2,71.44],[-99.17,71.37],[-100.59,72.15],[-102.71,72.77],[-102.2,73.08],[-101.27,72.72],[-100.13,72.91],[-100.54,73.2],[-99.82,73.21],[-101.52,73.49],[-100.52,73.45],[-100.99,73.77],[-100.14,73.93]],[[55.32,73.31],[56.43,73.2],[56.12,72.81],[55.4,72.55],[55.52,72.22],[55.3,71.94],[56.45,71.11],[57.62,70.73],[56.26,70.71],[56.44,70.56],[53.72,70.81],[53.38,70.87],[54.16,71.12],[53.41,71.34],[53.41,71.53],[51.81,71.49],[51.44,71.78],[51.58,72.07],[52.62,72.3],[52.92,72.67],[52.55,72.77],[53.37,72.92],[53.25,73.18],[55.12,73.36]],[[-84.92,65.26],[-84.5,65.46],[-82.05,64.64],[-81.68,64.21],[-81.89,64.02],[-80.83,64.09],[-80.26,63.8],[-81.05,63.46],[-83.3,64.14],[-84.63,63.31],[-85.39,63.12],[-85.77,63.7],[-87.18,63.6],[-86.25,64.14],[-86.37,64.57],[-85.81,65.83],[-85.24,65.8],[-85.06,65.44]],[[126.01,9.32],[126.09,9.26],[126.19,9.28],[126.19,9.12],[126.21,9.08],[126.3,8.95],[126.32,8.84],[126.26,8.74],[126.22,8.7],[126.14,8.63],[126.14,8.6],[126.17,8.56],[126.28,8.54],[126.37,8.48],[126.38,8.33],[126.46,8.2],[126.46,8.15],[126.43,7.93],[126.44,7.83],[126.49,7.76],[126.54,7.72],[126.57,7.68],[126.59,7.55],[126.59,7.33],[126.58,7.25],[126.55,7.18],[126.44,7.01],[126.29,6.88],[126.22,6.89],[126.19,6.85],[126.24,6.73],[126.22,6.48],[126.19,6.31],[126.14,6.4],[126.11,6.49],[126.08,6.73],[126.04,6.84],[125.98,6.94],[125.96,7.03],[125.9,7.12],[125.82,7.33],[125.77,7.32],[125.69,7.26],[125.67,7.22],[125.66,7.16],[125.64,7.11],[125.54,7.02],[125.46,6.91],[125.4,6.8],[125.38,6.69],[125.43,6.61],[125.49,6.57],[125.56,6.5],[125.59,6.47],[125.67,6.23],[125.67,5.98],[125.61,5.87],[125.46,5.66],[125.35,5.6],[125.29,5.63],[125.24,5.76],[125.23,5.81],[125.26,5.93],[125.27,6.03],[125.23,6.07],[125.19,6.06],[125.17,6.05],[125.08,5.91],[125.04,5.87],[124.98,5.87],[124.93,5.88],[124.64,6],[124.4,6.12],[124.21,6.23],[124.08,6.4],[124.05,6.53],[124.05,6.67],[123.99,6.86],[123.98,6.93],[123.99,6.99],[124.05,7.11],[124.12,7.18],[124.16,7.22],[124.19,7.27],[124.21,7.33],[124.21,7.4],[124.18,7.44],[124.07,7.58],[123.97,7.66],[123.76,7.74],[123.72,7.79],[123.67,7.82],[123.61,7.83],[123.55,7.83],[123.49,7.81],[123.48,7.76],[123.48,7.71],[123.48,7.67],[123.39,7.41],[123.28,7.46],[123.18,7.53],[123.15,7.58],[123.14,7.63],[123.12,7.67],[123.1,7.7],[123.05,7.61],[122.99,7.55],[122.92,7.53],[122.84,7.53],[122.82,7.56],[122.79,7.72],[122.71,7.77],[122.62,7.76],[122.5,7.67],[122.47,7.64],[122.45,7.56],[122.32,7.34],[122.25,7.17],[122.18,7],[122.14,6.95],[122.1,6.91],[122.03,6.93],[121.96,6.97],[121.9,7.08],[121.92,7.2],[121.99,7.28],[122.05,7.36],[122.11,7.66],[122.12,7.77],[122.13,7.81],[122.24,7.95],[122.34,8.03],[122.39,8.05],[122.59,8.09],[122.67,8.13],[122.8,8.13],[122.91,8.16],[123,8.22],[123,8.29],[123,8.36],[123.02,8.4],[123.05,8.43],[123.1,8.48],[123.15,8.52],[123.29,8.54],[123.34,8.57],[123.38,8.62],[123.43,8.7],[123.5,8.68],[123.56,8.65],[123.68,8.62],[123.78,8.55],[123.85,8.43],[123.86,8.38],[123.88,8.19],[123.85,8.15],[123.75,8.06],[123.8,8.05],[123.93,8.13],[124,8.16],[124.16,8.2],[124.2,8.23],[124.23,8.27],[124.28,8.39],[124.33,8.51],[124.36,8.56],[124.4,8.6],[124.45,8.61],[124.62,8.52],[124.73,8.56],[124.76,8.69],[124.79,8.87],[124.81,8.92],[124.87,8.97],[124.94,8.96],[125.05,8.89],[125.14,8.87],[125.18,8.92],[125.21,9.03],[125.25,9.03],[125.38,8.99],[125.5,9.01],[125.53,9.14],[125.51,9.28],[125.41,9.67],[125.47,9.76],[125.52,9.76],[125.64,9.65],[125.88,9.51],[125.95,9.43]],[[140.05,75.83],[140.82,75.63],[140.99,75.96],[141.49,76.14],[145.36,75.53],[144.02,75.04],[142.82,75.27],[142.7,75.45],[142.94,75.71],[142.31,75.69],[142.09,75.66],[142.2,75.39],[143.13,74.97],[139.68,74.96],[139.1,74.66],[138.09,74.8],[136.95,75.33],[137.29,75.35],[137.27,75.75],[137.71,75.76],[137.56,75.96],[138.21,76.12],[138.92,76.2],[139.74,75.95]],[[-93.17,74.16],[-90.36,73.87],[-92.12,72.75],[-94.21,72.76],[-93.54,72.44],[-94.14,72],[-95.19,72.03],[-95.6,72.88],[-95.63,73.7],[-94.7,73.66],[-95.15,73.91],[-94.97,74.04],[-93.41,74.18]],[[145.04,-40.79],[146.32,-41.16],[148.22,-40.85],[148.34,-42.22],[148.22,-41.97],[148.02,-42.26],[147.98,-43.16],[147.3,-42.79],[146.87,-43.61],[146.04,-43.55],[146.21,-43.32],[145.49,-42.93],[145.2,-42.23],[145.52,-42.35],[144.77,-41.39],[144.72,-40.67],[144.82,-40.72]],[[20.9,80.25],[22.29,80.05],[22.45,80.4],[23.01,80.47],[23.32,80.42],[23.11,80.19],[24.4,80.36],[26.86,80.16],[27.2,79.91],[23.95,79.19],[20.13,79.49],[19.68,79.59],[20.78,79.75],[18.73,79.76],[18.25,79.93],[18.86,80.04],[17.92,80.14],[19.34,80.12],[19.54,80.16],[19.18,80.33],[19.75,80.23],[19.73,80.48],[20.69,80.3]],[[-71.95,19.72],[-69.96,19.67],[-69.74,19.3],[-69.32,19.33],[-69.23,19.27],[-69.32,19.2],[-69.61,19.21],[-69.62,19.12],[-68.36,18.54],[-68.69,18.21],[-68.93,18.41],[-69.27,18.44],[-69.77,18.44],[-70.02,18.37],[-70.18,18.25],[-70.48,18.22],[-70.64,18.34],[-71.03,18.27],[-71.11,18.07],[-71.44,17.64],[-72.06,18.23],[-73.88,18.04],[-74.39,18.62],[-72.35,18.62],[-72.7,19.44],[-73.4,19.81]],[[-69.17,-52.67],[-68.63,-52.65],[-68.24,-53.08],[-68.49,-53.26],[-67.29,-54.05],[-66.24,-54.53],[-65.18,-54.68],[-66.51,-55.03],[-71.9,-54.6],[-70.8,-54.33],[-70.31,-54.53],[-70.86,-54.11],[-70.53,-53.63],[-70.38,-53.99],[-70.63,-54],[-70.24,-54.35],[-69.05,-54.43],[-70.15,-53.89],[-69.39,-53.37],[-70.21,-53.41],[-70.46,-53.21],[-70.13,-52.94],[-70.38,-52.75],[-69.94,-52.82],[-69.5,-52.49],[-69.41,-52.49]],[[97.67,80.16],[98.02,80.02],[97.65,79.76],[98.6,80.05],[99.95,79.85],[99.68,79.32],[99.04,79.29],[99.93,78.96],[97.56,78.83],[93.07,79.5],[94.99,80.1],[97.59,80.17]],[[-115.55,77.36],[-116.33,77.14],[-115.81,76.94],[-116.25,76.9],[-115.94,76.71],[-117,76.53],[-117.23,76.28],[-117.99,76.41],[-117.88,76.8],[-118.79,76.51],[-118.62,76.37],[-118.99,76.15],[-119.58,76.33],[-119.74,76.12],[-119.54,75.98],[-119.91,75.86],[-120.41,75.83],[-120.85,76.18],[-122.4,75.94],[-122.9,76.13],[-119.09,77.3],[-116.84,77.34],[-117.04,77.46],[-116.51,77.55],[-116.01,77.46]],[[79.98,9.81],[80.71,9.37],[81.83,7.43],[81.77,6.61],[81.38,6.24],[80.73,5.98],[80.5,5.95],[80.27,6.01],[80.1,6.15],[79.86,6.83],[79.71,8.07],[79.75,8.29],[79.75,8.05],[79.81,8.05],[79.85,8.41],[80.08,9.58],[80.43,9.48],[79.97,9.79]],[[-97.7,76.47],[-97.53,76.11],[-97.89,75.76],[-97.41,75.67],[-97.34,75.42],[-97.88,75.42],[-97.66,75.15],[-98.07,75.2],[-97.99,75.05],[-100.23,75.01],[-100.48,75.19],[-100.14,75.25],[-100.73,75.35],[-99.19,75.7],[-102.8,75.6],[-102.15,75.87],[-100.97,75.8],[-101.87,76.08],[-101.56,76.24],[-102.14,76.28],[-101.79,76.45],[-99.87,75.92],[-99.69,75.96],[-100.11,76.12],[-99.54,76.15],[-100.89,76.48],[-100.07,76.63],[-98.89,76.47],[-99.02,76.61],[-98.71,76.69],[-97.72,76.5]],[[96.53,81.08],[97.86,80.7],[97.11,80.61],[97.42,80.32],[97.17,80.24],[93.87,80.01],[91.53,80.36],[92.83,80.62],[93.26,80.79],[92.61,80.81],[93.36,81.03],[95.16,81.27],[96.47,81.1]],[[-103.43,79.32],[-102.58,78.88],[-101.7,79.08],[-100.01,78.73],[-99.58,78.56],[-99.75,78.3],[-99,78],[-99.96,77.79],[-101.07,78.19],[-104.51,78.29],[-105,78.52],[-103.57,78.54],[-104.02,78.63],[-103.37,78.74],[-104.18,78.78],[-103.88,78.9],[-104.15,78.99],[-104.9,78.81],[-104.75,79.03],[-105.58,79.11],[-105.39,79.32],[-103.71,79.35]],[[102.88,79.25],[102.41,78.84],[103.8,79.15],[105.34,78.59],[104.74,78.34],[99.29,78.04],[100.42,78.75],[100.95,78.79],[101.05,79.12],[101.59,79.35],[103.1,79.3],[102.94,79.27]],[[131.18,33.6],[131.69,33.6],[131.54,33.27],[131.9,33.25],[132.01,32.92],[131.34,31.4],[131.07,31.44],[130.69,31.01],[130.78,31.71],[130.59,31.18],[130.15,31.41],[130.55,32.83],[130.24,33.18],[130.34,32.7],[129.77,32.57],[129.68,33.06],[129.99,32.85],[129.58,33.24],[130.72,33.93],[131.06,33.67]],[[-127.2,50.64],[-125.48,50.32],[-124.83,49.53],[-123.85,49.12],[-123.5,48.58],[-123.41,48.7],[-123.29,48.46],[-123.31,48.41],[-123.45,48.43],[-123.57,48.32],[-125.12,48.76],[-124.81,49.21],[-125.49,48.93],[-125.93,49.4],[-126.52,49.4],[-126.54,49.59],[-126.13,49.67],[-127.12,49.88],[-127.25,50.14],[-127.86,50.13],[-127.91,50.45],[-127.49,50.41],[-127.46,50.58],[-128.35,50.7],[-127.92,50.86],[-127.71,50.82]],[[121.01,22.62],[120.84,21.92],[120.08,23.09],[120.13,23.65],[120.63,24.48],[121.04,25.03],[121.59,25.28],[121.91,25.06],[121.93,24.97],[121.82,24.82],[121.83,24.53],[121.64,24.13],[121.52,23.67],[121.16,22.78]],[[-79.54,73.65],[-77.21,73.5],[-76.09,72.88],[-79.5,72.76],[-80.78,73.33],[-80.86,73.67],[-79.89,73.7]],[[-49.63,-0.23],[-48.39,-0.3],[-48.83,-1.39],[-49.8,-1.79],[-50.51,-1.79],[-50.79,-0.91],[-50.65,-0.27],[-50.25,-0.12]],[[110.89,19.99],[111.01,19.66],[110.02,18.42],[109.52,18.22],[108.7,18.54],[108.67,19.3],[109.26,19.88],[110.65,20.14],[110.81,20.02]],[[151.92,-4.3],[152.41,-4.34],[152.35,-4.82],[151.98,-5.07],[152.08,-5.46],[151.52,-5.55],[150.47,-6.26],[149.65,-6.29],[148.34,-5.67],[148.43,-5.47],[149.83,-5.52],[150.09,-5.01],[150.18,-5.52],[150.74,-5.51],[151.67,-4.88],[151.59,-4.2],[151.87,-4.26]],[[-97.44,69.64],[-95.27,68.83],[-96.6,68.46],[-99.56,69.03],[-98.5,69.31],[-98.55,69.57],[-98.04,69.46],[-98.3,69.67],[-98.08,69.83],[-97.47,69.67]],[[21.61,78.6],[22.04,78.58],[22.3,78.23],[23.45,78.15],[23.12,77.99],[24.9,77.76],[22.8,77.28],[22.43,77.32],[22.69,77.55],[21.05,77.44],[20.87,77.57],[21.65,77.92],[20.23,78.48],[21.45,78.6]],[[15.58,38.22],[15.1,37.46],[15.29,37.06],[15.11,36.69],[14.37,36.97],[14.14,37.1],[13.8,37.14],[12.92,37.57],[12.64,37.59],[12.44,37.82],[12.55,38.05],[12.74,38.18],[12.9,38.03],[13.16,38.19],[13.35,38.18],[13.38,38.13],[13.79,37.98],[14.05,38.04],[14.51,38.05],[14.79,38.17],[15.63,38.27]],[[9.63,40.88],[9.8,40.5],[9.56,39.17],[9.06,39.24],[8.97,38.96],[8.65,38.93],[8.42,39.21],[8.55,39.84],[8.2,40.87],[9.23,41.26],[9.57,40.91]],[[127.3,-8.42],[125.41,-9.28],[124.43,-10.15],[123.61,-10.27],[123.71,-9.62],[125.18,-8.65],[127.26,-8.39]],[[-93.54,75.03],[-93.57,74.67],[-94.54,74.64],[-96.6,75.06],[-95.95,75.44],[-94.88,75.63],[-93.91,75.42],[-93.55,75.05]],[[134.36,34.26],[134.64,34.23],[134.68,33.85],[134.74,33.82],[134.38,33.61],[134.18,33.25],[133.69,33.52],[133.29,33.36],[132.87,32.75],[132.49,32.92],[132.41,33.43],[132.03,33.34],[132.94,34.1],[133.47,33.97],[133.95,34.35],[134.07,34.36],[134.22,34.32]],[[-75.67,68.32],[-75.06,68.14],[-75.13,67.54],[-75.4,67.37],[-76.95,67.25],[-77.31,67.69],[-76.69,68.26],[-75.87,68.34]],[[-96.21,78.53],[-94.92,78.39],[-95.33,78.22],[-94.93,78.08],[-96.99,77.81],[-97.66,78.09],[-96.94,78.15],[-98.05,78.33],[-98.34,78.75],[-96.26,78.55]],[[-52.73,69.94],[-51.9,69.6],[-53.75,69.26],[-54.18,69.4],[-53.66,69.47],[-53.83,69.54],[-54.92,69.71],[-54.79,69.95],[-54.32,69.94],[-54.83,70.13],[-54.37,70.32],[-53.1,70.14]],[[-110.46,78.1],[-109.62,78.06],[-110.86,77.83],[-110.15,77.76],[-110.2,77.53],[-111.95,77.34],[-113.17,77.53],[-113.28,77.81],[-110.73,78.1]],[[146.8,75.37],[150.82,75.16],[150.58,74.92],[149.05,74.77],[146.15,75.2],[146.44,75.56],[146.75,75.43]],[[127.73,0.85],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[128.43,-0.89],[127.69,-0.24],[127.43,1.14],[127.63,1.84],[128.04,2.2],[128.01,1.33],[127.68,0.89]],[[180,71.54],[181.56,71.54],[182.5,71.22],[178.79,70.82],[178.63,71.05],[179.88,71.52]],[[142.19,73.9],[143.34,73.57],[143.49,73.25],[139.69,73.42],[141.08,73.87],[141.93,73.91]],[[-152.9,57.82],[-152.43,57.83],[-152.21,57.58],[-152.94,57.5],[-152.68,57.34],[-153.97,56.77],[-153.79,56.99],[-154.25,57.14],[-154.34,56.92],[-154.71,57.34],[-154.12,57.65],[-153.69,57.3],[-153.84,57.86],[-152.85,57.9]],[[129.75,-2.87],[130.57,-3.13],[130.81,-3.86],[129.84,-3.33],[129.47,-3.45],[128.86,-3.24],[128.52,-3.45],[128.13,-3.16],[127.9,-3.5],[128.2,-2.87],[129.6,-2.81]],[[50.28,80.93],[51.7,80.69],[48.9,80.37],[48.68,80.3],[48.98,80.16],[48.39,80.1],[46.64,80.3],[49.09,80.52],[49.24,80.82],[50.13,80.92]],[[164.2,-20.25],[165.19,-20.77],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.06,-20.14]],[[122.78,-8.61],[121.04,-8.93],[119.81,-8.7],[119.88,-8.42],[120.61,-8.24],[122.32,-8.63],[122.92,-8.1],[122.82,-8.6]],[[125.24,12.53],[125.54,12.19],[125.74,11.05],[125.03,11.34],[125,11.77],[124.44,12.15],[124.29,12.57],[125.15,12.57]],[[-105.29,72.92],[-106.95,73.51],[-105.51,73.77],[-104.59,73.58],[-104.62,73.31],[-105.2,72.95]],[[-133.57,56.34],[-133.2,56.32],[-132.17,55.48],[-132.63,55.47],[-131.98,55.21],[-132.02,54.73],[-133.12,55.33],[-133.03,55.59],[-133.68,55.79],[-133.24,55.92],[-133.74,55.96],[-133.6,56.32]],[[12.57,55.79],[12.54,55.66],[12.32,55.59],[12.22,55.47],[12.39,55.39],[12.41,55.29],[12.09,55.19],[12.05,54.81],[11.86,54.77],[11.74,54.92],[11.66,55.19],[11.29,55.2],[11.17,55.33],[11.19,55.47],[11.12,55.6],[11.01,55.64],[10.98,55.72],[11.32,55.75],[11.48,55.94],[11.63,55.96],[11.69,55.91],[11.69,55.73],[11.82,55.7],[11.94,55.9],[11.87,55.97],[12.22,56.12],[12.58,56.06],[12.61,56.03],[12.53,55.92]],[[34.46,35.59],[33.94,35.29],[34.05,34.99],[33.01,34.57],[32.32,34.95],[32.94,35.39],[34.55,35.66]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.46,70.94]],[[106.04,-1.67],[106.36,-2.46],[106.82,-2.57],[106.67,-3.07],[106,-2.83],[105.79,-2.18],[105.13,-2.04],[105.46,-1.57],[106.03,-1.59]],[[-82,62.96],[-82.12,62.65],[-83.02,62.21],[-83.7,62.16],[-83.91,62.43],[-83.38,62.9],[-82.05,62.97]],[[122.5,11.61],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.4,11.7]],[[-61.11,45.94],[-60.86,45.98],[-61.06,45.7],[-60.74,45.75],[-60.3,46.31],[-59.83,45.96],[-60.67,45.59],[-61.45,45.72],[-61.41,46.17],[-60.49,47.01],[-60.49,46.27],[-60.91,46.04]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.19,9.09]],[[-73.77,-43.35],[-74.39,-43.23],[-74.04,-41.8],[-73.53,-41.9],[-73.42,-42.19],[-73.79,-42.59],[-73.44,-42.94],[-73.74,-43.29]],[[118.24,-8.32],[118.93,-8.3],[119.13,-8.67],[116.79,-9.01],[116.83,-8.53],[117.16,-8.37],[117.97,-8.73],[118.23,-8.59],[117.76,-8.15],[118.2,-8.27]],[[62.17,80.83],[62.08,80.62],[61.05,80.42],[59.29,80.57],[59.72,80.84],[62.1,80.87]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[117.41,8.5]],[[-109.82,78.65],[-109.35,78.37],[-113.29,78.33],[-110.88,78.74],[-109.94,78.68]],[[54.72,81.12],[57.69,80.79],[55.89,80.63],[54.07,80.81],[54.63,81.11]],[[9.48,42.81],[9.56,42.16],[9.19,41.39],[8.81,41.59],[8.57,42.36],[9.32,42.71],[9.36,43.02],[9.48,42.86]],[[50.27,69.19],[48.91,68.74],[48.28,69.04],[48.42,69.35],[48.96,69.51],[50.17,69.26]],[[178.28,-17.37],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.51,-17.54],[178.25,-17.33]],[[-61.8,49.09],[-63.04,49.23],[-64.49,49.89],[-62.86,49.71],[-61.75,49.11]],[[-77.26,18.46],[-76.91,18.39],[-76.7,18.26],[-76.35,18.15],[-76.21,17.91],[-76.52,17.87],[-76.85,17.97],[-76.94,17.85],[-77.12,17.88],[-77.2,17.71],[-77.36,17.83],[-77.77,17.88],[-78.33,18.35],[-77.87,18.52]],[[-44.87,82.08],[-47.35,82.6],[-44.92,82.48],[-44.78,82.24]],[[-158.28,21.58],[-158.12,21.71],[-157.98,21.71],[-157.65,21.31],[-157.71,21.26],[-157.95,21.3],[-158.1,21.3],[-158.23,21.46]],[[-155.87,20.27],[-155.1,19.86],[-154.81,19.51],[-155.62,18.91],[-155.88,19.07],[-156.05,19.73],[-155.83,20]],[[-156.69,20.95],[-156.4,20.92],[-156,20.8],[-156,20.62],[-156.45,20.58],[-156.51,20.78],[-156.69,20.88]],[[-159.79,22.07],[-159.4,22.23],[-159.29,22.1],[-159.38,21.88],[-159.68,21.95]],[[-157.31,21.1],[-156.71,21.16],[-156.75,21.08],[-157.25,21.08]],[[144.62,13.24],[144.66,13.43],[144.79,13.53],[144.95,13.65],[144.88,13.43],[144.76,13.25],[144.7,13.23]],[[134.45,7.35],[134.48,7.28],[134.56,7.42],[134.65,7.7],[134.6,7.73],[134.52,7.55]],[[171,7.04],[171.42,7.03],[171.45,7.14],[171,7.12]],[[159.6,-9.25],[160.2,-9.4],[160.8,-9.85],[160.6,-9.95],[159.95,-9.75],[159.6,-9.5]],[[-149.62,-17.5],[-149.37,-17.53],[-149.18,-17.87],[-149.32,-17.78],[-149.6,-17.8],[-149.62,-17.66]],[[-172.07,-13.8],[-171.44,-13.79],[-171.43,-14.05],[-172,-14.04]],[[-172.78,-13.48],[-172.21,-13.58],[-172.25,-13.8],[-172.7,-13.78]],[[-170.84,-14.29],[-170.56,-14.24],[-170.56,-14.31],[-170.82,-14.36]],[[-175.36,-21.1],[-175.05,-21.13],[-175.08,-21.24],[-175.3,-21.2]],[[146.95,-9.25],[147.45,-9.2],[147.55,-9.55],[147.05,-9.65]],[[166.25,-22.1],[166.65,-22.05],[166.7,-22.4],[166.3,-22.45]],[[178.2,-17.95],[178.6,-17.95],[178.6,-18.25],[178.2,-18.25]],[[-64.89,32.25],[-64.82,32.29],[-64.7,32.36],[-64.64,32.39],[-64.67,32.35],[-64.76,32.28],[-64.85,32.23]],[[-25.86,37.9],[-25.48,37.83],[-25.13,37.83],[-25.15,37.72],[-25.5,37.71],[-25.85,37.76]],[[-27.38,38.78],[-27.05,38.76],[-27.04,38.64],[-27.35,38.66]],[[-28.55,38.55],[-28.05,38.43],[-28.1,38.39],[-28.5,38.46]],[[-28.83,38.64],[-28.6,38.62],[-28.62,38.52],[-28.8,38.53]],[[-16.92,28.37],[-16.65,28.4],[-16.13,28.58],[-16.35,28.37],[-16.5,28.06],[-16.75,28.03],[-16.88,28.2]],[[-15.8,28.15],[-15.4,28.17],[-15.36,27.9],[-15.6,27.74],[-15.82,27.9]],[[-13.85,29.22],[-13.45,29.24],[-13.47,28.88],[-13.85,28.9]],[[-14.2,28.75],[-13.84,28.72],[-13.9,28.25],[-14.5,28.06]],[[-17.92,28.85],[-17.75,28.83],[-17.83,28.46],[-17.96,28.62]],[[-17.35,28.2],[-17.1,28.2],[-17.12,28.02],[-17.32,28.03]],[[-18.15,27.8],[-17.9,27.83],[-17.95,27.65],[-18.12,27.7]],[[-23.76,15.27],[-23.47,15.33],[-23.43,15.02],[-23.52,14.91],[-23.78,15.05]],[[-24.5,15],[-24.3,15],[-24.3,14.82],[-24.5,14.82]],[[-25.08,16.9],[-24.88,16.9],[-24.88,16.78],[-25.05,16.8]],[[-25.35,17.2],[-24.98,17.1],[-25,16.98],[-25.33,17]],[[-22.98,16.84],[-22.88,16.84],[-22.88,16.6],[-22.98,16.6]],[[-22.95,16.2],[-22.7,16.15],[-22.72,15.98],[-22.93,16]],[[-5.79,-15.9],[-5.65,-15.9],[-5.63,-16],[-5.75,-16.03]],[[-65.63,18.28],[-65.6,18.22],[-65.74,18.18],[-65.94,17.97],[-66.2,17.92],[-66.77,18],[-66.93,17.93],[-67.18,17.94],[-67.15,18.2],[-67.27,18.36],[-67.1,18.52],[-66.38,18.49],[-65.62,18.39]],[[-77.48,24.99],[-77.55,25],[-77.56,25.02],[-77.55,25.04],[-77.5,25.06],[-77.34,25.08],[-77.26,25.06],[-77.38,25],[-77.44,25.01],[-77.47,24.99]],[[-61,10.7],[-61.04,10.51],[-60.96,10.33],[-61,10.14],[-61.19,10.07],[-61.93,10.06],[-61.67,10.18],[-61.63,10.25],[-61.51,10.24],[-61.46,10.28],[-61.49,10.63],[-61.67,10.71],[-61.37,10.8],[-60.95,10.85],[-60.91,10.84]],[[-59.43,13.16],[-59.43,13.13],[-59.51,13.06],[-59.62,13.09],[-59.65,13.16],[-59.65,13.32],[-59.59,13.33],[-59.54,13.23]],[[-60.81,14.46],[-61.07,14.47],[-61.11,14.52],[-61,14.57],[-61.16,14.67],[-61.22,14.85],[-60.88,14.78],[-60.94,14.67]],[[-68.78,12.1],[-68.74,12.05],[-68.81,12.04],[-68.98,12.12],[-69.16,12.29],[-69.17,12.39],[-69.07,12.34],[-69,12.22],[-68.84,12.17]],[[55.79,-21.1],[55.85,-21.16],[55.81,-21.34],[55.58,-21.37],[55.35,-21.27],[55.23,-21.03],[55.29,-20.91],[55.41,-20.86],[55.58,-20.87],[55.7,-20.94]],[[57.8,-20.22],[57.78,-20.34],[57.67,-20.48],[57.38,-20.51],[57.31,-20.44],[57.36,-20.41],[57.4,-20.2],[57.6,-19.98],[57.68,-20]],[[55.4,-4.66],[55.37,-4.64],[55.43,-4.56],[55.46,-4.57],[55.46,-4.63],[55.53,-4.68],[55.54,-4.8],[55.46,-4.76],[55.48,-4.71]],[[-130.12,-25.07],[-130.11,-25.06],[-130.1,-25.06],[-130.09,-25.07],[-130.09,-25.08],[-130.1,-25.08],[-130.11,-25.08],[-130.11,-25.07]],[[-166.29,53.73],[-167.85,53.31],[-166.8,53.63],[-167.16,53.83],[-167.02,53.96],[-166.37,54.01],[-166.22,53.91],[-166.58,53.71]],[[73.55,4.24],[73.55,4.23],[73.54,4.18],[73.51,4.16],[73.43,4.18],[73.51,4.19]]]; // Cebu, from the same Natural Earth 1:50m land (the simplified rings had dropped it). COAST_LL.push([[123.37,9.45],[123.33,9.42],[123.32,9.49],[123.33,9.58],[123.4,9.89],[123.39,9.97],[123.51,10.14],[123.59,10.3],[123.71,10.47],[123.73,10.56],[123.83,10.73],[123.93,10.96],[123.92,11.04],[123.95,11.08],[123.96,11.14],[123.97,11.19],[124.04,11.27],[124.06,11.22],[124.04,11.11],[124.04,11.05],[124.05,11.03],[124.05,10.93],[124.03,10.77],[124.05,10.59],[124,10.4],[123.95,10.32],[123.87,10.26],[123.79,10.22],[123.7,10.13],[123.64,10.02],[123.63,9.92],[123.49,9.59]]); const COAST=COAST_LL.map(poly=>poly.map(q=>proj(q[0],q[1]))); diff --git a/src/game/20-world/40-city-coords.js b/src/game/20-world/40-city-coords.js index 4304849..93bffa2 100644 --- a/src/game/20-world/40-city-coords.js +++ b/src/game/20-world/40-city-coords.js @@ -71,6 +71,7 @@ const CITY_LL={ "dur":[31.03,-29.86], "dus":[6.78,51.22], "dut":[-166.53,53.88], + "dvo":[125.6,7.08], "dxb":[55.27,25.2], "dyr":[177.4,64.7], "ebj":[8.52,55.48], diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index dfdb524..990c5dd 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -242,6 +242,7 @@ const CITIES=[ {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')}, // The Philippines beyond Luzon {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',P:100,ix:'GotchaFIX Cebu',dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, + {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',P:80,ix:'GotchaFIX Davao',dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, ]; // 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/20-world/60-cables.js b/src/game/20-world/60-cables.js index 4e01d1e..c3d4e51 100644 --- a/src/game/20-world/60-cables.js +++ b/src/game/20-world/60-cables.js @@ -31,7 +31,7 @@ const CABLES=[ {"id":"cook","name":"Cook Strait Talking","price":1.0,"age":"mid","blurb":tr('cables.down_the_west_coast_and_across'),"pairs":[["akl","chc",[[175.75,-36.25],[178,-37],[179,-38],[178.5,-39.25],[174.25,-43.5]]]]}, {"id":"ring","name":"Lord of the Tasman Rings","price":0.9,"age":"new","blurb":tr('cables.one_ring_to_bind_invercargill_to'),"pairs":[["ivc","syd",[[167.6,-46.9],[160,-42],[153,-35]]],["ivc","mel",[[167.6,-46.9],[156,-43.5],[146.2,-39.4]]],["ivc","akl",[[169,-47.25],[170.5,-47.25],[178.5,-39.25],[179,-38],[178,-37],[175.75,-36.25]]]]}, {"id":"tasman","name":"Tasman Global Excess","price":0.95,"age":"new","blurb":tr('cables.sydney_to_auckland_with_plenty_to'),"pairs":[["akl","syd",[[170,-36],[158,-34.5]]]]}, - {"id":"bifrost","name":"Bi-Frosted","price":0.9,"age":"new","blurb":tr('cables.a_rainbow_bridge_from_singapore_to'),"pairs":[["sin","jkt",[[107,-2]]],["jkt","mnl",[[108.5,1.5]]],["mnl","lax",[[123,15],[140,20],[180,25],[210,30],[235,33.5]]],["mnl","gum",[[123,15],[136,14.5],[144.3,13.6]]],["gum","lax",[[145.5,14.2],[180,22],[210,30],[235,33.5]]],["jkt","gum",[[107.25,-5.25],[113,-5.25],[116,-4.25],[121,2],[139.42,11.57],[143.5,13.5]]],["gum","sea",[[149.93,19.74],[155.17,25.45],[160.51,30.59],[165.55,34.81],[170.63,38.48],[176.24,41.9],[181.86,44.75],[188.04,47.3],[190.71,48.15],[198.76,49.45],[205.61,50.09],[211.8,50.31],[218.01,50.21],[224.91,49.69],[234.5,48.25],[235.75,48.5],[236,48.25],[237.25,48.25]]]]}, + {"id":"bifrost","name":"Bi-Frosted","price":0.9,"age":"new","blurb":tr('cables.a_rainbow_bridge_from_singapore_to'),"pairs":[["sin","jkt",[[107,-2]]],["gum","lax",[[145.5,14.2],[180,22],[210,30],[235,33.5]]],["jkt","gum",[[107.25,-5.25],[113,-5.25],[116,-4.25],[121,2],[139.42,11.57],[143.5,13.5]]],["jkt","dvo",[[107.25,-5.25],[113,-5.25],[116,-4.25],[121,2],[124.5,4.6],[125.5,5.3],[125.75,6.2],[125.7,6.8]]],["dvo","gum",[[125.75,6.4],[126.1,5.6],[127,5.8],[130,8],[139.42,11.57],[143.5,13.5]]],["gum","sea",[[149.93,19.74],[155.17,25.45],[160.51,30.59],[165.55,34.81],[170.63,38.48],[176.24,41.9],[181.86,44.75],[188.04,47.3],[190.71,48.15],[198.76,49.45],[205.61,50.09],[211.8,50.31],[218.01,50.21],[224.91,49.69],[234.5,48.25],[235.75,48.5],[236,48.25],[237.25,48.25]]]]}, {"id":"sjcph","name":"Sushi-Jollibee Cable","price":0.9,"age":"mid","blurb":tr('cables.southeast_asia_to_japan_with_snacks'),"pairs":[["hkg","mnl",[[116,21],[119.5,16],[120.3,14.6]]],["mnl","sin",[[119,12],[115,8],[110,5],[105,2]]],["mnl","tok",[[120,14.25],[119.25,15.25],[119.5,18],[128.03,26.23],[139,34.5]]],["sin","hkg",[[104.75,1.75],[109.75,11.5]]],["hkg","tok",[[116.5,22.25],[127,30],[130.75,30.5],[139,34.5]]]]}, {"id":"farice","name":"Far-Ice-1","price":1.2,"age":"old","blurb":tr('cables.iceland_s_lifeline_to_scotland'),"pairs":[["rek","lon",[[-23,64],[-22.25,63.25],[-20.25,63],[-7,63],[-1.63,57.93],[2,53],[1.75,51.75]]]]}, {"id":"danice","name":"Dance-Ice","price":1.0,"age":"mid","blurb":tr('cables.iceland_to_denmark_choreographed'),"pairs":[["rek","cph",[[-23,64],[-22.25,63.25],[7,57.5],[10.5,57.75],[11,57.5],[10.5,55.25],[12,54.75]]]]}, @@ -97,7 +97,7 @@ const CABLES=[ {"id":"ouzo","name":"Ouzo Express","price":0.9,"age":"new","blurb":tr('cables.athens_to_alexandria_and_up_the'),"pairs":[["ath","cai",[[24,37.5],[25.2,35.5],[28,33],[29.9,31.4]]],["ath","ist",[[24.3,38.5],[25.6,39.9],[26.5,40.3],[28.2,40.8]]]]}, {"id":"tea","name":"Boston Tea Party Line","price":0.9,"age":"mid","blurb":tr('cables.boston_to_dublin_nobody_has_thrown'),"pairs":[["bos","dub",[[-65.25,43],[-26,51],[-8.5,51],[-5.75,52.25],[-5.5,53.25]]]]}, {"id":"clementine","name":"Clementine","price":0.6,"age":"new","df":true,"blurb":tr('cables.a_small_sweet_cable_from_broadstairs'),"pairs":[["lon","oos",[[1.44,51.36],[2.92,51.23]]]]}, - {"id":"seaus","name":"SEA-US Later","price":1.0,"age":"mid","blurb":tr('cables.los_angeles_to_hawaii_guam_and'),"pairs":[["lax","hnl",[[-119,33.5],[-140,27],[-157.6,21.6]]],["hnl","gum",[[-158.3,21.2],[-180,18],[-200,15],[-214.6,13.5]]],["gum","mnl",[[125.76,13.3],[123.5,12.5],[120.75,13.25],[120.5,14.25]]],["gum","ror",[[144.5,13.1],[139,9.5],[134.8,7.5]]]]}, + {"id":"seaus","name":"SEA-US Later","price":1.0,"age":"mid","blurb":tr('cables.los_angeles_to_hawaii_guam_and'),"pairs":[["lax","hnl",[[-119,33.5],[-140,27],[-157.6,21.6]]],["hnl","gum",[[-158.3,21.2],[-180,18],[-200,15],[-214.6,13.5]]],["gum","dvo",[[144,13.7],[135,10.5],[128,6.8],[126.4,5.7],[125.85,6.2],[125.7,6.75]]],["gum","ror",[[144.5,13.1],[139,9.5],[134.8,7.5]]]]}, {"id":"aag","name":"Asia-America Gateaux","price":1.25,"age":"old","blurb":tr('cables.california_to_hong_kong_via_hawaii'),"pairs":[["sjc","hnl",[[-122.8,35],[-140,27.5],[-158.2,21.4]]],["hnl","gum",[[-158.4,21.5],[-180,19],[-200,16],[-214.4,13.7]]],["gum","hkg",[[144.5,14],[130,17.5],[121,20],[115,21.6],[114.3,22.2]]]]}, {"id":"echo","name":"Echo-Chamber","price":0.85,"age":"new","blurb":tr('cables.california_to_singapore_via_guam'),"pairs":[["sjc","gum",[[-125,38],[-150,30],[-180,21],[-214.8,14]]],["gum","sin",[[137.45,12.58],[125,10.25],[123.75,9],[122,9],[108,5],[104.25,1.25]]]]}, {"id":"hantru","name":"HANTRU-ly Yours","price":1.3,"age":"mid","blurb":tr('cables.guam_to_the_marshall_islands_with'),"pairs":[["gum","maj",[[145,13.3],[158,7],[167,8.5],[171.2,7.2]]]]}, @@ -161,8 +161,9 @@ const CABLES=[ {"id":"tw1","name":"TW1-light","price":1.1,"age":"mid","blurb":tr('cables.the_emirates_oman_and_pakistan_on'),"pairs":[["fuj","mct",[[58.25,24.25]]],["mct","khi",[[58.75,24]]]]}, {"id":"mct1","name":"MCT (Malaysia, Cambodia, Tuk-tuks)","price":0.95,"age":"new","blurb":tr('cables.malaysia_to_thailand_round_the_gulf'),"pairs":[["kul","bkk",[[101.75,2.5],[102.5,1.5],[103.5,0.75],[103.75,0.75],[104.75,1.75],[104.75,2.75],[100.5,12.75]]]]}, {"id":"kjcn","name":"KJCN (Kimchi-Japan Cable Network)","price":1,"age":"mid","blurb":tr('cables.busan_to_kyushu_the_shortest_way'),"pairs":[["icn","fuk",[[126,36.75],[126,34],[130,34]]]]}, - {"id":"pdscn","name":"Pan de Sal Cable Network","price":0.9,"age":"new","blurb":tr('cables.the_philippines_longest_domestic_cable_fresh'),"pairs":[["mnl","ceb",[[120.6,14.4],[120.45,13.95],[120.85,13.6],[121.9,12.9],[122.7,12.3],[123.6,11.6],[124.2,11.2],[124.15,10.5]]]]}, - {"id":"dfon","name":"Philippines Long Distance Relationship","price":1.1,"age":"mid","blurb":tr('cables.the_incumbent_s_own_line_south'),"pairs":[["mnl","ceb",[[121.6,13.85],[122.1,13.2],[122.9,12.45],[123.75,11.7],[124.3,11.1],[124.2,10.45]]]]}, + {"id":"pdscn","name":"Pan de Sal Cable Network","price":0.9,"age":"new","blurb":tr('cables.the_philippines_longest_domestic_cable_fresh'),"pairs":[["mnl","ceb",[[120.6,14.4],[120.45,13.95],[120.85,13.6],[121.9,12.9],[122.7,12.3],[123.6,11.6],[124.2,11.2],[124.15,10.5]]],["ceb","dvo",[[124.05,10.2],[124.1,9.6],[124.5,8.9],[124.62,8.55]]]]}, + {"id":"dfon","name":"Philippines Long Distance Relationship","price":1.1,"age":"mid","blurb":tr('cables.the_incumbent_s_own_line_south'),"pairs":[["mnl","ceb",[[121.6,13.85],[122.1,13.2],[122.9,12.45],[123.75,11.7],[124.3,11.1],[124.2,10.45]]],["ceb","dvo",[[123.95,10.05],[124.4,9.5],[124.75,9.05]]]]}, + {"id":"vismin","name":"Diverge VisMin Express","price":0.9,"age":"new","blurb":tr('cables.the_upstart_s_own_cable_from'),"pairs":[["ceb","dvo",[[124.15,10.9],[124.25,10.2],[124.4,9.3],[124.65,8.6]]]]}, ]; const CAB=Object.fromEntries(CABLES.map(c=>[c.id,c])); const CABLE_PAIRS=CABLES.flatMap(c=>c.pairs.map(([a,b,mid])=>{const A=CITY[a],B=CITY[b];const near=(x,ref)=>x+W*Math.round((ref-x)/W); diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index 4106893..ffc612b 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -37,9 +37,9 @@ 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:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#D62027',pops:['mnl','ceb','hkg','sin'],ix:['hkg','mnl~3'],blurb:tr('networks.philippine_giant_peering_requests')}, - {id:'glb',name:'Snow Globe',asn:4775,type:'t2',pol:'open',share:.007,price:6,col:'#1A3D8F',pops:['mnl','ceb','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.shake_it_and_coverage_falls_gently')}, - {id:'cvg',name:'Diverge',asn:17639,type:'eye',pol:'open',share:.005,col:'#F26B21',pops:['mnl','ceb','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, + {id:'pld',name:'PLDTea Time',asn:9299,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#D62027',pops:['mnl','ceb','dvo','hkg','sin'],ix:['hkg','mnl~3'],blurb:tr('networks.philippine_giant_peering_requests')}, + {id:'glb',name:'Snow Globe',asn:4775,type:'t2',pol:'open',share:.007,price:6,col:'#1A3D8F',pops:['mnl','ceb','dvo','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.shake_it_and_coverage_falls_gently')}, + {id:'cvg',name:'Diverge',asn:17639,type:'eye',pol:'open',share:.005,col:'#F26B21',pops:['mnl','ceb','dvo','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, {id:'smt',name:'Smarty Pants',asn:10139,type:'eye',pol:'selective',up:['pld'],minIx:10,minPni:30,share:.006,col:'#00A859',pops:['mnl'],ix:[],blurb:tr('networks.pldtea_time_s_mobile_sibling_buy')}, {id:'dto',name:'Ditto',asn:139831,type:'eye',pol:'open',share:.002,col:'#B5121B',pops:['mnl'],ix:['mnl','mnl~2'],blurb:tr('networks.the_third_mobile_network_same_towers')}, {id:'rsh',name:'RISE & Shine',asn:63927,type:'eye',pol:'open',share:.002,col:'#F5A623',pops:['mnl','sin','hkg','tok','fra','ams','lon','sto','lax'],ix:['mnl','mnl~2','mnl~3','sin','sin~2','hkg','hkg~2','tok','fra','ams','lon','sto','lax'],blurb:tr('networks.up_early_in_cebu_and_already')}, diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 8961762..011f0e9 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -14,7 +14,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.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;}); + 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)||!cablePair(l.cable,l.a,l.b)))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); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */ diff --git a/src/i18n/en.js b/src/i18n/en.js index edffb87..69a0a60 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -274,7 +274,7 @@ "cables.a_friendly_cable_with_french_manners":"A friendly cable with French manners.", "cables.a_gateway_from_europe_to_india":"A gateway from Europe to India, through the Red Sea. Pronounced like a very surprised cable.", "cables.a_quick_hop_across_the_red":"A quick hop across the Red Sea between Egypt and Saudi Arabia.", -"cables.a_rainbow_bridge_from_singapore_to":"A rainbow bridge from Singapore to California, via Jakarta and Manila.", +"cables.a_rainbow_bridge_from_singapore_to":"A rainbow bridge from Singapore to California, via Jakarta, Davao and Guam.", "cables.a_ring_around_the_caribbean_from":"A ring around the Caribbean from Florida to Central America, older than most of its customers.", "cables.a_ring_round_east_asia_from":"A ring round East Asia from 2001: Singapore, Hong Kong, Manila, Taipei, Shanghai, Seoul and Tokyo.", "cables.a_short_cable_across_a_very":"A short cable across a very tense strait.", @@ -430,6 +430,7 @@ "cables.the_sequel_singapore_to_hong_kong":"The sequel: Singapore to Hong Kong, Taiwan, Japan and Korea, lit in 2025.", "cables.the_seychelles_first_cable_to_tanzania":"The Seychelles’ first cable, to Tanzania, after years on satellite.", "cables.the_straightest_line_across_the":"The straightest line across the Atlantic. Traders pay double to save a few milliseconds.", +"cables.the_upstart_s_own_cable_from":"The upstart's own cable from Cebu to Mindanao's north coast, then overland to Davao. Laid in a pandemic.", "cables.tokyo_to_los_angeles_built_by":"Tokyo to Los Angeles, built by a search engine and five telcos holding hands.", "cables.up_the_west_coast_of_africa":"Up the west coast of Africa. Something on it is always down.", "cables.west_africa_s_first_big_cable":"West Africa’s first big cable, from Portugal to Cape Town. Old and wobbly, but still holding things up.", @@ -562,6 +563,7 @@ "cities.mexico_s_data_center_boom_town":"Mexico’s data center boom town, high and dry in the middle of the country. Every cloud wants a region here.", "cities.mexico_s_industrial_capital_a_few":"Mexico’s industrial capital, a few hours from Texas. Factories, steel and grilled goat on weekends.", "cities.mexico_s_silicon_valley_home_of":"Mexico’s Silicon Valley, home of mariachi and tequila. Chip design by day, music by night.", +"cities.mindanao_s_big_city_and_the":"Mindanao's big city and the Philippines' Pacific door: the trans-Pacific cables land here, south of the typhoon belt.", "cities.morocco_s_business_capital_on_the":"Morocco’s business capital on the Atlantic, the gateway between Europe and West Africa.", "cities.most_uae_cables_land_on_this":"Most UAE cables land on this coast, outside the Strait of Hormuz. Getting from here to Dubai means renting from the duopoly.", "cities.mountains_mines_and_more_bars_per":"Mountains, mines and more bars per head than anywhere else in Brazil. Peering deals get signed over cheese bread.", diff --git a/tests/philippines.test.js b/tests/philippines.test.js index 50fea8d..d311262 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -84,3 +84,42 @@ test('Cebu: its own island, GotchaFIX Cebu, reached by two domestic cables, in t ev('cam.z=5;cam.x=CITY.ceb.x;cam.y=CITY.ceb.y;draw(0)'); assert.deepEqual(errors, []); }); + +test('Davao: Mindanao, GotchaFIX Davao, the trans-Pacific landings moved from Manila, and cables from Cebu', () => { + const { ev, errors } = load(); + start(ev); + assert.ok(ev("isSub('dvo','mnl')&&isSub('dvo','ceb')"), 'Davao is on Mindanao'); + assert.ok(ev('onLand(CITY.dvo.x,CITY.dvo.y)'), 'Davao is drawn on land'); + assert.equal(ev('CITY.dvo.ix'), 'GotchaFIX Davao'); + assert.equal(ev('CITY.dvo.dc'), "Heimdall's Hut"); + // Bi-Frosted's Philippine branch and SEA-US land at Davao, not Manila + const at = (cid, c) => ids(ev, `CABLE_PAIRS.filter(p=>p.cid==='${cid}'&&(p.a==='${c}'||p.b==='${c}')).map(p=>p.a==='${c}'?p.b:p.a)`).sort(); + assert.deepEqual(at('bifrost', 'mnl'), []); + assert.deepEqual(at('bifrost', 'dvo'), ['gum', 'jkt']); + assert.deepEqual(at('seaus', 'mnl'), []); + assert.deepEqual(at('seaus', 'dvo'), ['gum']); + assert.ok(ev("cablesFor('jkt','gum').some(p=>p.cid==='bifrost')&&cablesFor('gum','lax').some(p=>p.cid==='bifrost')"), 'the trunk stays'); + assert.deepEqual(ids(ev, "cablesFor('ceb','dvo').map(p=>p.cid)").sort(), ['dfon', 'pdscn', 'vismin']); + for (const n of ['pld', 'glb']) assert.ok(ev(`sellsAt(NET.${n},'dvo')`), `${n} sells transit in Davao`); + assert.ok(ev("NET.cvg.pops.includes('dvo')")); + ev('cam.z=5;cam.x=CITY.dvo.x;cam.y=CITY.dvo.y;draw(0)'); + assert.deepEqual(errors, []); +}); + +test('Davao: a saved link on a Bi-Frosted or SEA-US pair that moved keeps working, without the cable', () => { + const { ev, errors } = load(); + start(ev); + for (const c of ['mnl', 'jkt', 'hkg']) ev(`ACT.buildPop({city:'${c}'});S.pops.${c}.rgen=3`); + ev("UI.via='sjcph';UI.route='same';openLinkModal('mnl','hkg');ACT.buildLink({tier:2});closeModal()"); + ev("UI.via='sjcph';UI.route='same';openLinkModal('mnl','hkg');ACT.buildLink({tier:2});closeModal()"); + assert.equal(ev('S.links.length'), 2); + // as an old save had them: Bi-Frosted Jakarta–Manila and an untouched Manila–Hong Kong link + ev("const l=S.links[0];l.a='jkt';l.b='mnl';l.km=kmBetween('jkt','mnl');l.cable='bifrost'"); + ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); + assert.equal(ev('__o.links.length'), 2, 'the link survives'); + assert.equal(ev("__o.links.find(l=>l.a==='jkt').cable"), null, 'its cable tag is dropped'); + assert.equal(ev("__o.links.find(l=>l.b==='hkg').cable"), 'sjcph', 'a pair that still exists keeps its cable'); + ev('S=__o;after();compute()'); + ev('cam.z=1;draw(0)'); + assert.deepEqual(errors, []); +}); From 2b6a28203ad309d179a4abf9f781c00f94254b2f Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Thu, 29 Oct 2026 23:00:29 +1100 Subject: [PATCH 146/491] Pan de Sal Cable Network runs straight from Manila to Davao MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PDSCN's Luzon–Mindanao segment (lit February 2024) runs from Lucena through the Visayas to Cagayan de Oro, so the cable gets a Manila–Davao pair alongside its Cebu landings: overland to Lucena, subsea to Mindanao's north coast, overland to Davao. --- CHANGELOG.md | 2 +- site/i18n/es.js | 2 +- site/i18n/fr.js | 2 +- site/i18n/it.js | 2 +- site/i18n/pt.js | 2 +- src/game/20-world/60-cables.js | 2 +- src/i18n/en.js | 2 +- tests/philippines.test.js | 2 ++ 8 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6838fd8..12fe0d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to this project are documented here. The project follows - Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. - Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe and Diverge reach Cebu, and typhoons can hit it too. -- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. +- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. The Pan de Sal Cable Network also runs straight from Manila to Davao. ## [1.37.0] — 2026-10-28 diff --git a/site/i18n/es.js b/site/i18n/es.js index b3f3601..95fc96a 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -422,7 +422,7 @@ "cables.the_incumbent_s_own_line_south":"La línea propia del operador histórico hacia el sur: por tierra hasta Lucena y luego bajo el mar hasta Cebú. Sigue llamando cada noche.", "cables.the_newest_cable_from_south_africa":"El cable más nuevo de Sudáfrica a Madagascar, Reunión y Mauricio, compartido por las telcos de las propias islas.", "cables.the_old_workhorse_s_younger_sibling":"El hermano menor del viejo caballo de batalla: de Los Ángeles a Sídney con una rama a Fiyi.", -"cables.the_philippines_longest_domestic_cable_fresh":"El cable nacional más largo de Filipinas, recién hecho cada mañana. De Luzón a Cebú, isla a isla.", +"cables.the_philippines_longest_domestic_cable_fresh":"El cable nacional más largo de Filipinas, recién hecho cada mañana. De Luzón a Cebú y Mindanao, isla a isla.", "cables.the_pretty_way_around_east_asia":"El camino bonito alrededor de Asia Oriental.", "cables.the_previous_generation_still":"La generación anterior. Aún lleva la mayor parte de Pakistán, Sri Lanka y Bangladés, sostenida con esperanza.", "cables.the_sea_stallion_blackpool_to":"El Semental del Mar: de Blackpool a Dinamarca, galopando por el norte de Escocia.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index e0e6049..0d0c58c 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -422,7 +422,7 @@ "cables.the_incumbent_s_own_line_south":"La ligne de l'opérateur historique vers le sud : par la terre jusqu'à Lucena, puis sous la mer jusqu'à Cebu. Appelle encore tous les soirs.", "cables.the_newest_cable_from_south_africa":"Le câble le plus récent d’Afrique du Sud vers Madagascar, La Réunion et Maurice, partagé par les opérateurs des îles elles-mêmes.", "cables.the_old_workhorse_s_younger_sibling":"Le petit frère du vieux cheval de labour : de Los Angeles à Sydney, avec une dérivation vers les Fidji.", -"cables.the_philippines_longest_domestic_cable_fresh":"Le plus long câble national des Philippines, frais chaque matin. De Luçon à Cebu, île après île.", +"cables.the_philippines_longest_domestic_cable_fresh":"Le plus long câble national des Philippines, frais chaque matin. De Luçon à Cebu et Mindanao, île après île.", "cables.the_pretty_way_around_east_asia":"La route panoramique de l’Asie de l’Est.", "cables.the_previous_generation_still":"La génération précédente. Transporte encore l’essentiel du trafic du Pakistan, du Sri Lanka et du Bangladesh, le tout tenu par l’espoir.", "cables.the_sea_stallion_blackpool_to":"L’Étalon des mers : de Blackpool au Danemark, au galop autour du nord de l’Écosse.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 1c1a9ce..7d61b74 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -422,7 +422,7 @@ "cables.the_incumbent_s_own_line_south":"La linea dell'operatore storico verso sud: via terra fino a Lucena, poi sotto il mare fino a Cebu. Chiama ancora ogni sera.", "cables.the_newest_cable_from_south_africa":"Il cavo più recente dal Sudafrica a Madagascar, Riunione e Mauritius, condiviso dalle telco delle isole.", "cables.the_old_workhorse_s_younger_sibling":"Il fratellino del vecchio cavallo da tiro: da Los Angeles a Sydney con una diramazione per le Figi.", -"cables.the_philippines_longest_domestic_cable_fresh":"Il cavo nazionale più lungo delle Filippine, fresco ogni mattina. Da Luzon a Cebu, isola dopo isola.", +"cables.the_philippines_longest_domestic_cable_fresh":"Il cavo nazionale più lungo delle Filippine, fresco ogni mattina. Da Luzon a Cebu e Mindanao, isola dopo isola.", "cables.the_pretty_way_around_east_asia":"Il giro panoramico dell’Asia orientale.", "cables.the_previous_generation_still":"La generazione precedente. Porta ancora quasi tutto il traffico di Pakistan, Sri Lanka e Bangladesh, tenuto insieme dalla speranza.", "cables.the_sea_stallion_blackpool_to":"Lo Stallone del Mare: da Blackpool alla Danimarca, al galoppo attorno al nord della Scozia.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a54447d..a250562 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -422,7 +422,7 @@ "cables.the_incumbent_s_own_line_south":"A linha própria da operadora histórica rumo ao sul: por terra até Lucena, depois sob o mar até Cebu. Ainda liga toda noite.", "cables.the_newest_cable_from_south_africa":"O cabo mais novo da África do Sul para Madagascar, Reunião e Maurício, compartilhado pelas operadoras das próprias ilhas.", "cables.the_old_workhorse_s_younger_sibling":"O irmão mais novo do velho burro de carga: de Los Angeles a Sydney com um ramal para Fiji.", -"cables.the_philippines_longest_domestic_cable_fresh":"O cabo nacional mais longo das Filipinas, fresquinho toda manhã. De Luzon a Cebu, ilha por ilha.", +"cables.the_philippines_longest_domestic_cable_fresh":"O cabo nacional mais longo das Filipinas, fresquinho toda manhã. De Luzon a Cebu e Mindanao, ilha por ilha.", "cables.the_pretty_way_around_east_asia":"O caminho bonito pela Ásia Oriental.", "cables.the_previous_generation_still":"A geração anterior. Ainda leva quase tudo de Paquistão, Sri Lanka e Bangladesh, na base da esperança.", "cables.the_sea_stallion_blackpool_to":"O Sea Stallion: de Blackpool à Dinamarca, galopando pelo norte da Escócia.", diff --git a/src/game/20-world/60-cables.js b/src/game/20-world/60-cables.js index c3d4e51..294fa31 100644 --- a/src/game/20-world/60-cables.js +++ b/src/game/20-world/60-cables.js @@ -161,7 +161,7 @@ const CABLES=[ {"id":"tw1","name":"TW1-light","price":1.1,"age":"mid","blurb":tr('cables.the_emirates_oman_and_pakistan_on'),"pairs":[["fuj","mct",[[58.25,24.25]]],["mct","khi",[[58.75,24]]]]}, {"id":"mct1","name":"MCT (Malaysia, Cambodia, Tuk-tuks)","price":0.95,"age":"new","blurb":tr('cables.malaysia_to_thailand_round_the_gulf'),"pairs":[["kul","bkk",[[101.75,2.5],[102.5,1.5],[103.5,0.75],[103.75,0.75],[104.75,1.75],[104.75,2.75],[100.5,12.75]]]]}, {"id":"kjcn","name":"KJCN (Kimchi-Japan Cable Network)","price":1,"age":"mid","blurb":tr('cables.busan_to_kyushu_the_shortest_way'),"pairs":[["icn","fuk",[[126,36.75],[126,34],[130,34]]]]}, - {"id":"pdscn","name":"Pan de Sal Cable Network","price":0.9,"age":"new","blurb":tr('cables.the_philippines_longest_domestic_cable_fresh'),"pairs":[["mnl","ceb",[[120.6,14.4],[120.45,13.95],[120.85,13.6],[121.9,12.9],[122.7,12.3],[123.6,11.6],[124.2,11.2],[124.15,10.5]]],["ceb","dvo",[[124.05,10.2],[124.1,9.6],[124.5,8.9],[124.62,8.55]]]]}, + {"id":"pdscn","name":"Pan de Sal Cable Network","price":0.9,"age":"new","blurb":tr('cables.the_philippines_longest_domestic_cable_fresh'),"pairs":[["mnl","ceb",[[120.6,14.4],[120.45,13.95],[120.85,13.6],[121.9,12.9],[122.7,12.3],[123.6,11.6],[124.2,11.2],[124.15,10.5]]],["ceb","dvo",[[124.05,10.2],[124.1,9.6],[124.5,8.9],[124.62,8.55]]],["mnl","dvo",[[121.6,13.85],[122.1,13.2],[122.9,12.45],[123.75,11.7],[124.3,11.1],[124.25,10.3],[124.1,9.6],[124.5,8.9],[124.62,8.55]]]]}, {"id":"dfon","name":"Philippines Long Distance Relationship","price":1.1,"age":"mid","blurb":tr('cables.the_incumbent_s_own_line_south'),"pairs":[["mnl","ceb",[[121.6,13.85],[122.1,13.2],[122.9,12.45],[123.75,11.7],[124.3,11.1],[124.2,10.45]]],["ceb","dvo",[[123.95,10.05],[124.4,9.5],[124.75,9.05]]]]}, {"id":"vismin","name":"Diverge VisMin Express","price":0.9,"age":"new","blurb":tr('cables.the_upstart_s_own_cable_from'),"pairs":[["ceb","dvo",[[124.15,10.9],[124.25,10.2],[124.4,9.3],[124.65,8.6]]]]}, ]; diff --git a/src/i18n/en.js b/src/i18n/en.js index 69a0a60..fcf4ec3 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -423,7 +423,7 @@ "cables.the_incumbent_s_own_line_south":"The incumbent's own line south: overland to Lucena, then under the sea to Cebu. Still calls every night.", "cables.the_newest_cable_from_south_africa":"The newest cable from South Africa to Madagascar, Réunion and Mauritius, shared by the islands’ own telcos.", "cables.the_old_workhorse_s_younger_sibling":"The old workhorse’s younger sibling: Los Angeles to Sydney with a branch to Fiji.", -"cables.the_philippines_longest_domestic_cable_fresh":"The Philippines' longest domestic cable, fresh every morning. Luzon to Cebu, island by island.", +"cables.the_philippines_longest_domestic_cable_fresh":"The Philippines' longest domestic cable, fresh every morning. Luzon to Cebu and Mindanao, island by island.", "cables.the_pretty_way_around_east_asia":"The pretty way around East Asia.", "cables.the_previous_generation_still":"The previous generation. Still carries most of Pakistan, Sri Lanka and Bangladesh, held together with hope.", "cables.the_sea_stallion_blackpool_to":"The Sea Stallion: Blackpool to Denmark, galloping round the north of Scotland.", diff --git a/tests/philippines.test.js b/tests/philippines.test.js index d311262..436fd2a 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -100,6 +100,8 @@ test('Davao: Mindanao, GotchaFIX Davao, the trans-Pacific landings moved from Ma assert.deepEqual(at('seaus', 'dvo'), ['gum']); assert.ok(ev("cablesFor('jkt','gum').some(p=>p.cid==='bifrost')&&cablesFor('gum','lax').some(p=>p.cid==='bifrost')"), 'the trunk stays'); assert.deepEqual(ids(ev, "cablesFor('ceb','dvo').map(p=>p.cid)").sort(), ['dfon', 'pdscn', 'vismin']); + // PDSCN's Luzon–Mindanao segment runs the whole way, so Manila reaches Davao in one hop + assert.deepEqual(ids(ev, "cablesFor('mnl','dvo').map(p=>p.cid)"), ['pdscn']); for (const n of ['pld', 'glb']) assert.ok(ev(`sellsAt(NET.${n},'dvo')`), `${n} sells transit in Davao`); assert.ok(ev("NET.cvg.pops.includes('dvo')")); ev('cam.z=5;cam.x=CITY.dvo.x;cam.y=CITY.dvo.y;draw(0)'); From 55a62d32b2a0efb5f36bb0716c802005bcf5721c Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Fri, 30 Oct 2026 16:24:24 +1100 Subject: [PATCH 147/491] RISE & Shine at GotchaFIX Cebu and GotchaFIX Davao RISE.ph (AS63927) peers at GetaFIX Cebu and GetaFIX Davao in PeeringDB, so RISE & Shine gets PoPs in Cebu and Davao and joins both GotchaFIX exchanges. --- CHANGELOG.md | 4 ++-- src/game/30-networks/10-networks.js | 2 +- tests/philippines.test.js | 7 +++++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12fe0d3..dc7794e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. -- Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe and Diverge reach Cebu, and typhoons can hit it too. -- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. The Pan de Sal Cable Network also runs straight from Manila to Davao. +- Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too. +- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. ## [1.37.0] — 2026-10-28 diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index ffc612b..40dcede 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -42,7 +42,7 @@ NETS.push( {id:'cvg',name:'Diverge',asn:17639,type:'eye',pol:'open',share:.005,col:'#F26B21',pops:['mnl','ceb','dvo','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, {id:'smt',name:'Smarty Pants',asn:10139,type:'eye',pol:'selective',up:['pld'],minIx:10,minPni:30,share:.006,col:'#00A859',pops:['mnl'],ix:[],blurb:tr('networks.pldtea_time_s_mobile_sibling_buy')}, {id:'dto',name:'Ditto',asn:139831,type:'eye',pol:'open',share:.002,col:'#B5121B',pops:['mnl'],ix:['mnl','mnl~2'],blurb:tr('networks.the_third_mobile_network_same_towers')}, - {id:'rsh',name:'RISE & Shine',asn:63927,type:'eye',pol:'open',share:.002,col:'#F5A623',pops:['mnl','sin','hkg','tok','fra','ams','lon','sto','lax'],ix:['mnl','mnl~2','mnl~3','sin','sin~2','hkg','hkg~2','tok','fra','ams','lon','sto','lax'],blurb:tr('networks.up_early_in_cebu_and_already')}, + {id:'rsh',name:'RISE & Shine',asn:63927,type:'eye',pol:'open',share:.002,col:'#F5A623',pops:['mnl','ceb','dvo','sin','hkg','tok','fra','ams','lon','sto','lax'],ix:['mnl','mnl~2','mnl~3','ceb','dvo','sin','sin~2','hkg','hkg~2','tok','fra','ams','lon','sto','lax'],blurb:tr('networks.up_early_in_cebu_and_already')}, {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( diff --git a/tests/philippines.test.js b/tests/philippines.test.js index 436fd2a..4ae568a 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -125,3 +125,10 @@ test('Davao: a saved link on a Bi-Frosted or SEA-US pair that moved keeps workin ev('cam.z=1;draw(0)'); assert.deepEqual(errors, []); }); + +test('Cebu and Davao: RISE & Shine is on GotchaFIX Cebu and GotchaFIX Davao', () => { + const { ev, errors } = load(); + start(ev); + for (const c of ['ceb', 'dvo']) assert.ok(ids(ev, `ixMembers('${c}')`).includes('rsh'), `RISE & Shine on ${c}`); + assert.deepEqual(errors, []); +}); From 870a2eba9598cff0f0006801fff932b158a4294a Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Thu, 29 Oct 2026 23:08:25 +1100 Subject: [PATCH 148/491] Philippine pricing: transit 1.9 times the Asian rate, broadband ARPU 0.7 Manila's 100 GigE transit is $2.25 per Mbps against Jakarta's $1.21 (TeleGeography, 2026), so Manila, Cebu and Davao get PH_TRANSIT 4.7, about 1.9 times the 2.5 every other Asian city pays. PLDT Home's full-year 2025 ARPU was PHP 1,447 a month (about US$25), so Philippine homes pay 0.7 of the base broadband rate. --- CHANGELOG.md | 1 + src/game/10-catalog/10-economy.js | 4 ++++ src/game/20-world/50-cities.js | 6 +++--- .../80-simulation/80-geography-and-latency.js | 2 +- tests/philippines.test.js | 16 ++++++++++++++++ 5 files changed, 25 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc7794e..36703b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project are documented here. The project follows - Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. - Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too. - Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. +- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. ## [1.37.0] — 2026-10-28 diff --git a/src/game/10-catalog/10-economy.js b/src/game/10-catalog/10-economy.js index eb90c86..45d2e52 100644 --- a/src/game/10-catalog/10-economy.js +++ b/src/game/10-catalog/10-economy.js @@ -14,6 +14,10 @@ const AU_TRANSIT=3,AU_WAVE={land:1.8,sub:2.6,ew:1.3},AU_IX=0.8,AU_ARPU=1.8,AU_WH // Fibre to the Basement: on your own fibre you skip the wholesale cut, but competing networks pay the // Regional Broadband Scheme levy instead (about $7 a month on a ~$90 bill). const AU_LEVY=0.08; +/* The Philippines: few, thin routes out and an incumbent that owns most of them. 100 GigE transit in Manila + costs about 1.9 times Jakarta's (TeleGeography, 2026: $2.25 against $1.21 per Mbps), so the islands pay + 1.9 times the Asian rate. Homes pay about ₱1,450 (US$25) a month, the incumbent's own figure (PLDT, 2025). */ +const PH_TRANSIT=4.7,PH_ARPU=0.7; const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000; const SITE2_N=[tr('economy.the_other_building'),tr('economy.campus_b_the_one_with_parking'),tr('economy.across_the_river_dc'),tr('common.the_annex'),tr('economy.suburban_mega_shed'),tr('economy.the_cheaper_one'),tr('economy.formerly_a_shopping_mall'),tr('common.bunker_two')]; // A city's buildings: '#' becomes a site number from 1 to dcN (dc2N for the second building) that stays put for this network. diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index 990c5dd..91d929b 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -35,7 +35,7 @@ const CITIES=[ {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:'GotchaFIX Manila',dc:'Typhoon-rated DC',note:tr('cities.typhoons_earthquakes_and_a_lot_of')}, + {id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',ph:true,arpu:PH_ARPU,P:600,ix:'GotchaFIX Manila',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')}, @@ -241,8 +241,8 @@ const CITIES=[ {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')}, // The Philippines beyond Luzon - {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',P:100,ix:'GotchaFIX Cebu',dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, - {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',P:80,ix:'GotchaFIX Davao',dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, + {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',ph:true,arpu:PH_ARPU,P:100,ix:'GotchaFIX Cebu',dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, + {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',ph:true,arpu:PH_ARPU,P:80,ix:'GotchaFIX Davao',dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, ]; // 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 c928d65..d4b1d80 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -1,5 +1,5 @@ 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.au)return AU_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;} +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.ph)return PH_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;} // A network's own markup on top of that, where it is far from home (Glowball Sakura Lager in Asia and New Zealand). 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; diff --git a/tests/philippines.test.js b/tests/philippines.test.js index 4ae568a..ae545f3 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -132,3 +132,19 @@ test('Cebu and Davao: RISE & Shine is on GotchaFIX Cebu and GotchaFIX Davao', () for (const c of ['ceb', 'dvo']) assert.ok(ids(ev, `ixMembers('${c}')`).includes('rsh'), `RISE & Shine on ${c}`); assert.deepEqual(errors, []); }); + +test('the Philippines: transit about 1.9 times the Asian rate, homes pay about US$25 a month', () => { + const { ev, errors } = load(); + start(ev); + for (const c of ['mnl', 'ceb', 'dvo']) { + assert.equal(ev(`regionMult('${c}')`), ev('PH_TRANSIT'), `${c} pays the Philippine transit rate`); + assert.equal(ev(`CITY.${c}.arpu`), ev('PH_ARPU')); + } + // Manila's 100 GigE transit is about 1.9 times Jakarta's + assert.ok(Math.abs(ev("regionMult('mnl')/regionMult('jkt')") - 1.9) < 0.1); + assert.equal(ev("regionMult('sin')"), 2.5, 'the rest of Asia is unchanged'); + // the same transit port costs more in Manila than in Jakarta + ev("ACT.buildPop({city:'mnl'});ACT.buildPop({city:'jkt'})"); + assert.ok(ev("transitMo({net:'sgt',city:'mnl',tier:1},10)>transitMo({net:'sgt',city:'jkt',tier:1},10)")); + assert.deepEqual(errors, []); +}); From cb7d5912d2b7d33dee3767126ebccf0a5dae78dc Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Thu, 29 Oct 2026 23:15:05 +1100 Subject: [PATCH 149/491] GotchaFIX ports at GetaFIX's real prices GetaFIX charges $700 a month for 10G and $2,800 for 100G. One multiplier cannot hit both, so GotchaFIX Manila, Cebu and Davao get ixCheap 1.8: $720 and $2,700, within 4% of each. In-Vitro-IX goes to 2.2 so the incumbent's exchange stays the dearest in Manila. --- CHANGELOG.md | 2 +- src/game/20-world/50-cities.js | 6 +++--- src/game/30-networks/20-rival-exchanges.js | 2 +- tests/philippines.test.js | 6 ++++++ 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36703b1..106b0aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ All notable changes to this project are documented here. The project follows - Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. - Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too. - Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. -- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. +- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. ## [1.37.0] — 2026-10-28 diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index 91d929b..40c5742 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -35,7 +35,7 @@ const CITIES=[ {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',ph:true,arpu:PH_ARPU,P:600,ix:'GotchaFIX Manila',dc:'Typhoon-rated DC',note:tr('cities.typhoons_earthquakes_and_a_lot_of')}, + {id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',ph:true,arpu:PH_ARPU,P:600,ix:'GotchaFIX Manila',ixCheap:1.8,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')}, @@ -241,8 +241,8 @@ const CITIES=[ {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')}, // The Philippines beyond Luzon - {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',ph:true,arpu:PH_ARPU,P:100,ix:'GotchaFIX Cebu',dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, - {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',ph:true,arpu:PH_ARPU,P:80,ix:'GotchaFIX Davao',dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, + {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',ph:true,arpu:PH_ARPU,P:100,ix:'GotchaFIX Cebu',ixCheap:1.8,dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, + {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',ph:true,arpu:PH_ARPU,P:80,ix:'GotchaFIX Davao',ixCheap:1.8,dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, ]; // 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/30-networks/20-rival-exchanges.js b/src/game/30-networks/20-rival-exchanges.js index 246c4ba..d1583cf 100644 --- a/src/game/30-networks/20-rival-exchanges.js +++ b/src/game/30-networks/20-rival-exchanges.js @@ -24,7 +24,7 @@ const XIX=[ {id:'sin~2',c:'sin',name:'Kopi-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.strong_sweet_and_cheaper_than_the')}, {id:'hkg~2',c:'hkg',name:'Dim-Sum-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.lots_of_small_sessions_on_little')}, {id:'mnl~2',c:'mnl',name:'Bayanihan-IX',cheap:0.3,take:0.4,blurb:tr('rival_exchanges.the_whole_neighbourhood_carries_the')}, - {id:'mnl~3',c:'mnl',name:'In-Vitro-IX',cheap:1.4,take:0.2,core:['pld','smt'],blurb:tr('rival_exchanges.grown_in_a_lab_by_the')}, + {id:'mnl~3',c:'mnl',name:'In-Vitro-IX',cheap:2.2,take:0.2,core:['pld','smt'],blurb:tr('rival_exchanges.grown_in_a_lab_by_the')}, {id:'tok~2',c:'tok',name:'Bento-IX',cheap:0.65,take:0.5,core:['drz','akm','cfl','sgt','msf','amz'],blurb:tr('rival_exchanges.tokyo_has_more_exchanges_than_anyone')}, {id:'syd~2',c:'syd',name:'At-The-Edge IX',cheap:.7,take:0.5,core:['drz','nfx','ggl','fbk','akm','cfl','amz','msf','bdc','slw','abb','voc','stb','spl','lpt','npt','mag'],blurb:tr('rival_exchanges.the_challenger_to_ix_straya_pops')}, {id:'bom~2',c:'bom',name:'Vada-Pav-IX',cheap:0.45,take:0.45,blurb:tr('rival_exchanges.mumbai_s_street_food_exchange_fast')}, diff --git a/tests/philippines.test.js b/tests/philippines.test.js index ae545f3..bebbf42 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -21,6 +21,12 @@ test('Manila: GotchaFIX, Bayanihan-IX and the incumbent-run In-Vitro-IX', () => const vitro = ids(ev, "ixMembers('mnl~3')"); assert.ok(vitro.includes('pld') && vitro.includes('smt')); assert.ok(ids(ev, "ixMembers('mnl~2')").includes('dto')); + // GetaFIX's price list: 10G for $700 and 100G for $2,800 a month, within a few percent + for (const c of ['mnl', 'ceb', 'dvo']) { + ev(`ACT.buildPop({city:'${c}'})`); + assert.ok(Math.abs(ev(`ixPortMo('${c}',0)`) - 700) <= 35, `${c} 10G is ${ev(`ixPortMo('${c}',0)`)}`); + assert.ok(Math.abs(ev(`ixPortMo('${c}',1)`) - 2800) <= 140, `${c} 100G is ${ev(`ixPortMo('${c}',1)`)}`); + } // the community exchange is the cheapest port in town, the incumbent's the dearest assert.ok(ev("ixMul('mnl~2') Date: Fri, 30 Oct 2026 14:07:58 +1100 Subject: [PATCH 150/491] In-Vitro-IX ports at double GotchaFIX's price The incumbent's exchange now charges about twice what GotchaFIX Manila does: $1,760 a month for 10G and $6,600 for 100G (multiplier 4.4, up from 2.2). --- CHANGELOG.md | 2 +- src/game/30-networks/20-rival-exchanges.js | 2 +- tests/philippines.test.js | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 106b0aa..64b8f34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ All notable changes to this project are documented here. The project follows - Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Snow Globe, Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Snow Globe now sell transit. - Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too. - Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. -- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. +- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. In-Vitro-IX charges about double that. ## [1.37.0] — 2026-10-28 diff --git a/src/game/30-networks/20-rival-exchanges.js b/src/game/30-networks/20-rival-exchanges.js index d1583cf..3abb2cc 100644 --- a/src/game/30-networks/20-rival-exchanges.js +++ b/src/game/30-networks/20-rival-exchanges.js @@ -24,7 +24,7 @@ const XIX=[ {id:'sin~2',c:'sin',name:'Kopi-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.strong_sweet_and_cheaper_than_the')}, {id:'hkg~2',c:'hkg',name:'Dim-Sum-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.lots_of_small_sessions_on_little')}, {id:'mnl~2',c:'mnl',name:'Bayanihan-IX',cheap:0.3,take:0.4,blurb:tr('rival_exchanges.the_whole_neighbourhood_carries_the')}, - {id:'mnl~3',c:'mnl',name:'In-Vitro-IX',cheap:2.2,take:0.2,core:['pld','smt'],blurb:tr('rival_exchanges.grown_in_a_lab_by_the')}, + {id:'mnl~3',c:'mnl',name:'In-Vitro-IX',cheap:4.4,take:0.2,core:['pld','smt'],blurb:tr('rival_exchanges.grown_in_a_lab_by_the')}, {id:'tok~2',c:'tok',name:'Bento-IX',cheap:0.65,take:0.5,core:['drz','akm','cfl','sgt','msf','amz'],blurb:tr('rival_exchanges.tokyo_has_more_exchanges_than_anyone')}, {id:'syd~2',c:'syd',name:'At-The-Edge IX',cheap:.7,take:0.5,core:['drz','nfx','ggl','fbk','akm','cfl','amz','msf','bdc','slw','abb','voc','stb','spl','lpt','npt','mag'],blurb:tr('rival_exchanges.the_challenger_to_ix_straya_pops')}, {id:'bom~2',c:'bom',name:'Vada-Pav-IX',cheap:0.45,take:0.45,blurb:tr('rival_exchanges.mumbai_s_street_food_exchange_fast')}, diff --git a/tests/philippines.test.js b/tests/philippines.test.js index bebbf42..9ca63aa 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -29,6 +29,9 @@ test('Manila: GotchaFIX, Bayanihan-IX and the incumbent-run In-Vitro-IX', () => } // the community exchange is the cheapest port in town, the incumbent's the dearest assert.ok(ev("ixMul('mnl~2') Date: Fri, 30 Oct 2026 14:33:32 +1100 Subject: [PATCH 151/491] Waves between Philippine islands cost twice Manila to Hong Kong MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Routes with both ends in the Philippines get their own subsea market rate, PH_WAVE 3.7 instead of Asia's 1.5, so a 10G Manila–Cebu wave costs about $7,900 a month: twice Manila–Hong Kong and level with Manila–Singapore. International routes out of the Philippines keep the Asian rate. Leases already signed keep their price. --- CHANGELOG.md | 1 + src/game/10-catalog/10-economy.js | 6 ++++-- src/game/80-simulation/80-geography-and-latency.js | 2 +- tests/philippines.test.js | 13 +++++++++++++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64b8f34..08481b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows - Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Snow Globe, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too. - Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. - Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. In-Vitro-IX charges about double that. +- Waves between Philippine islands now cost more than waves out of the country: Manila to Cebu costs about twice Manila to Hong Kong. ## [1.37.0] — 2026-10-28 diff --git a/src/game/10-catalog/10-economy.js b/src/game/10-catalog/10-economy.js index 45d2e52..42341c7 100644 --- a/src/game/10-catalog/10-economy.js +++ b/src/game/10-catalog/10-economy.js @@ -16,8 +16,10 @@ const AU_TRANSIT=3,AU_WAVE={land:1.8,sub:2.6,ew:1.3},AU_IX=0.8,AU_ARPU=1.8,AU_WH const AU_LEVY=0.08; /* The Philippines: few, thin routes out and an incumbent that owns most of them. 100 GigE transit in Manila costs about 1.9 times Jakarta's (TeleGeography, 2026: $2.25 against $1.21 per Mbps), so the islands pay - 1.9 times the Asian rate. Homes pay about ₱1,450 (US$25) a month, the incumbent's own figure (PLDT, 2025). */ -const PH_TRANSIT=4.7,PH_ARPU=0.7; + 1.9 times the Asian rate. Homes pay about ₱1,450 (US$25) a month, the incumbent's own figure (PLDT, 2025). + Between the islands capacity is dearer than out of the country: a Manila–Cebu wave costs about what + Manila–Singapore does, twice Manila–Hong Kong. */ +const PH_TRANSIT=4.7,PH_ARPU=0.7,PH_WAVE=3.7; const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000; const SITE2_N=[tr('economy.the_other_building'),tr('economy.campus_b_the_one_with_parking'),tr('economy.across_the_river_dc'),tr('common.the_annex'),tr('economy.suburban_mega_shed'),tr('economy.the_cheaper_one'),tr('economy.formerly_a_shopping_mall'),tr('common.bunker_two')]; // A city's buildings: '#' becomes a site number from 1 to dcN (dc2N for the second building) that stays put for this network. diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index d4b1d80..b23a276 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -23,7 +23,7 @@ function linkLat(l){const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1) const WAVE_LAND={EU:0.65,AM:1,SA:1.6,AS:1.4,OC:1.2,AF:2.2},WAVE_SUB={EU:0.8,AM:1,SA:2,AS:1.5,OC:1.5,AF:4.5}; const WAVE_NAME={EU:tr('common.europe'),AM:tr('common.north_america'),SA:tr('common.south_america'),AS:tr('common.asia'),OC:tr('common.oceania'),AF:tr('common.africa')}; function waveMarket(a,b,sub){const ra=CITY[a].reg,rb=CITY[b].reg,T=sub?WAVE_SUB:WAVE_LAND,au=sub?AU_WAVE.sub:AU_WAVE.land; - const fa=CITY[a].au?au:(T[ra]||1),fb=CITY[b].au?au:(T[rb]||1),reg=sub&&nullPair(a,b)?AU_WAVE.ew:sub?Math.max(fa,fb):(fa+fb)/2; + const fa=CITY[a].au?au:(T[ra]||1),fb=CITY[b].au?au:(T[rb]||1),reg=sub&&nullPair(a,b)?AU_WAVE.ew:sub&&CITY[a].ph&&CITY[b].ph?PH_WAVE:sub?Math.max(fa,fb):(fa+fb)/2; const key=atransitMo({net:'sgt',city:'jkt',tier:1},10)")); assert.deepEqual(errors, []); }); + +test('Philippines: waves between the islands cost more than waves out of the country', () => { + const { ev, errors } = load(); + start(ev); + // cheapest 10G wave on any cable between two cities + const w = (a, b) => ev(`Math.min(...cablesOk('${a}','${b}').map(c=>waveMo(c.km,true,0)*CAB[c.cid].price*waveMarket('${a}','${b}',true).m))`); + assert.equal(ev("waveMarket('mnl','ceb',true).reg"), ev('PH_WAVE')); + assert.equal(ev("waveMarket('mnl','hkg',true).reg"), 1.5, 'international routes keep the Asian rate'); + const ratio = w('mnl', 'ceb') / w('mnl', 'hkg'); + assert.ok(ratio > 1.8 && ratio < 2.2, `Manila–Cebu is ${ratio.toFixed(2)} times Manila–Hong Kong`); + assert.ok(w('ceb', 'dvo') > w('mnl', 'hkg'), 'even the short Cebu–Davao hop costs more than Hong Kong'); + assert.deepEqual(errors, []); +}); From 807e981a4d40c8ad35ed118232fedc3af4a43e02 Mon Sep 17 00:00:00 2001 From: fmcglinn Date: Fri, 30 Oct 2026 14:45:23 +1100 Subject: [PATCH 152/491] Philippine eyeballs in line with real populations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Most cities on the map carry about 40G of eyeballs per million people (São Paulo 41, Recife 39, Seoul 39, Tokyo 37). Manila and Davao sat at 24 and Cebu at 32. At 40G per million: Manila 600 to 1,000 (Demographia 2022 urban area, 24.9 million), Cebu 100 to 125 (Metro Cebu, 2020 census, 3.17 million) and Davao 80 to 135 (Metro Davao, 2020 census, 3.34 million). --- CHANGELOG.md | 1 + src/game/20-world/50-cities.js | 6 +++--- tests/philippines.test.js | 10 ++++++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08481b7..d77b675 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows - Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. - Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. In-Vitro-IX charges about double that. - Waves between Philippine islands now cost more than waves out of the country: Manila to Cebu costs about twice Manila to Hong Kong. +- Manila, Cebu and Davao have more people online, in line with their real populations. ## [1.37.0] — 2026-10-28 diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index 40c5742..89970ee 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -35,7 +35,7 @@ const CITIES=[ {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',ph:true,arpu:PH_ARPU,P:600,ix:'GotchaFIX Manila',ixCheap:1.8,dc:'Typhoon-rated DC',note:tr('cities.typhoons_earthquakes_and_a_lot_of')}, + {id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',ph:true,arpu:PH_ARPU,P:1000,ix:'GotchaFIX Manila',ixCheap:1.8,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')}, @@ -241,8 +241,8 @@ const CITIES=[ {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')}, // The Philippines beyond Luzon - {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',ph:true,arpu:PH_ARPU,P:100,ix:'GotchaFIX Cebu',ixCheap:1.8,dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, - {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',ph:true,arpu:PH_ARPU,P:80,ix:'GotchaFIX Davao',ixCheap:1.8,dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, + {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',ph:true,arpu:PH_ARPU,P:125,ix:'GotchaFIX Cebu',ixCheap:1.8,dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, + {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',ph:true,arpu:PH_ARPU,P:135,ix:'GotchaFIX Davao',ixCheap:1.8,dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, ]; // 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/tests/philippines.test.js b/tests/philippines.test.js index 3ea06d4..3c5fdca 100644 --- a/tests/philippines.test.js +++ b/tests/philippines.test.js @@ -170,3 +170,13 @@ test('Philippines: waves between the islands cost more than waves out of the cou assert.ok(w('ceb', 'dvo') > w('mnl', 'hkg'), 'even the short Cebu–Davao hop costs more than Hong Kong'); assert.deepEqual(errors, []); }); + +test('Philippines: eyeballs at about 40G per million people, like the rest of the map', () => { + const { ev, errors } = load(); + // Demographia 2022 urban area for Manila, the 2020 census for Metro Cebu and Metro Davao + for (const [c, millions] of [['mnl', 24.9], ['ceb', 3.17], ['dvo', 3.34]]) { + const perM = ev(`CITY.${c}.P`) / millions; + assert.ok(perM > 37 && perM < 43, `${c} has ${perM.toFixed(1)}G per million people`); + } + assert.deepEqual(errors, []); +}); From 644e6174d9483fdd777980de721db77acea7d5e2 Mon Sep 17 00:00:00 2001 From: tkjaer Date: Fri, 30 Oct 2026 08:01:42 +0100 Subject: [PATCH 153/491] 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 154/491] 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 155/491] 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 156/491] =?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 157/491] 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 158/491] 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 159/491] 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 160/491] 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 161/491] 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 162/491] 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 163/491] 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 164/491] 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 165/491] 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 166/491] 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 167/491] 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 168/491] 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 169/491] 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 170/491] 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 171/491] 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 172/491] 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 173/491] 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 174/491] 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 175/491] 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 176/491] 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 `; return html.replace('', `${hint}${RELOAD}`); diff --git a/scripts/i18n-check.js b/scripts/i18n-check.js index 8d8e657..fd21bb2 100644 --- a/scripts/i18n-check.js +++ b/scripts/i18n-check.js @@ -16,7 +16,8 @@ const D = require('./lib/dict'); const { CALL } = require('./legacy/labels'); const SITE = path.join(__dirname, '..', 'site'); -const page = () => require('./lib/page').assemble().html; +// The development page: it has every label, the agent's (src/agent/) too. +const page = () => require('./lib/page').assemble({ dev: true }).html; const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/; // The labels the game uses, with problems in how they are used. diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 4586d55..d2a6f35 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -1,4 +1,4 @@ -// Runs inside a game page (scripts/route-fuzz.js loads two: main's and this checkout's), next to scripts/lib/mcp-page.js. +// Runs inside a game page (scripts/route-fuzz.js loads two: main's and this checkout's). // The driver picks every move with its own seeded random numbers and sends the same calls to both pages, so the pages // stay in lockstep; this file only offers what a player could do now (buttons on screen, POPs, cities) and digests what // routing gave, as strings the driver compares. diff --git a/scripts/lib/mcp-game.js b/scripts/lib/mcp-game.js index fbf0983..1b357ac 100644 --- a/scripts/lib/mcp-game.js +++ b/scripts/lib/mcp-game.js @@ -1,12 +1,14 @@ -// The game behind the MCP server (scripts/mcp.js): one game page from src/, loaded in jsdom like the tests load it -// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-commands.js (the typed command tables) and -// scripts/lib/mcp-page.js added to read and drive it. TOOLS is the list the server offers; each run() gets the -// session and the tool's arguments and returns JSON. +// The game behind the MCP server (scripts/mcp.js): one game page of its own, the development page from src/ (with the +// agent facade, src/agent/), loaded in jsdom as the tests load it (tests/harness.js: seeded, no animation loop), with +// scripts/lib/mcp-headless.js added to start, load and export games. Every other tool is the page's own facade +// (TUBES.call), so the server plays the game the way the page itself would be played. +// +// TOOLS is the list the server offers; each run() gets the session and the tool's arguments and returns JSON. const fs = require('node:fs'); const path = require('node:path'); const { load } = require('../../tests/harness'); -const PAGE_JS = ['mcp-commands.js', 'mcp-page.js'].map((f) => fs.readFileSync(path.join(__dirname, f), 'utf8')); +const HEADLESS_JS = fs.readFileSync(path.join(__dirname, 'mcp-headless.js'), 'utf8'); const ACT_DIR = path.join(__dirname, '..', '..', 'src', 'game', '90-actions'); // The arguments of the actions the command tables do not type (the drafts), read from their source @@ -24,23 +26,30 @@ function actArgs() { } const MAX_INLINE_SAVE = 200000; +// One call into a jsdom page's facade, as JSON both ways: nothing but plain data crosses. +function pageCall(g, tool, args = {}) { + const w = g.dom.window; + w.__mcpTool = tool; w.__mcpArgs = JSON.parse(JSON.stringify(args)); + return JSON.parse(g.ev('JSON.stringify(TUBES.call(__mcpTool,__mcpArgs))') || 'null'); +} + +// opts.seed, opts.file as tests/harness.js takes them (a file must be a development page: it carries the facade). function createSession(opts = {}) { let game = null; const boot = () => { - const g = load({ seed: opts.seed || 12345, file: opts.file }); - for (const js of PAGE_JS) g.ev(js); - g.call = (fn, ...args) => { - g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args)); - return JSON.parse(g.ev(`JSON.stringify(__mcp.${fn}(...window.__mcpArgs))`) || 'null'); - }; - g.call('newGame', { city: 'fra', name: 'Scratch Networks', preset: 'oncall' }); + const g = load({ seed: opts.seed || 12345, file: opts.file, agent: true }); + g.ev(HEADLESS_JS); + g.headless = (fn, ...args) => { g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args)); return JSON.parse(g.ev(`JSON.stringify(__mcpHeadless.${fn}(...window.__mcpArgs))`) || 'null'); }; + g.headless('newGame', { city: 'fra', name: 'Scratch Networks', preset: 'oncall' }); return g; }; const session = { get game() { return game || (game = boot()); }, - call(fn, ...args) { return session.game.call(fn, ...args); }, + // The page's own tools (TUBES.call). + call(name, args) { return pageCall(session.game, name, args); }, + headless(fn, ...args) { return session.game.headless(fn, ...args); }, // Text into the page without building a giant eval string (saves run to megabytes). - loadSave(txt) { session.game.dom.window.__mcpSave = txt; return JSON.parse(session.game.ev('JSON.stringify(__mcp.loadSave(window.__mcpSave))')); }, + loadSave(txt) { session.game.dom.window.__mcpSave = txt; return JSON.parse(session.game.ev('JSON.stringify(__mcpHeadless.loadSave(window.__mcpSave))')); }, errors() { return game ? game.errors.slice() : []; }, }; return session; @@ -52,6 +61,8 @@ const bool = (description) => ({ type: 'boolean', description }); const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false }); const SECTIONS = ['clock', 'commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results']; const WHERE = ['modal', 'bank', 'dash', 'panel', 'left', 'puzzle']; +// A page tool, passed straight through: the MCP tool's arguments are the facade's. +const page = (name) => (s, a) => s.call(name, a); const TOOLS = [ { @@ -60,7 +71,7 @@ const TOOLS = [ inputSchema: obj({ city: str('Home city: id (fra) or name (Frankfurt). Default Frankfurt.'), name: str('Network name (24 characters at most). Default: a random pun.'), preset: str('Rules preset', { enum: ['soft', 'freeze', 'oncall', 'bgp', 'sandbox'] }), seed: num('Random seed, default 12345.'), asn: num('Your own AS number, as the title screen takes it. Default: a free one.'), chaos: str('Sandbox only: how often things break. Default none.', { enum: ['none', 'calm', 'normal', 'spicy'] }) }), - run: (s, a) => s.call('newGame', a), + run: (s, a) => s.headless('newGame', a), }, { name: 'load_save', @@ -77,7 +88,7 @@ const TOOLS = [ description: 'Export the current game as a save file the real game can import (Menu → Import save). Writes it to path, or returns it when it is small.', inputSchema: obj({ path: str('Where to write the .json file.') }), run: (s, a) => { - const txt = s.call('exportSave', require('../../package.json').version); + const txt = s.headless('exportSave', require('../../package.json').version); if (a.path) { fs.writeFileSync(path.resolve(a.path), txt); return { wrote: path.resolve(a.path), bytes: Buffer.byteLength(txt) }; } if (txt.length > MAX_INLINE_SAVE) throw new Error(`The save is ${txt.length} characters; give a path to write it to.`); return JSON.parse(txt); @@ -87,86 +98,86 @@ const TOOLS = [ name: 'status', description: 'The network at a glance: date, cash, monthly revenue and costs by kind, level, tier and why it is not Tier 1 yet, the current goal, traffic, reach, counts, POPs and open incidents.', inputSchema: obj(), - run: (s) => s.call('status'), + run: page('status'), }, { name: 'advance', description: 'Run the game forward day by day, as the game loop does. Stops early when a window opens (then read it with screen and answer it with click or act; decision says when it is a question with options) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took.', inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }), - run: (s, a) => s.call('advance', a.days), + run: page('advance'), }, { name: 'network', description: 'Everything about one network (a carrier, eyeball network, CDN…): type, peering policy and what it asks for, traffic share, transit price, PoPs, exchanges, upstreams and customer cone, whether Tier 1 needs it, and for you: demand, how its traffic leaves you (egress by kind), your PNIs and sessions with it, and how to move it to peering.', inputSchema: obj({ network: str('Id (dtk), name (Doitsche Telekomm) or ASN.') }, ['network']), - run: (s, a) => s.call('network', a.network), + run: page('network'), }, { name: 'city', description: 'One city: country, exchanges and their member counts, data center, who sells transit there and at what price, the networks present, the cables that land there, and your POP if you have one.', inputSchema: obj({ city: str('Id (fra) or name (Frankfurt).') }, ['city']), - run: (s, a) => s.call('city', a.city), + run: page('city'), }, { name: 'find', description: 'Search cities, networks, cables and exchanges by name, id or ASN. Use it to get the ids other tools and actions take.', inputSchema: obj({ query: str('Part of a name, an id or an ASN.'), kind: str('Only this kind', { enum: ['city', 'network', 'cable', 'exchange'] }) }, ['query']), - run: (s, a) => s.call('find', a.query, a.kind), + run: page('find'), }, { name: 'traceroute', description: 'The game\'s looking glass: the path traffic takes from one of your POPs to a network (which exit wins and why, with the AS path) or to another of your POPs (prefix it city:).', inputSchema: obj({ from: str('One of your POPs: id or name.'), to: str('A network (id, name or ASN), or city:.') }, ['from', 'to']), - run: (s, a) => s.call('trace', a.from, a.to), + run: page('traceroute'), }, { name: 'peering_check', description: 'Would this network peer with you, and if not, why not? Checks a PNI at each of your POPs where it is, and a session at each exchange you are on where it is a member, with the game\'s own reasons (traffic it wants, paid peering, the Tier 1 club…).', inputSchema: obj({ network: str('Id, name or ASN.'), city: str('Only this city.'), via: str('Only this way', { enum: ['pni', 'ix'] }) }, ['network']), - run: (s, a) => s.call('peering', a.network, a.city, a.via), + run: page('peering_check'), }, { name: 'hot_spots', description: 'Where it hurts: the fullest links, transit ports and PNIs, the transit bill by carrier, and the networks with the most traffic still over transit, each with the cheapest way to peer with it.', inputSchema: obj({ limit: num('How many of each, default 10.') }), - run: (s, a) => s.call('hotSpots', a.limit || 10), + run: page('hot_spots'), }, { name: 'schema', description: 'The typed contract act checks against: every game command with its arguments, their domains and a description, which ones dry-run, decide or confirm; view commands; session actions (scenarios, puzzles, runs); drafts (inputs another command reads); what is not available and why; the argument domains; and a field-by-field reference of state and results. Give section for one part.', inputSchema: obj({ section: str('One part only', { enum: SECTIONS }) }), - run: (s, a) => s.call('schema', a.section), + run: page('schema'), }, { name: 'catalog', description: 'The game\'s reference tables, which the argument domains point at: CITIES, NETS, CABLES, PORT, LT, OPT, DF_SYS, FAB, INTERNS, OPSK, CHARTERS, SCN, BANKS… plus three made for you: conferences (the upcoming calendar with the keys confGo and confSponsor take), TE_RECIPES (each RouteScript recipe with its script, ready for teDeploy) and BADGES (as the badge wall shows them). Omit name for the list of tables with their sizes.', inputSchema: obj({ name: str('One table; omit for the list.') }), - run: (s, a) => s.call('catalog', a.name), + run: page('catalog'), }, { name: 'state', description: 'The saved game itself as JSON, the same object the game saves: offers, loan offers, links, ports, PNIs, customers, the intern, events… with their ids. schema section "state" documents each field. Give a path (pops.fra, links, loanOffers, biz.3, links.): the whole state of a big network is hundreds of KB.', inputSchema: obj({ path: str('Dotted path: a key, an array index or an entity id per step.') }), - run: (s, a) => s.call('state', a.path), + run: page('state'), }, { name: 'results', description: 'The game\'s last traffic computation (R), rebuilt after every action and every day: load per link, use per port, demand and served per city, egress per network, monthly cost and revenue by kind, latency, reach. schema section "results" documents each field. Give a path (load, cost, netEg.ggl).', inputSchema: obj({ path: str('Dotted path.') }), - run: (s, a) => s.call('results', a.path), + run: page('results'), }, { name: 'ui', description: 'The view state actions read and write (the selection, the pending link pair, the drafts of the link, fiber and cable windows, the RouteScript draft, confirmations), without render caches. For working out why an action did what it did.', inputSchema: obj(), - run: (s) => s.call('ui'), + run: page('ui'), }, { name: 'actions', description: 'Every action act can run, with its arguments (? marks an optional one), e.g. buildPop(city), buyTransit(city,net,tier), buildLink(a,b,tier,cable?,route?,premiumCrossing?). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=. schema has each one\'s argument domains and what it does.', inputSchema: obj(), run: (s) => { - const { typed, drafts } = s.call('actions'), a = actArgs(); + const { typed, drafts } = s.call('actions', {}), a = actArgs(); return [...Object.entries(typed).map(([k, sig]) => `${k}(${sig})`), ...drafts.map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k))].sort(); }, }, @@ -175,36 +186,32 @@ const TOOLS = [ description: 'Do something in the game: run one action with its arguments (see actions and schema). Arguments are checked first (a wrong id or value is an error that lists what fits); the action then runs as the game runs it: windows that take typed text are filled in (renameGo, teDeploy, teCheck, metricSet), multi-step builds take their choices as arguments (buildLink, orderDf, orderCable, decomGo), and confirmations are given (rmLink, cancelTransit…). outcome says what happened: applied (something changed), rejected (the game said no, see toasts), no_effect (nothing changed and nothing was said), shown (a view or draft: only the screen changed), decision (a window asks a question: answer with one of decision.options or closeModal; other game commands wait), quote (dryRun), stopped (bankrupt). charged is what the money gate took; cashChange also counts goal rewards. With dryRun, a game command is priced with the game\'s own helpers and nothing happens.', inputSchema: obj({ action: str('Action name, e.g. buildPop (view. prefixes are accepted).'), command: str('Same as action.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' }, dryRun: bool('Price it and check it can be done: {setup, monthly, days, blocked}. Nothing happens.') }), - run: (s, a) => { - const name = a.action || a.command; - if (!name) throw new Error('Give action, e.g. {"action":"buildPop","args":{"city":"ams"}}.'); - return s.call('run', name, a.args || {}, { dryRun: !!a.dryRun }); - }, + run: page('act'), }, { name: 'screen', description: 'What the player sees, as text with numbered buttons for click: the open window, else the bank or the NOC dashboard when open, else the side panel, else the puzzle box. where picks one: modal, bank, dash, panel, left (the left drawer: goals, deals, noc or nets) or puzzle. open lists what is showing. Long text comes in pages: textMore says the offset of the next one. Lists the game acts on when they change come with their options; click them with a value.', inputSchema: obj({ where: str('Which surface', { enum: WHERE }), offset: num('Start the text here (from textMore).') }), - run: (s, a) => s.call('screen', a.where, a.offset), + run: page('screen'), }, { name: 'panel', description: 'Open the side panel of a city or a link, a network in the network list, or a tab of the left drawer (goals, deals: offers and loans, noc, nets), optionally on a tab (a city has cust, up, peer, infra…), and show it as text with numbered buttons.', inputSchema: obj({ city: str('City id or name.'), link: str('Link id (from status, hot_spots or state links).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.'), left: str('A tab of the left drawer', { enum: ['goals', 'deals', 'noc', 'nets'] }) }), - run: (s, a) => s.call('panel', a), + run: page('panel'), }, { name: 'click', description: 'Press a numbered button from the last screen, panel or act result, as a player\'s click does: with the button\'s own arguments, so confirmations arm first and windows step on as in the game. For a list (it has options), give value.', inputSchema: obj({ button: num('The button\'s n.'), value: str('For a list: the option to pick.') }, ['button']), - run: (s, a) => s.call('click', a.button, a.value), + run: page('click'), }, { name: 'open_link', description: 'Open the build window for a link (a leased wave, dark fiber or your own cable) from one of your POPs to any city, to compare the routes and sizes it offers; then click through it. act buildLink, orderDf and orderCable do the same in one call.', inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']), - run: (s, a) => s.call('openLink', a.from, a.to), + run: page('open_link'), }, ]; diff --git a/scripts/lib/mcp-headless.js b/scripts/lib/mcp-headless.js new file mode 100644 index 0000000..5c6a05d --- /dev/null +++ b/scripts/lib/mcp-headless.js @@ -0,0 +1,34 @@ +// Runs inside the MCP server's own game page (scripts/lib/mcp-game.js), in the game's global scope, after the page has +// loaded: the half of a session only that page has. It starts, loads and exports games, which in a player's browser +// are the player's alone, so it is not part of any page. Everything else a tool does goes through the page's own +// facade (window.TUBES, src/agent/). +(() => { + // Out of the way of the game: no sheet of a previous game, no title screen or pitch, the clock left to the server. + const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); API_SHEET = null; compute(); renderAll(); }; + const newGame = ({ city = 'fra', name, preset = 'oncall', seed, asn, chaos } = {}) => { + const c = apiCityOf(city).id; + if (!homeOk(c)) apiFail(`${apiCityName(c)} cannot be a home city.`); + if (!['soft', 'freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) apiFail('preset is one of soft, freeze, oncall, bgp, sandbox'); + if (asn !== undefined && !asnOk(+asn)) apiFail(`AS${asn} cannot be yours: it is reserved, private or another network's. Leave asn out for a free one.`); + if (chaos !== undefined && preset !== 'sandbox') apiFail('chaos is the sandbox\'s dial: give preset "sandbox" with it.'); + if (chaos !== undefined && !own(CHAOS, chaos)) apiFail(`chaos is one of ${Object.keys(CHAOS).join(', ')}.`); + if (seed !== undefined && window.__reseed) window.__reseed(Math.max(1, Math.floor(+seed) || 1)); + if (UI.pendGame) UI.pendGame = null; + UI.pitched = true; + const nm = String(name || randomNetworkName()).slice(0, 24), was = UI.asnTxt; + // beginGame takes the ASN typed on the title screen. + UI.asnTxt = asn !== undefined ? String(+asn) : ''; + try { beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: chaos || 'none' } } : { mode: 'normal', preset }); } finally { UI.asnTxt = was; } + settle(); + return apiStatus(); + }; + const loadSave = (txt) => { + const r = parseSave(txt); + if (r.err) apiFail(apiText(r.err)); + S = migrate(JSON.parse(JSON.stringify(r.s))); + settle(); + return { savedBy: r.ver, ...apiStatus() }; + }; + const exportSave = (version) => JSON.stringify({ app: 'series-of-tubes', version: /^\d/.test(APP_VERSION) ? APP_VERSION : version, exported: new Date().toISOString(), S: packSave(S) }); + window.__mcpHeadless = { newGame, loadSave, exportSave }; +})(); diff --git a/scripts/lib/mcp-page.js b/scripts/lib/mcp-page.js deleted file mode 100644 index 2eb6717..0000000 --- a/scripts/lib/mcp-page.js +++ /dev/null @@ -1,487 +0,0 @@ -// Runs inside the game page (see scripts/lib/mcp-game.js), in the game's own global scope, so it reads S, R, NET, -// CITY… directly. Every function takes and returns plain JSON. It only reads the game, except run(), click(), -// panel(), advance() and the game loaders, which go through the same ACT actions and dayTick() the page uses. -// The command tables run() checks arguments against come from scripts/lib/mcp-commands.js, evaluated first. -(() => { - const { API_DOMAINS, API_CMD, API_VIEW, API_BOUND, API_SESSION, API_STATE_DOC, API_RESULTS_DOC, API_TABLES, API_MADE, - API_UI_HIDDEN, apiDomCheck, apiDomValues, apiPath, apiJson } = window.__mcpCmds; - const BLOCK = /^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/; - const MAX_TEXT = 8000; - // Text as a player would read it: one line per block, no runs of spaces. jsdom has no innerText. - const fullText = (x) => { - let el = x; - if (typeof x === 'string') { el = document.createElement('div'); el.innerHTML = x; } - if (!el) return ''; - const out = []; - const walk = (n) => { - if (n.nodeType === 3) { out.push(n.nodeValue); return; } - if (n.nodeType !== 1 || n.hidden || /^(SCRIPT|STYLE|SVG|CANVAS)$/i.test(n.tagName)) return; - if (n.tagName === 'BR') { out.push('\n'); return; } - // A dropdown reads as its choice: hundreds of options would crowd out the rest (the catalog lists them). - if (n.tagName === 'SELECT') { const o = n.options[n.selectedIndex]; out.push(' ', o ? o.text : '', ' '); return; } - // Blocks get their own line; inline tags a space, so "Revenue$2k" does not read as one word. - const sep = BLOCK.test(n.tagName) ? '\n' : ' '; - out.push(sep); - for (const c of n.childNodes) walk(c); - out.push(sep); - }; - walk(el); - return out.join('').split('\n').map((l) => l.replace(/\s+/g, ' ').replace(/ ([.,;:!?)])/g, '$1').replace(/\( /g, '(').trim()).filter(Boolean).join('\n'); - }; - const text = (x, max = MAX_TEXT) => { const s = fullText(x); return s.length > max ? s.slice(0, max) + '\n…' : s; }; - const r1 = (v) => (typeof v === 'number' && isFinite(v) ? Math.round(v * 10) / 10 : v); - const fail = (msg) => { throw new Error(msg); }; - const norm = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').trim(); - const parse = (s) => { try { return JSON.parse(s || '{}'); } catch (e) { return {}; } }; - - // ---------- finding things by id or by name ---------- - const best = (list, q, keys) => { - const n = norm(q); - if (!n) return null; - for (const test of [(v) => v === n, (v) => v.startsWith(n), (v) => v.includes(n)]) { - const hit = list.find((x) => keys(x).some((k) => test(norm(k)))); - if (hit) return hit; - } - return null; - }; - const netOf = (q) => NET[q] || best(NETS, q, (n) => [n.id, n.name, 'as' + n.asn, String(n.asn)]) || fail(`No network matches "${q}". Try find.`); - const cityOf = (q) => CITY[q] || best(CITIES, q, (c) => [c.id, c.name]) || fail(`No city matches "${q}". Try find.`); - const allIx = () => { - const o = []; - for (const c of CITIES) for (const x of ixStatic(c.id)) o.push(x); - for (const c of Object.keys(S.myIx || {})) if (!o.includes(c)) o.push(c); - return o; - }; - const cityName = (c) => (CITY[c] ? CITY[c].name : c); - const incText = (i) => text(i.msg || incTitle(i), 400); - - // ---------- toasts: what the game tells the player ---------- - let toasts = []; - const t0 = toast; - toast = function (h, kind) { toasts.push({ kind: kind || '', text: text(String(h), 600) }); return t0.apply(this, arguments); }; - const takeToasts = () => { const t = toasts; toasts = []; return t; }; - const toastLines = (t) => t.map((x) => (x.kind ? x.kind + ': ' : '') + x.text); - - // ---------- what is on screen ---------- - // The surfaces a player can read, by the name screen() takes. The left drawer has tabs (goals, deals, noc, nets). - const ROOT = { modal: 'modal', bank: 'bankBox', dash: 'dash', panel: 'panel', left: 'leftBody', puzzle: 'pzBox' }; - const shown = (w) => { const el = $(ROOT[w]); return !!el && !el.hidden; }; - const modalOpen = () => shown('modal'); - let last = []; - const controls = (root) => { - const out = []; - for (const b of root.querySelectorAll('[data-act],select[data-chg]')) { - if (b.dataset.act) out.push({ label: text(b, 200).replace(/\n/g, ' ') || b.getAttribute('aria-label') || b.dataset.act, act: b.dataset.act, args: parse(b.dataset.args), disabled: !!b.disabled }); - // A list the game acts on when its value changes (the change handler in src/game/96-map/95-clicks.js): click - // it with a value. - else out.push({ label: b.getAttribute('aria-label') || (b.closest('label') && text(b.closest('label'), 120).split('\n')[0]) || b.dataset.chg, - select: b.dataset.chg, value: b.value, options: [...b.options].map((o) => ({ value: o.value, label: o.textContent.trim() })), disabled: !!b.disabled }); - } - return out; - }; - const screen = (where, offset = 0) => { - if (where === null) where = undefined; - if (where !== undefined && !ROOT[where]) fail(`where is one of ${Object.keys(ROOT).join(', ')}.`); - const open = Object.keys(ROOT).filter((w) => w !== 'left' && shown(w)); - const w = where || ['modal', 'bank', 'dash', 'panel', 'puzzle'].find(shown) || 'panel'; - const root = $(ROOT[w]); - last = root ? controls(root) : []; - const all = root ? fullText(root) : '', from = Math.max(0, Math.floor(+offset) || 0), more = all.length - from - MAX_TEXT; - const out = { where: w, open, selected: UI.sel, tab: UI.tab }; - if (w === 'left') out.leftTab = UI.left || 'goals'; - if (w === 'modal') { const d = decision(); out.question = !!d; } - out.text = all.slice(from, from + MAX_TEXT); - if (from) out.textFrom = from; - if (more > 0) out.textMore = `${more} more characters: call screen with where "${w}" and offset ${from + MAX_TEXT}`; - out.buttons = last.map((b, i) => ({ n: i, ...b })); - return out; - }; - - // ---------- windows: the agent's own sheets, and the game's questions ---------- - // A window the agent opened itself (a view, a draft, the link window, a sheet it clicked inside) is something to read - // and click through. A window the game opened in answer to a game command, or during a day, is a question when one - // of its buttons runs a game command other than closeModal (a De-Kicks quote, a retention offer); then other game - // commands wait until it is answered or closed, as clicks outside an open window do in the game. - let sheet = null; - const card = () => $('modalCard').firstChild; - const markSheet = () => { sheet = modalOpen() ? card() : null; }; - const isSheet = () => modalOpen() && !!sheet && card() === sheet; - const decision = () => { - if (!modalOpen() || isSheet()) return null; - const b = [...$('modal').querySelectorAll('[data-act]')].filter((x) => x.dataset.act !== 'closeModal' && API_CMD[x.dataset.act]); - if (!b.length) return null; - return { text: text($('modal'), 1500), options: b.map((x) => ({ command: x.dataset.act, args: parse(x.dataset.args), label: text(x, 120).replace(/\n/g, ' ') })) }; - }; - - // ---------- starting and loading ---------- - const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); sheet = null; compute(); renderAll(); takeToasts(); }; - const newGame = ({ city = 'fra', name, preset = 'oncall', seed, asn, chaos }) => { - const c = cityOf(city).id; - if (!homeOk(c)) fail(`${cityName(c)} cannot be a home city.`); - if (!['soft', 'freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) fail('preset is one of soft, freeze, oncall, bgp, sandbox'); - if (asn !== undefined && !asnOk(+asn)) fail(`AS${asn} cannot be yours: it is reserved, private or another network's. Leave asn out for a free one.`); - if (chaos !== undefined && preset !== 'sandbox') fail('chaos is the sandbox\'s dial: give preset "sandbox" with it.'); - if (chaos !== undefined && !own(CHAOS, chaos)) fail(`chaos is one of ${Object.keys(CHAOS).join(', ')}.`); - if (seed !== undefined && window.__reseed) window.__reseed(Math.max(1, Math.floor(+seed) || 1)); - if (UI.pendGame) UI.pendGame = null; - UI.pitched = true; - const nm = String(name || randomNetworkName()).slice(0, 24), was = UI.asnTxt; - // beginGame takes the ASN typed on the title screen. - UI.asnTxt = asn !== undefined ? String(+asn) : ''; - try { beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: chaos || 'none' } } : { mode: 'normal', preset }); } finally { UI.asnTxt = was; } - settle(); - return status(); - }; - const loadSave = (txt) => { - const r = parseSave(txt); - if (r.err) fail(text(r.err)); - S = migrate(JSON.parse(JSON.stringify(r.s))); - settle(); - return { savedBy: r.ver, ...status() }; - }; - const exportSave = (version) => JSON.stringify({ app: 'series-of-tubes', version: /^\d/.test(APP_VERSION) ? APP_VERSION : version, exported: new Date().toISOString(), S: packSave(S) }); - - // ---------- reading the network ---------- - const status = () => { - const goal = GOALS.find((g) => S.done[g.id] === undefined); - const t1 = isTier1(); - return { - name: S.name, asn: S.asn, home: cityName(S.home), mode: S.mode, rules: S.rules && S.rules.preset, - day: S.day, date: dateStr(S.day), cash: Math.round(S.cash), level: S.lvl || 0, - tier: tierLabel(), whyNotTier1: t1 ? null : text(t1Why()), - goal: goal ? { title: text(goal.t), what: text(goal.d) } : null, - monthly: { revenue: Math.round(R.revMo), cost: Math.round(R.costMo), profit: Math.round(R.revMo - R.costMo), - revenueBy: Object.fromEntries(Object.entries(R.rev || {}).map(([k, v]) => [k, Math.round(v)]).filter(([, v]) => v)), - costBy: Object.fromEntries(Object.entries(R.cost || {}).map(([k, v]) => [k, Math.round(v)]).filter(([, v]) => v)) }, - traffic: { demandGbps: r1(R.demand), servedGbps: r1(R.served), reach: r1((R.reach || 0) * 100) + '%', peeringSessions: R.sessions }, - counts: { pops: Object.keys(S.pops).length, links: S.links.length, transitPorts: S.transit.length, exchangePorts: Object.keys(S.ixp).length, - pnis: S.pni.length, cacheBoxes: S.caches.length, customers: S.biz.length, offers: S.offers.length }, - pops: Object.keys(S.pops).map(cityName), - incidents: S.inc.map((i) => ({ id: i.id, type: i.type, what: incText(i), until: i.until !== undefined ? dateStr(i.until) : undefined, rushRepairCost: i.cost || undefined })), - lost: !!S.lost, won: !!S.won, - }; - }; - - const network = (q) => { - const n = netOf(q), id = n.id, eg = R.netEg && R.netEg[id]; - return { - id, name: n.name, asn: n.asn, type: TYPE_L[n.type], policy: n.pol, - requirements: { minIxGbps: n.minIx, minPniGbps: n.minPni, paidFeePerMonth: n.paidFee, freeFromLevel: n.freeLv }, - trafficShare: r1(NSH[id] * 100) + '%', transitPerGbps: n.price ? r1(n.price * S.priceMul) : null, - homeMarkets: n.cc ? [].concat(n.cc) : [], pops: n.pops.map(cityName), - exchanges: n.ix === 'ALL' ? 'most exchanges where it has a PoP' : (n.ix || []).map((x) => ixName(x)), - upstreams: (n.up || []).map((u) => NET[u] ? NET[u].name : u), customerCone: (DOWN[id] || []).length, - neededForTier1: t1Need().some((x) => x.id === id), mergedInto: merged(id) ? (MERGERS.find((m) => m.id === id) || {}).into : undefined, - about: text(n.blurb), - you: { - reachable: !!(R.reachable && R.reachable[id]), demandGbps: r1((R.demTo && R.demTo[id]) || 0), - egressGbps: eg ? Object.fromEntries(Object.entries(eg).map(([k, v]) => [k, r1(v)])) : null, - pnis: S.pni.filter((p) => p.net === id).map((p) => ({ id: p.id, city: cityName(p.city), port: pniPN(p), count: p.n || 1, ready: pniOn(p) })), - exchangeSessions: Object.keys(S.ixp).filter((x) => ixSessions(x).has(id)).map(ixName), - howToPeer: text(offTransitHint(id, S.home)), - }, - }; - }; - - const city = (q) => { - const C = cityOf(q), c = C.id, P = S.pops[c]; - const cab = CABLE_PAIRS.filter((p) => p.a === c || p.b === c).map((p) => ({ cable: CAB[p.cid] ? CAB[p.cid].name : p.cid, to: cityName(p.a === c ? p.b : p.a), km: p.km })); - const here = NETS.filter((n) => n.pops.includes(c) && !n.tail).sort((a, b) => b.share - a.share); - return { - id: c, name: C.name, country: C.cc, region: C.reg, about: C.note ? text(C.note) : undefined, dataCenter: C.dc, - canBeHome: homeOk(c), - exchanges: ixIdsIn(c).map((x) => ({ id: x, name: ixName(x), members: ixMembers(x).length, yourPort: S.ixp[x] !== undefined })), - transit: NETS.filter((n) => sellsAt(n, c)).map((n) => ({ id: n.id, name: n.name, type: TYPE_L[n.type], perGbps: r1(transitPerG(n, c, false) * S.priceMul) })).sort((a, b) => a.perGbps - b.perGbps), - networksHere: here.length, biggestNetworksHere: here.slice(0, 15).map((n) => n.name), cables: cab, - you: P ? { demandGbps: r1((R.cityDem || {})[c] || 0), servedGbps: r1((R.citySrv || {})[c] || 0), routers: P.routers, down: P.down > S.day ? dateStr(P.down) : false, - broadband: !!P.bb, links: S.links.filter((l) => l.a === c || l.b === c).length } : null, - }; - }; - - const find = (q, kind) => { - const n = norm(q), hit = (...k) => k.some((v) => norm(v).includes(n)), out = {}; - if (!n) fail('Give a word to search for.'); - if (!kind || kind === 'city') out.cities = CITIES.filter((c) => hit(c.id, c.name)).slice(0, 20).map((c) => ({ id: c.id, name: c.name, country: c.cc })); - if (!kind || kind === 'network') out.networks = NETS.filter((x) => hit(x.id, x.name, String(x.asn))).slice(0, 20).map((x) => ({ id: x.id, name: x.name, asn: x.asn, type: TYPE_L[x.type] })); - if (!kind || kind === 'cable') out.cables = Object.values(CAB).filter((x) => hit(x.id, x.name)).slice(0, 20).map((x) => ({ id: x.id, name: x.name, lands: [...new Set(x.pairs.flatMap((p) => [p[0], p[1]]))].map(cityName) })); - if (!kind || kind === 'exchange') out.exchanges = allIx().filter((x) => hit(x, ixName(x))).slice(0, 20).map((x) => ({ id: x, name: ixName(x), city: cityName(ixCity(x)) })); - return out; - }; - - const trace = (from, to) => { - const src = cityOf(from).id; - if (!S.pops[src]) fail(`You have no POP in ${cityName(src)}. Yours: ${Object.keys(S.pops).map(cityName).join(', ')}.`); - let target = null; - if (typeof to === 'string' && /^city:/i.test(to)) target = { city: cityOf(to.slice(5)).id }; - else { try { target = { net: netOf(to).id }; } catch (e) { target = { city: cityOf(to).id }; } } - if (target.city && !S.pops[target.city]) fail(`A traceroute to a city goes to one of your POPs: ${Object.keys(S.pops).map(cityName).join(', ')}.`); - const r = traceroute(src, target); - return { text: r.text, why: text(r.why || ''), asPath: r.asPath || null }; - }; - - const peering = (q, where, via) => { - const n = netOf(q), id = n.id, out = []; - if (!via || via === 'pni') for (const c of (where ? [cityOf(where).id] : Object.keys(S.pops).filter((c) => n.pops.includes(c)))) { - const r = peerOk(id, 'pni', c); - out.push({ via: 'pni', city: cityName(c), ok: !!r.ok, why: r.why ? text(r.why) : undefined, feePerMonth: r.fee, free: r.free, minimumPort: PORT[pniMin(id)].n }); - } - if (!via || via === 'ix') for (const x of Object.keys(S.ixp).filter((x) => ixMembers(x).includes(id) && (!where || ixCity(x) === cityOf(where).id))) { - const r = peerOk(id, 'ix', x); - out.push({ via: 'ix', exchange: ixName(x), ok: !!r.ok, why: r.why ? text(r.why) : undefined, session: ixSessions(x).has(id) }); - } - return { network: n.name, policy: n.pol, hint: text(offTransitHint(id, where ? cityOf(where).id : S.home)), - checks: out, note: out.length ? undefined : 'No POP or exchange port of yours is where this network is. Build one first: see network.' }; - }; - - const hotSpots = (limit = 10) => { - const top = (a) => a.sort((x, y) => y.util - x.util).slice(0, limit); - const pct = (u, c) => (c > 0 ? r1((u / c) * 100) : null); - const links = S.links.map((l) => { const cap = capOf(l), u = (R.load || {})[l.id] || 0; return { id: l.id, between: cityName(l.a) + ' – ' + cityName(l.b), kind: l.kind, capacity: capName(l), usedGbps: r1(u), util: pct(u, cap), down: linkDown(l) }; }); - const transit = S.transit.map((t) => { const cap = lagCap(PORT[t.tier].g, t.n), u = (R.useT || {})[t.id] || 0, q = (R.p95 && R.p95[t.id]) || u; - return { id: t.id, city: cityName(t.city), carrier: NET[t.net].name, port: lagName(t.tier, t.n), usedGbps: r1(u), util: pct(u, cap), billPerMonth: Math.round(transitMo(t, q)) }; }); - const pnis = S.pni.filter(pniOn).map((p) => { const cap = pniG(p) * (p.n || 1), u = (R.usePni || {})[p.id] || 0; return { id: p.id, network: NET[p.net].name, city: cityName(p.city), port: pniPN(p), usedGbps: r1(u), util: pct(u, cap) }; }); - const viaTransit = NETS.filter((n) => R.netEg && R.netEg[n.id] && R.netEg[n.id].t > 0.05).sort((a, b) => R.netEg[b.id].t - R.netEg[a.id].t).slice(0, limit) - .map((n) => ({ id: n.id, network: n.name, overTransitGbps: r1(R.netEg[n.id].t), howToPeer: text(offTransitHint(n.id, S.home)) })); - const bill = {}; - for (const t of transit) bill[t.carrier] = (bill[t.carrier] || 0) + t.billPerMonth; - return { links: top(links), transitPorts: top(transit), pnis: top(pnis), transitBillByCarrier: bill, biggestTrafficStillOnTransit: viaTransit }; - }; - - // ---------- the contract: commands, arguments, reference tables, raw state ---------- - // Actions the server never runs: files, storage slots, settings and the title screen are not the game's, and time - // only moves through advance. - const WHY = { - time: 'use advance to move time', start: 'use new_game', files: 'use load_save or export_save', - slots: 'saved networks in browser storage are not part of this game', prefs: 'device and player settings are not part of the game', - browser: 'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', - }; - const DENY_WHY = { - speed: 'time', phonePlay: 'time', phoneSpeed: 'time', - start: 'start', newgame: 'start', cont: 'start', toTitle: 'start', resetAsk: 'start', - exportSave: 'files', importGo: 'files', importPick: 'files', slotExport: 'files', - slotBack: 'slots', slotDel: 'slots', slotDelGo: 'slots', slotMenu: 'slots', slotRetry: 'slots', slotSpace: 'slots', slotSwitch: 'slots', slotTake: 'slots', - animSet: 'prefs', langSet: 'prefs', menu: 'prefs', mute: 'prefs', prefSet: 'prefs', settings: 'prefs', settingsClose: 'prefs', soundSet: 'prefs', vpSet: 'prefs', - install: 'browser', share: 'browser', shareDl: 'browser', shareGo: 'browser', traceCopy: 'browser', updateLater: 'browser', updateNow: 'browser', wsShare: 'browser', pzShare: 'browser', - }; - const denied = (name) => (Object.prototype.hasOwnProperty.call(DENY_WHY, name) ? WHY[DENY_WHY[name]] : null); - const kindOf = (name) => (API_CMD[name] ? 'game' : API_VIEW[name] ? 'view' : API_BOUND[name] ? 'draft' : API_SESSION[name] ? 'session' : null); - const specOf = (name) => API_CMD[name] || API_VIEW[name] || API_SESSION[name] || null; - const classes = () => ({ game: Object.keys(API_CMD), view: Object.keys(API_VIEW), draft: Object.keys(API_BOUND), session: Object.keys(API_SESSION), denied: Object.keys(DENY_WHY) }); - - // One argument as the schema states it. Table domains name their catalog table rather than list every id. - const argDoc = ([name, dom, req]) => { - const a = { name, required: req !== false }, d = API_DOMAINS[dom]; - if (!d) { a.type = dom; return a; } - a.domain = dom; - if (d.table) a.from = d.table; - else { const v = apiDomValues(dom); if (Array.isArray(v)) a.values = v; else if (v && v.from !== undefined) a.range = v; } - return a; - }; - const schema = (section) => { - const cmd = (s) => ({ args: (s.args || []).map(argDoc), doc: s.doc }); - const doc = { - clock: 'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.', - commands: Object.fromEntries(Object.entries(API_CMD).map(([n, s]) => [n, { ...cmd(s), dryRun: !!s.quote, - ...(s.decides ? { decides: true } : {}), ...(s.confirm ? { confirm: s.confirm } : {}), ...(s.open ? { opens: s.open } : {}), ...(s.reads ? { report: true } : {}) }])), - view: Object.fromEntries(Object.entries(API_VIEW).map(([n, s]) => [n, cmd(s)])), - session: Object.fromEntries(Object.entries(API_SESSION).map(([n, s]) => [n, cmd(s)])), - drafts: API_BOUND, - denied: Object.fromEntries(Object.keys(DENY_WHY).sort().map((n) => [n, denied(n)])), - domains: Object.fromEntries(Object.entries(API_DOMAINS).map(([n, d]) => { const v = apiDomValues(n); - return [n, { kind: d.kind === 'fn' ? 'custom' : d.kind, ...(d.table ? { from: d.table } : {}), - ...(!d.table && Array.isArray(v) ? { values: v } : v && v.from !== undefined ? { range: v } : v && v.of ? { of: v.of } : {}) }]; })), - state: API_STATE_DOC, results: API_RESULTS_DOC, - }; - if (section === undefined || section === null || section === '') return doc; - if (!(section in doc)) fail(`No section "${section}". Sections: ${Object.keys(doc).join(', ')}.`); - return doc[section]; - }; - const catalog = (name) => { - if (name === undefined || name === null || name === '') { - return { tables: [...Object.keys(API_TABLES), ...Object.keys(API_MADE)].sort().map((k) => { const t = k in API_MADE ? API_MADE[k]() : API_TABLES[k]; - return { name: k, n: Array.isArray(t) ? t.length : t && typeof t === 'object' ? Object.keys(t).length : 1 }; }) }; - } - if (name in API_MADE) return apiJson(API_MADE[name]()); - if (name in API_TABLES) return apiJson(API_TABLES[name]); - fail(`No table "${name}". Call catalog without a name for the list.`); - }; - const state = (path) => { if (!S) return null; const v = apiJson(apiPath(S, path)); return v === undefined ? null : v; }; - const results = (path) => { const v = apiJson(apiPath(R, path)); return v === undefined ? null : v; }; - const ui = () => { const o = {}; for (const k of Object.keys(UI)) if (!API_UI_HIDDEN[k]) o[k] = apiJson(UI[k]); return o; }; - const actions = () => { - const sig = (s) => (s.args || []).map((a) => a[0] + (a[2] === false ? '?' : '')).join(','); - const typed = {}; - for (const t of [API_CMD, API_VIEW, API_SESSION]) for (const [n, s] of Object.entries(t)) typed[n] = sig(s); - return { typed, drafts: Object.keys(API_BOUND) }; - }; - - // ---------- doing things ---------- - // Arguments: shape and domain only. Anything beyond that is the game's to answer. - const validate = (spec, args) => { - const problems = [], out = {}; - for (const [name, dom, req] of spec.args || []) { - const v = args[name]; - if (v === undefined) { if (req !== false) problems.push(`${name} is required`); continue; } - if (apiDomCheck(dom, v).ok) { out[name] = v; continue; } - const vs = apiDomValues(dom), d = API_DOMAINS[dom]; - problems.push(`${name}: ${JSON.stringify(v)} is not a ${dom}${d && d.table && d.kind === 'id' ? ` (see catalog ${d.table} or find)` : Array.isArray(vs) ? ` (one of ${vs.slice(0, 12).join(', ')}${vs.length > 12 ? '…' : ''})` : vs && typeof vs === 'object' && vs.from !== undefined ? ` (${vs.from}..${vs.to})` : ''}`); - } - for (const k of Object.keys(args)) if (!(spec.args || []).some((a) => a[0] === k)) problems.push(`${k} is not an argument of this action`); - return { ok: !problems.length, problems, args: out }; - }; - // The fingerprint tells "did nothing" from "did something quietly": cash, day, the entity counts, the small - // settings maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action. - const FP_LEN = ['links', 'transit', 'pni', 'caches', 'biz', 'offers', 'nni', 'loans', 'loanOffers', 'inc', 'scrubs']; - const FP_KEYS = ['pops', 'ixp', 'peers', 'myIx', 'done', 'ach', 'merged', 'confReg']; - const FP_JSON = ['name', 'pairMet', 'rs', 'ixn', 'ixSite', 'ixPref', 'spares', 'te', 'cnLic', 'hw', 'scrubMode', 'ppol', 'ops', 'core', 'ddosAuto', 'popStd', 'demo', 'charter', 'monkey', 'seatOff', 'pz', 'ar', 'dk', 'ev']; - const fp = (watch, args) => { - if (!S) return null; - const f = { cash: S.cash, day: S.day, lvl: S.lvl || 1, won: !!S.won, lost: !!S.lost }; - for (const k of FP_LEN) f[k] = (S[k] || []).length; - for (const k of FP_KEYS) f[k] = Object.keys(S[k] || {}).length; - for (const k of FP_JSON) f[k] = JSON.stringify(apiJson(S[k]) ?? null); - for (const p of watch || []) f['@' + p] = JSON.stringify(apiJson(apiPath(S, String(p).replace(/#(\w+)/g, (m, k) => (args && args[k] !== undefined ? args[k] : m)))) ?? null); - return JSON.stringify(f); - }; - // spend() is the game's money gate and a top-level function, so every action reaches it by its global name. - const meter = () => { const real = window.spend; let paid = 0; window.spend = (c) => { const ok = real(c); if (ok) paid += c; return ok; }; return () => { window.spend = real; return paid; }; }; - - // One action, run as the game runs it, and reported: what the game said (toasts), what it charged at the money gate - // (goal rewards that land in the same call are not a price), whether anything changed, and what is on screen now. - // typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button - // click does it, with the button's own arguments. - const dispatch = (name, kind, spec, args, typed) => { - const mine = isSheet() || (typed && kind === 'game' && !!spec.open); - takeToasts(); - const ref = S, cash = S ? S.cash : 0, f0 = fp(spec && spec.watch, args), paid = meter(); - let threw = null, report; - try { - if (typed && kind === 'game') { - if (spec.open) { ACT[spec.open]({}); markSheet(); } - // The custom metric's field lives in the link's panel. - if (name === 'metricSet' && !$('metIn')) { UI.sel = { type: 'link', id: args.id }; renderAll(); } - const gone = (spec.dom || []).filter((f) => !$(f)); - if (gone.length) throw new Error(`the field it types into (${gone.join(', ')}) is not on screen${name === 'metricSet' ? ': set the link\'s metric to custom first (setMetric v "custom")' : ''}`); - if (spec.bind) spec.bind(args); - const a = spec.pass ? spec.pass(args) : args; - ACT[name](a); - if (spec.confirm === 'double') ACT[name](a); - if (spec.reads === 'modal' && modalOpen()) { report = text($('modal')); closeModal(); } - } else ACT[name](args); - } catch (e) { threw = e; } - const charged = paid(); - if (threw) { takeToasts(); fail(`${name} failed: ${threw && threw.message || threw}`); } - if (!modalOpen()) sheet = null; - else if (mine || kind !== 'game') markSheet(); - else sheet = null; - const said = takeToasts(), d = decision(); - const outcome = d ? 'decision' : S !== ref || fp(spec && spec.watch, args) !== f0 || report !== undefined ? 'applied' - : said.some((t) => t.kind === 'bad') ? 'rejected' : kind === 'view' || kind === 'draft' ? 'shown' : 'no_effect'; - return { action: name, outcome, toasts: toastLines(said), charged, cashChange: Math.round((S ? S.cash : 0) - cash), - ...(report !== undefined ? { report } : {}), ...(d ? { decision: d } : {}), screen: screen() }; - }; - // While the game waits for an answer, game commands other than its options report the question instead. - const waiting = (name) => { - const d = decision(); - return d && name !== 'closeModal' && !d.options.some((o) => o.command === name) - ? { action: name, outcome: 'decision', reason: 'A window is waiting for an answer: run one of its options, or closeModal.', decision: d, screen: screen() } : null; - }; - const quote = (name, spec, args) => { - const ui0 = {}; - for (const k of spec.bindsUI || []) ui0[k] = UI[k]; - const f0 = fp(spec.watch, args); - // A dry run must not use up the dice: some helpers draw (a PNI's lead time), and a draw here would move the seeded - // game. They get the middle of the range instead, so a drawn figure in a quote is a typical one. - const dice = Math.random; - Math.random = () => 0.5; - let q = {}; - try { - if (spec.bind && !spec.dom) spec.bind(args); - if (spec.quote) q = spec.quote(args) || {}; - } catch (e) { fail(`${name}: the price could not be worked out: ${e && e.message || e}`); } finally { Math.random = dice; for (const k of Object.keys(ui0)) UI[k] = ui0[k]; } - return { action: name, outcome: 'quote', quote: { setup: 0, monthly: 0, ...q, blocked: (q.blocked || []).map((b) => text(String(b), 400)) }, consistent: fp(spec.watch, args) === f0, - ...(spec.quote ? {} : { note: 'This command has no price of its own: it costs nothing up front.' }) }; - }; - const run = (name, args, opts = {}) => { - name = String(name || ''); - if (name.startsWith('view.')) name = name.slice(5); - const no = denied(name); - if (no) fail(`${name} is not available here: ${no}.`); - const kind = kindOf(name); - if (!kind || typeof ACT[name] !== 'function') fail(`There is no action "${name}". See actions or schema.`); - args = args && typeof args === 'object' && !Array.isArray(args) ? args : {}; - const spec = specOf(name); - if (spec) { const v = validate(spec, args); if (!v.ok) fail(`${name}: ${v.problems.join('; ')}. See schema for its arguments.`); args = v.args; } - if (kind === 'game') { - if (S && S.lost && name !== 'closeModal') return { action: name, outcome: 'stopped', reason: 'The network went bankrupt: start or load another game.' }; - const w = waiting(name); - if (w) return w; - if (opts.dryRun) return quote(name, spec, args); - } else if (opts.dryRun) fail(`${name} has no price: only game commands (see schema commands) dry-run.`); - return dispatch(name, kind, spec, args, true); - }; - const click = (n, value) => { - const b = last[n]; - if (!b) fail(`No button ${n} on the last screen. Call screen first.`); - if (b.disabled) fail(`"${b.label}" is greyed out.`); - const name = b.select || b.act, args = b.select ? { v: value === undefined ? undefined : String(value) } : b.args; - if (b.select && !b.options.some((o) => o.value === args.v)) fail(`"${b.label}" is a list: click it with a value, one of ${b.options.map((o) => JSON.stringify(o.value)).join(', ')}.`); - const no = denied(name); - if (no) fail(`${name} is not available here: ${no}.`); - const kind = kindOf(name); - if (!kind || typeof ACT[name] !== 'function') fail(`"${b.label}" runs ${name}, which is not an action.`); - if (kind === 'game') { const w = waiting(name); if (w) return { clicked: b.label, ...w }; } - return { clicked: b.label, ...dispatch(name, kind, specOf(name), args, false) }; - }; - const panel = ({ city: c, link, network: q, tab, left }) => { - if (left !== undefined) { if (!['goals', 'deals', 'noc', 'nets'].includes(left)) fail('left is one of goals, deals, noc, nets.'); ACT.leftTab({ t: left }); return screen('left'); } - if (c) UI.sel = { type: 'city', id: cityOf(c).id }; - else if (link) { if (!S.links.some((l) => l.id === link)) fail(`No link ${link}. See status or hot_spots for link ids.`); UI.sel = { type: 'link', id: link }; } - else if (q) ACT.netFocus({ id: netOf(q).id }); - if (tab) UI.tab = tab; - renderAll(); - return screen(q ? 'left' : 'panel'); - }; - const openLink = (a, b) => { - const x = cityOf(a).id, y = cityOf(b).id; - if (!S.pops[x]) fail(`A link starts at one of your POPs: ${Object.keys(S.pops).map(cityName).join(', ')}.`); - takeToasts(); - openLinkModal(x, y); - markSheet(); - return { toasts: toastLines(takeToasts()), screen: screen() }; - }; - - // ---------- time ---------- - const advance = (days = 1) => { - days = Math.max(1, Math.min(3650, Math.floor(+days) || 1)); - if (modalOpen()) fail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.'); - sheet = null; - const start = S.day, cash = S.cash, inc0 = new Set(S.inc.map((i) => i.id)), times = []; - takeToasts(); - let ran = 0, stop = null; - while (ran < days) { - if (S.lost) { stop = 'bankrupt'; break; } - const t = performance.now(); - dayTick(); - times.push({ day: S.day, ms: r1(performance.now() - t) }); - ran++; - if (modalOpen()) { stop = 'a window opened'; break; } - } - renderAll(); - // The log keeps what mattered; toasts that only repeat a log line are left out. - const entries = (S.log || []).filter((e) => e.d > start).slice(-60), logged = entries.map((e) => norm(text(e.t, 400))); - const log = entries.map((e) => `${dateStr(e.d)}: ${text(e.t, 400)}`); - const total = times.reduce((a, x) => a + x.ms, 0), d = stop === 'a window opened' ? decision() : null; - return { - from: dateStr(start), to: dateStr(S.day), daysRun: ran, stoppedBecause: stop, cash: Math.round(S.cash), cashChange: Math.round(S.cash - cash), - newIncidents: S.inc.filter((i) => !inc0.has(i.id)).map(incText), - log, toasts: [...new Set(toastLines(takeToasts()))].filter((t) => { const f = norm(t.replace(/^\w+: /, '').split('\n')[0]); return !logged.some((l) => l.startsWith(f)); }).slice(-40), - timing: { totalMs: r1(total), perDayMs: r1(total / (ran || 1)), slowestDays: times.slice().sort((a, b) => b.ms - a.ms).slice(0, 5).map((x) => ({ date: dateStr(x.day), ms: x.ms })) }, - ...(d ? { decision: d } : {}), - screen: stop === 'a window opened' ? screen() : undefined, - }; - }; - - window.__mcp = { newGame, loadSave, exportSave, status, network, city, find, trace, peering, hotSpots, run, click, panel, openLink, actions, advance, screen, - schema, catalog, state, results, ui, classes }; -})(); diff --git a/scripts/lib/page.js b/scripts/lib/page.js index 880af5c..b905f26 100644 --- a/scripts/lib/page.js +++ b/scripts/lib/page.js @@ -3,8 +3,14 @@ // The result is the same single, self-contained index.html the game has always shipped: one request, // no module loader, no runtime cost. See docs/ARCHITECTURE.md ("Source layout") and docs/adr/. // +// A line `` is the same, but only in the development page (dev: true): the +// tools' side of the game (src/agent/, the agent facade the MCP server drives) for npm run dev, the +// MCP server's own page and the tests that ask for it. Everywhere else the line is dropped whole, so +// the page players get is exactly what it would be without it (docs/adr/0004-dev-only-code.md). +// // node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default) -// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests and npm run dev use) +// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests use) +// node scripts/lib/page.js --source --dev [-o FILE] the development page: with src/agent/ (what npm run dev serves) // node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref // // --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before @@ -15,7 +21,7 @@ const path = require('node:path'); const { execFileSync } = require('node:child_process'); const ROOT = path.join(__dirname, '..', '..'); -const INCLUDE = /^$/; +const INCLUDE = /^$/; // Every file under dir, as paths relative to dir with '/' separators, in a stable order // (plain code-unit comparison, so the order never depends on the machine's locale). @@ -45,7 +51,8 @@ function partials(src, dir) { } // The assembled page as a string, plus a map of which output line came from which source file. -function assemble({ src = path.join(ROOT, 'src') } = {}) { +// dev: also the @include-dev parts (the development page); without it, their lines are left out entirely. +function assemble({ src = path.join(ROOT, 'src'), dev = false } = {}) { const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8'); const out = [], map = []; let line = 1; @@ -57,7 +64,8 @@ function assemble({ src = path.join(ROOT, 'src') } = {}) { line++; return; } - for (const p of partials(src, m[1])) { + if (m[1] && !dev) return; + for (const p of partials(src, m[2])) { const n = p.text.split('\n').length - 1; map.push({ file: p.file, from: line, to: line + n - 1 }); out.push(p.text); @@ -104,7 +112,7 @@ module.exports = { assemble, assembleRef, shipped, pageFile, locate, listFiles, if (require.main === module) { const args = process.argv.slice(2); const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; }; - const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble().html : shipped().html; + const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev') }).html : shipped().html; const out = opt('-o'); if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); } else process.stdout.write(html); diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js new file mode 100644 index 0000000..bdbb762 --- /dev/null +++ b/src/agent/10-domains.js @@ -0,0 +1,104 @@ +/* ================= AGENT API: argument domains ================= + The agent facade (window.TUBES, this folder) is how tools play the game: the MCP server (scripts/mcp.js) calls it in + its own jsdom page. It is part of the development page only (): the page players get has + none of it, so nothing in src/game/ may name anything defined here. Nothing here runs until a tool calls it: these + files only define tables and functions. + A domain is what an argument may be: an id in a catalog table, a key, an index, a small fixed list, or a check. */ +const API_DOMAINS={ + // Tables from the catalog: an id in a list, a key in an object, or an index into a list. + cityId:{table:'CITIES',kind:'id'}, + netId:{table:'NETS',kind:'id'}, + cableId:{table:'CABLES',kind:'id'}, + fabId:{table:'FAB',kind:'key'}, + opticId:{table:'OPT',kind:'key'}, + systemId:{table:'DF_SYS',kind:'key'}, + designId:{table:'SEA_DESIGNS',kind:'key'}, + upgradeId:{table:'SUB_UPGRADES',kind:'key'}, + bizTypeId:{table:'BIZ_T',kind:'key'}, + portTier:{table:'PORT',kind:'index'}, + linkTier:{table:'LT',kind:'index'}, + nniTier:{table:'NNI',kind:'index'}, + vxcTier:{table:'VXC',kind:'index'}, + routerModel:{table:'RG',kind:'index'}, + scrubTier:{table:'SCRUB_TIERS',kind:'index'}, + // Small fixed vocabularies the game itself checks by list membership. + // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). + metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, + egress:{table:'PREF',kind:'key'}, + routeMode:{table:'RT',kind:'key'}, + site:{kind:'enum',values:['a','b','ab']}, + step:{kind:'enum',values:[1,-1]}, + connKind:{kind:'enum',values:['t','p','ix','c','nni']}, + egressKind:{kind:'enum',values:['t','p','ix','c','nni','l2']}, + peerPolicy:{table:'PPOL',kind:'enum'}, + // The intern, their orders and the new-POP template (opsHire, opsToggle, opsParam…). + internId:{table:'INTERNS',kind:'key'}, + opsKey:{table:'OPSK',kind:'key'}, + opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, + opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, + // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. + seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, + charterKey:{table:'CHARTERS',kind:'key'}, + // The link metric editor: a factor or an exact weight (metricMode, metricSet). + metricKind:{kind:'enum',values:['f','w']}, + // The NOC's auto-mitigation switches (ddosAuto). + ddosKey:{kind:'enum',values:['rtbh','scrub']}, + // Puzzle and architect builds: the tiers a puzzle may light, the router models it offers. + pztTier:{kind:'fn',ok:v=>PZ_TIERS.includes(+v)||AR_TIERS.includes(+v)}, + pzRouterModel:{table:'PZ_RG',kind:'index'}, + pzRouteMode:{kind:'enum',values:['normal','fast']}, + // The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll). + pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])}, + dashTab:{kind:'enum',values:()=>DTABS.slice()}, + dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']}, + leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, + netFilter:{kind:'enum',values:['all','out']}, + pniFilter:{kind:'enum',values:['all','t','worth','pni']}, + listPage:{kind:'enum',values:['conn','cust','nets','pni']}, + custSortKey:{kind:'enum',values:['mood','mo','name','city']}, + connFilter:{kind:'enum',values:['all','k']}, + connSortKey:{kind:'enum',values:['k','city','name','use','mo']}, + dfSource:{kind:'enum',values:['lease','build','cable']}, + cityIdArray:{kind:'array',of:'cityId'}, + // Anything a panel can reach: an exchange city, a rival exchange id, one of your own exchanges. + ixId:{kind:'fn',ok:v=>isIx(v)}, + // A PNI also takes tier:-1, the 1G courtesy port a network may offer (ACT.pni). + pniTier:{kind:'fn',ok:v=>v===-1||(Number.isInteger(v)&&v>=0&&vtypeof v==='string'&&upcomingConfs(75).some(c=>c.key===v)}, + // traceroute goes to your own POPs and to networks; traceModal parses a net:/city: prefix. + traceTo:{kind:'fn',ok:v=>typeof v==='string'&&(NET[v]||isCity(v))}, + // Entity ids (uid()) cannot be validated against a table: shape only. A wrong id is the game's + // to answer, honestly, with no_effect — never a refusal invented on this side of the wall. + entityId:{kind:'string'}, + scnId:{table:'SCN',kind:'id'}, + // A traceroute target in the modal's own terms. +}; + +/* Type names an arg can take instead of a domain: 'string' | 'boolean' | 'integer'. */ + +function apiDomCheck(dom,v){ + const d=API_DOMAINS[dom]; + // The game's own buttons ship truthiness as 0 and 1 (custOpen's {"sad":0}); accept the game's dialect. + if(dom==='boolean')return {ok:v===true||v===false||v===0||v===1}; + if(!d)return {ok:dom==='integer'?Number.isInteger(v):typeof v===dom}; // 'string' | 'integer' + if(d.kind==='array')return {ok:Array.isArray(v)&&v.every(x=>apiDomCheck(d.of,x).ok)}; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='id')return {ok:!!t&&t.some(x=>x&&x.id===v)}; + if(d.kind==='string')return {ok:typeof v==='string'}; + if(d.kind==='key'||d.kind==='enum'){ + const vs=d.kind==='key'?Object.keys(t||{}):(t||(typeof d.values==='function'?d.values():d.values)||[]); + return {ok:vs.includes(v)};} + if(d.kind==='index')return {ok:Number.isInteger(v)&&v>=0&&v<(t?t.length:0)}; + return {ok:!!d.ok&&d.ok(v)}; +} +function apiDomValues(dom){ + const d=API_DOMAINS[dom];if(!d)return null; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='array')return {of:d.of}; + if(d.kind==='id')return t?t.map(x=>x.id):[]; + if(d.kind==='key')return t?Object.keys(t):[]; + if(d.kind==='enum')return t||(typeof d.values==='function'?d.values():d.values)||[]; + if(d.kind==='index')return {from:0,to:(t?t.length:1)-1}; + return null; +} diff --git a/scripts/lib/mcp-commands.js b/src/agent/20-commands.js similarity index 66% rename from scripts/lib/mcp-commands.js rename to src/agent/20-commands.js index eac4c1d..2669c80 100644 --- a/scripts/lib/mcp-commands.js +++ b/src/agent/20-commands.js @@ -1,115 +1,13 @@ -// Runs inside the game page before scripts/lib/mcp-page.js, in the game's own global scope: the typed command -// tables the MCP server's act tool dispatches through. Data and small helpers only, no state. -// -// Every action in ACT is in exactly one class (tests/mcp-commands.test.js fails otherwise, so a new action forces a -// decision): CMD, a game command with typed arguments; VIEW, which changes only what is on screen; BOUND, which only -// drafts an input another command reads; SESSION, which starts, retries or leaves a game or dismisses a coaching -// screen; or the server's DENY list (scripts/lib/mcp-page.js). CMD fields: args [name, domain|'string'|'boolean'|'integer', required]; bind(args) writes the UI -// a panel would set (bindsUI: the UI keys it touches, restored after a dry run); open/dom: the window an input lives -// in and the fields that must exist before dispatch; pass(args) reshapes the args for the action (confirmations); -// confirm 'arg' (passed through) or 'double' (the game arms a button first); decides (may end in a question); reads -// 'modal' (the window's text is the report); watch (extra fingerprint paths, #name filled from args); quote (the dry -// run, priced with the game's own helpers); doc. -window.__mcpCmds = (() => { -const API_DOMAINS={ - // Tables from the catalog: an id in a list, a key in an object, or an index into a list. - cityId:{table:'CITIES',kind:'id'}, - netId:{table:'NETS',kind:'id'}, - cableId:{table:'CABLES',kind:'id'}, - fabId:{table:'FAB',kind:'key'}, - opticId:{table:'OPT',kind:'key'}, - systemId:{table:'DF_SYS',kind:'key'}, - designId:{table:'SEA_DESIGNS',kind:'key'}, - upgradeId:{table:'SUB_UPGRADES',kind:'key'}, - bizTypeId:{table:'BIZ_T',kind:'key'}, - portTier:{table:'PORT',kind:'index'}, - linkTier:{table:'LT',kind:'index'}, - nniTier:{table:'NNI',kind:'index'}, - vxcTier:{table:'VXC',kind:'index'}, - routerModel:{table:'RG',kind:'index'}, - scrubTier:{table:'SCRUB_TIERS',kind:'index'}, - // Small fixed vocabularies the game itself checks by list membership. - // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). - metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, - egress:{table:'PREF',kind:'key'}, - routeMode:{table:'RT',kind:'key'}, - site:{kind:'enum',values:['a','b','ab']}, - step:{kind:'enum',values:[1,-1]}, - connKind:{kind:'enum',values:['t','p','ix','c','nni']}, - egressKind:{kind:'enum',values:['t','p','ix','c','nni','l2']}, - peerPolicy:{table:'PPOL',kind:'enum'}, - // The intern, their orders and the new-POP template (opsHire, opsToggle, opsParam…). - internId:{table:'INTERNS',kind:'key'}, - opsKey:{table:'OPSK',kind:'key'}, - opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, - opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, - // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. - seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, - charterKey:{table:'CHARTERS',kind:'key'}, - // The link metric editor: a factor or an exact weight (metricMode, metricSet). - metricKind:{kind:'enum',values:['f','w']}, - // The NOC's auto-mitigation switches (ddosAuto). - ddosKey:{kind:'enum',values:['rtbh','scrub']}, - // Puzzle and architect builds: the tiers a puzzle may light, the router models it offers. - pztTier:{kind:'fn',ok:v=>PZ_TIERS.includes(+v)||AR_TIERS.includes(+v)}, - pzRouterModel:{table:'PZ_RG',kind:'index'}, - pzRouteMode:{kind:'enum',values:['normal','fast']}, - // The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll). - pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])}, - dashTab:{kind:'enum',values:()=>DTABS.slice()}, - dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']}, - leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, - netFilter:{kind:'enum',values:['all','out']}, - pniFilter:{kind:'enum',values:['all','t','worth','pni']}, - listPage:{kind:'enum',values:['conn','cust','nets','pni']}, - custSortKey:{kind:'enum',values:['mood','mo','name','city']}, - connFilter:{kind:'enum',values:['all','k']}, - connSortKey:{kind:'enum',values:['k','city','name','use','mo']}, - dfSource:{kind:'enum',values:['lease','build','cable']}, - cityIdArray:{kind:'array',of:'cityId'}, - // Anything a panel can reach: an exchange city, a rival exchange id, one of your own exchanges. - ixId:{kind:'fn',ok:v=>isIx(v)}, - // A PNI also takes tier:-1, the 1G courtesy port a network may offer (ACT.pni). - pniTier:{kind:'fn',ok:v=>v===-1||(Number.isInteger(v)&&v>=0&&vtypeof v==='string'&&upcomingConfs(75).some(c=>c.key===v)}, - // traceroute goes to your own POPs and to networks; traceModal parses a net:/city: prefix. - traceTo:{kind:'fn',ok:v=>typeof v==='string'&&(NET[v]||isCity(v))}, - // Entity ids (uid()) cannot be validated against a table: shape only. A wrong id is the game's - // to answer, honestly, with no_effect — never a refusal invented on this side of the wall. - entityId:{kind:'string'}, - scnId:{table:'SCN',kind:'id'}, - // A traceroute target in the modal's own terms. -}; - -/* Type names an arg can take instead of a domain: 'string' | 'boolean' | 'integer'. */ - -function apiDomCheck(dom,v){ - const d=API_DOMAINS[dom]; - // The game's own buttons ship truthiness as 0 and 1 (custOpen's {"sad":0}); accept the game's dialect. - if(dom==='boolean')return {ok:v===true||v===false||v===0||v===1}; - if(!d)return {ok:dom==='integer'?Number.isInteger(v):typeof v===dom}; // 'string' | 'integer' - if(d.kind==='array')return {ok:Array.isArray(v)&&v.every(x=>apiDomCheck(d.of,x).ok)}; - const t=d.table?API_CATALOG_TABLE(d.table):null; - if(d.kind==='id')return {ok:!!t&&t.some(x=>x&&x.id===v)}; - if(d.kind==='string')return {ok:typeof v==='string'}; - if(d.kind==='key'||d.kind==='enum'){ - const vs=d.kind==='key'?Object.keys(t||{}):(t||(typeof d.values==='function'?d.values():d.values)||[]); - return {ok:vs.includes(v)};} - if(d.kind==='index')return {ok:Number.isInteger(v)&&v>=0&&v<(t?t.length:0)}; - return {ok:!!d.ok&&d.ok(v)}; -} -function apiDomValues(dom){ - const d=API_DOMAINS[dom];if(!d)return null; - const t=d.table?API_CATALOG_TABLE(d.table):null; - if(d.kind==='array')return {of:d.of}; - if(d.kind==='id')return t?t.map(x=>x.id):[]; - if(d.kind==='key')return t?Object.keys(t):[]; - if(d.kind==='enum')return t||(typeof d.values==='function'?d.values():d.values)||[]; - if(d.kind==='index')return {from:0,to:(t?t.length:1)-1}; - return null; -} - +/* ================= AGENT API: the command tables ================= + Every action in ACT is in exactly one class (tests/mcp-commands.test.js fails otherwise, so a new action forces a + decision): API_CMD, a game command with typed arguments; API_VIEW, which changes only what is on screen; API_BOUND, + which only drafts an input another command reads; API_SESSION, which starts, retries or leaves a game or dismisses a + coaching screen; or API_DENY, never run by a tool. CMD fields: args [name, domain|'string'|'boolean'|'integer', + required]; bind(args) writes the UI a panel would set (bindsUI: the UI keys it touches, restored after a dry run); + open/dom: the window an input lives in and the fields that must exist before dispatch; pass(args) reshapes the args + for the action (confirmations); confirm 'arg' (passed through) or 'double' (the game arms a button first); decides + (may end in a question); reads 'modal' (the window's text is the report); watch (extra fingerprint paths, #name + filled from args); quote (the dry run, priced with the game's own helpers); doc. */ const API_CMD={ /* ---------- footprint: buildings, routers, POPs ---------- */ buildPop:{args:[['city','cityId']], @@ -611,7 +509,8 @@ const API_BOUND={ }; /* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run - as their buttons run them; new_game, load_save and export_save are the other half of the session (mcp-page.js). */ + as their buttons run them; new_game, load_save and export_save are the other half of the session, and exist only in + the MCP server's own page (scripts/lib/mcp-headless.js). */ const API_SESSION={ startScn:{args:[['id','scnId']],doc:'Start a scenario (ids from catalog SCN), replacing the current game.'}, startWeekly:{args:[],doc:'Start this week\'s weekly scenario, replacing the current game. The week follows the real date.'}, @@ -625,199 +524,18 @@ const API_SESSION={ tutSkip:{args:[],doc:'Skip the tutorial coaching.'}, }; -const API_STATE_DOC={ - v:{type:'integer',doc:'Save format version.'}, - name:{type:'string',doc:'Your network\'s name.'}, - asn:{type:'integer',doc:'Your AS number.'}, - home:{type:'string',doc:'The city you started in.'}, - day:{type:'integer',doc:'Days since the company was founded.'}, - cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, - priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, - mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, - rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, - charter:{type:'string',doc:'The charter picked in the first month of a normal game: global | boutique.'}, - chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, - solWon:{type:'integer',doc:'The day the Speed of Light win landed (boutique charter), or 0.'}, - lvl:{type:'integer',doc:'Customer level (unlocks customer types).'}, - ltv:{type:'integer',doc:'Level at which Tier 1 vendors were visible (title-screen pick).'}, - t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, - auV:{type:'integer',doc:'Australia content level gate.'}, - seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, - pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, - links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'}, - transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, - ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, - rs:{type:'map',doc:'Route-server sessions by exchange city.'}, - ixn:{type:'map',doc:'LAG members on IX ports by exchange city.'}, - ixSite:{type:'map',doc:'Which building each IX port sits in (a, b or ab).'}, - ixPref:{type:'map',doc:'Egress preference per IX port.'}, - myIx:{type:'map',doc:'Exchanges you founded: name, members, join schedule, fabric step.'}, - peers:{type:'map',doc:'Peering sessions, keyed "net@ix".'}, - pairMet:{type:'map',doc:'Routing metric per city pair (prefer/avoid/backup/normal), keyed by pair.'}, - pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'}, - caches:{type:'array',doc:'CDN cache boxes: city, net, building.'}, - nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, - biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates.'}, - offers:{type:'array',doc:'Pending customer offers, each expiring on a day.'}, - done:{type:'map',doc:'Goals landed, by goal id → day.'}, - ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, - inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'}, - ddosStarts:{type:'array',doc:'The days the attacks of the last week started; at most 14 a week.'}, - ev:{type:'map',doc:'Live world events: the running DDoS, route leaks, fabric failures, price shocks.'}, - stats:{type:'map',doc:'Counters: incidents survived, loans taken, sharks, conferences attended, peak traffic…'}, - log:{type:'array',doc:'The NOC notification feed, newest first, capped at 60; identical notices within a minute fold with a count.'}, - nextFail:{type:'integer',doc:'The day the next failure fires.'}, - nextEvent:{type:'integer',doc:'The day the next world event fires.'}, - rng:{type:'integer',doc:'The scenario seed; it predicts every future random draw.'}, - usedNames:{type:'array',doc:'Customer names already handed out.'}, - spares:{type:'map',doc:'Spare optics on the shelf, by optic id.'}, - scrubs:{type:'array',doc:'Scrubbing centres: city and tier.'}, - scrubMode:{type:'string',doc:'always | ondemand.'}, - cnLic:{type:'map',doc:'Mainland China licence: none | pending (with ready day) | ok.'}, - ppol:{type:'string',doc:'Your published peering policy: open | selective | closed.'}, - pdesk:{type:'map',doc:'This week\'s peering desk summary: sessions accepted and declined at which exchanges.'}, - pdeskRep:{type:'map',doc:'Last week\'s peering desk summary, as the NOC log reported it.'}, - ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings, the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, - core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, - ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, - popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'}, - demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, - seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, - monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, - fleet:{type:'map',doc:'Cable-ship voyages by ship id: the cut it sails to, when it arrives, splices and comes home.'}, - achP:{type:'map',doc:'Which rule set each badge was earned under (oncall, freeze, bgp), by badge id.'}, - calV:{type:'integer',doc:'Calendar save-format marker: 1 once the real calendar (28-31-day months) applies.'}, - pz:{type:'map',doc:'The running puzzle: its id, cities, flows to deliver, budget and stars.'}, - ar:{type:'map',doc:'The running architect run: its HQ, brief index, gold sites, spend and the build it started from.'}, - loans:{type:'array',doc:'Active loans: bank, balance, APR, term, share (equity banks).'}, - loanOffers:{type:'array',doc:'Pending loan offers.'}, - loanStrikes:{type:'integer',doc:'How many loan offers you have let lapse.'}, - confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'}, - hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'}, - capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'}, - cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'}, - uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'}, - won:{type:'boolean',doc:'You reached Tier 1.'}, - t1Now:{type:'boolean',doc:'Tier 1 right now, as of the last day; falling out of it is announced.'}, - lost:{type:'boolean',doc:'The bank repossessed the routers.'}, - neg:{type:'integer',doc:'Days in the red in a row.'}, - hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'}, - scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'}, - dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'}, - grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'}, - merged:{type:'map',doc:'Networks merged into others this game.'}, - tut:{type:'map',doc:'Tutorial progress.'}, - conf:{type:'map',doc:'The conference glow: region and until when; sp when you sponsored.'}, - phpDone:{type:'boolean',doc:'One-shot flag.'}, - krExit:{type:'map',doc:'Korea exit state.'}, - auNews:{type:'boolean',doc:'One-shot flag: the Australia news toast.'}, - richTold:{type:'boolean',doc:'One-shot flag: the cash milestone toast.'}, +/* Actions no tool runs, by reason: files, storage slots, settings and the title screen are not the game's, and time + moves only through advance (or the page's own clock). */ +const API_WHY={ + time:'use advance to move time',start:'use new_game',files:'use load_save or export_save', + slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game', + browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', }; - -const API_RESULTS_DOC={ - nt:{type:'map',doc:'Traffic per network through transit, by net id.'}, - tNet:{type:'map',doc:'Traffic per network you hand to each upstream, by "net@upstream".'}, - reachNT:{type:'number',doc:'Networks reachable without transit.'}, - teBlack:{type:'number',doc:'Traffic blackholed by RouteScript rules.'}, - teMoved:{type:'number',doc:'Traffic Auto-TE spilled onto alternate paths.'}, - egT:{type:'map',doc:'Egress split by exit kind (c/p/ix/t/l2) in Gbps.'}, - egDesc:{type:'map',doc:'RouteScript drains per exit.'}, - netEg:{type:'map',doc:'Per-network egress split: which exit carries which network.'}, - ef:{type:'map',doc:'LAZY per-link exit breakdown: what crosses each link, per network, built only when a panel asks. What is in here depends on which panels have rendered.'}, - l2:{type:'map',doc:'Layer-2 traffic per customer (L2VPN, SD-WAN, waves).'}, - l2lat:{type:'map',doc:'Latency per L2 customer.'}, - l2route:{type:'map',doc:'Which path an L2 customer\'s traffic takes.'}, - l2split:{type:'map',doc:'L2 traffic split per path.'}, - nodeLoad:{type:'map',doc:'Router forwarding load per city.'}, - nodeCap:{type:'map',doc:'Router forwarding capacity per city.'}, - div:{type:'map',doc:'Traffic diversity per customer (how split their paths are).'}, - gfwLost:{type:'number',doc:'Traffic lost to the Great Firewall.'}, - gfwCross:{type:'number',doc:'Traffic crossing into mainland China.'}, - p95:{type:'map',doc:'95th-percentile transit readings per port.'}, - peered:{type:'number',doc:'Share of traffic that stays on peering.'}, - peerShare:{type:'number',doc:'Fraction of traffic served by peers (mood driver).'}, - load:{type:'map',doc:'Load per link in Gbps.'}, - useT:{type:'map',doc:'Transit use per port id.'}, - useIx:{type:'map',doc:'IX use per exchange city.'}, - usePni:{type:'map',doc:'PNI use per port id.'}, - useCache:{type:'map',doc:'Cache use per box id.'}, - cityDem:{type:'map',doc:'Eyeball + customer demand per city.'}, - citySrv:{type:'map',doc:'Traffic served per city.'}, - cityEye:{type:'map',doc:'Eyeballs online per city.'}, - latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, - latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, - demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, - served:{type:'number',doc:'Total traffic served, in Gbps.'}, - demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, - reach:{type:'number',doc:'Fraction of the internet you can reach (0..1).'}, - sessions:{type:'number',doc:'Peering sessions up.'}, - revMo:{type:'number',doc:'Revenue per month.'}, - costMo:{type:'number',doc:'Cost per month.'}, - cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'}, - rev:{type:'map',doc:'Monthly revenue by source.'}, - reachable:{type:'map',doc:'Networks reachable per net id.'}, - cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'}, - ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'}, - haul:{type:'array',doc:'Scrubbing detours: from the attacked city to each centre, one-way latency and how much they carry.'}, - tgtF:{type:'map',doc:'The share of a targeted customer\'s traffic that survives the attack, by customer id.'}, - bbF:{type:'map',doc:'The share of a city\'s broadband subscribers that survive an attack on them, by city id.'}, - fsUse:{type:'map',doc:'Flowspec rules in use per city: used of the routers\' rule capacity.'}, - bizDem:{type:'map',doc:'Business customers\' share of each city\'s demand, in Gbps (what RouteScript\'s protect customers serves first).'}, - bizSrv:{type:'map',doc:'Of that business demand, what was served, per city.'}, - graceNets:{type:'number',doc:'Networks reached over the courtesy route after a merger wave.'}, - cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'}, - ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'}, +const API_DENY={ + speed:'time',phonePlay:'time',phoneSpeed:'time', + start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', + exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', + slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', + animSet:'prefs',langSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', + install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', }; - -/* One arg of a spec as the schema states it: the domain when there is one (catalog() resolves - it), the bare type otherwise, and the concrete value list or range where it is fixed. */ -function apiArgSpec([name,dom,req]){ - const a={name,required:req!==false}; - if(API_DOMAINS[dom])a.domain=dom;else a.type=dom; - const v=apiDomValues(dom); - if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v; - return a;} - -/* Dotted subtrees, no wildcards. An array walks by index (`biz.3`) or by entity id (`links[#id]`). */ -function apiPath(o,p){ - if(p===undefined||p===null||p==='')return o; - let v=o; - for(const k of String(p).split('.')){ - if(v==null)return undefined; - if(Array.isArray(v)){const i=Number(k); - v=(Number.isInteger(i)&&String(i)===k&&i>=0&&ix&&typeof x==='object'&&x.id===k);} - else if(v instanceof Set)v=[...v]; - else if(v instanceof Map)v=Object.fromEntries(v); - else if(typeof v==='object')v=v[k]; - else return undefined;} - return v;} - -function apiJson(v){ - if(v instanceof Set)return [...v].map(apiJson); - if(v instanceof Map)return apiJson(Object.fromEntries(v)); - if(v&&typeof v==='object')return Array.isArray(v)?v.map(apiJson):Object.fromEntries(Object.entries(v).map(([k,x])=>[k,apiJson(x)])); - if(typeof v==='function')return undefined; - return v;} - -/* The tables the argument domains point at. Everything is a static reference except three, - each computed for a reason: BADGES hides unearned secrets like the badge wall; conferences - carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders - each recipe's script, because the source is a function and some read the live network. The - recipes' relevance score is not exposed: judging which one fits is the agent's job. */ -const API_TABLES={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; -const API_MADE={ - BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; - return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), - conferences:()=>!S?[]:upcomingConfs(75).map(cf=>({key:cf.key,name:cf.n,city:cf.c,day:cf.day,capacity:!!cf.cap,cost:confCost(cf),sponsorCost:confSp(cf)?CONF_SP:null})), - TE_RECIPES:()=>!S?[]:TE_RECIPES.map(r=>({id:r.id,name:tr(r.n),description:tr(r.d),script:r.src().join('\n')})), -}; -function API_CATALOG_TABLE(name){return name in API_MADE?API_MADE[name]():API_TABLES[name];} - -/* UI minus the render caches and pointer scratch, which are inputs to nothing. - Everything a command binds (pending, route, via, dfSrc, dfSys, seaDesign, cnPrem, decom, - teDraft, confirm) stays, so an agent can see what it was given. */ -const API_UI_HIDDEN={_lh:1,_ph:1,_tb:1,_layer:1,layerAt:1,hover:1,drag:1,snap:1}; - -return {API_DOMAINS,API_CMD,API_VIEW,API_BOUND,API_SESSION,API_STATE_DOC,API_RESULTS_DOC,API_TABLES,API_MADE,API_UI_HIDDEN, - apiDomCheck,apiDomValues,apiArgSpec,apiPath,apiJson}; -})(); diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js new file mode 100644 index 0000000..3849db2 --- /dev/null +++ b/src/agent/30-docs.js @@ -0,0 +1,145 @@ +/* ================= AGENT API: what the state and the results hold ================= + One line per field of S and of R (tests/mcp-commands.test.js fails on a field without one). */ +const API_STATE_DOC={ + v:{type:'integer',doc:'Save format version.'}, + name:{type:'string',doc:'Your network\'s name.'}, + asn:{type:'integer',doc:'Your AS number.'}, + home:{type:'string',doc:'The city you started in.'}, + day:{type:'integer',doc:'Days since the company was founded.'}, + cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, + priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, + mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, + rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, + charter:{type:'string',doc:'The charter picked in the first month of a normal game: global | boutique.'}, + chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, + solWon:{type:'integer',doc:'The day the Speed of Light win landed (boutique charter), or 0.'}, + lvl:{type:'integer',doc:'Customer level (unlocks customer types).'}, + ltv:{type:'integer',doc:'Level at which Tier 1 vendors were visible (title-screen pick).'}, + t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, + auV:{type:'integer',doc:'Australia content level gate.'}, + seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, + pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'}, + transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, + ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, + rs:{type:'map',doc:'Route-server sessions by exchange city.'}, + ixn:{type:'map',doc:'LAG members on IX ports by exchange city.'}, + ixSite:{type:'map',doc:'Which building each IX port sits in (a, b or ab).'}, + ixPref:{type:'map',doc:'Egress preference per IX port.'}, + myIx:{type:'map',doc:'Exchanges you founded: name, members, join schedule, fabric step.'}, + peers:{type:'map',doc:'Peering sessions, keyed "net@ix".'}, + pairMet:{type:'map',doc:'Routing metric per city pair (prefer/avoid/backup/normal), keyed by pair.'}, + pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'}, + caches:{type:'array',doc:'CDN cache boxes: city, net, building.'}, + nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, + biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates.'}, + offers:{type:'array',doc:'Pending customer offers, each expiring on a day.'}, + done:{type:'map',doc:'Goals landed, by goal id → day.'}, + ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, + inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'}, + ddosStarts:{type:'array',doc:'The days the attacks of the last week started; at most 14 a week.'}, + ev:{type:'map',doc:'Live world events: the running DDoS, route leaks, fabric failures, price shocks.'}, + stats:{type:'map',doc:'Counters: incidents survived, loans taken, sharks, conferences attended, peak traffic…'}, + log:{type:'array',doc:'The NOC notification feed, newest first, capped at 60; identical notices within a minute fold with a count.'}, + nextFail:{type:'integer',doc:'The day the next failure fires.'}, + nextEvent:{type:'integer',doc:'The day the next world event fires.'}, + rng:{type:'integer',doc:'The scenario seed; it predicts every future random draw.'}, + usedNames:{type:'array',doc:'Customer names already handed out.'}, + spares:{type:'map',doc:'Spare optics on the shelf, by optic id.'}, + scrubs:{type:'array',doc:'Scrubbing centres: city and tier.'}, + scrubMode:{type:'string',doc:'always | ondemand.'}, + cnLic:{type:'map',doc:'Mainland China licence: none | pending (with ready day) | ok.'}, + ppol:{type:'string',doc:'Your published peering policy: open | selective | closed.'}, + pdesk:{type:'map',doc:'This week\'s peering desk summary: sessions accepted and declined at which exchanges.'}, + pdeskRep:{type:'map',doc:'Last week\'s peering desk summary, as the NOC log reported it.'}, + ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings, the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, + core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, + ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, + popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'}, + demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, + seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, + monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, + fleet:{type:'map',doc:'Cable-ship voyages by ship id: the cut it sails to, when it arrives, splices and comes home.'}, + achP:{type:'map',doc:'Which rule set each badge was earned under (oncall, freeze, bgp), by badge id.'}, + calV:{type:'integer',doc:'Calendar save-format marker: 1 once the real calendar (28-31-day months) applies.'}, + pz:{type:'map',doc:'The running puzzle: its id, cities, flows to deliver, budget and stars.'}, + ar:{type:'map',doc:'The running architect run: its HQ, brief index, gold sites, spend and the build it started from.'}, + loans:{type:'array',doc:'Active loans: bank, balance, APR, term, share (equity banks).'}, + loanOffers:{type:'array',doc:'Pending loan offers.'}, + loanStrikes:{type:'integer',doc:'How many loan offers you have let lapse.'}, + confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'}, + hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'}, + capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'}, + cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'}, + uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'}, + won:{type:'boolean',doc:'You reached Tier 1.'}, + t1Now:{type:'boolean',doc:'Tier 1 right now, as of the last day; falling out of it is announced.'}, + lost:{type:'boolean',doc:'The bank repossessed the routers.'}, + neg:{type:'integer',doc:'Days in the red in a row.'}, + hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'}, + scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'}, + dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'}, + grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'}, + merged:{type:'map',doc:'Networks merged into others this game.'}, + tut:{type:'map',doc:'Tutorial progress.'}, + conf:{type:'map',doc:'The conference glow: region and until when; sp when you sponsored.'}, + phpDone:{type:'boolean',doc:'One-shot flag.'}, + krExit:{type:'map',doc:'Korea exit state.'}, + auNews:{type:'boolean',doc:'One-shot flag: the Australia news toast.'}, + richTold:{type:'boolean',doc:'One-shot flag: the cash milestone toast.'}, +}; + +const API_RESULTS_DOC={ + nt:{type:'map',doc:'Traffic per network through transit, by net id.'}, + tNet:{type:'map',doc:'Traffic per network you hand to each upstream, by "net@upstream".'}, + reachNT:{type:'number',doc:'Networks reachable without transit.'}, + teBlack:{type:'number',doc:'Traffic blackholed by RouteScript rules.'}, + teMoved:{type:'number',doc:'Traffic Auto-TE spilled onto alternate paths.'}, + egT:{type:'map',doc:'Egress split by exit kind (c/p/ix/t/l2) in Gbps.'}, + egDesc:{type:'map',doc:'RouteScript drains per exit.'}, + netEg:{type:'map',doc:'Per-network egress split: which exit carries which network.'}, + ef:{type:'map',doc:'LAZY per-link exit breakdown: what crosses each link, per network, built only when a panel asks. What is in here depends on which panels have rendered.'}, + l2:{type:'map',doc:'Layer-2 traffic per customer (L2VPN, SD-WAN, waves).'}, + l2lat:{type:'map',doc:'Latency per L2 customer.'}, + l2route:{type:'map',doc:'Which path an L2 customer\'s traffic takes.'}, + l2split:{type:'map',doc:'L2 traffic split per path.'}, + nodeLoad:{type:'map',doc:'Router forwarding load per city.'}, + nodeCap:{type:'map',doc:'Router forwarding capacity per city.'}, + div:{type:'map',doc:'Traffic diversity per customer (how split their paths are).'}, + gfwLost:{type:'number',doc:'Traffic lost to the Great Firewall.'}, + gfwCross:{type:'number',doc:'Traffic crossing into mainland China.'}, + p95:{type:'map',doc:'95th-percentile transit readings per port.'}, + peered:{type:'number',doc:'Share of traffic that stays on peering.'}, + peerShare:{type:'number',doc:'Fraction of traffic served by peers (mood driver).'}, + load:{type:'map',doc:'Load per link in Gbps.'}, + useT:{type:'map',doc:'Transit use per port id.'}, + useIx:{type:'map',doc:'IX use per exchange city.'}, + usePni:{type:'map',doc:'PNI use per port id.'}, + useCache:{type:'map',doc:'Cache use per box id.'}, + cityDem:{type:'map',doc:'Eyeball + customer demand per city.'}, + citySrv:{type:'map',doc:'Traffic served per city.'}, + cityEye:{type:'map',doc:'Eyeballs online per city.'}, + latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, + latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, + demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, + served:{type:'number',doc:'Total traffic served, in Gbps.'}, + demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, + reach:{type:'number',doc:'Fraction of the internet you can reach (0..1).'}, + sessions:{type:'number',doc:'Peering sessions up.'}, + revMo:{type:'number',doc:'Revenue per month.'}, + costMo:{type:'number',doc:'Cost per month.'}, + cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'}, + rev:{type:'map',doc:'Monthly revenue by source.'}, + reachable:{type:'map',doc:'Networks reachable per net id.'}, + cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'}, + ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'}, + haul:{type:'array',doc:'Scrubbing detours: from the attacked city to each centre, one-way latency and how much they carry.'}, + tgtF:{type:'map',doc:'The share of a targeted customer\'s traffic that survives the attack, by customer id.'}, + bbF:{type:'map',doc:'The share of a city\'s broadband subscribers that survive an attack on them, by city id.'}, + fsUse:{type:'map',doc:'Flowspec rules in use per city: used of the routers\' rule capacity.'}, + bizDem:{type:'map',doc:'Business customers\' share of each city\'s demand, in Gbps (what RouteScript\'s protect customers serves first).'}, + bizSrv:{type:'map',doc:'Of that business demand, what was served, per city.'}, + graceNets:{type:'number',doc:'Networks reached over the courtesy route after a merger wave.'}, + cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'}, + ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'}, +}; diff --git a/src/agent/40-read.js b/src/agent/40-read.js new file mode 100644 index 0000000..9a5a123 --- /dev/null +++ b/src/agent/40-read.js @@ -0,0 +1,217 @@ +/* ================= AGENT API: reading the game ================= + Every function takes and returns plain JSON and only reads the game. */ +/* Dotted subtrees, no wildcards. An array walks by index (`biz.3`) or by entity id (`links[#id]`). */ +function apiPath(o,p){ + if(p===undefined||p===null||p==='')return o; + let v=o; + for(const k of String(p).split('.')){ + if(v==null)return undefined; + if(Array.isArray(v)){const i=Number(k); + v=(Number.isInteger(i)&&String(i)===k&&i>=0&&ix&&typeof x==='object'&&x.id===k);} + else if(v instanceof Set)v=[...v]; + else if(v instanceof Map)v=Object.fromEntries(v); + else if(typeof v==='object')v=v[k]; + else return undefined;} + return v;} + +function apiJson(v){ + if(v instanceof Set)return [...v].map(apiJson); + if(v instanceof Map)return apiJson(Object.fromEntries(v)); + if(v&&typeof v==='object')return Array.isArray(v)?v.map(apiJson):Object.fromEntries(Object.entries(v).map(([k,x])=>[k,apiJson(x)])); + if(typeof v==='function')return undefined; + return v;} + +/* The tables the argument domains point at. Everything is a static reference except three, + each computed for a reason: BADGES hides unearned secrets like the badge wall; conferences + carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders + each recipe's script, because the source is a function and some read the live network. The + recipes' relevance score is not exposed: judging which one fits is the agent's job. */ +const API_TABLES={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_MADE={ + BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; + return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), + conferences:()=>!S?[]:upcomingConfs(75).map(cf=>({key:cf.key,name:cf.n,city:cf.c,day:cf.day,capacity:!!cf.cap,cost:confCost(cf),sponsorCost:confSp(cf)?CONF_SP:null})), + TE_RECIPES:()=>!S?[]:TE_RECIPES.map(r=>({id:r.id,name:tr(r.n),description:tr(r.d),script:r.src().join('\n')})), +}; +function API_CATALOG_TABLE(name){return name in API_MADE?API_MADE[name]():API_TABLES[name];} + +/* UI minus the render caches and pointer scratch, which are inputs to nothing. + Everything a command binds (pending, route, via, dfSrc, dfSys, seaDesign, cnPrem, decom, + teDraft, confirm) stays, so an agent can see what it was given. */ +const API_UI_HIDDEN={_lh:1,_ph:1,_tb:1,_layer:1,layerAt:1,hover:1,drag:1,snap:1}; + +/* ---------- text as a player reads it ---------- */ +const API_BLOCK=/^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/,API_MAX_TEXT=8000; +// One line per block, no runs of spaces. jsdom has no innerText, so this walks the nodes itself. +function apiFullText(x){ + let el=x; + if(typeof x==='string'){el=document.createElement('div');el.innerHTML=x;} + if(!el)return ''; + const out=[]; + const walk=n=>{ + if(n.nodeType===3){out.push(n.nodeValue);return;} + if(n.nodeType!==1||n.hidden||/^(SCRIPT|STYLE|SVG|CANVAS)$/i.test(n.tagName))return; + if(n.tagName==='BR'){out.push('\n');return;} + // A dropdown reads as its choice: hundreds of options would crowd out the rest (the catalog lists them). + if(n.tagName==='SELECT'){const o=n.options[n.selectedIndex];out.push(' ',o?o.text:'',' ');return;} + // Blocks get their own line; inline tags a space, so "Revenue$2k" does not read as one word. + const sep=API_BLOCK.test(n.tagName)?'\n':' '; + out.push(sep);for(const c of n.childNodes)walk(c);out.push(sep);}; + walk(el); + return out.join('').split('\n').map(l=>l.replace(/\s+/g,' ').replace(/ ([.,;:!?)])/g,'$1').replace(/\( /g,'(').trim()).filter(Boolean).join('\n');} +const apiText=(x,max=API_MAX_TEXT)=>{const s=apiFullText(x);return s.length>max?s.slice(0,max)+'\n…':s;}; +const apiR1=v=>typeof v==='number'&&isFinite(v)?Math.round(v*10)/10:v; +const apiFail=msg=>{throw new Error(msg);}; +const apiNorm=s=>String(s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').trim(); +const apiParse=s=>{try{return JSON.parse(s||'{}');}catch(e){return {};}}; + +/* ---------- finding things by id or by name ---------- */ +function apiBest(list,q,keys){const n=apiNorm(q);if(!n)return null; + for(const test of [v=>v===n,v=>v.startsWith(n),v=>v.includes(n)]){const hit=list.find(x=>keys(x).some(k=>test(apiNorm(k))));if(hit)return hit;} + return null;} +const apiNetOf=q=>NET[q]||apiBest(NETS,q,n=>[n.id,n.name,'as'+n.asn,String(n.asn)])||apiFail(`No network matches "${q}". Try find.`); +const apiCityOf=q=>CITY[q]||apiBest(CITIES,q,c=>[c.id,c.name])||apiFail(`No city matches "${q}". Try find.`); +function apiAllIx(){const o=[];for(const c of CITIES)for(const x of ixStatic(c.id))o.push(x);for(const c of Object.keys(S.myIx||{}))if(!o.includes(c))o.push(c);return o;} +const apiCityName=c=>CITY[c]?CITY[c].name:c; +const apiIncText=i=>apiText(i.msg||incTitle(i),400); +const apiMyPops=()=>Object.keys(S.pops).map(apiCityName).join(', '); + +/* ---------- the network at a glance, and the world ---------- */ +function apiStatus(){ + const goal=GOALS.find(g=>S.done[g.id]===undefined),t1=isTier1(),k=o=>Object.fromEntries(Object.entries(o||{}).map(([a,v])=>[a,Math.round(v)]).filter(([,v])=>v)); + return { + name:S.name,asn:S.asn,home:apiCityName(S.home),mode:S.mode,rules:S.rules&&S.rules.preset, + day:S.day,date:dateStr(S.day),cash:Math.round(S.cash),level:S.lvl||0, + tier:tierLabel(),whyNotTier1:t1?null:apiText(t1Why()), + goal:goal?{title:apiText(goal.t),what:apiText(goal.d)}:null, + monthly:{revenue:Math.round(R.revMo),cost:Math.round(R.costMo),profit:Math.round(R.revMo-R.costMo),revenueBy:k(R.rev),costBy:k(R.cost)}, + traffic:{demandGbps:apiR1(R.demand),servedGbps:apiR1(R.served),reach:apiR1((R.reach||0)*100)+'%',peeringSessions:R.sessions}, + counts:{pops:Object.keys(S.pops).length,links:S.links.length,transitPorts:S.transit.length,exchangePorts:Object.keys(S.ixp).length, + pnis:S.pni.length,cacheBoxes:S.caches.length,customers:S.biz.length,offers:S.offers.length}, + pops:Object.keys(S.pops).map(apiCityName), + incidents:S.inc.map(i=>({id:i.id,type:i.type,what:apiIncText(i),until:i.until!==undefined?dateStr(i.until):undefined,rushRepairCost:i.cost||undefined})), + lost:!!S.lost,won:!!S.won, + };} + +function apiNetwork(q){ + const n=apiNetOf(q),id=n.id,eg=R.netEg&&R.netEg[id]; + return { + id,name:n.name,asn:n.asn,type:TYPE_L[n.type],policy:n.pol, + requirements:{minIxGbps:n.minIx,minPniGbps:n.minPni,paidFeePerMonth:n.paidFee,freeFromLevel:n.freeLv}, + trafficShare:apiR1(NSH[id]*100)+'%',transitPerGbps:n.price?apiR1(n.price*S.priceMul):null, + homeMarkets:n.cc?[].concat(n.cc):[],pops:n.pops.map(apiCityName), + exchanges:n.ix==='ALL'?'most exchanges where it has a PoP':(n.ix||[]).map(x=>ixName(x)), + upstreams:(n.up||[]).map(u=>NET[u]?NET[u].name:u),customerCone:(DOWN[id]||[]).length, + neededForTier1:t1Need().some(x=>x.id===id),mergedInto:merged(id)?(MERGERS.find(m=>m.id===id)||{}).into:undefined, + about:apiText(n.blurb), + you:{ + reachable:!!(R.reachable&&R.reachable[id]),demandGbps:apiR1((R.demTo&&R.demTo[id])||0), + egressGbps:eg?Object.fromEntries(Object.entries(eg).map(([k,v])=>[k,apiR1(v)])):null, + pnis:S.pni.filter(p=>p.net===id).map(p=>({id:p.id,city:apiCityName(p.city),port:pniPN(p),count:p.n||1,ready:pniOn(p)})), + exchangeSessions:Object.keys(S.ixp).filter(x=>ixSessions(x).has(id)).map(ixName), + howToPeer:apiText(offTransitHint(id,S.home)), + }, + };} + +function apiCity(q){ + const C=apiCityOf(q),c=C.id,P=S.pops[c]; + const cab=CABLE_PAIRS.filter(p=>p.a===c||p.b===c).map(p=>({cable:CAB[p.cid]?CAB[p.cid].name:p.cid,to:apiCityName(p.a===c?p.b:p.a),km:p.km})); + const here=NETS.filter(n=>n.pops.includes(c)&&!n.tail).sort((a,b)=>b.share-a.share); + return { + id:c,name:C.name,country:C.cc,region:C.reg,about:C.note?apiText(C.note):undefined,dataCenter:C.dc, + canBeHome:homeOk(c), + exchanges:ixIdsIn(c).map(x=>({id:x,name:ixName(x),members:ixMembers(x).length,yourPort:S.ixp[x]!==undefined})), + transit:NETS.filter(n=>sellsAt(n,c)).map(n=>({id:n.id,name:n.name,type:TYPE_L[n.type],perGbps:apiR1(transitPerG(n,c,false)*S.priceMul)})).sort((a,b)=>a.perGbps-b.perGbps), + networksHere:here.length,biggestNetworksHere:here.slice(0,15).map(n=>n.name),cables:cab, + you:P?{demandGbps:apiR1((R.cityDem||{})[c]||0),servedGbps:apiR1((R.citySrv||{})[c]||0),routers:P.routers,down:P.down>S.day?dateStr(P.down):false, + broadband:!!P.bb,links:S.links.filter(l=>l.a===c||l.b===c).length}:null, + };} + +function apiFind(q,kind){ + const n=apiNorm(q),hit=(...k)=>k.some(v=>apiNorm(v).includes(n)),out={}; + if(!n)apiFail('Give a word to search for.'); + if(!kind||kind==='city')out.cities=CITIES.filter(c=>hit(c.id,c.name)).slice(0,20).map(c=>({id:c.id,name:c.name,country:c.cc})); + if(!kind||kind==='network')out.networks=NETS.filter(x=>hit(x.id,x.name,String(x.asn))).slice(0,20).map(x=>({id:x.id,name:x.name,asn:x.asn,type:TYPE_L[x.type]})); + if(!kind||kind==='cable')out.cables=Object.values(CAB).filter(x=>hit(x.id,x.name)).slice(0,20).map(x=>({id:x.id,name:x.name,lands:[...new Set(x.pairs.flatMap(p=>[p[0],p[1]]))].map(apiCityName)})); + if(!kind||kind==='exchange')out.exchanges=apiAllIx().filter(x=>hit(x,ixName(x))).slice(0,20).map(x=>({id:x,name:ixName(x),city:apiCityName(ixCity(x))})); + return out;} + +function apiTrace(from,to){ + const src=apiCityOf(from).id; + if(!S.pops[src])apiFail(`You have no POP in ${apiCityName(src)}. Yours: ${apiMyPops()}.`); + let target=null; + if(typeof to==='string'&&/^city:/i.test(to))target={city:apiCityOf(to.slice(5)).id}; + else{try{target={net:apiNetOf(to).id};}catch(e){target={city:apiCityOf(to).id};}} + if(target.city&&!S.pops[target.city])apiFail(`A traceroute to a city goes to one of your POPs: ${apiMyPops()}.`); + const r=traceroute(src,target); + return {text:r.text,why:apiText(r.why||''),asPath:r.asPath||null};} + +function apiPeering(q,where,via){ + const n=apiNetOf(q),id=n.id,out=[]; + if(!via||via==='pni')for(const c of (where?[apiCityOf(where).id]:Object.keys(S.pops).filter(c=>n.pops.includes(c)))){ + const r=peerOk(id,'pni',c); + out.push({via:'pni',city:apiCityName(c),ok:!!r.ok,why:r.why?apiText(r.why):undefined,feePerMonth:r.fee,free:r.free,minimumPort:PORT[pniMin(id)].n});} + if(!via||via==='ix')for(const x of Object.keys(S.ixp).filter(x=>ixMembers(x).includes(id)&&(!where||ixCity(x)===apiCityOf(where).id))){ + const r=peerOk(id,'ix',x); + out.push({via:'ix',exchange:ixName(x),ok:!!r.ok,why:r.why?apiText(r.why):undefined,session:ixSessions(x).has(id)});} + return {network:n.name,policy:n.pol,hint:apiText(offTransitHint(id,where?apiCityOf(where).id:S.home)), + checks:out,note:out.length?undefined:'No POP or exchange port of yours is where this network is. Build one first: see network.'};} + +function apiHotSpots(limit=10){ + const top=a=>a.sort((x,y)=>y.util-x.util).slice(0,limit),pct=(u,c)=>c>0?apiR1((u/c)*100):null; + const links=S.links.map(l=>{const cap=capOf(l),u=(R.load||{})[l.id]||0;return {id:l.id,between:apiCityName(l.a)+' – '+apiCityName(l.b),kind:l.kind,capacity:capName(l),usedGbps:apiR1(u),util:pct(u,cap),down:linkDown(l)};}); + const transit=S.transit.map(t=>{const cap=lagCap(PORT[t.tier].g,t.n),u=(R.useT||{})[t.id]||0,q=(R.p95&&R.p95[t.id])||u; + return {id:t.id,city:apiCityName(t.city),carrier:NET[t.net].name,port:lagName(t.tier,t.n),usedGbps:apiR1(u),util:pct(u,cap),billPerMonth:Math.round(transitMo(t,q))};}); + const pnis=S.pni.filter(pniOn).map(p=>{const cap=pniG(p)*(p.n||1),u=(R.usePni||{})[p.id]||0;return {id:p.id,network:NET[p.net].name,city:apiCityName(p.city),port:pniPN(p),usedGbps:apiR1(u),util:pct(u,cap)};}); + const viaTransit=NETS.filter(n=>R.netEg&&R.netEg[n.id]&&R.netEg[n.id].t>0.05).sort((a,b)=>R.netEg[b.id].t-R.netEg[a.id].t).slice(0,limit) + .map(n=>({id:n.id,network:n.name,overTransitGbps:apiR1(R.netEg[n.id].t),howToPeer:apiText(offTransitHint(n.id,S.home))})); + const bill={};for(const t of transit)bill[t.carrier]=(bill[t.carrier]||0)+t.billPerMonth; + return {links:top(links),transitPorts:top(transit),pnis:top(pnis),transitBillByCarrier:bill,biggestTrafficStillOnTransit:viaTransit};} + +/* ---------- the contract: commands, arguments, reference tables, raw state ---------- */ +const apiDenied=name=>own(API_DENY,name)?API_WHY[API_DENY[name]]:null; +const apiKind=name=>API_CMD[name]?'game':API_VIEW[name]?'view':API_BOUND[name]?'draft':API_SESSION[name]?'session':null; +const apiSpec=name=>API_CMD[name]||API_VIEW[name]||API_SESSION[name]||null; +const apiClasses=()=>({game:Object.keys(API_CMD),view:Object.keys(API_VIEW),draft:Object.keys(API_BOUND),session:Object.keys(API_SESSION),denied:Object.keys(API_DENY)}); + +// One argument as the schema states it. Table domains name their catalog table rather than list every id. +function apiArgDoc([name,dom,req]){ + const a={name,required:req!==false},d=API_DOMAINS[dom]; + if(!d){a.type=dom;return a;} + a.domain=dom; + if(d.table)a.from=d.table; + else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;} + return a;} +function apiSchema(section){ + const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}); + const doc={ + clock:apiClockDoc(), + commands:Object.fromEntries(Object.entries(API_CMD).map(([n,s])=>[n,{...cmd(s),dryRun:!!s.quote, + ...(s.decides?{decides:true}:{}),...(s.confirm?{confirm:s.confirm}:{}),...(s.open?{opens:s.open}:{}),...(s.reads?{report:true}:{})}])), + view:Object.fromEntries(Object.entries(API_VIEW).map(([n,s])=>[n,cmd(s)])), + session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,cmd(s)])), + drafts:API_BOUND, + denied:Object.fromEntries(Object.keys(API_DENY).sort().map(n=>[n,apiDenied(n)])), + domains:Object.fromEntries(Object.entries(API_DOMAINS).map(([n,d])=>{const v=apiDomValues(n); + return [n,{kind:d.kind==='fn'?'custom':d.kind,...(d.table?{from:d.table}:{}), + ...(!d.table&&Array.isArray(v)?{values:v}:v&&v.from!==undefined?{range:v}:v&&v.of?{of:v.of}:{})}];})), + state:API_STATE_DOC, + results:API_RESULTS_DOC, + }; + if(section===undefined||section===null||section==='')return doc; + if(!(section in doc))apiFail(`No section "${section}". Sections: ${Object.keys(doc).join(', ')}.`); + return doc[section];} +function apiCatalog(name){ + if(name===undefined||name===null||name===''){ + return {tables:[...Object.keys(API_TABLES),...Object.keys(API_MADE)].sort().map(k=>{const t=k in API_MADE?API_MADE[k]():API_TABLES[k]; + return {name:k,n:Array.isArray(t)?t.length:t&&typeof t==='object'?Object.keys(t).length:1};})};} + if(name in API_MADE)return apiJson(API_MADE[name]()); + if(name in API_TABLES)return apiJson(API_TABLES[name]); + apiFail(`No table "${name}". Call catalog without a name for the list.`);} +function apiState(path){if(!S)return null;const v=apiJson(apiPath(S,path));return v===undefined?null:v;} +function apiResults(path){const v=apiJson(apiPath(R,path));return v===undefined?null:v;} +function apiUi(){const o={};for(const k of Object.keys(UI))if(!API_UI_HIDDEN[k])o[k]=apiJson(UI[k]);return o;} +function apiActions(){ + const sig=s=>(s.args||[]).map(a=>a[0]+(a[2]===false?'?':'')).join(','),typed={}; + for(const t of [API_CMD,API_VIEW,API_SESSION])for(const [n,s] of Object.entries(t))typed[n]=sig(s); + return {typed,drafts:Object.keys(API_BOUND)};} diff --git a/src/agent/50-screen.js b/src/agent/50-screen.js new file mode 100644 index 0000000..58a2c8d --- /dev/null +++ b/src/agent/50-screen.js @@ -0,0 +1,64 @@ +/* ================= AGENT API: what is on screen ================= + The surfaces a player can read, as text with numbered buttons, by the name screen takes. The left drawer has tabs + (goals, deals, noc, nets). */ +const API_ROOT={modal:'modal',bank:'bankBox',dash:'dash',panel:'panel',left:'leftBody',puzzle:'pzBox'}; +const apiShown=w=>{const el=$(API_ROOT[w]);return !!el&&!el.hidden;}; +const apiModalOpen=()=>apiShown('modal'); +// The buttons of the last screen a tool read, for click. Set by apiScreen. +let API_LAST=[]; +function apiControls(root){ + const out=[]; + for(const b of root.querySelectorAll('[data-act],select[data-chg]')){ + const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled} + // A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value. + :{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg, + select:b.dataset.chg,value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled}; + out.push(o);} + return out;} +function apiScreen(where,offset=0){ + if(where===null)where=undefined; + if(where!==undefined&&!API_ROOT[where])apiFail(`where is one of ${Object.keys(API_ROOT).join(', ')}.`); + const open=Object.keys(API_ROOT).filter(w=>w!=='left'&&apiShown(w)); + const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel'; + const root=$(API_ROOT[w]); + API_LAST=root?apiControls(root):[]; + const all=root?apiFullText(root):'',from=Math.max(0,Math.floor(+offset)||0),more=all.length-from-API_MAX_TEXT; + const out={where:w,open,selected:UI.sel,tab:UI.tab}; + if(w==='left')out.leftTab=UI.left||'goals'; + if(w==='modal')out.question=!!apiDecision(); + out.text=all.slice(from,from+API_MAX_TEXT); + if(from)out.textFrom=from; + if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`; + out.buttons=API_LAST.map((b,i)=>({n:i,...b})); + return out;} + +/* ---------- windows: the tool's own sheets, and the game's questions ---------- + A window the tool opened itself (a view, a draft, the link window, a sheet it clicked inside) is something to read + and click through. A window the game opened in answer to a game command, or during a day, is a question when one + of its buttons runs a game command other than closeModal (a De-Kicks quote, a retention offer); then other game + commands wait until it is answered or closed, as clicks outside an open window do in the game. */ +let API_SHEET=null; +const apiCard=()=>$('modalCard').firstChild; +const apiMarkSheet=()=>{API_SHEET=apiModalOpen()?apiCard():null;}; +const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET; +function apiDecision(){ + if(!apiModalOpen()||apiIsSheet())return null; + const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]); + if(!b.length)return null; + return {text:apiText($('modal'),1500),options:b.map(x=>({command:x.dataset.act,args:apiParse(x.dataset.args),label:apiText(x,120).replace(/\n/g,' ')}))};} + +function apiPanel({city:c,link,network:q,tab,left}={}){ + if(left!==undefined){if(!['goals','deals','noc','nets'].includes(left))apiFail('left is one of goals, deals, noc, nets.');ACT.leftTab({t:left});return apiScreen('left');} + if(c)UI.sel={type:'city',id:apiCityOf(c).id}; + else if(link){if(!S.links.some(l=>l.id===link))apiFail(`No link ${link}. See status or hot_spots for link ids.`);UI.sel={type:'link',id:link};} + else if(q)ACT.netFocus({id:apiNetOf(q).id}); + if(tab)UI.tab=tab; + renderAll(); + return apiScreen(q?'left':'panel');} +function apiOpenLink(a,b){ + const x=apiCityOf(a).id,y=apiCityOf(b).id; + if(!S.pops[x])apiFail(`A link starts at one of your POPs: ${apiMyPops()}.`); + apiTake(); + openLinkModal(x,y); + apiMarkSheet(); + return {toasts:apiToastLines(apiTake()),screen:apiScreen()};} diff --git a/src/agent/60-dispatch.js b/src/agent/60-dispatch.js new file mode 100644 index 0000000..c3f2cd7 --- /dev/null +++ b/src/agent/60-dispatch.js @@ -0,0 +1,114 @@ +/* ================= AGENT API: doing things ================= + One action, run as the game runs it, and reported through the game's own channels: what it said (toast), what it + charged at the money gate (spend) and whether anything changed (a fingerprint of S). The API checks shape and domain + only; whether a move is allowed is the game's to answer. */ + +// Arguments: shape and domain only. Anything beyond that is the game's to answer. +function apiValidate(spec,args){ + const problems=[],out={}; + for(const [name,dom,req] of spec.args||[]){ + const v=args[name]; + if(v===undefined){if(req!==false)problems.push(`${name} is required`);continue;} + if(apiDomCheck(dom,v).ok){out[name]=v;continue;} + const vs=apiDomValues(dom),d=API_DOMAINS[dom]; + problems.push(`${name}: ${JSON.stringify(v)} is not a ${dom}${d&&d.table&&d.kind==='id'?` (see catalog ${d.table} or find)`:Array.isArray(vs)?` (one of ${vs.slice(0,12).join(', ')}${vs.length>12?'…':''})`:vs&&typeof vs==='object'&&vs.from!==undefined?` (${vs.from}..${vs.to})`:''}`);} + for(const k of Object.keys(args))if(!(spec.args||[]).some(a=>a[0]===k))problems.push(`${k} is not an argument of this action`); + return {ok:!problems.length,problems,args:out};} + +// The fingerprint tells "did nothing" from "did something quietly": cash, day, the entity counts, the small settings +// maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action. +const API_FP_LEN=['links','transit','pni','caches','biz','offers','nni','loans','loanOffers','inc','scrubs']; +const API_FP_KEYS=['pops','ixp','peers','myIx','done','ach','merged','confReg']; +const API_FP_JSON=['name','pairMet','rs','ixn','ixSite','ixPref','spares','te','cnLic','hw','scrubMode','ppol','ops','core','ddosAuto','popStd','demo','charter','monkey','seatOff','pz','ar','dk','ev']; +function apiFp(watch,args){ + if(!S)return null; + const f={cash:S.cash,day:S.day,lvl:S.lvl||1,won:!!S.won,lost:!!S.lost}; + for(const k of API_FP_LEN)f[k]=(S[k]||[]).length; + for(const k of API_FP_KEYS)f[k]=Object.keys(S[k]||{}).length; + for(const k of API_FP_JSON)f[k]=JSON.stringify(apiJson(S[k])??null); + for(const p of watch||[])f['@'+p]=JSON.stringify(apiJson(apiPath(S,String(p).replace(/#(\w+)/g,(m,k)=>args&&args[k]!==undefined?args[k]:m)))??null); + return JSON.stringify(f);} +// spend() is the game's money gate and a top-level function, so every action reaches it by its global name. +function apiMeter(){const real=window.spend;let paid=0;window.spend=c=>{const ok=real(c);if(ok)paid+=c;return ok;};return ()=>{window.spend=real;return paid;};} + +/* typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button click + does it, with the button's own arguments. */ +function apiDispatch(name,kind,spec,args,typed){ + const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open); + apiTake(); + const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter(); + let threw=null,report; + try{ + if(typed&&kind==='game'){ + if(spec.open){ACT[spec.open]({});apiMarkSheet();} + // The custom metric's field lives in the link's panel. + if(name==='metricSet'&&!$('metIn')){UI.sel={type:'link',id:args.id};renderAll();} + const gone=(spec.dom||[]).filter(f=>!$(f)); + if(gone.length)throw new Error(`the field it types into (${gone.join(', ')}) is not on screen${name==='metricSet'?': set the link\'s metric to custom first (setMetric v "custom")':''}`); + if(spec.bind)spec.bind(args); + const a=spec.pass?spec.pass(args):args; + ACT[name](a); + if(spec.confirm==='double')ACT[name](a); + if(spec.reads==='modal'&&apiModalOpen()){report=apiText($('modal'));closeModal();} + }else ACT[name](args); + }catch(e){threw=e;} + const charged=paid(); + if(threw){apiTake();apiFail(`${name} failed: ${threw&&threw.message||threw}`);} + if(!apiModalOpen())API_SHEET=null; + else if(mine||kind!=='game')apiMarkSheet(); + else API_SHEET=null; + const said=apiTake(),d=apiDecision(); + const outcome=d?'decision':S!==ref||apiFp(spec&&spec.watch,args)!==f0||report!==undefined?'applied' + :said.some(t=>t.kind==='bad')?'rejected':kind==='view'||kind==='draft'?'shown':'no_effect'; + return {action:name,outcome,toasts:apiToastLines(said),charged,cashChange:Math.round((S?S.cash:0)-cash), + ...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:apiScreen()};} +// While the game waits for an answer, game commands other than its options report the question instead. +function apiWaiting(name){ + const d=apiDecision(); + return d&&name!=='closeModal'&&!d.options.some(o=>o.command===name) + ?{action:name,outcome:'decision',reason:'A window is waiting for an answer: run one of its options, or closeModal.',decision:d,screen:apiScreen()}:null;} +function apiQuote(name,spec,args){ + const ui0={}; + for(const k of spec.bindsUI||[])ui0[k]=UI[k]; + const f0=apiFp(spec.watch,args); + // A dry run must not use up the dice: some helpers draw (a PNI's lead time), and a draw here would move the seeded + // game. They get the middle of the range instead, so a drawn figure in a quote is a typical one. + const dice=Math.random; + Math.random=()=>0.5; + let q={}; + try{ + if(spec.bind&&!spec.dom)spec.bind(args); + if(spec.quote)q=spec.quote(args)||{}; + }catch(e){apiFail(`${name}: the price could not be worked out: ${e&&e.message||e}`);}finally{Math.random=dice;for(const k of Object.keys(ui0))UI[k]=ui0[k];} + return {action:name,outcome:'quote',quote:{setup:0,monthly:0,...q,blocked:(q.blocked||[]).map(b=>apiText(String(b),400))},consistent:apiFp(spec.watch,args)===f0, + ...(spec.quote?{}:{note:'This command has no price of its own: it costs nothing up front.'})};} +// Checks shared by act and click: what no tool runs. +function apiAllowed(name,what){ + const no=apiDenied(name); + if(no)apiFail(`${name} is not available here: ${no}.`); + const kind=apiKind(name); + if(!kind||typeof ACT[name]!=='function')apiFail(what); + return kind;} +function apiRun(name,args,opts={}){ + name=String(name||''); + if(name.startsWith('view.'))name=name.slice(5); + const kind=apiAllowed(name,`There is no action "${name}". See actions or schema.`); + args=args&&typeof args==='object'&&!Array.isArray(args)?args:{}; + const spec=apiSpec(name); + if(spec){const v=apiValidate(spec,args);if(!v.ok)apiFail(`${name}: ${v.problems.join('; ')}. See schema for its arguments.`);args=v.args;} + if(kind==='game'){ + if(S&&S.lost&&name!=='closeModal')return {action:name,outcome:'stopped',reason:'The network went bankrupt: start or load another game.'}; + const w=apiWaiting(name); + if(w)return w; + if(opts.dryRun)return apiQuote(name,spec,args); + }else if(opts.dryRun)apiFail(`${name} has no price: only game commands (see schema commands) dry-run.`); + return apiDispatch(name,kind,spec,args,true);} +function apiClick(n,value){ + const b=API_LAST[n]; + if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`); + if(b.disabled)apiFail(`"${b.label}" is greyed out.`); + const name=b.select||b.act,args=b.select?{v:value===undefined?undefined:String(value)}:b.args; + if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`); + const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`); + if(kind==='game'){const w=apiWaiting(name);if(w)return {clicked:b.label,...w};} + return {clicked:b.label,...apiDispatch(name,kind,apiSpec(name),args,false)};} diff --git a/src/agent/70-time.js b/src/agent/70-time.js new file mode 100644 index 0000000..4f30a9d --- /dev/null +++ b/src/agent/70-time.js @@ -0,0 +1,38 @@ +/* ================= AGENT API: time ================= + The agent's clock: nothing moves until a tool asks for days with advance, one dayTick() per simulated day. */ +const apiClockDoc=()=>'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.'; + +// What happened since a moment (the start of an advance): the log, new incidents, cash. +// The log keeps what mattered; toasts that only repeat a log line are left out. +function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){ + const seen=new Set(inc),entries=(S.log||[]).filter(e=>e.d>day).slice(-60),logged=entries.map(e=>apiNorm(apiText(e.t,400))); + const d=apiDecision(); + return {from:dateStr(day),to:dateStr(S.day),daysRun:S.day-day,cash:Math.round(S.cash),cashChange:Math.round(S.cash-cash), + newIncidents:S.inc.filter(i=>!seen.has(i.id)).map(apiIncText), + log:entries.map(e=>`${dateStr(e.d)}: ${apiText(e.t,400)}`), + toasts:[...new Set(apiToastLines(toasts))].filter(t=>{const f=apiNorm(t.replace(/^\w+: /,'').split('\n')[0]);return !logged.some(l=>l.startsWith(f));}).slice(-40), + ...(d?{decision:d,screen:apiScreen()}:{})};} + +function apiAdvanceStart(days){ + if(!S)apiFail('No game is running.'); + if(apiModalOpen())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.'); + API_SHEET=null; + apiTake(); + return {days:Math.max(1,Math.min(3650,Math.floor(+days)||1)),start:S.day,cash:S.cash,inc:S.inc.map(i=>i.id),times:[],ran:0,stop:null};} +// One day of the run; false once it is over. +function apiAdvanceDay(a){ + if(a.ran>=a.days)return false; + if(S.lost){a.stop='bankrupt';return false;} + const t=performance.now(); + dayTick(); + a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++; + if(apiModalOpen()){a.stop='a window opened';return false;} + return a.ranx+t.ms,0),out=apiSince({day:a.start,cash:a.cash,inc:a.inc},apiTake()); + if(a.stop!=='a window opened'){delete out.decision;delete out.screen;} + return {from:out.from,to:out.to,daysRun:a.ran,stoppedBecause:a.stop,cash:out.cash,cashChange:out.cashChange,newIncidents:out.newIncidents,log:out.log,toasts:out.toasts, + timing:{totalMs:apiR1(total),perDayMs:apiR1(total/(a.ran||1)),slowestDays:a.times.slice().sort((x,y)=>y.ms-x.ms).slice(0,5).map(x=>({date:dateStr(x.day),ms:x.ms}))}, + ...(out.decision?{decision:out.decision,screen:out.screen}:{})};} +function apiAdvance(days){const a=apiAdvanceStart(days);while(apiAdvanceDay(a));return apiAdvanceEnd(a);} diff --git a/src/agent/90-facade.js b/src/agent/90-facade.js new file mode 100644 index 0000000..559c122 --- /dev/null +++ b/src/agent/90-facade.js @@ -0,0 +1,43 @@ +/* ================= AGENT API: the facade ================= + window.TUBES.call(tool, args) is the whole surface: one tool from API_TOOLS by name, with the MCP tool's own + arguments, answered as plain JSON. Nothing here listens, polls or runs on the day loop: toast() is only listened to + while a call runs. */ +const API_TOASTS={depth:0,list:[],real:null}; +function apiTake(){const t=API_TOASTS.list;API_TOASTS.list=[];return t;} +const apiToastLines=t=>t.map(x=>(x.kind?x.kind+': ':'')+x.text); +// toast() is a top-level function, so the game reaches it by its global name and this stands in for it. +function apiListen(on){ + if(on){if(API_TOASTS.depth++)return;const real=API_TOASTS.real=window.toast;API_TOASTS.list=[]; + window.toast=function(h,kind){API_TOASTS.list.push({kind:kind||'',text:apiText(String(h),600)});return real.apply(this,arguments);};} + else if(!--API_TOASTS.depth){window.toast=API_TOASTS.real;API_TOASTS.real=null;API_TOASTS.list=[];}} + +const API_TOOLS={ + status:()=>apiStatus(), + network:a=>apiNetwork(a.network), + city:a=>apiCity(a.city), + find:a=>apiFind(a.query,a.kind), + traceroute:a=>apiTrace(a.from,a.to), + peering_check:a=>apiPeering(a.network,a.city,a.via), + hot_spots:a=>apiHotSpots(a.limit||10), + schema:a=>apiSchema(a.section), + catalog:a=>apiCatalog(a.name), + state:a=>apiState(a.path), + results:a=>apiResults(a.path), + ui:()=>apiUi(), + actions:()=>apiActions(), + classes:()=>apiClasses(), + act:a=>{const name=a.action||a.command;if(!name)apiFail('Give action, e.g. {"action":"buildPop","args":{"city":"ams"}}.'); + return apiRun(name,a.args||{},{dryRun:!!a.dryRun});}, + screen:a=>apiScreen(a.where,a.offset), + panel:a=>apiPanel(a), + click:a=>apiClick(a.button,a.value), + open_link:a=>apiOpenLink(a.from,a.to), + advance:a=>apiAdvance(a.days), +}; +function apiCall(tool,args){ + if(typeof tool!=='string'||!own(API_TOOLS,tool))apiFail(`No tool "${tool}".`); + if(!S&&!['schema','catalog','classes','actions'].includes(tool))apiFail('No game is running.'); + apiListen(true); + try{return API_TOOLS[tool](args&&typeof args==='object'&&!Array.isArray(args)?args:{});} + finally{apiListen(false);}} +window.TUBES={version:1,tools:Object.keys(API_TOOLS),call:apiCall}; diff --git a/src/index.html b/src/index.html index 490d3db..4f7f526 100644 --- a/src/index.html +++ b/src/index.html @@ -164,6 +164,7 @@ 'use strict'; + diff --git a/tests/agent-api.test.js b/tests/agent-api.test.js new file mode 100644 index 0000000..ab7bf16 --- /dev/null +++ b/tests/agent-api.test.js @@ -0,0 +1,74 @@ +// The agent facade (src/agent/, window.TUBES) and where it lives: in the development page only. It does nothing until +// a tool calls it, listens to toast() only during a call, and the page players get carries none of it. +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 page = require('../scripts/lib/page'); + +// Names the agent files define at the top level: none may appear in the page players get. +const AGENT_NAMES = ['TUBES', 'API_CMD', 'API_DOMAINS', 'apiCall', 'apiDispatch', 'apiSchema']; + +test('the facade is inert until called, and listens to the game only during a call', () => { + const a = load({ agent: true }); + assert.equal(a.ev('toast.name'), 'toast', 'loading the page leaves toast() alone'); + assert.equal(a.ev('spend.name'), 'spend', 'and spend()'); + assert.equal(a.ev('API_TOASTS.depth'), 0); + assert.deepEqual(JSON.parse(a.ev('JSON.stringify(TUBES.tools)')).sort(), ['act', 'actions', 'advance', 'catalog', 'city', 'classes', 'click', 'find', + 'hot_spots', 'network', 'open_link', 'panel', 'peering_check', 'results', 'schema', 'screen', 'state', 'status', 'traceroute', 'ui'].sort()); + // Before a game there is a contract to read, and nothing else. + assert.ok(a.ev("TUBES.call('schema',{section:'commands'}).buildPop")); + assert.throws(() => a.ev("TUBES.call('status',{})"), /No game is running/); + assert.throws(() => a.ev("TUBES.call('eval',{})"), /No tool "eval"/); + a.ev('ACT.start({});S.cash=1e6;compute()'); + // A call hears what the game says while it runs, and gives toast() back after, also when it fails. + const r = a.ev("TUBES.call('act',{action:'buyTransit',args:{city:'fra',net:'cog',tier:1}})"); + assert.equal(r.outcome, 'applied'); + assert.ok(r.toasts.some((t) => /Cogentle/.test(t)), 'the game\'s own words'); + assert.equal(a.ev('toast.name'), 'toast'); + assert.throws(() => a.ev("TUBES.call('act',{action:'buildPop',args:{city:'atlantis'}})"), /not a cityId/); + assert.equal(a.ev('toast.name+spend.name+API_TOASTS.depth'), 'toastspend0', 'a failing call restores both'); + // A toast outside a call is the game's alone. + a.ev("toast('hello','good')"); + assert.equal(a.ev('API_TOASTS.list.length'), 0); + assert.deepEqual(a.errors, []); +}); + +test('the page players get has no agent code; the development page has it', () => { + const ship = page.assemble().html, dev = page.assemble({ dev: true }).html; + assert.ok(!ship.includes('@include-dev'), 'the marker line is dropped whole'); + for (const n of AGENT_NAMES) { + assert.ok(!new RegExp(`\\b${n}\\b`).test(ship), `${n} is not in the page players get`); + assert.ok(new RegExp(`\\b${n}\\b`).test(dev), `${n} is in the development page`); + } + // The agent files are pasted in where the marker is, after the game, inside the same script. + const at = dev.indexOf('/* ================= AGENT API: argument domains'); + assert.ok(at > dev.indexOf('/* ================= LOOP ================='), 'after the game'); + assert.ok(at < dev.lastIndexOf(''), 'inside the game\'s script'); + assert.equal(page.shipped().html.match(/\bTUBES\b/), null, 'nor in the shipped page, labels compiled'); + // The players' page is the game alone: no facade, and it boots and plays. + const p = load(); + assert.equal(p.ev('typeof TUBES+typeof apiCall+typeof API_CMD'), 'undefinedundefinedundefined'); + p.ev("ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<5;i++)dayTick()"); + assert.ok(p.ev('R.served') > 0); + assert.deepEqual(p.errors, []); +}); + +test('an @include-dev line only expands in the development page', () => { + const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-dev-include-')); + try { + fs.mkdirSync(path.join(src, 'a')); + fs.mkdirSync(path.join(src, 'b')); + fs.writeFileSync(path.join(src, 'a', '10-a.js'), 'const A=1;\n'); + fs.writeFileSync(path.join(src, 'b', '10-b.js'), 'const B=2;\n'); + fs.writeFileSync(path.join(src, 'index.html'), '\n'); + const ship = page.assemble({ src }), dev = page.assemble({ src, dev: true }); + assert.equal(ship.html, '\n'); + assert.equal(dev.html, '\n'); + // Error lines still map to their files in both. + assert.deepEqual(page.locate(dev.map, 3), { file: 'b/10-b.js', line: 1 }); + assert.deepEqual(page.locate(ship.map, 3), { file: 'index.html (shell)', line: 3 }); + } finally { fs.rmSync(src, { recursive: true, force: true }); } +}); diff --git a/tests/build.test.js b/tests/build.test.js index a6c9966..ceea51a 100644 --- a/tests/build.test.js +++ b/tests/build.test.js @@ -46,10 +46,28 @@ test('src: partials follow the layout rules (docs/adr/0002-one-page-assembled-at const src = path.join(root, 'src'); for (const f of listFiles(src)) { if (f === 'index.html' || f === 'i18n/en.js') continue; - assert.match(f, /^(styles\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.css|game\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.js)$/, `${f}: name it NN-lower-case under styles/ or game/`); + assert.match(f, /^(styles\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.css|(game|agent)\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.js)$/, `${f}: name it NN-lower-case under styles/, game/ or agent/`); + } + for (const dev of [false, true]) { + const { html, map } = assemble({ dev }); + assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})'); + assert.equal((html.match(/`); + +http.createServer((req, res) => { + const url = new URL(req.url, 'http://localhost'); + try { + if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); } + if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); } + if (url.pathname === '/__bench/results' && req.method === 'POST') { + let body = ''; req.on('data', (c) => { body += c; }); req.on('end', () => { + try { const r = JSON.parse(body); console.log('\n' + r.md + '\n'); if (OUT) { fs.writeFileSync(OUT, r.md + '\n\n```json\n' + JSON.stringify(r, null, 1) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results', e); } + res.writeHead(204); res.end(); }); + return; + } + // The service worker would cache this page over the real one: none here. + if (url.pathname === '/sw.js') { res.writeHead(404); return res.end(); } + const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, '')); + if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); } + res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); + fs.createReadStream(file).pipe(res); + } catch (e) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); res.end(String(e && e.stack || e)); } +}).listen(PORT, HOST, () => { + const s = JSON.parse(save).S; + console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`); + console.log(`Open http://localhost:${PORT}/ in your browser, press Start and keep the tab in front.`); + if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4' && !l.internal) console.log(` from another device: http://${l.address}:${PORT}/`); + console.log('Ctrl+C to stop.'); +}); diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 71d5ca5..f7c413c 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -3,7 +3,7 @@ // stay in lockstep; this file only offers what a player could do now (buttons on screen, POPs, cities) and digests what // routing gave, as strings the driver compares. (() => { - const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed', + const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'mapSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed', 'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu', 'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare', // Leave the game or open what is not this game: the title screen, menus of other modes, AI helpers that fetch. diff --git a/scripts/lib/gpu-bench-client.js b/scripts/lib/gpu-bench-client.js new file mode 100644 index 0000000..7c0f6bb --- /dev/null +++ b/scripts/lib/gpu-bench-client.js @@ -0,0 +1,96 @@ +// The benchmark panel that scripts/gpu-bench.js adds to the game page. It runs in your own browser, so it measures your +// graphics card: the save is loaded, then each scenario plays for a few seconds with the 2D map and with the WebGL +// tubes, and the frames are timed as they really reach the screen (requestAnimationFrame). Results show in the panel +// and go back to the terminal that started the server. Nothing is saved: the page's save() is switched off. +(() => { + const CFG = window.__BENCH__ || {}, SECS = CFG.secs || 6, WARM = 1500; + const SCEN = [ + { id: 'x1-far', label: 'Map at x1, zoomed out (0.6)', speed: 1, z: 0.6 }, + { id: 'x1-mid', label: 'Map at x1 (zoom 1.4)', speed: 1, z: 1.4 }, + { id: 'x1-near', label: 'Map at x1, zoomed in (3.2)', speed: 1, z: 3.2 }, + { id: 'pan', label: 'Panning at x1 (zoom 1.4)', speed: 1, z: 1.4, pan: true }, + { id: 'x8', label: 'Game at x8 (zoom 1.4)', speed: 8, z: 1.4 }, + ]; + // ?only=gl or ?only=2d runs one renderer; ?scen=x1-mid,pan runs only those scenarios; ?dpr=2 below. + const QS = new URLSearchParams(location.search), ONLY = QS.get('only'), PICK = QS.get('scen'); + if (PICK) SCEN.splice(0, SCEN.length, ...SCEN.filter((s) => PICK.split(',').includes(s.id))); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const box = document.createElement('div'); + box.style.cssText = 'position:fixed;top:8px;left:50%;transform:translateX(-50%);z-index:100000;background:rgba(30,38,64,.94);color:#fff;font:13px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:12px;max-width:94vw;max-height:80vh;overflow:auto;box-shadow:0 6px 24px rgba(0,0,0,.35)'; + box.innerHTML = 'Series of Tubes · GPU benchmark
Loading…
'; + const st = (t) => { box.querySelector('#bst').textContent = t; }; + let SAVE = null, MD = ''; + + function fresh() { + S = migrate(JSON.parse(SAVE)); UI.started = true; UI.pitched = true; UI.sel = null; UI.anim = 'on'; applyAnim(); + closeModal(); compute(); renderAll(); + const h = CITY[S.home] || CITIES[0]; cam.x = h.x; cam.y = h.y; + } + const q = (s, x) => (s.length ? s[Math.min(s.length - 1, Math.floor(s.length * x))] : 0); + async function measure(sc, hz) { + fresh(); cam.z = sc.z; UI.speed = sc.speed; WL.key = null; + await sleep(WARM); + const fr = [], dr = [], day0 = S.day; let last = 0, stop = false, hidden = false, long = 0, panX = cam.x; + const D0 = draw; + draw = function (t) { const a = performance.now(); try { return D0(t); } finally { dr.push(performance.now() - a); } }; + let po = null; try { po = new PerformanceObserver((l) => { long += l.getEntries().length; }); po.observe({ type: 'longtask' }); } catch (e) { /* not in this browser */ } + // Frames slower than three refreshes, with the day they fell on and their draw(): where the stutters are. + const t00 = performance.now(), slow = []; + const tick = (t) => { if (last) { fr.push(t - last); if (t - last > 50) slow.push({ at: Math.round(t - t00), ms: Math.round(t - last), day: S.day, draw: +(dr[dr.length - 1] || 0).toFixed(1) }); } last = t; if (document.hidden) hidden = true; + if (sc.pan) { panX += 0.18 * (t - (tick.p || t)) / cam.z; cam.x = panX; tick.p = t; } + if (!stop) requestAnimationFrame(tick); }; + requestAnimationFrame(tick); + const t0 = performance.now(); await sleep(SECS * 1000); stop = true; const T = (performance.now() - t0) / 1000; + draw = D0; if (po) po.disconnect(); UI.speed = 0; + const s = fr.slice().sort((a, b) => a - b), d = dr.slice().sort((a, b) => a - b), budget = 1000 / hz; + return { fps: +(fr.length / T).toFixed(1), p50: +q(s, 0.5).toFixed(1), p95: +q(s, 0.95).toFixed(1), p99: +q(s, 0.99).toFixed(1), max: +q(s, 1).toFixed(1), + dropped: +(100 * fr.filter((x) => x > budget * 1.5).length / Math.max(1, fr.length)).toFixed(1), + drawMs: +(d.reduce((a, x) => a + x, 0) / Math.max(1, d.length)).toFixed(2), drawP95: +q(d, 0.95).toFixed(2), + daysPerSec: +((S.day - day0) / T).toFixed(2), longTasks: long, hidden, drawMax: +q(d, 1).toFixed(1), slow }; + } + async function refresh() { + const a = []; let l = 0; await new Promise((r) => { const f = (t) => { if (l) a.push(t - l); l = t; if (a.length < 90) requestAnimationFrame(f); else r(); }; requestAnimationFrame(f); }); + a.sort((x, y) => x - y); return Math.round(1000 / a[a.length >> 1]); + } + function table(res, env) { + const rows = SCEN.map((sc) => { const a = res['2d'][sc.id], b = res.gl && res.gl[sc.id]; + const f = (m, k, u = '') => (m ? `${m[k]}${u}` : '-'); + return `| ${sc.label} | ${f(a, 'fps')} | ${f(b, 'fps')} | ${f(a, 'p95', ' ms')} | ${f(b, 'p95', ' ms')} | ${f(a, 'drawMs', ' ms')} | ${f(b, 'drawMs', ' ms')} |`; }); + return [`**${env.gpu || 'unknown GPU'}** · ${env.ua}`, `${env.w}×${env.h} at ${env.dpr}× · ${env.hz} Hz screen · ${env.cores} threads · ${env.save}`, '', + '| Scenario | 2D fps | WebGL fps | 2D p95 frame | WebGL p95 frame | 2D draw() | WebGL draw() |', + '|---|--:|--:|--:|--:|--:|--:|', ...rows, + '', `p95 frame: the slowest 5% of frames. draw(): CPU time per frame on the main thread.${env.invalid ? ' ⚠️ The tab was hidden during a run: those numbers are not valid.' : ''}`].join('\n'); + } + async function run() { + const go = box.querySelector('#bgo'); go.disabled = true; + save = () => {}; + // An incident pauses the game (autoPause): the clock must keep running for the timings to mean anything. + autoPause = () => false; + fresh(); UI.speed = 0; st('Measuring the screen refresh…'); await sleep(500); + const hz = await refresh(); + const want0 = GLX.want, glOk = mapGl(true, false) && glInit(); const env = { gpu: GLX.gpu, ua: navigator.userAgent.replace(/^Mozilla\/5\.0 /, ''), w: innerWidth, h: innerHeight, dpr: devicePixelRatio, hz, cores: navigator.hardwareConcurrency, save: `${Object.keys(S.pops).length} POPs · ${S.links.length} links` }; + mapGl(false, false); + const res = { '2d': {}, gl: glOk ? {} : null }; + for (const r of (glOk ? ['2d', 'gl'] : ['2d']).filter((x) => !ONLY || x === ONLY)) { mapGl(r === 'gl', false); + for (const sc of SCEN) { st(`${r === 'gl' ? 'WebGL' : '2D'} · ${sc.label} (${SECS}s)… keep this tab in front`); const m = await measure(sc, hz); res[r][sc.id] = m; if (m.hidden) env.invalid = true; } } + mapGl(want0, false); fresh(); UI.speed = 0; + MD = table(res, env); + st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).'); + box.querySelector('#bout').innerHTML = '
' + MD.replace(/&/g, '&').replace(/';
+    box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
+    try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
+  }
+  addEventListener('load', async () => {
+    document.body.appendChild(box);
+    while (typeof migrate !== 'function' || typeof GLX === 'undefined') await sleep(50);
+    // ?dpr=2 draws the map as a screen of that density would (a 4K screen's pixels, measured on a smaller one).
+    const DPRQ = +QS.get('dpr'); if (DPRQ > 0) { Object.defineProperty(window, 'devicePixelRatio', { get: () => DPRQ }); resize(); WL.key = null; }
+    await sleep(800);
+    try { SAVE = JSON.stringify((await (await fetch('/__bench/save.json')).json()).S || null); } catch (e) { st('Could not load the save: ' + e); return; }
+    if (SAVE === 'null') { st('The save file has no game in it.'); return; }
+    st(`Ready: ${SCEN.length} scenarios × 2 renderers, about ${Math.ceil(SCEN.length * 2 * (SECS + 3) / 60)} minutes. Keep this tab in front and do not touch the map.`);
+    const go = box.querySelector('#bgo'); go.disabled = false; go.onclick = () => run().catch((e) => st('Failed: ' + (e && e.stack || e)));
+    box.querySelector('#bcp').onclick = () => navigator.clipboard.writeText(MD).then(() => st('Copied.'), () => st('Copy failed: select the table instead.'));
+    if (/[?&]auto\b/.test(location.search)) go.onclick();
+  });
+})();
diff --git a/site/i18n/de.js b/site/i18n/de.js
index 3ffe669..809873c 100644
--- a/site/i18n/de.js
+++ b/site/i18n/de.js
@@ -3911,12 +3911,15 @@
 "settings.agent_api":"Agent-API",
 "settings.agent_relay_connected":"Agenten-Relay verbunden: Jetzt kann ein Tool dieses Spiel in diesem Tab spielen.",
 "settings.agent_s_clock":"Uhr des Agenten",
+"settings.always_2d":"Immer 2D",
 "settings.an_early_heads_up_below_60":"Eine frühe Warnung unter 60 % Zufriedenheit, lange bevor sie wütend sind.",
+"settings.auto_draws_the_map_with_your":"Auto zeichnet die Karte mit deiner Grafikkarte, wenn der Browser es erlaubt, damit auch große Netze flüssig bleiben. Immer 2D läuft überall, ist auf großen Karten aber langsamer.",
 "settings.auto_follows_your_device_s_reduce":"Auto folgt der Einstellung „Bewegung reduzieren“ deines Geräts. Aus friert die Karte ein: keine wandernden Pakete, kein Pulsieren, kein schwebender Text.",
 "settings.customers_and_alerts":"Kunden und Warnungen",
 "settings.display_and_sound":"Anzeige und Ton",
 "settings.for_reporting_layout_bugs_shows_what":"Zum Melden von Layout-Fehlern: zeigt, was dein Bildschirm dem Spiel mitteilt.",
 "settings.let_an_ai_agent_drive_this_game":"Eine KI soll dieses Spiel spielen",
+"settings.map_drawing":"Kartendarstellung",
 "settings.n_min":"{n} Min.",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Nur Ärger und Meilensteine poppen auf; alles andere landet still im NOC-Log. In Best Effort standardmäßig an.",
@@ -3929,6 +3932,7 @@
 "settings.the_agent_moves_it":"Der Agent stellt sie",
 "settings.the_clock_while_an_agent_plays":"Die Uhr, während ein Agent spielt",
 "settings.the_game_stops_so_you_can":"Das Spiel hält an, damit du ihren Dienst reparieren kannst, bevor sie kündigen. Am nützlichsten bei hoher Geschwindigkeit.",
+"settings.this_browser_cannot_so_the_map":"Dieser Browser kann das nicht, also wird die Karte in 2D gezeichnet.",
 "settings.warn_when_a_customer_gets_unhappy":"Bei unzufriedenen Kunden warnen",
 "settings.while_agent_mode_is_on_the":"Solange der Agenten-Modus an ist, gehört die Uhr nicht dir. Mit Tempo läuft sie von selbst und lässt sich von Hand nicht anhalten, auch nicht durch ein offenes Fenster (deins eingeschlossen), und sie wartet, solange kein Agent verbunden ist. Oder der Agent stellt sie, und nichts passiert, bis er nach Tagen fragt. Die Seite verbindet sich mit dem lokalen Agenten-Relay (npm run dev bringt eins mit), damit Tools wie der MCP-Server dieses Spiel spielen können, während du zusiehst.",
 "share_card.build_the_internet_one_tube_at":"Bau das Internet, eine Röhre nach der anderen",
diff --git a/site/i18n/es.js b/site/i18n/es.js
index e90856f..9744b6b 100644
--- a/site/i18n/es.js
+++ b/site/i18n/es.js
@@ -3909,12 +3909,15 @@
 "settings.agent_api":"API de agentes",
 "settings.agent_relay_connected":"Relay de agentes conectado: ahora una herramienta puede jugar esta partida en esta pestaña.",
 "settings.agent_s_clock":"Reloj del agente",
+"settings.always_2d":"Siempre 2D",
 "settings.an_early_heads_up_below_60":"Un aviso temprano por debajo del 60 % de felicidad, mucho antes de que estén furiosos.",
+"settings.auto_draws_the_map_with_your":"Auto dibuja el mapa con tu tarjeta gráfica cuando el navegador lo permite, y así las redes grandes siguen fluidas. Siempre 2D funciona en todas partes, pero va más lento en mapas grandes.",
 "settings.auto_follows_your_device_s_reduce":"Auto sigue el ajuste de reducir movimiento de tu dispositivo. Desactivado congela el mapa: sin paquetes en movimiento, pulsos ni texto flotante.",
 "settings.customers_and_alerts":"Clientes y alertas",
 "settings.display_and_sound":"Pantalla y sonido",
 "settings.for_reporting_layout_bugs_shows_what":"Para informar de fallos de diseño: muestra lo que tu pantalla le dice al juego.",
 "settings.let_an_ai_agent_drive_this_game":"Deja que un agente de IA juegue",
+"settings.map_drawing":"Dibujo del mapa",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Solo aparecen los problemas y los hitos; todo lo demás va en silencio al registro del NOC. Activado por defecto en Best Effort.",
@@ -3927,6 +3930,7 @@
 "settings.the_agent_moves_it":"Lo mueve el agente",
 "settings.the_clock_while_an_agent_plays":"El reloj mientras juega un agente",
 "settings.the_game_stops_so_you_can":"El juego se detiene para que arregles su servicio antes de que cancelen. Muy útil a alta velocidad.",
+"settings.this_browser_cannot_so_the_map":"Este navegador no puede, así que el mapa se dibuja en 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Avisar cuando un cliente se descontenta",
 "settings.while_agent_mode_is_on_the":"Mientras el modo agente está activo, el reloj no es tuyo. Con un ritmo, corre solo y no se puede pausar a mano, ni siquiera con una ventana abierta (las tuyas incluidas), y espera mientras no haya ningún agente conectado. O lo mueve el agente, y no pasa nada hasta que pide días. La página se conecta al relay local de agentes (npm run dev trae uno), para que herramientas como el servidor MCP jueguen esta partida mientras miras.",
 "share_card.build_the_internet_one_tube_at":"Construye internet, un tubo a la vez",
diff --git a/site/i18n/fr.js b/site/i18n/fr.js
index 2c7461a..85ebe05 100644
--- a/site/i18n/fr.js
+++ b/site/i18n/fr.js
@@ -3909,12 +3909,15 @@
 "settings.agent_api":"API agent",
 "settings.agent_relay_connected":"Relais pour agents connecté : un outil peut maintenant jouer cette partie dans cet onglet.",
 "settings.agent_s_clock":"Horloge de l'agent",
+"settings.always_2d":"Toujours en 2D",
 "settings.an_early_heads_up_below_60":"Une alerte précoce sous 60 % de satisfaction, bien avant qu’il soit furieux.",
+"settings.auto_draws_the_map_with_your":"Auto dessine la carte avec ta carte graphique quand le navigateur le permet, ce qui garde les grands réseaux fluides. Toujours en 2D marche partout mais rame sur les grandes cartes.",
 "settings.auto_follows_your_device_s_reduce":"Auto suit le réglage « réduire les animations » de ton appareil. Inactif fige la carte : plus de paquets en mouvement, de pulsations ni de texte flottant.",
 "settings.customers_and_alerts":"Clients et alertes",
 "settings.display_and_sound":"Affichage et son",
 "settings.for_reporting_layout_bugs_shows_what":"Pour signaler des bugs de mise en page : montre ce que ton écran dit au jeu.",
 "settings.let_an_ai_agent_drive_this_game":"Laisser un agent IA jouer",
+"settings.map_drawing":"Dessin de la carte",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Seuls les problèmes et les étapes s'affichent ; tout le reste va discrètement dans le journal du NOC. Activé par défaut en Best Effort.",
@@ -3927,6 +3930,7 @@
 "settings.the_agent_moves_it":"L'agent l'avance",
 "settings.the_clock_while_an_agent_plays":"L'horloge pendant qu'un agent joue",
 "settings.the_game_stops_so_you_can":"Le jeu s’arrête pour que tu répares leur service avant qu’ils résilient. Surtout utile à grande vitesse.",
+"settings.this_browser_cannot_so_the_map":"Ce navigateur ne peut pas, la carte est donc dessinée en 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Prévenir quand un client devient mécontent",
 "settings.while_agent_mode_is_on_the":"Tant que le mode agent est actif, l'horloge n'est plus à toi. Avec un rythme, elle tourne toute seule et ne peut pas être mise en pause à la main, pas même par une fenêtre ouverte (les tiennes comprises), et elle attend tant qu'aucun agent n'est connecté. Ou bien c'est l'agent qui l'avance, et rien ne se passe tant qu'il ne demande pas de jours. La page se connecte au relais local pour agents (npm run dev en lance un), pour que des outils comme le serveur MCP jouent cette partie pendant que tu regardes.",
 "share_card.build_the_internet_one_tube_at":"Construis Internet, un tube à la fois",
diff --git a/site/i18n/it.js b/site/i18n/it.js
index 3381ff8..31ade7b 100644
--- a/site/i18n/it.js
+++ b/site/i18n/it.js
@@ -3909,12 +3909,15 @@
 "settings.agent_api":"API per agenti",
 "settings.agent_relay_connected":"Relay per agenti collegato: ora uno strumento può giocare questa partita in questa scheda.",
 "settings.agent_s_clock":"Orologio dell'agente",
+"settings.always_2d":"Sempre 2D",
 "settings.an_early_heads_up_below_60":"Un avviso in anticipo sotto il 60% di soddisfazione, molto prima che siano furiosi.",
+"settings.auto_draws_the_map_with_your":"Auto disegna la mappa con la tua scheda grafica quando il browser lo consente, così anche le reti grandi restano fluide. Sempre 2D funziona ovunque ma è più lento sulle mappe grandi.",
 "settings.auto_follows_your_device_s_reduce":"Auto segue l’impostazione “riduci movimento” del tuo dispositivo. Off congela la mappa: niente pacchetti in movimento, pulsazioni o testo fluttuante.",
 "settings.customers_and_alerts":"Clienti e avvisi",
 "settings.display_and_sound":"Schermo e audio",
 "settings.for_reporting_layout_bugs_shows_what":"Per segnalare bug di layout: mostra cosa lo schermo dice al gioco.",
 "settings.let_an_ai_agent_drive_this_game":"Lascia giocare un agente IA",
+"settings.map_drawing":"Disegno della mappa",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Compaiono solo i problemi e i traguardi; tutto il resto finisce in silenzio nel registro del NOC. Attivo di default in Best Effort.",
@@ -3927,6 +3930,7 @@
 "settings.the_agent_moves_it":"Lo muove l'agente",
 "settings.the_clock_while_an_agent_plays":"L'orologio mentre gioca un agente",
 "settings.the_game_stops_so_you_can":"Il gioco si ferma così puoi sistemare il servizio prima che disdicano. Utilissimo ad alta velocità.",
+"settings.this_browser_cannot_so_the_map":"Questo browser non può, quindi la mappa è disegnata in 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Avvisa quando un cliente diventa scontento",
 "settings.while_agent_mode_is_on_the":"Finché la modalità agente è attiva, l'orologio non è tuo. Con un ritmo va da solo e non si può fermare a mano, nemmeno con una finestra aperta (comprese le tue), e aspetta finché non è collegato nessun agente. Oppure lo muove l'agente, e non succede nulla finché non chiede dei giorni. La pagina si collega al relay locale per agenti (npm run dev ne avvia uno), così strumenti come il server MCP possono giocare questa partita mentre guardi.",
 "share_card.build_the_internet_one_tube_at":"Costruisci internet, un tubo alla volta",
diff --git a/site/i18n/pt.js b/site/i18n/pt.js
index e021902..b46d71c 100644
--- a/site/i18n/pt.js
+++ b/site/i18n/pt.js
@@ -3909,12 +3909,15 @@
 "settings.agent_api":"API para agentes",
 "settings.agent_relay_connected":"Relay de agentes ligado: agora uma ferramenta pode jogar este jogo nesta aba.",
 "settings.agent_s_clock":"Relógio do agente",
+"settings.always_2d":"Sempre 2D",
 "settings.an_early_heads_up_below_60":"Um aviso antecipado abaixo de 60% de satisfação, bem antes de ficarem furiosos.",
+"settings.auto_draws_the_map_with_your":"Auto desenha o mapa com sua placa de vídeo quando o navegador permite, o que mantém redes grandes fluidas. Sempre 2D funciona em qualquer lugar, mas é mais lento em mapas grandes.",
 "settings.auto_follows_your_device_s_reduce":"Auto segue a configuração de reduzir movimento do seu aparelho. Desligado congela o mapa: sem pacotes andando, pulsos ou texto flutuante.",
 "settings.customers_and_alerts":"Clientes e alertas",
 "settings.display_and_sound":"Tela e som",
 "settings.for_reporting_layout_bugs_shows_what":"Para reportar bugs de layout: mostra o que sua tela informa ao jogo.",
 "settings.let_an_ai_agent_drive_this_game":"Deixa um agente de IA jogar",
+"settings.map_drawing":"Desenho do mapa",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Só aparecem problemas e marcos; todo o resto vai em silêncio para o registro do NOC. Ligado por padrão no Best Effort.",
@@ -3927,6 +3930,7 @@
 "settings.the_agent_moves_it":"O agente move-o",
 "settings.the_clock_while_an_agent_plays":"O relógio enquanto um agente joga",
 "settings.the_game_stops_so_you_can":"O jogo para para você consertar o serviço antes que cancelem. Muito útil em alta velocidade.",
+"settings.this_browser_cannot_so_the_map":"Este navegador não consegue, então o mapa é desenhado em 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Avisar quando um cliente ficar insatisfeito",
 "settings.while_agent_mode_is_on_the":"Enquanto o modo agente estiver ligado, o relógio não é teu. Com um ritmo, corre sozinho e não pode ser parado à mão, nem por uma janela aberta (as tuas incluídas), e espera enquanto nenhum agente estiver ligado. Ou é o agente que o move, e nada acontece até ele pedir dias. A página liga-se ao relay local de agentes (npm run dev traz um), para que ferramentas como o servidor MCP joguem este jogo enquanto vês.",
 "share_card.build_the_internet_one_tube_at":"Construa a internet, um tubo de cada vez",
diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js
index 7c58a63..e558955 100644
--- a/src/agent/20-commands.js
+++ b/src/agent/20-commands.js
@@ -551,6 +551,6 @@ const API_DENY={
   start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start',
   exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',
   slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots',
-  animSet:'prefs',langSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs',
+  animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs',
   install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',
 };
diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js
index b75c863..4224aac 100644
--- a/src/game/90-actions/10-interface.js
+++ b/src/game/90-actions/10-interface.js
@@ -22,6 +22,7 @@ const ACT={
    toast(B.equity?tr('interface.you_bought_out_bank_they_flew',{bank:esc(B.name)}):tr('interface.loan_from_bank_repaid_early',{bank:esc(B.name)}),'good');after();renderBank();},
  leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=lvl()>=3?'roadm':'lite';openLinkModal(a,b);},
  dashLink:({id})=>{$('dash').hidden=true;selectLink(id);focusLink(id);},
+ mapSet:({v})=>{if(!['auto','2d'].includes(v))return;mapGl(v==='auto');refreshSettings();},
  animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();},
  soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();},
  langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();},
diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js
index 69433ea..3af3af5 100644
--- a/src/game/90-actions/95-puzzles.js
+++ b/src/game/90-actions/95-puzzles.js
@@ -58,6 +58,6 @@ Object.assign(ACT,{
 // 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_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','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/96-map/10-canvas.js b/src/game/96-map/10-canvas.js
index 3210b61..e3021cc 100644
--- a/src/game/96-map/10-canvas.js
+++ b/src/game/96-map/10-canvas.js
@@ -1,5 +1,6 @@
 /* ================= CANVAS ================= */
-const cv=$('map'),ctx=cv.getContext('2d');
+// ctx is the 2D context draw() paints with: the map's own (CTX0), or with WebGL on the overlay above the card (56-webgl.js).
+const cv=$('map'),CTX0=cv.getContext('2d');let ctx=CTX0;
 const cam={x:1050,y:330,z:0.8};
 let CW=0,CH=0,DPR=1;
 /* Installed on an iPhone home screen with a translucent status bar, iOS can report a viewport one status bar
diff --git a/src/game/96-map/30-settings.js b/src/game/96-map/30-settings.js
index 98750ea..348036a 100644
--- a/src/game/96-map/30-settings.js
+++ b/src/game/96-map/30-settings.js
@@ -30,6 +30,7 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${tr('settings.display_and_sound')} ${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))} + ${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glInit()?' '+tr('settings.this_browser_cannot_so_the_map'):''))} ${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])}
${langPick('langSel')}
${seg(tr('common.viewport_info'),'vpSet',VP_T?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_reporting_layout_bugs_shows_what'))} diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index 5c03a54..f737267 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -30,8 +30,9 @@ function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const // Cable names are drawn in one font, so each width is measured once. const LBW=new Map(),labW=t=>{let w=LBW.get(t);if(w===undefined)LBW.set(t,w=ctx.measureText(t).width);return w;}; try{document.fonts&&document.fonts.ready.then(()=>LBW.clear());}catch(e){} -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; +function drawCables(ks){const G=glOn(),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)&&!G; + // On the card the cables are drawn by glBegin(); here only their labels are left. + if(!selC&&z<1.7&&cached)return;if(G&&!selC&&z<1.7)return; ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle'; // Labels that would sit on another, or on a segment shorter than the name, are left out (a selected city's always show). // Placed labels go in a 64px grid, so each check only looks at its neighbours. @@ -41,8 +42,8 @@ function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.dra for(let cx=c0;cx<=c1;cx++)for(let cy=r0;cy<=r1;cy++){const k=cx*8192+cy;let o=LG.get(k);if(!o)LG.set(k,o=[]);o.push(b);}return true;}; 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&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){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(!G&&(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&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,'rgba(255,255,255,.85)',3,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/55-link-look.js b/src/game/96-map/55-link-look.js new file mode 100644 index 0000000..8ca98b6 --- /dev/null +++ b/src/game/96-map/55-link-look.js @@ -0,0 +1,17 @@ +/* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in + 58-webgl-links.js), so they cannot drift apart. */ +// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable. +const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5]]; +// A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. +function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; + const 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); + return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), + col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:bld?3:idle?4:0, + pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills +// The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the +// links and with the day's routing (R), not with the camera, so it is kept until one of those changes. +let MLK=null; +function mapLinks(day){const key=[S.links,S.links.length,R,day]; + if(MLK&&key.every((v,i)=>v===MLK.key[i]))return MLK; + const PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))); + return MLK={key,PI,LG,GM,looks:LG.map(g=>linkLook(g,day))};} diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js new file mode 100644 index 0000000..1469c6c --- /dev/null +++ b/src/game/96-map/56-webgl.js @@ -0,0 +1,59 @@ +/* The map on the graphics card (WebGL2), wherever the browser can; Settings › Map drawing › Always 2D keeps the 2D + canvas instead (a choice per device). A late-game map sends the 2D canvas several strokes per tube every frame (thousands on a + big network) and repaints the land whenever you pan; here the card draws it all from buffers that change only with + the network, so a frame costs the processor a few draws and uniforms. + Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and + packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for + the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used. + Puzzles, and any browser without WebGL2 or whose context fails or is lost, keep the 2D map. */ +const GLX={want:true,dead:false,gl:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,sel:false,shown:false,gpu:''}; +try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){} +const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit(); +// Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not. +function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){} + if(!on)glShow(false);GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;} +function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;} +function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;glShow(false);} +const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n'; +// Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing). +const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n'; +function glProg(gl,vs,fs){const sh=(t,s)=>{const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))throw new Error('shader: '+gl.getShaderInfoLog(x));return x;}; + const p=gl.createProgram();gl.attachShader(p,sh(gl.VERTEX_SHADER,vs));gl.attachShader(p,sh(gl.FRAGMENT_SHADER,fs));gl.linkProgram(p); + if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw new Error('link: '+gl.getProgramInfoLog(p)); + const u={},n=gl.getProgramParameter(p,gl.ACTIVE_UNIFORMS);for(let i=0;ia+x,0)*4; + gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW); + let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;}); + gl.bindVertexArray(null);return {v,b};} +function glInit(){if(GLX.gl)return true;if(GLX.dead)return false; + try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers'); + const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'}); + if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2'); + const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)}; + // The tubes' points for the packets: floats read with texelFetch, never filtered. + const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST); + c.addEventListener('webglcontextlost',e=>{e.preventDefault();glKill('the graphics context was lost');UI.drawnAt=0;}); + try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){} + glsInit(gl); + // The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every + // frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself. + const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype; + for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};} + const V=s=>glVao(gl,s); + Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;} + catch(e){glKill(e);return false;}} +// Colours as [r,g,b,a] from '#rrggbb', '#rgb' or 'rgba(r,g,b,a)', kept by string. +const GLCOL=new Map(); +function glColor(s){let v=GLCOL.get(s);if(v)return v;let r=0,g=0,b=0,a=1; + if(s[0]==='#'){let h=s.slice(1);if(h.length===3)h=h.replace(/./g,x=>x+x);r=parseInt(h.slice(0,2),16)/255;g=parseInt(h.slice(2,4),16)/255;b=parseInt(h.slice(4,6),16)/255;} + else{const m=/rgba?\(([^)]*)\)/.exec(s);if(m){const p=m[1].split(',').map(x=>parseFloat(x));r=p[0]/255;g=p[1]/255;b=p[2]/255;a=p.length>3?p[3]:1;}} + v=[r,g,b,a];GLCOL.set(s,v);return v;} +// Sets a line or a point program's view for copy k of the map (wm: the line width multiplier). +function glSet(gl,P,k,wm){gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.uniform1f(P.u.uWMul,wm);gl.uniform1f(P.u.uDpr,DPR);} +// A full-screen fill, from one premultiplied colour at the bottom to another at the top (the sea), or of one colour +// (the land and the clouds, through the stencil). +const FILL_VS=GL_HEAD+`void main(){vec2 p=vec2((gl_VertexID&1)==0?-1.:1.,(gl_VertexID&2)==0?-1.:1.);gl_Position=vec4(p,0.,1.);}`; +const FILL_FS=GL_HEAD+`uniform vec4 uTop,uBot;uniform float uH;out vec4 o;void main(){o=mix(uBot,uTop,gl_FragCoord.y/uH);}`; +function glFill(gl,top,bot=top){const P=GLX.fill;gl.useProgram(P.p);gl.uniform4fv(P.u.uTop,top);gl.uniform4fv(P.u.uBot,bot);gl.uniform1f(P.u.uH,GLX.c.height);gl.bindVertexArray(GLX.empty);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);} diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js new file mode 100644 index 0000000..d696257 --- /dev/null +++ b/src/game/96-map/57-webgl-background.js @@ -0,0 +1,93 @@ +/* The background on the card, painted first each frame: the sea, the land, the waves, the clouds and the cables, as + the 2D map paints them (drawFrame(), paintWorld()) and in the same colours. The land and the cables are geometry + built once, so panning and zooming repaint nothing; only the waves and the clouds move. */ +const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends +const SEA_TOP=glPm('#62CBEA'),SEA_BOT=glPm('#43AED6'),CLOUD_COL=glPm('rgba(255,255,255,.55)'); +const LAND_SHADOW=glPm('rgba(20,90,130,.35)'),LAND_GRASS=glPm('#9BDA6C'),HILL_COL=glPm('#86CB5B'),HILL_SHINE=glPm('rgba(255,255,255,.18)'); +// The land's fill: a fan of triangles per coastline, counted in the stencil (each pixel flips once per triangle over +// it, so what is inside ends odd), then one cover where the stencil is odd. uOff shifts it in CSS px (the shadow). +const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam; +void main(){gl_Position=clip((aV-uCam.xy)*uCam.z+uView*.5+uOff,uView,0.);}`; +const FAN_FS=GL_HEAD+`out vec4 o;void main(){o=vec4(0.);}`; +// Ellipses (the hills and their shine): centre and radii in map units, one premultiplied colour, smooth edges. +const ELL_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aE;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out vec2 vr; +void main(){vec2 c=(aE.xy-uCam.xy)*uCam.z+uView*.5,r=aE.zw*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m.x:m.x,(gl_VertexID&2)==0?-m.y:m.y);vr=r;gl_Position=clip(c+vq,uView,0.);}`; +const ELL_FS=GL_HEAD+`in vec2 vq;flat in vec2 vr;uniform vec4 uCol;uniform float uDpr;out vec4 o; +void main(){float d=(length(vq/vr)-1.)*min(vr.x,vr.y),a=clamp(.5-d*uDpr,0.,1.);if(a<=0.)discard;o=uCol*a;}`; +// Discs for the stencil only (the clouds' puffs): centre and radius in map units. +const CIRC_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aC;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out float vr; +void main(){vec2 c=(aC.xy-uCam.xy)*uCam.z+uView*.5;float r=aC.z*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vr=r;gl_Position=clip(c+vq,uView,0.);}`; +const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(length(vq)>vr)discard;o=vec4(1.);}`; +/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does): the fan for the + fills, the coastlines as line segments (paintWorld()'s curves, four segments each) for the sand and the dark edge, + and the hills. */ +function glLandGeo(gl,far){const key=far?'far':'all';let G=GLX.land[key];if(G)return G; + const keep=far?new Set(LANDP_FAR):null,fan=[],sand=[],edge=[],SAND=glColor('#F8E6A8'),EDGE=glColor('#1E2640'); + COAST.forEach((ring,ri)=>{if(keep&&!keep.has(LANDP_ALL[ri]))return;const n=ring.length;if(n<3)return; + // As smoothPath(): a quadratic curve from the middle of each side to the next, through the corner between them. + const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2],P=[];let m=mid(ring[n-1],ring[0]);P.push(m); + for(let i=0;inew Float32Array(a); + return GLX.land[key]={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE, + hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};} +// Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map. +function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST); + gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan); + gl.colorMask(false,false,false,false);gl.stencilFunc(gl.ALWAYS,0,1);gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);gl.stencilMask(1); + for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArrays(gl.TRIANGLES,0,G.nFan);} + // The cover paints where the count is odd and sets the stencil back to zero for the next user. + gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,1);gl.stencilOp(gl.ZERO,gl.ZERO,gl.ZERO);gl.stencilMask(255); + glFill(gl,col);gl.disable(gl.STENCIL_TEST);} +function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col); + for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} +// In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline. +function glLand(gl,ks){const G=glLandGeo(gl,lodFar()); + glLandFill(gl,G,ks,5,7,LAND_SHADOW); + glLines(gl,G.sand,G.nSeg,ks); + glLandFill(gl,G,ks,0,0,LAND_GRASS); + glEllipses(gl,G.hills,G.nHill,ks,HILL_COL);glEllipses(gl,G.shine,G.nHill,ks,HILL_SHINE); + glLines(gl,G.edge,G.nSeg,ks);} +// The waves: each one two quadratic curves of four segments, swaying with the map's clock as in drawFrame(). They are +// written into the same array every frame (no garbage for the collector to pick up while you play). +const WAVE_COL=glColor('rgba(255,255,255,.45)'); +function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0; + for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3; + for(const [x0,cx,cy,x1] of [[x-9+o,x-4.5+o,y-4,x+o],[x+o,x+4.5+o,y+4,x+9+o]]){let px=x0,py=y; + for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}} + gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);} +// The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack. +function glClouds(gl,now,ks){const A=[];for(const k of ks)for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100+k*W,y=c.y; + A.push(x,y,16*c.s,0, x+18*c.s,y-8*c.s,20*c.s,0, x+40*c.s,y,15*c.s,0);} + if(!A.length)return;const F=new Float32Array(A),P=GLX.circ;gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cl.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW); + gl.enable(gl.STENCIL_TEST);gl.stencilFunc(gl.ALWAYS,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE);gl.colorMask(false,false,false,false); + gl.useProgram(P.p);gl.bindVertexArray(GLX.cl.v);gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,F.length/4); + gl.colorMask(true,true,true,true);gl.stencilFunc(gl.EQUAL,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);glFill(gl,CLOUD_COL);gl.disable(gl.STENCIL_TEST);} +// The cables, as drawCables() strokes them: rebuilt only when the highlighted city or the architect view changes. +function glCables(gl,ks,selC,ar){const key=[selC,ar]; + if(!GLX.ckey||key.some((v,i)=>v!==GLX.ckey[i])){const A=[]; + for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue; + const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0; + for(let j=0;j+1d.length?`if(k==${i})return vec2(${d[0]}.,${d[1]}.);`:'').join('')}return vec2(0.);} +void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h; + float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false; + if(uPass==${LP.halo}){hw=(w+14.)*.5;col=vec4(1.,79./255.,154./255.,.35);dash=vec2(0.);skip=(fl&${LINE_SEL})==0;} + else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(30./255.,38./255.,64./255.,1.);} + else if(uPass==${LP.dots}){hw=max(1.,w*.25)*.5;col=vec4(1.,1.,1.,.75);dash=dashOf(5);skip=(fl&${LINE_FIBER})==0||uBusy>.5;} + else if(uPass==${LP.plain})col.a=aC.x; + if(skip){gl_Position=vec4(2.,2.,2.,1.);return;} + vec2 d=b-a;float L=length(d);vec2 t=L>1e-4?d/L:vec2(1.,0.),n=vec2(-t.y,t.x);float m=hw+1./uDpr; + float sx=(gl_VertexID&1)==0?-m:L+m,sy=(gl_VertexID&2)==0?-m:m; + vLoc=vec2(sx,sy);vLen=L;vS0=aP.x*uCam.z;vHalf=hw;vCol=col;vDash=dash;vButt=uPass==${LP.plain}&&(fl&${LINE_ROUND})==0?1.:0.; + gl_Position=clip(a+t*sx+n*sy,uView,(uPass==${LP.plain}?.9998:aC.x)*2.-1.);}`; +const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol;flat in vec2 vDash;uniform float uDpr;out vec4 o; +void main(){float x=vLoc.x,y=vLoc.y,d; + if(vButt>.5&&(x<0.||x>vLen))discard; + if(vDash.x<=0.){float c=clamp(x,0.,vLen);d=length(vec2(x-c,y));} + else{float P=vDash.x+vDash.y,g=vS0+x,k=floor(g/P);d=1e9; + for(int i=-1;i<=1;i++){float a0=(k+float(i))*P,lo=max(a0,vS0),hi=min(a0+vDash.x,vS0+vLen);if(lo<=hi){float c=clamp(g,lo,hi);d=min(d,length(vec2(g-c,y)));}}} + float al=clamp((vHalf-d)*uDpr+.5,0.,1.);if(al<=0.)discard;o=vec4(vCol.rgb*vCol.a*al,vCol.a*al);}`; +// Plain lines (coasts, waves, cables): colour and opacity from the data, flat ends unless LINE_ROUND, under the tubes. +function glLines(gl,vao,n,ks){const L=GLX.line;gl.useProgram(L.p);gl.bindVertexArray(vao);gl.uniform1i(L.u.uPass,LP.plain);gl.uniform1f(L.u.uBusy,0); + for(const k of ks){glSet(gl,L,k,1);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} +/* Packets: one instance per packet; where it is on its tube comes from the tube's points (a float texture of x, y and + the share of the length so far, GL_PTS_W texels a row), found by bisection the way polyAtXY() finds it. */ +const GL_PTS_W=2048; +const GL_PK_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aK;layout(location=1) in vec4 aQ; +uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uT,uFar;uniform highp sampler2D uPts; +out vec2 vLoc;flat out float vR,vLw; +vec4 P(int i){return texelFetch(uPts,ivec2(i%${GL_PTS_W},i/${GL_PTS_W}),0);} +void main(){float n=uFar>.5?max(1.,floor(aK.w*.5)):aK.w,i=aQ.x;if(i>=n){gl_Position=vec4(2.,2.,2.,1.);return;} + float t=fract(uT*90./max(aK.z*uCam.z,40.)+i/n);if(mod(i,2.)>.5)t=1.-t; + int o=int(aK.x+.5),lo=1,hi=int(aK.y+.5)-1;for(int s=0;s<16&&lop0.z?(t-p0.z)/(p1.z-p0.z):0.;vec2 c=(mix(p0.xy,p1.xy,f)-uCam.xy)*uCam.z+uView*.5; + float w=aQ.y*uWMul,r=uFar>.5?1.6:max(2.2,w*.42),lw=uFar>.5?1.:1.5,m=r+lw*.5+1./uDpr; + vec2 q=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vLoc=q;vR=r;vLw=lw; + gl_Position=clip(c+q,uView,aQ.z*2.-1.);}`; +const GL_PK_FS=GL_HEAD+`in vec2 vLoc;flat in float vR,vLw;uniform float uDpr;out vec4 o; +void main(){float d=length(vLoc),out_=clamp((vR+vLw*.5-d)*uDpr+.5,0.,1.);if(out_<=0.)discard; + float inn=clamp((vR-vLw*.5-d)*uDpr+.5,0.,1.);vec3 c=mix(vec3(30./255.,38./255.,64./255.),vec3(1.),inn);o=vec4(c*out_,out_);}`; +/* The tubes as instance data: their segments (see LINE_STRIDE; later tubes are nearer), their packets (first point, + points, length, packets | which, base width, depth, -), and every tube's points in the texture. */ +function glBuild(LG,GM,looks,selId){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0; + for(let gi=0;gix.id===selId);if(hot)sel=true;const fl=(hot?LINE_SEL:0)|(L.df&&!L.bld&&!L.dark?LINE_FIBER:0),p0=pi; + for(let j=0;jv!==GLX.key[i])){glBuild(ML.LG,ML.GM,ML.looks,selId);GLX.key=key;} + gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.depthMask(true); + const L=GLX.line,K=GLX.pk,wm=sc*(far?0.5:1),lines=(pass)=>{gl.useProgram(L.p);gl.bindVertexArray(GLX.lv.v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass); + for(const k of ks){glSet(gl,L,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,GLX.nSeg);}}; + if(GLX.nSeg)for(const pass of [LP.casing,LP.colour,LP.dots])lines(pass); + if(GLX.nPk){gl.useProgram(K.p);gl.bindVertexArray(GLX.pv.v);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.uniform1i(K.u.uPts,0); + gl.uniform1f(K.u.uT,now/1000);gl.uniform1f(K.u.uFar,far?1:0);for(const k of ks){glSet(gl,K,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,GLX.nPk);}} + // The selection's halo goes over earlier tubes but under its own line and later ones, as in 2D. + if(GLX.sel&&GLX.nSeg){gl.depthFunc(gl.LESS);gl.depthMask(false);lines(LP.halo);gl.depthMask(true);} + gl.bindVertexArray(null);} diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js new file mode 100644 index 0000000..ff44065 --- /dev/null +++ b/src/game/96-map/59-gl-sprites.js @@ -0,0 +1,76 @@ +/* Pictures on the card. Cities, labels, markers and everything that bobs or pulses on them (cones, ships, offer + bubbles, hot badges, floaters) are painted once with the 2D canvas, packed into one texture (the atlas), and drawn + as instanced quads, with the small round things (lights, steam, glows) as discs, in one draw per frame after the + tubes. Without WebGL the same calls draw the pictures with the 2D canvas, so the map's code does not care which. */ +const SPR_MAX=1400,SPR_STRIDE=13; +const SPRS=new Map(); +const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0}; +/* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its + colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */ +const SPR_VS=GL_HEAD+`layout(location=0) in vec4 aP;layout(location=1) in vec4 aUV;layout(location=2) in vec4 aC;layout(location=3) in float aK; +uniform vec2 uDev;uniform float uDpr;out vec2 vUV,vQ;out vec4 vC;flat out float vK,vR; +void main(){vec2 c=vec2((gl_VertexID&1)==0?0.:1.,(gl_VertexID&2)==0?0.:1.),p; + if(aK>.5){float m=aP.z+1./uDpr;vQ=(c*2.-1.)*m;vR=aP.z;vUV=vec2(0.);p=aP.xy+vQ;} + else{vQ=vec2(0.);vR=0.;vUV=mix(aUV.xy,aUV.zw,c);p=aP.xy+c*aP.zw;} + vC=aC;vK=aK;gl_Position=vec4(p.x*uDpr/uDev.x*2.-1.,1.-p.y*uDpr/uDev.y*2.,0.,1.);}`; +const SPR_FS=GL_HEAD+`uniform sampler2D uTex;uniform float uDpr;in vec2 vUV,vQ;in vec4 vC;flat in float vK,vR;out vec4 o; +void main(){if(vK>.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);} + else o=texture(uTex,vUV)*vC.a;}`; +function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b; + // 4096 px square (64 MB), or what the card allows if that is less (some phones). + GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096); + GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex); + gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null); + for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR); + for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE); + GLS.shx=GLS.shy=GLS.shh=0;} +// Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it). +function spritesReset(){glsDrawNow();SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} +// A picture of w×h CSS px with its anchor at (ax,ay): painted once by paint(g) (the 2D canvas, at the screen's pixel +// density, which is part of the key), and kept in SPRS. +function spriteEntry(key,w,h,ax,ay,paint){key=DPR+'|'+key;let e=SPRS.get(key);if(e)return e; + if(SPRS.size>=SPR_MAX)spritesReset(); + const cv=document.createElement('canvas');cv.width=Math.ceil(w*DPR);cv.height=Math.ceil(h*DPR); + const g=cv.getContext('2d'),saved=ctx;ctx=g; + try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;} + e={cv,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1};SPRS.set(key,e);return e;} +// Puts a picture into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame. +function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog)return false; + const pw=e.cv.width,ph=e.cv.height,A=GLS.size;if(pw>A||ph>A)return false; + if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;} + if(GLS.shy+ph>A){spritesReset();return false;} + const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph); + gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true); + gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,gl.RGBA,gl.UNSIGNED_BYTE,e.cv);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); + Object.assign(e,{up:true,u0:x/A,v0:y/A,u1:(x+pw)/A,v1:(y+ph)/A});return true;} +// The next record in GLS.data, which grows as needed. +function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;} +// Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas. +function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const d=GLS.data,o=glsNext(); + d[o]=x;d[o+1]=y;d[o+2]=w;d[o+3]=h;d[o+4]=e.u0;d[o+5]=e.v0;d[o+6]=e.u1;d[o+7]=e.v1;d[o+8]=d[o+9]=d[o+10]=0;d[o+11]=ctx.globalAlpha;d[o+12]=0;} + else ctx.drawImage(e.cv,x,y,w,h);} +// A round dot of radius r at (x,y), in colour col (CSS colour string) at opacity a, on the card or the 2D canvas. +function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),d=GLS.data,o=glsNext(); + d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;} + else{const sa=ctx.globalAlpha;if(a!==undefined)ctx.globalAlpha=a;ctx.fillStyle=col;ctx.beginPath();ctx.arc(x,y,r,0,7);ctx.fill();ctx.globalAlpha=sa;}} +// A small picture w×h px at scale k with its anchor at (ax,ay), painted once by paint(g) with the origin on the anchor +// (k in steps of 1/24, as the cities), then drawn with the anchor at (x,y). Things that bob or pulse are drawn as these +// at a moving place, so the overlay above the card stays untouched (repainting it costs a whole screen of pixels). +function stamp(key,w,h,ax,ay,k,x,y,paint){const kq=Math.max(1/24,Math.round(k*24)/24),r=k/kq; + const e=spriteEntry(key+'|'+kq,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);}); + blit(e,x-e.ax*r,y-e.ay*r,e.w*r,e.h*r);} +// Text with an outline, centred on (x,y), as a picture placed on whole device pixels; tw is its width, px its size. +function textStamp(t,font,px,tw,fill,stroke,lw,x,y){const W=Math.ceil(tw+lw+4),H=Math.ceil(px*1.5+lw+2); + const e=spriteEntry(['txt',t,font,fill,stroke,lw].join('|'),W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.font=font;g.textAlign='center';g.textBaseline='middle'; + if(lw){g.lineWidth=lw;g.lineJoin='round';g.strokeStyle=stroke;g.strokeText(t,0,0);}g.fillStyle=fill;g.fillText(t,0,0);}); + blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);} +// Sends the queued pictures to the card in one draw. +function glsDrawNow(){const gl=GLX.gl;if(!gl||!GLS.prog||!GLS.n){GLS.n=0;return;} + gl.useProgram(GLS.prog.p);gl.bindVertexArray(GLS.vao);gl.bindBuffer(gl.ARRAY_BUFFER,GLS.buf); + gl.bufferData(gl.ARRAY_BUFFER,GLS.data.subarray(0,GLS.n*SPR_STRIDE),gl.STREAM_DRAW); + gl.uniform2f(GLS.prog.u.uDev,GLX.c.width,GLX.c.height);gl.uniform1f(GLS.prog.u.uDpr,DPR);gl.uniform1i(GLS.prog.u.uTex,0); + gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex); + gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST); + gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,GLS.n);gl.bindVertexArray(null);GLS.n=0;} +// The end of a frame on the card: the pictures go up over the tubes. +function glsFrameEnd(){if(GLS.frame){glsDrawNow();GLS.frame=false;}} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 6324735..321fff0 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -1,11 +1,19 @@ -function draw(now){DFC=new Map();try{drawFrame(now);}finally{DFC=null;}} +function draw(now){DFC=new Map();try{drawFrame(now);}finally{DFC=null;glsFrameEnd();ctx=CTX0;}} +// Rectangles on a 64 px grid: a new one is compared only with the few that share its cells (a plain list made the +// label placement quadratic in the number of cities). +class RGrid{constructor(){this.m=new Map();} + cells(r,f){for(let cx=Math.floor(r.x/64);cx<=Math.floor((r.x+r.w)/64);cx++)for(let cy=Math.floor(r.y/64);cy<=Math.floor((r.y+r.h)/64);cy++)f(cx*100003+cy);} + push(r){this.cells(r,k=>{const a=this.m.get(k);if(a)a.push(r);else this.m.set(k,[r]);});} + hits(r){let h=false;this.cells(r,k=>{if(h)return;const a=this.m.get(k);if(a)for(const q of a)if(r.xlinkGeom(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 far=lodFar(),ML=mapLinks(day),LG=ML.LG,GM=ML.GM,PI=ML.PI,busy=linesOnScreen(GM,ks)>MAP_BUSY; + // WebGL on: the card draws every line and packet now, and the rest (labels, markers, cities…) goes on the overlay. + const G=glOn();if(G)glFrame(ML,ks,far,busy,now,sc);else glShow(false); + for(let gi=0;gix.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; + // Only what sits at the middle of a line is still painted here when the card draws the lines. + if(G&&!(bld||cut&&!vx||sel||z>0.9&&!busy))continue; + const w=w0*sc*(far?0.5:1),np=gm.pts.length; if(SX.length{let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity;for(const p of gm.pts){if(p[0]b)b=p[0];if(p[1]d)d=p[1];}return [a,b,c,d];})()); if((bb[1]+k*W-cam.x)*cam.z+CW/2<-40||(bb[0]+k*W-cam.x)*cam.z+CW/2>CW+40||(bb[3]-cam.y)*cam.z+CH/2<-40||(bb[2]-cam.y)*cam.z+CH/2>CH+40)continue; + let mxx,my; + if(G){const m=gm.mid||(gm.mid=polyAt(gm.pts,gm.cum,.5));mxx=(m[0]+k*W-cam.x)*cam.z+CW/2;my=(m[1]-cam.y)*cam.z+CH/2;}else{ // Screen points as toS() gives them, kept in SX/SY. for(let i=0;i{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;i0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]); + ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(LDASH[dash]);path();ctx.stroke(); + ctx.strokeStyle=col;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(pz&&many){ctx.strokeStyle='#1E2640';ctx.lineWidth=1.3;for(let j=1;jpolyAtXY(SX,SY,gm.cum,t); - if(!cut&&load>0.01){const n=clamp(Math.round(2+u*10),2,12)>>(far?1:0)||1,len=gm.len*z,spd=90; + if(pk){const n=pk>>(far?1:0)||1,len=gm.len*z,spd=90; ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=far?1:1.5; 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;i0.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);} + [mxx,my]=at(.5);} + if(bld){if(far)stamp('bldfar',12,12,6,6,1,mxx,my,g=>{g.fillStyle='#FF8A3D';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,4,0,7);g.fill();g.stroke();});else drawCone(mxx,my,now);} + else if(cut&&!vx){if(far)stamp('cutfar',14,14,7,7,1,mxx,my,g=>{g.fillStyle='#FF4D5E';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,5,0,7);g.fill();g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText('!',0,0.5);});else if(!arPz)drawBackhoe(mxx,my,now,l.sub);} + 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);pill(t,ctx.font,tw,17,8,'#fff','#1E2640','#1E2640',2,mxx,my-0.5,1.5);} // 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]); } @@ -78,7 +92,7 @@ function drawFrame(now){ // 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;if(pzHide(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.xrects.hits(r); const farL=lodFar(); // 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);}} @@ -93,7 +107,7 @@ function drawFrame(now){ const h=farL?6:cityTop(v.C.id,p);const below=farL?v.sy+15:v.sy+16*csc+8,above=farL?v.sy-15:v.sy-h*csc-17*csc;let ly=null; for(const y of [below,above]){const r={x:v.sx-tw/2-2,y:y-10,w:tw+4,h:21};if(!hit(r)){ly=y;rects.push(r);labs.push(r);break;}} // Your POPs may sit over a city icon, but not over another name: that one waits until you zoom in. - if(ly===null&&prio(v)===1)for(const y of [below,above]){const r={x:v.sx-tw/2,y:y-10,w:tw,h:21};if(!labs.some(q=>r.x=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;}} + const font='800 17px "Baloo 2", sans-serif';if(f.w===undefined){ctx.font=font;f.w=ctx.measureText(f.text).width;} + for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;textStamp(f.text,font,17,f.w,f.col,'#fff',4,sx,sy-a*40);ctx.globalAlpha=1;}} } /* A map with more than MAP_BUSY lines on screen (huge late-game networks) is a tangle where nobody reads thousands of overlapping labels or fiber dots, and painting them took about half of every frame. They come back once fewer lines @@ -116,7 +131,7 @@ function linesOnScreen(GM,ks){let n=0;for(const gm of GM){const b=gm.box||(gm.bo for(const k of ks){const x0=(b[0]+k*W-cam.x)*cam.z+CW/2,x1=(b[2]+k*W-cam.x)*cam.z+CW/2,y0=(b[1]-cam.y)*cam.z+CH/2,y1=(b[3]-cam.y)*cam.z+CH/2; if(!(x1<-40||x0>CW+40||y1<-40||y0>CH+40))n++;}}return n;} function ptsBox(pts){let a=Infinity,b=Infinity,c=-Infinity,d=-Infinity;for(const p of pts){if(p[0]c)c=p[0];if(p[1]>d)d=p[1];}return [a,b,c,d];} -function drawCone(x,y,now){const b=Math.sin(now/300)*1.5;ctx.save();ctx.translate(x,y-12+b);ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();ctx.restore();} +function drawCone(x,y,now){stamp('cone',26,28,13,13,1,x,y-12+Math.sin(now/300)*1.5,()=>{ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();});} // Static land + cable map, rendered once per zoom bucket into an offscreen canvas. function paintWorld(c,z,withCables){const LANDP=lodFar()?LANDP_FAR:LANDP_ALL; for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle='rgba(20,90,130,.35)';for(const p of LANDP)c.fill(p);c.restore();} diff --git a/src/game/96-map/70-world-layer.js b/src/game/96-map/70-world-layer.js index ab36726..426de70 100644 --- a/src/game/96-map/70-world-layer.js +++ b/src/game/96-map/70-world-layer.js @@ -21,14 +21,12 @@ function worldLayer(z){ 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); ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(wl.cv,Math.round(DPR*((ox-cam.x)*z+CW/2)),Math.round(DPR*((wl.oy-cam.y)*z+CH/2)),wl.cv.width*f,wl.cv.height*f);} function cableCol(C){return C.price<=0.85?'#14A88C':C.price<=1.1?'#2F7BEA':'#A05AE0';} -function drawBackhoe(x,y,now,sub){ - const b=Math.sin(now/180)*2;ctx.save();ctx.translate(x,y-14+b); +function drawBackhoe(x,y,now,sub){stamp('hoe|'+(sub?1:0),38,32,15,16,1,x,y-14+Math.sin(now/180)*2,()=>{ ctx.strokeStyle='#1E2640';ctx.lineWidth=2.2; if(sub){ // shark fin ctx.fillStyle='#6B7C99';ctx.beginPath();ctx.moveTo(-12,8);ctx.quadraticCurveTo(-2,-14,10,-12);ctx.quadraticCurveTo(4,-2,12,8);ctx.closePath();ctx.fill();ctx.stroke(); }else{ ctx.fillStyle='#FFD23F';rr(-12,-4,18,12,3);ctx.fill();ctx.stroke();rr(-8,-12,10,9,2);ctx.fillStyle='#BDE8FF';ctx.fill();ctx.stroke(); ctx.beginPath();ctx.moveTo(6,0);ctx.lineTo(14,-10);ctx.lineTo(19,2);ctx.stroke();ctx.fillStyle='#1E2640';ctx.beginPath();ctx.arc(-7,10,3,0,7);ctx.arc(2,10,3,0,7);ctx.fill(); - } - ctx.restore(); + }}); } diff --git a/src/game/96-map/80-cities.js b/src/game/96-map/80-cities.js index 31b55ec..d3be7ae 100644 --- a/src/game/96-map/80-cities.js +++ b/src/game/96-map/80-cities.js @@ -1,12 +1,26 @@ // Label widths by text (city labels by id, link labels and far-view labels by text): measuring text every frame is slow. const LBLW={},LINKW=new Map(),LBLF=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false}; -try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;});}catch(e){} +try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;spritesReset();});}catch(e){} +// A label on a pill: its text and look never change, so it is painted once (spriteEntry) and drawn as a picture. The +// centre is x, y; the text sits at y+ty. The pill's box is w×h with corners r; the picture also takes the outline. +function pill(t,font,w,h,r,fill,ink,stroke,lw,x,y,ty){ + const pad=lw+2,W=Math.ceil(w+pad*2),H=Math.ceil(h+pad*2),key=['pill',t,font,w,h,r,fill,ink,stroke,lw,ty].join('|'); + const e=spriteEntry(key,W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.fillStyle=fill;g.strokeStyle=stroke;g.lineWidth=lw; + rr(-w/2,-h/2,w,h,r);g.fill();g.stroke();g.fillStyle=ink;g.font=font;g.textAlign='center';g.textBaseline='middle';g.fillText(t,0,ty);}); + // Whole device pixels, so the text stays as sharp as before. + blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);} +// Zoomed out a city is a small picture (a dot, or your POP's box), kept as a sprite; a POP in trouble glows under it. function drawCityFar(C,sx,sy,sc,now,lyOverride){ const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id); - ctx.save();ctx.translate(sx,sy);ctx.strokeStyle='#1E2640'; - if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.strokeStyle='#1E2640';} + if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9)dot(sx,sy,12,'rgba(255,77,94,1)',.35+.25*Math.sin(now/200)); + const t=cTier(C.id),ph=sel?Math.floor(now/40)%8:-1,key=['far',p?1:0,down?1:0,p&&p.site2?1:0,p?(p.routers||1)>=2?1:0:0,t,hov?1:0,hasIxAt(C.id)?1:0,CM.off.has(C.id)?1:0,CM.inc.has(C.id)?1:0,ph].join('|'); + stamp(key,36,36,18,18,1,sx,sy,()=>cityFarStatic(C,p,down,sel,hov,ph)); + if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride; + pill(t,ctx.font,tw,16,8,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',1.6,sx,ly,1);} +} +function cityFarStatic(C,p,down,sel,hov,ph){ctx.strokeStyle='#1E2640'; + if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-ph;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;ctx.strokeStyle='#1E2640';} if(p){ - if(!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){ctx.fillStyle=`rgba(255,77,94,${.35+.25*Math.sin(now/200)})`;ctx.beginPath();ctx.arc(0,0,12,0,7);ctx.fill();} const col=down?'#8A91A8':'#FF4F9A';ctx.lineWidth=1.8; if(p.site2){ctx.setLineDash([2,2]);ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(9,6);ctx.stroke();ctx.setLineDash([]);ctx.fillStyle=col;rr(5,3,9,7,3);ctx.fill();ctx.stroke();} if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-6,-7,15,10,4);ctx.fill();ctx.stroke();} @@ -15,26 +29,25 @@ function drawCityFar(C,sx,sy,sc,now,lyOverride){ const t=cTier(C.id),r=FAR_R[t]*(hov?1.3:1);if(t===4){ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath();ctx.arc(0,0,r+4.5,0,7);ctx.fill();} ctx.fillStyle=hasIxAt(C.id)?'#FFD23F':'#FFFFFF';ctx.lineWidth=t>=3?1.6:1.3;ctx.beginPath();ctx.arc(0,0,r,0,7);ctx.fill();ctx.stroke();} if(CM.off.has(C.id)){ctx.fillStyle='#16A866';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?9:5,p?-7:-5,3,0,7);ctx.fill();ctx.stroke();} - if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();} - ctx.restore(); - if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride; - ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;rr(sx-tw/2,ly-8,tw,16,8);ctx.fill();ctx.stroke(); - ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);} -} -function drawCity(C,sx,sy,sc,now,lyOverride,dem){ - if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride); - const hot=(UI.hotMap||{})[C.id]; - const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id); - // No room for its skyline here: a quiet dot, a little bigger for bigger cities, until you zoom in (cityRoom). - if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc;ctx.fillStyle=hasIxAt(C.id)?'#FFD23F':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;ctx.beginPath();ctx.arc(sx,sy+2*sc,r,0,7);ctx.fill();ctx.stroke();return;} - const t=cTier(C.id),cs=p?1:CSC[t]; - const k=sc*(hov?1.15:1); - ctx.save();ctx.translate(sx,sy); - if(UI.feed&&UI.feed.has(C.id)){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);} - if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);} - // A flood is filling ports here: they pulse until it is over (#242). - if(p&&R.ddosHot&&R.ddosHot[C.id]){ctx.strokeStyle='#FF4D5E';ctx.lineWidth=3;ctx.setLineDash([4,4]);ctx.lineDashOffset=now/30;ctx.beginPath();ctx.arc(0,-6*k,33*k,0,7);ctx.stroke();ctx.setLineDash([]);} - if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){const a=.35+.25*Math.sin(now/200);ctx.fillStyle=`rgba(255,77,94,${a})`;ctx.beginPath();ctx.arc(0,-6*k,26*k,0,7);ctx.fill();} + if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}} +// A city's picture is painted once per state and kept as a sprite (citySprite). What moves every frame is painted on top +// (cityMoving): the lights, the steam, a flashing IX, the hot badges and the offer bubble. The rings and the glow move too, +// but in steps (cityPhase), so their sprite changes only at a step. +const CSPR_STEP=24; +function cityPhase(C,p,sel,now){const ph={sel:0,dd:0,gl:-1}; + if(sel)ph.sel=Math.floor(now/40)%12; // dash period 12 px, lineDashOffset -now/40 + if(p&&R.ddosHot&&R.ddosHot[C.id])ph.dd=Math.floor(now/30)%8; // dash period 8 px, lineDashOffset now/30 + if(p&&!(p.down>S.day)&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9)ph.gl=Math.round((Math.sin(now/200)+1)*3.5); // 8 levels of .35+.25·sin + return ph;} +// The IX badge. Hot (a flood or a fault) it flashes: cityMoving() then draws it from two pictures, one per colour. +function cityIX(C,p,t,h,hot,now){const mine=!!S.myIx[C.id],joined=hasIxAt(C.id),q=!p&&!hot&&ixQuiet(C.id),Rr=q?6.5:8.5,ix=p?19:SKY_W[t]/2+(q?2:4); + ctx.fillStyle=hot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(ix+Rr*Math.cos(a),-h+2+Rr*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=q?1.4:2;ctx.stroke(); + ctx.fillStyle=mine||hot?'#fff':'#1E2640';ctx.font=`900 ${q?6.5:8}px Nunito, sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',ix,-h+2.5);} +// Everything about the city that does not move, in the city's own frame (origin on the city). Drawn into a sprite. +function cityStatic(C,p,t,cs,k,ph,st){const down=st.down; + if(st.feed){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);} + if(st.sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-ph.sel;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;} + if(p&&R.ddosHot&&R.ddosHot[C.id]){ctx.strokeStyle='#FF4D5E';ctx.lineWidth=3;ctx.setLineDash([4,4]);ctx.lineDashOffset=ph.dd;ctx.beginPath();ctx.arc(0,-6*k,33*k,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;} ctx.scale(k*cs,k*cs); ctx.fillStyle='rgba(30,38,64,.2)';ctx.beginPath();ctx.ellipse(0,9,p?20:SKY_W[t]/2+5,5,0,0,7);ctx.fill(); const h=p?18:SKY_H[t]; @@ -56,30 +69,56 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){ if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-13,-13,34,16,6);ctx.fill();ctx.stroke();} if(p.gen){ctx.fillStyle='#FFD23F';rr(-27,-1,9,11,2);ctx.fill();ctx.stroke();} ctx.fillStyle=down?'#8A91A8':'#FF4F9A';rr(-17,-7,34,16,6);ctx.fill();ctx.stroke(); - if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const t=(now/700+i/3)%1;ctx.fillStyle=`rgba(90,98,130,${0.55*(1-t)})`;ctx.beginPath();ctx.arc(6+i*3,-12-t*18,3+t*4,0,7);ctx.fill();}} if((p.rgen||0)>0){const G=RG[p.rgen||0];ctx.fillStyle=G.badge?'#7CFFB2':'#FFD23F';ctx.beginPath();ctx.arc(17,-7,6,0,7);ctx.fill();ctx.lineWidth=1.8;ctx.stroke();ctx.fillStyle='#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(G.badge||String(G.cls+1),17,-6.5);ctx.lineWidth=2.2;} - const sf=sfOf(R,C.id); - for(let i=0;i<4;i++){const on=down?false:(((now/(160+i*37))|0)+i)%3!==0;ctx.fillStyle=down?'#3B4260':on?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';ctx.beginPath();ctx.arc(-10+i*6.6,1,2.1,0,7);ctx.fill();} if(down){ctx.fillStyle='#fff';ctx.font='900 14px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.fillText('zzz',20,-14);} if(flip)ctx.restore(); ctx.translate(0,-2); } - const ixn=ixName(C.id); - // The IX badge sits at the skyline's top right, whatever its width. - if(ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov)){const mine=!!S.myIx[C.id],joined=hasIxAt(C.id),ixHot=hot&&hot.ix,q=!p&&!ixHot&&ixQuiet(C.id),R=q?6.5:8.5,ix=p?19:SKY_W[t]/2+(q?2:4); - ctx.fillStyle=ixHot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(ix+R*Math.cos(a),-h+2+R*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=q?1.4:2;ctx.stroke(); - ctx.fillStyle=mine||ixHot?'#fff':'#1E2640';ctx.font=`900 ${q?6.5:8}px Nunito, sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',ix,-h+2.5);} - if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const k of ['r','t','p','c']){if(!hot[k])continue;ctx.globalAlpha=pulse;ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-29,y,6.5,0,7);ctx.fill();ctx.globalAlpha=1;ctx.lineWidth=2;ctx.strokeStyle='#1E2640';ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(HOTL[k],-29,y+0.5);y+=14;}} - const off=CM.off.has(C.id); - if(off){const by=-h-16+Math.sin(now/250)*3;ctx.fillStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.ellipse(-2,by,11,9,0,0,7);ctx.fill();ctx.stroke();ctx.beginPath();ctx.moveTo(-5,by+8);ctx.lineTo(-7,by+14);ctx.lineTo(0,by+8);ctx.fillStyle='#fff';ctx.fill();const big=CM.big.has(C.id);ctx.fillStyle=big?'#FF4F9A':'#16A866';ctx.font='900 13px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(big?'$$':'$',-2,by+1);} - const inc=CM.inc.has(C.id); - if(inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);} - ctx.restore(); + if(st.ixDraw&&!st.ixHot)cityIX(C,p,t,h,false,0); + if(st.inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);} +} +// The picture of a city in a given state, at the quantised scale kq: painted once and kept until it is not needed. +function citySprite(C,p,t,cs,kq,ph,st){ + const key=['city',C.id,t,kq,st.down?1:0,p?1:0,p&&p.site2?1:0,p&&p.site2&&siteDown(C.id,'b')?1:0,p&&p.ringcut>S.day?1:0,p?(p.routers||1):0,p&&p.gen?1:0,p?(p.rgen||0):0,C.au?1:0, + st.ixDraw?1:0,st.ixHot?1:0,ixName(C.id)||'',S.myIx[C.id]?1:0,hasIxAt(C.id)?1:0,!p&&ixQuiet(C.id)?1:0,st.feed?1:0,st.sel?ph.sel:-1,ph.dd,st.inc?1:0].join('|'); + const W=Math.ceil(92*kq),H=Math.ceil(84*kq),ax=45*kq,ay=46*kq; + return spriteEntry(key,W,H,ax,ay,g=>{g.translate(ax,ay);cityStatic(C,p,t,cs,kq,ph,st);});} +// The parts that move, in the city's frame at the true scale k. +function cityMoving(C,p,t,cs,k,sx,sy,now,h,st,hot){const down=st.down,K=k*cs; + if(p){// The POP's own frame is shifted 2 down, and mirrored Down Under (C.au): mp() takes a point of that frame to the city's. + const fl=!!C.au,mp=(x,y)=>fl?[-x,-y-2]:[x,y+2],sf=sfOf(R,C.id),at=(x,y)=>{const q=mp(x,y);return [sx+q[0]*K,sy+q[1]*K];}; + if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const tt=(now/700+i/3)%1,[x,y]=at(6+i*3,-12-tt*18);dot(x,y,(3+tt*4)*K,'rgba(90,98,130,1)',0.55*(1-tt));}} + // The four lights: a disc each, lit or not. + for(let i=0;i<4;i++){const lit=down?false:(((now/(160+i*37))|0)+i)%3!==0,[x,y]=at(-10+i*6.6,1),col=down?'#3B4260':lit?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';dot(x,y,2.1*K,col,1);} + } + // A flashing IX: two pictures, one per colour. + if(st.ixDraw&&st.ixHot){const on=Math.sin(now/180)>0,ix=p?19:SKY_W[t]/2+4;stamp('ixhot'+(on?1:0),22,22,11,11,K,sx+ix*K,sy+(2-h)*K,()=>{ctx.translate(-ix,h-2);ctx.strokeStyle='#1E2640';cityIX(C,p,t,h,true,on?1:-1);});} + // Hot badges: the red disc pulses, the ring and the letter over it stay. + if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const kk of ['r','t','p','c']){if(!hot[kk])continue;const bx=sx-29*K,by=sy+y*K;dot(bx,by,6.5*K,'#FF4D5E',pulse); + stamp('hotb|'+HOTL[kk],18,18,9,9,K,bx,by,g=>{g.lineWidth=2;g.strokeStyle='#1E2640';g.beginPath();g.arc(0,0,6.5,0,7);g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(HOTL[kk],0,0.5);});y+=14;}} + // The offer bubble bobs over the city. + if(st.off)stamp('offer|'+(st.big?2:1),30,28,15,12,K,sx-2*K,sy+(-h-16+Math.sin(now/250)*3)*K,g=>{g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=2.2;g.beginPath();g.ellipse(0,0,11,9,0,0,7);g.fill();g.stroke(); + g.beginPath();g.moveTo(-3,8);g.lineTo(-5,14);g.lineTo(2,8);g.fill();g.fillStyle=st.big?'#FF4F9A':'#16A866';g.font='900 13px "Baloo 2", sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(st.big?'$$':'$',0,1);});} +function drawCity(C,sx,sy,sc,now,lyOverride,dem){ + if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride); + const hot=(UI.hotMap||{})[C.id]; + const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id); + // No room for its skyline here: a quiet dot, a little bigger for bigger cities, until you zoom in (cityRoom). + if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc,rq=Math.round(r*4)/4,fill=hasIxAt(C.id)?'#FFD23F':'#FFFFFF',S2=Math.ceil(rq*2+4); + const e=spriteEntry(['quiet',rq,fill].join('|'),S2,S2,S2/2,S2/2,g=>{g.translate(S2/2,S2/2);g.fillStyle=fill;g.strokeStyle='#1E2640';g.lineWidth=1.6;g.beginPath();g.arc(0,0,rq,0,7);g.fill();g.stroke();}); + blit(e,sx-e.ax,sy+2*sc-e.ay,e.w,e.h);return;} + const t=cTier(C.id),cs=p?1:CSC[t],k=sc*(hov?1.15:1),kq=Math.round(k*CSPR_STEP)/CSPR_STEP; + const ixn=ixName(C.id),ixDraw=!!ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov),ixHot=!!(ixDraw&&hot&&hot.ix); + const st={down:!!down,feed:!!(UI.feed&&UI.feed.has(C.id)),sel:!!sel,inc:CM.inc.has(C.id),ixDraw,ixHot,off:CM.off.has(C.id),big:CM.big.has(C.id)}; + const ph=cityPhase(C,p,sel,now),spr=citySprite(C,p,t,cs,kq,ph,st),r=k/kq; + // The glow of a city in trouble pulses: a disc each frame, under the picture (as it was under the skyline). + if(ph.gl>=0)dot(sx,sy-6*k,26*k,'rgba(255,77,94,1)',.35+.25*(2*ph.gl/7-1)); + blit(spr,sx-spr.ax*r,sy-spr.ay*r,spr.w*r,spr.h*r); + cityMoving(C,p,t,cs,k,sx,sy,now,p?18:SKY_H[t],st,hot); // label if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){ ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=LBLW[C.id+(p?1:0)]||(LBLW[C.id+(p?1:0)]=ctx.measureText(t).width+14),ly=lyOverride==null?sy+16*sc+8:lyOverride; - ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(sx-tw/2,ly-9,tw,19,9);ctx.fill();ctx.stroke(); - ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1); + pill(t,ctx.font,tw,19,9,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',2,sx,ly+0.5,0.5); } } diff --git a/src/game/96-map/88-cable-ships.js b/src/game/96-map/88-cable-ships.js index e9af80b..f3a4744 100644 --- a/src/game/96-map/88-cable-ships.js +++ b/src/game/96-map/88-cable-ships.js @@ -24,13 +24,13 @@ function shipAt(s,T){const f=S.fleet&&S.fleet[s.id],H=shipHomePt(s);if(!f||T>=f. else{p=1-(T-f.done)/Math.max(0.01,f.back-f.done);mode='back';} p=clamp(p,0,1);const [x,y]=polyAt(r.pts,r.cum,p),[x2]=polyAt(r.pts,r.cum,clamp(p+(mode==='back'?-0.01:0.01),0,1));return {x,y,m:mode,dx:x2-x||1};} // A cartoon cable ship: red hull, white bridge, the yellow bow sheave cable ships are known by; a wake when under way. -function shipSprite(x,y,face,sc,col,now,mode){const c=ctx;c.save();c.translate(x,y+Math.sin(now/420+x*0.05)*1.2*sc);c.scale(face*sc,sc); +function shipSprite(x,y,face,sc,col,now,mode){const bl=mode==='work'&&Math.floor(now/350)%2; + stamp(['ship',col,face,mode,bl?1:0].join('|'),52,32,26,18,sc,x,y+Math.sin(now/420+x*0.05)*1.2*sc,c=>{c.scale(face,1); if(mode!=='port'&&mode!=='work'){c.strokeStyle='rgba(255,255,255,.85)';c.lineWidth=1.6;c.beginPath();c.moveTo(-10,3);c.quadraticCurveTo(-16,1,-22,4);c.moveTo(-10,5);c.quadraticCurveTo(-15,8,-21,9);c.stroke();} c.fillStyle=col;c.strokeStyle='#1E2640';c.lineWidth=1.6;c.lineJoin='round';c.beginPath();c.moveTo(-11,0);c.lineTo(11,0);c.lineTo(8,6);c.lineTo(-9,6);c.closePath();c.fill();c.stroke(); c.fillStyle='#fff';c.beginPath();c.rect(-7,-7,8,7);c.fill();c.stroke();c.fillStyle='#1E2640';c.fillRect(-5,-5,4,2); c.beginPath();c.arc(9,-2,2.6,0,7);c.fillStyle='#FFD23F';c.fill();c.stroke(); - if(mode==='work'&&Math.floor(now/350)%2){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);} - c.restore();} + if(bl){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}});} function drawShips(ks,now){SHIP_HITS.length=0;if(!S||pzOn()||!S.fleet)return; const T=S.day+(UI.speed?clamp(acc/DAY_MS,0,0.999):0),z=cam.z,sc=Math.max(0.85,Math.min(1.5,Math.sqrt(z)))*(lodFar()?0.9:1.05),list=[]; for(const s of SHIPS){const p=shipAt(s,T);if(p.m==='port'&&z<1.1)continue;list.push({p,s,col:s.club==='prv'?'#7A5CFF':'#FF4D5E'});} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index 85479d9..dd6bd7c 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','keys','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);}); +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','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','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/game/96-map/97-fps-meter.js b/src/game/96-map/97-fps-meter.js new file mode 100644 index 0000000..4ad6efd --- /dev/null +++ b/src/game/96-map/97-fps-meter.js @@ -0,0 +1,11 @@ +/* A frame meter for measuring the map on a real device: open the game once with ?fps (?nofps hides it again). + Frames per second, the slowest frames, the time draw() takes, and which renderer and graphics card draw the map. */ +const FPSM={on:false,el:null,fr:[],dr:[],last:0,shown:0,dms:-1}; +try{const q=location.search;if(/[?&]fps\b/.test(q))localStorage.setItem('sot-fps','1');else if(/[?&]nofps\b/.test(q))localStorage.removeItem('sot-fps'); + FPSM.on=localStorage.getItem('sot-fps')==='1';}catch(e){} +function fpsNote(now){const M=FPSM;if(M.last)M.fr.push(now-M.last);M.last=now;if(M.dms>=0){M.dr.push(M.dms);M.dms=-1;} + if(now-M.shown<500)return;M.shown=now; + if(!M.el){M.el=document.createElement('pre');M.el.id='fpsm';M.el.style.cssText='position:fixed;right:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none;white-space:pre';document.body.appendChild(M.el);} + const f=M.fr.splice(0),d=M.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0),q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-'; + const gl=GLX.shown&&!GLX.dead; + M.el.textContent=`${sum?(f.length*1000/sum).toFixed(0):0} fps · p95 ${q(.95)} ms · max ${q(1)} ms\ndraw ${d.length?(d.reduce((a,x)=>a+x,0)/d.length).toFixed(1):'-'} ms · ${gl?'WebGL':'2D'} · x${UI.speed||0}`+(gl?`\n${GLX.nSeg} segments · ${GLX.nPk} packets\n${GLX.gpu.slice(0,60)}`:'');} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 2020ceb..b139bd3 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -12,7 +12,8 @@ function frame(now){ if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt); 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;} + if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=FPSM.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(FPSM.on)FPSM.dms=performance.now()-d0;} + if(FPSM.on)fpsNote(now); } // dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames // do not (src/agent/, a hidden tab), under the frame's own conditions otherwise. @@ -27,12 +28,12 @@ function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c const r=c.getBoundingClientRect();if(r.top<=1&&r.left<=1&&r.right>=innerWidth-1&&r.bottom>=innerHeight-1)return true;}return false;} /* Paused, or with animations off, the map only changes when you move it, point at something or the network changes. Until then the last frame is still right, so it is not drawn again (phones keep cool). It is redrawn at least once - a second anyway, and every frame while the land picture is still catching up with a zoom. */ + a second anyway, and every frame while the land picture is still catching up with a zoom (the WebGL map has none). */ 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:0,UI.mk?UI.mk.mood:0]; let same=v.length===FRAME.length;for(let i=0;i +
'; const st = (t) => { box.querySelector('#bst').textContent = t; }; - let SAVE = null, MD = ''; + let SAVE = null, MD = '', TRIAL = 0; + // Ends what the last trial left running before the next one starts, so nothing of one lands on the other: the clock + // stops, its frame callback is cancelled (measure() does that, and TRIAL turns away one already queued), and a day + // still being routed in the worker is waited for. Its answer runs dayPost() on the old save; one that never comes is + // dropped (rwDone() ignores an answer to no job). Then the clock's leftovers are cleared. + async function settle() { + UI.speed = 0; TRIAL++; + const t0 = performance.now(); + while (RW.job && performance.now() - t0 < SETTLE) await sleep(10); + if (RW.job) { console.warn('[bench] the route worker did not answer: its day is dropped'); RW.job = null; } + acc = 0; animT = 0; + } + // The save again, with the same random numbers every time (S.rng makes Math.random() follow it, as in a scenario). function fresh() { - S = migrate(JSON.parse(SAVE)); UI.started = true; UI.pitched = true; UI.sel = null; UI.anim = 'on'; applyAnim(); + S = migrate(JSON.parse(SAVE)); S.rng = SEED; UI.started = true; UI.pitched = true; UI.sel = null; UI.anim = 'on'; applyAnim(); closeModal(); compute(); renderAll(); const h = CITY[S.home] || CITIES[0]; cam.x = h.x; cam.y = h.y; } + async function reset() { await settle(); fresh(); } const q = (s, x) => (s.length ? s[Math.min(s.length - 1, Math.floor(s.length * x))] : 0); - async function measure(sc, hz) { - fresh(); cam.z = sc.z; UI.speed = sc.speed; WL.key = null; + async function measure(sc, hz, r) { + await reset(); cam.z = sc.z; UI.speed = sc.speed; WL.key = null; + const trial = TRIAL; await sleep(WARM); - const fr = [], dr = [], day0 = S.day; let last = 0, stop = false, hidden = false, long = 0, panX = cam.x; + const fr = [], dr = [], gpu = [], pend = [], day0 = S.day; let last = 0, stop = false, hidden = false, long = 0, panX = cam.x, raf = 0, glF = 0, flatF = 0, disjoint = 0; + // The card's own time, where the browser lets us read it: a timer around each WebGL draw(), read when it is ready. + const gl = r === 'gl' ? GLX.gl : null; let tq = null; try { tq = gl && gl.getExtension('EXT_disjoint_timer_query_webgl2'); } catch (e) { /* none */ } + const poll = () => { while (pend.length) { const x = pend[0]; if (!gl.getQueryParameter(x, gl.QUERY_RESULT_AVAILABLE)) break; pend.shift(); + const ns = gl.getQueryParameter(x, gl.QUERY_RESULT); gl.deleteQuery(x); if (gl.getParameter(tq.GPU_DISJOINT_EXT)) disjoint++; else gpu.push(ns / 1e6); } }; const D0 = draw; - draw = function (t) { const a = performance.now(); try { return D0(t); } finally { dr.push(performance.now() - a); } }; + draw = function (t) { let x = null; if (tq && GLX.gl === gl && pend.length < 16) { x = gl.createQuery(); gl.beginQuery(tq.TIME_ELAPSED_EXT, x); } + const a = performance.now(); + try { return D0(t); } finally { dr.push(performance.now() - a); if (x) { gl.endQuery(tq.TIME_ELAPSED_EXT); pend.push(x); } if (GLX.shown) glF++; else flatF++; } }; let po = null; try { po = new PerformanceObserver((l) => { long += l.getEntries().length; }); po.observe({ type: 'longtask' }); } catch (e) { /* not in this browser */ } // Frames slower than three refreshes, with the day they fell on and their draw(): where the stutters are. const t00 = performance.now(), slow = []; - const tick = (t) => { if (last) { fr.push(t - last); if (t - last > 50) slow.push({ at: Math.round(t - t00), ms: Math.round(t - last), day: S.day, draw: +(dr[dr.length - 1] || 0).toFixed(1) }); } last = t; if (document.hidden) hidden = true; + const tick = (t) => { if (stop || trial !== TRIAL) return; + if (last) { fr.push(t - last); if (t - last > 50) slow.push({ at: Math.round(t - t00), ms: Math.round(t - last), day: S.day, draw: +(dr[dr.length - 1] || 0).toFixed(1) }); } last = t; if (document.hidden) hidden = true; if (sc.pan) { panX += 0.18 * (t - (tick.p || t)) / cam.z; cam.x = panX; tick.p = t; } - if (!stop) requestAnimationFrame(tick); }; - requestAnimationFrame(tick); - const t0 = performance.now(); await sleep(SECS * 1000); stop = true; const T = (performance.now() - t0) / 1000; + if (tq) poll(); + raf = requestAnimationFrame(tick); }; + raf = requestAnimationFrame(tick); + const t0 = performance.now(); await sleep(SECS * 1000); stop = true; cancelAnimationFrame(raf); const T = (performance.now() - t0) / 1000; draw = D0; if (po) po.disconnect(); UI.speed = 0; - const s = fr.slice().sort((a, b) => a - b), d = dr.slice().sort((a, b) => a - b), budget = 1000 / hz; + if (tq) { poll(); for (const x of pend) gl.deleteQuery(x); } + const s = fr.slice().sort((a, b) => a - b), d = dr.slice().sort((a, b) => a - b), g = gpu.slice().sort((a, b) => a - b), budget = 1000 / hz; return { fps: +(fr.length / T).toFixed(1), p50: +q(s, 0.5).toFixed(1), p95: +q(s, 0.95).toFixed(1), p99: +q(s, 0.99).toFixed(1), max: +q(s, 1).toFixed(1), dropped: +(100 * fr.filter((x) => x > budget * 1.5).length / Math.max(1, fr.length)).toFixed(1), drawMs: +(d.reduce((a, x) => a + x, 0) / Math.max(1, d.length)).toFixed(2), drawP95: +q(d, 0.95).toFixed(2), + gpuMs: g.length ? +(g.reduce((a, x) => a + x, 0) / g.length).toFixed(2) : null, gpuP95: g.length ? +q(g, 0.95).toFixed(2) : null, gpuN: g.length, disjoint, + // Which map really drew the frames: a WebGL run that fell back to 2D (or a 2D run on the card) is not what it says. + drawn: glF && flatF ? 'mixed' : glF ? 'gl' : flatF ? '2d' : 'none', glFrames: glF, flatFrames: flatF, daysPerSec: +((S.day - day0) / T).toFixed(2), longTasks: long, hidden, drawMax: +q(d, 1).toFixed(1), slow }; } + // Several runs of one scenario: the median of each number; the flags and the stutters of all of them. + function merge(ms) { + if (ms.length === 1) return ms[0]; + const o = {}, med = (a) => { const s = a.slice().sort((x, y) => x - y); return s[(s.length - 1) >> 1]; }; + for (const k of Object.keys(ms[0])) { + const v = ms.map((m) => m[k]); + o[k] = k === 'slow' ? v.flat() : k === 'drawn' ? [...new Set(v)].join('+') : typeof v[0] === 'boolean' ? v.some(Boolean) : v.every((x) => typeof x === 'number') ? med(v) : v[0]; + } + o.runs = ms.length; return o; + } async function refresh() { const a = []; let l = 0; await new Promise((r) => { const f = (t) => { if (l) a.push(t - l); l = t; if (a.length < 90) requestAnimationFrame(f); else r(); }; requestAnimationFrame(f); }); a.sort((x, y) => x - y); return Math.round(1000 / a[a.length >> 1]); } function table(res, env) { - const rows = SCEN.map((sc) => { const a = res['2d'][sc.id], b = res.gl && res.gl[sc.id]; - const f = (m, k, u = '') => (m ? `${m[k]}${u}` : '-'); - return `| ${sc.label} | ${f(a, 'fps')} | ${f(b, 'fps')} | ${f(a, 'p95', ' ms')} | ${f(b, 'p95', ' ms')} | ${f(a, 'drawMs', ' ms')} | ${f(b, 'drawMs', ' ms')} |`; }); - return [`**${env.gpu || 'unknown GPU'}** · ${env.ua}`, `${env.w}×${env.h} at ${env.dpr}× · ${env.hz} Hz screen · ${env.cores} threads · ${env.save}`, '', - '| Scenario | 2D fps | WebGL fps | 2D p95 frame | WebGL p95 frame | 2D draw() | WebGL draw() |', - '|---|--:|--:|--:|--:|--:|--:|', ...rows, - '', `p95 frame: the slowest 5% of frames. draw(): CPU time per frame on the main thread.${env.invalid ? ' ⚠️ The tab was hidden during a run: those numbers are not valid.' : ''}`].join('\n'); + const gpu = res.gl && SCEN.some((sc) => res.gl[sc.id] && res.gl[sc.id].gpuMs != null); + const rows = SCEN.map((sc) => { const a = res['2d'] && res['2d'][sc.id], b = res.gl && res.gl[sc.id]; + const f = (m, k, u = '') => (m && m[k] != null ? `${m[k]}${u}` : '-'); + return `| ${sc.label} | ${f(a, 'fps')} | ${f(b, 'fps')} | ${f(a, 'p95', ' ms')} | ${f(b, 'p95', ' ms')} | ${f(a, 'drawMs', ' ms')} | ${f(b, 'drawMs', ' ms')} |${gpu ? ` ${f(b, 'gpuMs', ' ms')} |` : ''}`; }); + // A run is only what it says if its frames were drawn by the map it names. + const off = []; for (const [r, want] of [['2d', '2d'], ['gl', 'gl']]) for (const sc of SCEN) { const m = res[r] && res[r][sc.id]; if (m && m.drawn !== want && m.drawn !== 'none') off.push(`${sc.label} (${r === 'gl' ? 'WebGL' : '2D'}: ${m.flatFrames} frames in 2D, ${m.glFrames} on the card)`); } + return [`**${env.gpu || 'unknown GPU'}** · ${env.ua}`, `${env.w}×${env.h} at ${env.dpr}× · ${env.hz} Hz screen · ${env.cores} threads · ${env.save}${env.reps > 1 ? ` · median of ${env.reps} runs` : ''}`, '', + `| Scenario | 2D fps | WebGL fps | 2D p95 frame | WebGL p95 frame | 2D draw() | WebGL draw() |${gpu ? ' WebGL GPU |' : ''}`, + `|---|--:|--:|--:|--:|--:|--:|${gpu ? '--:|' : ''}`, ...rows, + '', `fps and p95 frame: requestAnimationFrame's cadence (p95: the slowest 5% of frames). draw(): CPU time on the main thread to build and submit a frame; the card may still be working when it returns, so it is not the cost of drawing.${gpu ? ' WebGL GPU: the card\'s own time per frame (EXT_disjoint_timer_query_webgl2).' : ' No GPU timer in this browser: the card\'s own time is not measured.'}${env.invalid ? ' ⚠️ The tab was hidden during a run: those numbers are not valid.' : ''}`, + ...(off.length ? ['', `⚠️ Not drawn by the map they name: ${off.join('; ')}.`] : [])].join('\n'); } async function run() { const go = box.querySelector('#bgo'); go.disabled = true; save = () => {}; // An incident pauses the game (autoPause): the clock must keep running for the timings to mean anything. autoPause = () => false; - fresh(); UI.speed = 0; st('Measuring the screen refresh…'); await sleep(500); + await reset(); st('Measuring the screen refresh…'); await sleep(500); const hz = await refresh(); - const want0 = GLX.want, glOk = mapGl(true, false) && glInit(); const env = { gpu: GLX.gpu, ua: navigator.userAgent.replace(/^Mozilla\/5\.0 /, ''), w: innerWidth, h: innerHeight, dpr: devicePixelRatio, hz, cores: navigator.hardwareConcurrency, save: `${Object.keys(S.pops).length} POPs · ${S.links.length} links` }; + const want0 = GLX.want, glOk = mapGl(true, false) && glInit(); const env = { gpu: GLX.gpu, ua: navigator.userAgent.replace(/^Mozilla\/5\.0 /, ''), w: innerWidth, h: innerHeight, dpr: devicePixelRatio, hz, cores: navigator.hardwareConcurrency, save: `${Object.keys(S.pops).length} POPs · ${S.links.length} links`, reps: REPS }; mapGl(false, false); - const res = { '2d': {}, gl: glOk ? {} : null }; - for (const r of (glOk ? ['2d', 'gl'] : ['2d']).filter((x) => !ONLY || x === ONLY)) { mapGl(r === 'gl', false); - for (const sc of SCEN) { st(`${r === 'gl' ? 'WebGL' : '2D'} · ${sc.label} (${SECS}s)… keep this tab in front`); const m = await measure(sc, hz); res[r][sc.id] = m; if (m.hidden) env.invalid = true; } } - mapGl(want0, false); fresh(); UI.speed = 0; + const rends = (glOk ? ['2d', 'gl'] : ['2d']).filter((x) => !ONLY || x === ONLY), all = {}; + // Scenario by scenario, both renderers in turn, the first one changing every time: neither always runs on a cold or + // a tired browser. + let n = 0; + for (let rep = 0; rep < REPS; rep++) for (const [i, sc] of SCEN.entries()) for (const r of (rep + i) % 2 ? rends.slice().reverse() : rends) { + mapGl(r === 'gl', false); n++; + st(`${r === 'gl' ? 'WebGL' : '2D'} · ${sc.label}${REPS > 1 ? ` · run ${rep + 1}/${REPS}` : ''} (${SECS}s, ${n}/${REPS * SCEN.length * rends.length})… keep this tab in front`); + const m = await measure(sc, hz, r); ((all[r] = all[r] || {})[sc.id] = all[r][sc.id] || []).push(m); if (m.hidden) env.invalid = true; + } + const res = { '2d': null, gl: null }; + for (const r of Object.keys(all)) { res[r] = {}; for (const id of Object.keys(all[r])) res[r][id] = merge(all[r][id]); } + mapGl(want0, false); await reset(); MD = table(res, env); st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).'); box.querySelector('#bout').innerHTML = '
' + MD.replace(/&/g, '&').replace(/';
     box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
     try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
   }
+  // tests/gpu-bench.test.js drives the pieces without the panel.
+  if (CFG.expose) { window.__bench = { settle, reset, measure, merge, table, setSave: (s) => { SAVE = s; } }; return; }
   addEventListener('load', async () => {
     document.body.appendChild(box);
     while (typeof migrate !== 'function' || typeof GLX === 'undefined') await sleep(50);
@@ -88,7 +144,8 @@
     await sleep(800);
     try { SAVE = JSON.stringify((await (await fetch('/__bench/save.json')).json()).S || null); } catch (e) { st('Could not load the save: ' + e); return; }
     if (SAVE === 'null') { st('The save file has no game in it.'); return; }
-    st(`Ready: ${SCEN.length} scenarios × 2 renderers, about ${Math.ceil(SCEN.length * 2 * (SECS + 3) / 60)} minutes. Keep this tab in front and do not touch the map.`);
+    const runs = SCEN.length * (ONLY ? 1 : 2) * REPS;
+    st(`Ready: ${SCEN.length} scenarios × ${ONLY ? 1 : 2} renderers${REPS > 1 ? ` × ${REPS}` : ''}, about ${Math.ceil(runs * (SECS + 3) / 60)} minutes. Keep this tab in front and do not touch the map.`);
     const go = box.querySelector('#bgo'); go.disabled = false; go.onclick = () => run().catch((e) => st('Failed: ' + (e && e.stack || e)));
     box.querySelector('#bcp').onclick = () => navigator.clipboard.writeText(MD).then(() => st('Copied.'), () => st('Copy failed: select the table instead.'));
     if (/[?&]auto\b/.test(location.search)) go.onclick();
diff --git a/scripts/perf-bench.js b/scripts/perf-bench.js
index 272e9ac..2732cf2 100644
--- a/scripts/perf-bench.js
+++ b/scripts/perf-bench.js
@@ -98,7 +98,10 @@ md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its
 const slow = base ? slowIn(res, 2) : [];
 const { PROFILES } = browser ? require('./perf-browser') : { PROFILES: [] };
 for (const p of PROFILES) {
-  md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.\n\n` + table(browser.profiles[p.key], 2 * p.rate);
+  // The map row is the whole frame, up to a pixel read back from the surface that drew it; say which one that was.
+  const mp = browser.profiles[p.key].maps, mapName = (m) => (!m || !m.length ? 'no map' : m.map((x) => (x === 'gl' ? 'WebGL' : '2D canvas')).join(' then '));
+  const drew = mp ? ` The map was drawn with ${base ? `${mapName(mp.base)} (base) and ${mapName(mp.head)} (this PR)` : mapName(mp.head)}; its row waits for that surface to finish.` : '';
+  md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.${drew}\n\n` + table(browser.profiles[p.key], 2 * p.rate);
   if (base) slow.push(...slowIn(browser.profiles[p.key], 2 * p.rate).map((l) => `${l} (Chromium ${p.key})`));
 }
 if (base) {
diff --git a/scripts/perf-browser.js b/scripts/perf-browser.js
index a8a7123..01bf39e 100644
--- a/scripts/perf-browser.js
+++ b/scripts/perf-browser.js
@@ -36,10 +36,15 @@ async function openPage(browser, profile, file, save, errors) {
   // One run of a workload, timed inside the page so the round trip to Node does not count. Garbage is collected
   // first, so a run never pays for the one before it (its own garbage still costs it, as in the game).
   // The browser leaves layout and canvas drawing for the next frame, so code that changes the DOM or draws the map
-  // would look free: each run ends by forcing both (reading a size, and one pixel back from the map canvas).
+  // would look free: each run ends by forcing both (reading a size, and one pixel back from the surface the map was
+  // last drawn on: the WebGL canvas when the card drew it, which waits for the card to finish, else the 2D canvas).
+  // A run also says which map drew (gl, 2d, or none when it drew nothing).
   const time = async (k, body) => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(([k, body]) => {
     const F = window.__fx || (window.__fx = {}); const f = F[k] || (F[k] = new Function(body)); const map = document.getElementById('map').getContext('2d');
-    const t = performance.now(); f(); void document.documentElement.offsetHeight; map.getImageData(0, 0, 1, 1); return performance.now() - t; }, [k, body]); };
+    const G = typeof GLX === 'object' ? GLX : null, px = window.__px || (window.__px = new Uint8Array(4));
+    const t = performance.now(); f(); void document.documentElement.offsetHeight;
+    const gl = G && G.shown && G.gl; if (gl) gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); else map.getImageData(0, 0, 1, 1);
+    return { ms: performance.now() - t, map: G && G.shown ? 'gl' : '2d' }; }, [k, body]); };
   return { ctx, time };
 }
 
@@ -54,15 +59,18 @@ async function runBrowser({ head, base, save, metrics, runs, exe }) {
     for (const p of PROFILES) {
       const h = await openPage(hb, p, head, save, errors), b = base ? await openPage(bb, p, base, save, errors) : null;
       const res = out.profiles[p.key] = {};
+      // Which map each version drew with, over all the runs that drew one (a version falling back mid-run shows both).
+      const maps = res.maps = { head: new Set(), base: new Set() };
       for (const [k, , body] of metrics) {
-        const H = [], B = [];
+        const H = [], B = [], go = async (v, into, m) => { const r = await v.time(k, body); into.push(r.ms); if (k === 'map') m.add(r.map); };
         for (const v of [h, b].filter(Boolean)) { await v.time(k, body); await v.time(k, body); }   // warm up
         for (let i = 0; i < runs; i++) {
           // Alternate who goes first, like the jsdom runs.
-          if (b && i % 2) { B.push(await b.time(k, body)); H.push(await h.time(k, body)); } else { H.push(await h.time(k, body)); if (b) B.push(await b.time(k, body)); }
+          if (b && i % 2) { await go(b, B, maps.base); await go(h, H, maps.head); } else { await go(h, H, maps.head); if (b) await go(b, B, maps.base); }
         }
         res[k] = { head: median(H), base: b ? median(B) : null, samples: { head: H.map((x) => +x.toFixed(1)), base: b ? B.map((x) => +x.toFixed(1)) : null } };
       }
+      res.maps = { head: [...maps.head], base: b ? [...maps.base] : null };
       await h.ctx.close(); if (b) await b.ctx.close();
     }
   } finally { await hb.close(); if (bb) await bb.close(); }
diff --git a/tests/gpu-bench.test.js b/tests/gpu-bench.test.js
new file mode 100644
index 0000000..d72670c
--- /dev/null
+++ b/tests/gpu-bench.test.js
@@ -0,0 +1,80 @@
+// The GPU benchmark's panel (scripts/lib/gpu-bench-client.js): one trial must never reach into the next. A day the route
+// worker is still routing lands on the save it was routed for, a pan's frame callback stops with its trial, every
+// trial starts from the same random numbers, and the table says which map really drew each run.
+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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+const CLIENT = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'gpu-bench-client.js'), 'utf8');
+
+function open(cfg = {}) {
+  const h = load({ seed: 777 });
+  h.ev(`window.__BENCH__=${JSON.stringify({ expose: true, secs: 0.15, warm: 0, settleMs: 300, ...cfg })};`);
+  h.ev(CLIENT);
+  h.ev(`__bench.setSave(${JSON.stringify(SAVE)});save=()=>{};`);
+  return h;
+}
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// A day in flight in the worker when the trial ends: rwDone() would run its dayPost() whenever the answer comes.
+const IN_FLIGHT = `window.__old=S;RW.seq=41;RW.job={seq:41,d:201,gen:RW.gen-1,t:0};window.__posts=[];
+  dayPost=function(d){__posts.push({d,old:S===__old});};`;
+
+test('a late answer from the route worker lands on the trial it belongs to, not the next one', async () => {
+  const { ev, errors } = open();
+  await ev('__bench.reset()');
+  ev(IN_FLIGHT);
+  ev('setTimeout(()=>rwDone({seq:41}),60)');
+  await ev('__bench.reset()');
+  assert.deepEqual(JSON.parse(ev('JSON.stringify(__posts)')), [{ d: 201, old: true }], 'its day ran on the old save, before the new one was loaded');
+  assert.equal(ev('S!==__old&&RW.job===null'), true);
+  assert.deepEqual(errors, []);
+});
+
+test('an answer that never comes is dropped, and coming late it changes nothing', async () => {
+  const { ev, errors } = open();
+  await ev('__bench.reset()');
+  ev(IN_FLIGHT);
+  ev('console.warn=()=>{}');
+  await ev('__bench.reset()');
+  assert.equal(ev('RW.job'), null, 'the next trial does not wait for it forever');
+  ev('rwDone({seq:41})');
+  assert.deepEqual(JSON.parse(ev('JSON.stringify(__posts)')), [], 'nothing ran on the new save');
+  assert.deepEqual(errors, []);
+});
+
+test('a pan stops with its trial: the next trial’s camera is left alone', async () => {
+  const { ev, errors } = open();
+  const m = JSON.parse(await ev('__bench.measure({id:"pan",pan:true,z:1.4,speed:0},60,"2d").then(JSON.stringify)'));
+  assert.ok(m.fps > 0, 'the pan ran');
+  ev('cam.x=0');
+  await wait(120);
+  assert.equal(ev('cam.x'), 0, 'no frame of the pan came after it');
+  const x8 = await ev('(async()=>{const p=__bench.measure({id:"x8",z:1.4,speed:8},60,"2d");await new Promise(r=>setTimeout(r,20));const x=cam.x;await p;return [x,cam.x];})()');
+  assert.equal(x8[0], x8[1], 'the next scenario keeps its camera where it put it');
+  assert.deepEqual(errors, []);
+});
+
+test('every trial starts from the same random numbers and an empty clock', async () => {
+  const { ev, errors } = open();
+  const draws = async () => { await ev('acc=12345;animT=999;__bench.reset()'); return ev('JSON.stringify([acc,animT,Math.random(),Math.random(),Math.random()])'); };
+  const a = await draws(), b = await draws();
+  assert.equal(a, b);
+  assert.deepEqual(JSON.parse(a).slice(0, 2), [0, 0]);
+  assert.deepEqual(errors, []);
+});
+
+test('the table says which map drew each run, and what each column measures', () => {
+  const { ev } = open();
+  const md = ev(`(()=>{const m=(drawn,gl,flat,gpu)=>({fps:60,p95:17,drawMs:1,drawn,glFrames:gl,flatFrames:flat,gpuMs:gpu});
+    const res={'2d':{'x1-mid':m('2d',0,300,null)},gl:{'x1-mid':m('mixed',12,288,0.8)}};
+    return __bench.table(res,{gpu:'stub',ua:'ua',w:1,h:1,dpr:1,hz:60,cores:1,save:'s',reps:1});})()`);
+  assert.match(md, /WebGL GPU/, 'a GPU column when the card timed its frames');
+  assert.match(md, /CPU time on the main thread/, 'draw() is said to be CPU time');
+  assert.match(md, /Not drawn by the map they name: Map at x1 \(zoom 1\.4\) \(WebGL: 288 frames in 2D/, 'a run that fell back to 2D is flagged');
+  const merged = JSON.parse(ev(`JSON.stringify(__bench.merge([{fps:50,drawn:'gl',hidden:false,slow:[1]},{fps:70,drawn:'gl',hidden:true,slow:[2]},{fps:60,drawn:'2d',hidden:false,slow:[]}]))`));
+  assert.deepEqual(merged, { fps: 60, drawn: 'gl+2d', hidden: true, slow: [1, 2], runs: 3 });
+});

From 39941c257e5704b4a01ef8edb2431dd285636fba Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 14:45:48 +0100
Subject: [PATCH 315/491] WebGL map: keep the 2D map where WebGL is drawn by
 the processor
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

With the perf benchmark now waiting for the surface the map was drawn on,
headless Chromium showed what WebGL costs without a graphics card: its
SwiftShader renderer spends about 8 µs per instance, so the coastlines alone
(29k segments, twice) took about 480 ms and a big map 1.4 s a frame, where the
2D canvas takes 46 ms. Players get the same with a blocked driver, a virtual
machine or Mesa's llvmpipe. glInit() now reads the renderer first and keeps
the 2D map on SwiftShader, llvmpipe, softpipe, lavapipe, WARP or any
"software" renderer; GLX.soft lets the GPU benchmark measure them anyway.
---
 CHANGELOG.md                    |  2 +-
 scripts/lib/gpu-bench-client.js |  2 ++
 src/game/96-map/56-webgl.js     |  9 +++++++--
 tests/webgl-map.test.js         | 25 +++++++++++++++++++++++++
 4 files changed, 35 insertions(+), 3 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 64021a0..1f268f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,7 @@ All notable changes to this project are documented here. The project follows
 - The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts.
 - Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid.
 - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in.
-- The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same; Settings › Map drawing › Always 2D keeps the old drawing, and browsers without WebGL2 keep it on their own, as does a game whose graphics card fails while you play.
+- The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same; Settings › Map drawing › Always 2D keeps the old drawing, and browsers without WebGL2 or without a usable graphics card keep it on their own, as does a game whose graphics card fails while you play.
 - Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the usual map also draws far fewer shapes each frame.
 
 ## [2.9.1] — 2026-11-04
diff --git a/scripts/lib/gpu-bench-client.js b/scripts/lib/gpu-bench-client.js
index 4fe4d42..690fbb3 100644
--- a/scripts/lib/gpu-bench-client.js
+++ b/scripts/lib/gpu-bench-client.js
@@ -139,6 +139,8 @@
   addEventListener('load', async () => {
     document.body.appendChild(box);
     while (typeof migrate !== 'function' || typeof GLX === 'undefined') await sleep(50);
+    // A software renderer is measured too here (the game itself keeps the 2D map on one); the table names the renderer.
+    GLX.soft = true;
     // ?dpr=2 draws the map as a screen of that density would (a 4K screen's pixels, measured on a smaller one).
     const DPRQ = +QS.get('dpr'); if (DPRQ > 0) { Object.defineProperty(window, 'devicePixelRatio', { get: () => DPRQ }); resize(); WL.key = null; }
     await sleep(800);
diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js
index 5306506..d6be4f4 100644
--- a/src/game/96-map/56-webgl.js
+++ b/src/game/96-map/56-webgl.js
@@ -5,9 +5,13 @@
    Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and
    packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for
    the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used.
-   Puzzles, and any browser without WebGL2 or whose context fails or is lost, keep the 2D map. */
+   Puzzles, and any browser without WebGL2 or whose context fails or is lost, keep the 2D map. So does WebGL drawn by
+   the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs
+   microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */
 const GLX={want:true,dead:false,gl:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''};
 try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){}
+// Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark).
+const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i;
 const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit();
 // Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not.
 function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){}
@@ -33,11 +37,12 @@ function glInit(){if(GLX.gl)return true;if(GLX.dead)return false;
   try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers');
     const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'});
     if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');
+    try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){}
+    if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu);
     const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)};
     // The tubes' points for the packets: floats read with texelFetch, never filtered.
     const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST);
     c.addEventListener('webglcontextlost',e=>{e.preventDefault();glKill('the graphics context was lost');UI.drawnAt=0;});
-    try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){}
     glsInit(gl);
     // The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every
     // frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself.
diff --git a/tests/webgl-map.test.js b/tests/webgl-map.test.js
index baacae9..2d70dea 100644
--- a/tests/webgl-map.test.js
+++ b/tests/webgl-map.test.js
@@ -305,3 +305,28 @@ test('selecting a tube sends its halo to the card, not the network again', () =>
   assert.equal(r.haloDraw, 0, 'and the halo is gone');
   assert.deepEqual(errors, []);
 });
+
+// A WebGL2 context that compiles everything and names its renderer: enough for glInit() to run to the end.
+const FAKE_GL = (name) => `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};const c=document.getElementById('mapgl');c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){
+  if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+  if(k==='getExtension')return ()=>({UNMASKED_RENDERER_WEBGL:'REN'});
+  if(k==='getParameter')return (p)=>p==='REN'?${JSON.stringify(name)}:p==='ACTIVE_UNIFORMS'?0:4096;
+  if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
+  return ()=>({});}});})()`;
+
+test('a graphics card drawn by the processor keeps the 2D map; a real one gets the card', () => {
+  for (const [name, gl] of [['ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)', false],
+    ['llvmpipe (LLVM 17.0.6, 256 bits)', false], ['Microsoft Basic Render Driver', false],
+    ['ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 Direct3D11 vs_5_0 ps_5_0, D3D11)', true], ['Apple M2', true], ['Mali-G78', true]]) {
+    const { ev } = open();
+    ev(FAKE_GL(name));
+    ev('console.warn=()=>{}');
+    assert.equal(ev('glInit()'), gl, name);
+    assert.equal(ev('GLX.dead'), !gl, name);
+    assert.equal(ev('GLX.gpu'), name, 'the renderer is still named');
+  }
+  const { ev } = open();
+  ev(FAKE_GL('SwiftShader driver'));
+  ev('GLX.soft=true');
+  assert.equal(ev('glInit()'), true, 'the GPU benchmark can still measure it');
+});

From 2ff634a0eddaca06e5d1fd682cdfd4dbf5a777d9 Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 16:37:32 +0100
Subject: [PATCH 316/491] WebGL map: paint the card's pictures on one canvas,
 so a long zoom keeps the context

Every sprite kept its own  once it was in the atlas: a long pan and zoom made
~20,000 of them, then a frame of one to two seconds, then CONTEXT_LOST and a silent
fallback to 2D (4 sweeps out of 5). The card's pictures are now painted on one reused
canvas and sent to the atlas at once (texSubImage2D with a sub-rectangle); a full atlas
restarts and takes the picture at once. The 2D map, and a picture too big for the atlas,
keep a canvas each. The card's and the 2D map's pictures are kept apart, and giving the
card up drops its pictures.
---
 CHANGELOG.md                     |   1 +
 src/game/96-map/56-webgl.js      |   2 +-
 src/game/96-map/59-gl-sprites.js |  40 ++++++++----
 tests/webgl-sprites.test.js      | 102 +++++++++++++++++++++++++++++++
 4 files changed, 132 insertions(+), 13 deletions(-)
 create mode 100644 tests/webgl-sprites.test.js

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1f268f8..2640db8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows
 - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in.
 - The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same; Settings › Map drawing › Always 2D keeps the old drawing, and browsers without WebGL2 or without a usable graphics card keep it on their own, as does a game whose graphics card fails while you play.
 - Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the usual map also draws far fewer shapes each frame.
+- Long zooms stay on the graphics card: the pictures of cities and labels are painted on one shared canvas instead of each keeping its own, so the browser no longer runs out of room for them and switches to the slower drawing.
 
 ## [2.9.1] — 2026-11-04
 
diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js
index d6be4f4..2819c7d 100644
--- a/src/game/96-map/56-webgl.js
+++ b/src/game/96-map/56-webgl.js
@@ -19,7 +19,7 @@ function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeIte
 function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;}
 // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame.
 function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;}
-function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;glShow(false);}
+function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);}
 const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n';
 // Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing).
 const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n';
diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js
index 87eeee6..234cf94 100644
--- a/src/game/96-map/59-gl-sprites.js
+++ b/src/game/96-map/59-gl-sprites.js
@@ -26,30 +26,46 @@ function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4
   GLS.shx=GLS.shy=GLS.shh=0;}
 // Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it).
 function spritesReset(){glsDrawNow();SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;}
+// The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten.
+function spritesDrop(){GLS.n=0;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;}
+/* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a
+   canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context
+   and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. */
+const GLS_PAD={cv:null,g:null};
+function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('canvas');P.cv.width=P.cv.height=256;}
+  if(P.cv.width=SPR_MAX)spritesReset();
-  const cv=document.createElement('canvas');cv.width=Math.ceil(w*DPR);cv.height=Math.ceil(h*DPR);
-  const g=cv.getContext('2d'),saved=ctx;ctx=g;
-  try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;}
-  e={cv,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1};SPRS.set(key,e);return e;}
-// Puts a picture into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame.
-function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog)return false;
-  try{return glsPut(gl,e);}catch(x){throw glErr(x);}}
-function glsPut(gl,e){const pw=e.cv.width,ph=e.cv.height,A=GLS.size;if(pw>A||ph>A)return false;
+  const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx;
+  e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1};
+  if(gpu&&pw<=GLS.size&&ph<=GLS.size){const P=glsPad(pw,ph),g=P.g;
+    g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw,ph);ctx=g;
+    try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;g.restore();}
+    // A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next.
+    try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);}
+  }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g;
+    try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;}e.cv=cv;}
+  SPRS.set(key,e);return e;}
+// Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame.
+function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog||!e.cv)return false;
+  try{return glsPut(gl,e,e.cv);}catch(x){throw glErr(x);}}
+function glsPut(gl,e,src){const pw=e.pw,ph=e.ph,A=GLS.size;if(pw>A||ph>A)return false;
   if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;}
   if(GLS.shy+ph>A){spritesReset();return false;}
   const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph);
   gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true);
-  gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,gl.RGBA,gl.UNSIGNED_BYTE,e.cv);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false);
+  // Only the picture's corner of the source: the pad is bigger than most pictures.
+  gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false);
   Object.assign(e,{up:true,u0:x/A,v0:y/A,u1:(x+pw)/A,v1:(y+ph)/A});return true;}
 // The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace.
 function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;}
 // Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas.
 function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const o=glsNext(),d=GLS.data;
     d[o]=x;d[o+1]=y;d[o+2]=w;d[o+3]=h;d[o+4]=e.u0;d[o+5]=e.v0;d[o+6]=e.u1;d[o+7]=e.v1;d[o+8]=d[o+9]=d[o+10]=0;d[o+11]=ctx.globalAlpha;d[o+12]=0;}
-  else ctx.drawImage(e.cv,x,y,w,h);}
+  else if(e.cv)ctx.drawImage(e.cv,x,y,w,h);}
 // A round dot of radius r at (x,y), in colour col (CSS colour string) at opacity a, on the card or the 2D canvas.
 function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),o=glsNext(),d=GLS.data;
     d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;}
diff --git a/tests/webgl-sprites.test.js b/tests/webgl-sprites.test.js
new file mode 100644
index 0000000..e5d765c
--- /dev/null
+++ b/tests/webgl-sprites.test.js
@@ -0,0 +1,102 @@
+// The card's pictures (src/game/96-map/59-gl-sprites.js): painted on one reused canvas and sent to the atlas at once, so
+// a long zoom does not leave the browser holding a canvas per picture (it lost the graphics context and fell back to 2D).
+// The 2D map keeps a canvas per picture. jsdom has no WebGL: a stand-in context records what would go to the card.
+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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+
+function open() {
+  const h = load({ seed: 777 });
+  h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
+  return h;
+}
+
+const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+  return (...a)=>{calls.push([k,...a]);return {};};}});
+  const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
+  const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+  GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;
+  // Counts the canvases the page makes from here on.
+  const ce=document.createElement.bind(document);window.__canvases=0;document.createElement=function(t){if(String(t).toLowerCase()==='canvas')__canvases++;return ce.apply(document,arguments);};
+  return gl;})()`;
+
+// Frames over a zoom from far to near and back, as a player pinching would.
+const ZOOM = `(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;for(let i=0;i<=40;i++){cam.z=0.5*Math.pow(9,(1-Math.cos(i/40*Math.PI*2))/2);draw(1000+i*16);}})()`;
+
+test('on the card, pictures are painted on one canvas and each goes into the atlas as it is painted', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  ev(ZOOM);
+  const r = JSON.parse(ev(`(()=>{const subs=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D'),es=[...SPRS.values()];
+    return JSON.stringify({canvases:__canvases,subs:subs.length,sprites:es.length,mine:es.filter(e=>e.cv).length,
+      allUp:es.every(e=>e.up),rect:subs.every(c=>c.length===10&&c[9]===GLS_PAD.cv&&c[5]>0&&c[6]>0),
+      fit:subs.every(c=>c[5]<=GLS_PAD.cv.width&&c[6]<=GLS_PAD.cv.height),keys:es.length?[...SPRS.keys()].every(k=>k[0]==='g'):false});})()`));
+  assert.ok(r.sprites > 50, `a zoom paints many pictures (${r.sprites})`);
+  assert.ok(r.canvases <= 1, `one canvas for all of them, not one each (${r.canvases} made)`);
+  assert.equal(r.mine, 0, 'no picture keeps a canvas of its own');
+  assert.equal(r.allUp, true, 'every picture is in the atlas');
+  assert.ok(r.subs >= r.sprites, 'each was sent once, when painted');
+  assert.equal(r.rect, true, 'only its corner of the pad, from the pad');
+  assert.equal(r.fit, true);
+  assert.equal(r.keys, true, 'kept apart from the 2D map’s pictures');
+  assert.deepEqual(errors, []);
+});
+
+test('a full atlas starts again and the picture that did not fit goes into the new one at once', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.shy=GLS.size-4;GLS.shx=GLS.size-2;GLS.shh=4;
+    const before=SPRS.size;let draws=0;const gd=glsDraw;glsDraw=function(){draws++;};
+    const e=spriteEntry('big',40,40,20,20,g=>{g.fillRect(0,0,40,40);});blit(e,10,10,40,40);
+    glsDraw=gd;const r={up:e.up,u0:e.u0,v0:e.v0,kept:SPRS.get('g'+DPR+'|big')===e,size:SPRS.size,n:GLS.n,cv:!!e.cv,shy:GLS.shy};GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify(r);})()`));
+  assert.equal(r.up, true, 'the picture is in the atlas');
+  assert.equal(r.u0, 0); assert.equal(r.v0, 0);
+  assert.equal(r.kept, true, 'and kept under its key after the restart');
+  assert.equal(r.size, 1, 'the old pictures are gone');
+  assert.equal(r.n, 1, 'drawn this frame');
+  assert.equal(r.cv, false);
+  assert.deepEqual(errors, []);
+});
+
+test('the 2D map keeps a canvas per picture, and its pictures are not the card’s', () => {
+  const { ev, errors } = open();
+  ev(`mapGl(false);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
+  const r = JSON.parse(ev(`(()=>{const es=[...SPRS.entries()];return JSON.stringify({n:es.length,cv:es.every(([k,e])=>k[0]==='c'&&e.cv&&e.cv.width===e.pw&&e.cv.height===e.ph),up:es.some(([,e])=>e.up)});})()`));
+  assert.ok(r.n > 10);
+  assert.equal(r.cv, true, 'each with its own canvas, at its size');
+  assert.equal(r.up, false, 'nothing went to a card');
+  assert.deepEqual(errors, []);
+});
+
+test('giving the card up drops its pictures; the 2D map paints its own', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
+  assert.ok(ev('SPRS.size') > 10);
+  ev(`window.__warn=0;console.warn=function(){__warn++;};glKill('test')`);
+  assert.equal(ev('SPRS.size'), 0, 'no picture without a canvas is left behind');
+  assert.equal(ev('GLS.shx+GLS.shy+GLS.shh'), 0, 'the atlas is forgotten');
+  ev('draw(1016)');
+  assert.ok(ev('SPRS.size') > 10);
+  assert.equal(ev(`[...SPRS.values()].every(e=>e.cv)`), true, 'the 2D map’s pictures have their canvas');
+  assert.ok(ev('ctx===CTX0'));
+  assert.deepEqual(errors, []);
+});
+
+test('a picture too big for the atlas keeps its own canvas and is painted on the overlay', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.size=64;const n0=GLX.fx.calls.n;
+    const e=spriteEntry('huge',200,30,100,15,g=>{g.fillRect(0,0,200,30);});blit(e,0,0,200,30);
+    const r={cv:!!e.cv,up:e.up,n:GLS.n,fx:GLX.fx.calls.n-n0};GLS.frame=false;GLS.n=0;ctx=CTX0;GLS.size=4096;return JSON.stringify(r);})()`));
+  assert.equal(r.cv, true);
+  assert.equal(r.up, false);
+  assert.equal(r.n, 0, 'not queued for the card');
+  assert.ok(r.fx >= 1, 'drawn on the overlay instead');
+  assert.deepEqual(errors, []);
+});

From eeeccc60d42bcdaed7c7895aef0c91d206563f77 Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 16:39:57 +0100
Subject: [PATCH 317/491] WebGL map: keep the cities' pictures while the zoom
 moves, paint them sharp once it rests

The scale of a city's picture is in steps of 1/24, so a pinch repainted every city every
~4 % of zoom: hundreds of pictures a frame, and the atlas full and reset over and over.
On the card, while the zoom moves, pictures that grow with it (cities, ships, badges) keep
the step of the scale held when it began, stretched by up to 1.25x either way by the
card's filtering, and take a new one beyond that; 250 ms after the zoom stops they are
painted at their own step again, and a still map is drawn once more for it. The 2D map
paints every step as before.
---
 CHANGELOG.md                      |  1 +
 src/game/96-map/59-gl-sprites.js  | 18 +++++-
 src/game/96-map/60-draw.js        |  2 +-
 src/game/96-map/80-cities.js      | 11 ++--
 src/game/96-map/88-cable-ships.js |  2 +-
 src/game/99-loop.js               |  2 +-
 tests/webgl-zoom-sprites.test.js  | 91 +++++++++++++++++++++++++++++++
 7 files changed, 115 insertions(+), 12 deletions(-)
 create mode 100644 tests/webgl-zoom-sprites.test.js

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2640db8..946f84e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ All notable changes to this project are documented here. The project follows
 - The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same; Settings › Map drawing › Always 2D keeps the old drawing, and browsers without WebGL2 or without a usable graphics card keep it on their own, as does a game whose graphics card fails while you play.
 - Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the usual map also draws far fewer shapes each frame.
 - Long zooms stay on the graphics card: the pictures of cities and labels are painted on one shared canvas instead of each keeping its own, so the browser no longer runs out of room for them and switches to the slower drawing.
+- Zooming is smoother on big maps: while you zoom, cities and ships keep their picture and are only redrawn sharp once the zoom stops, instead of being repainted at every small step.
 
 ## [2.9.1] — 2026-11-04
 
diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js
index 234cf94..b2aef43 100644
--- a/src/game/96-map/59-gl-sprites.js
+++ b/src/game/96-map/59-gl-sprites.js
@@ -70,10 +70,22 @@ function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const o=glsNext(),d=GLS.dat
 function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),o=glsNext(),d=GLS.data;
     d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;}
   else{const sa=ctx.globalAlpha;if(a!==undefined)ctx.globalAlpha=a;ctx.fillStyle=col;ctx.beginPath();ctx.arc(x,y,r,0,7);ctx.fill();ctx.globalAlpha=sa;}}
+/* Pictures that grow with the zoom (cities, ships, badges) are painted at steps of 1/24 of their scale. On the card,
+   while the zoom moves, they keep the step of the scale they had when it began, stretched by up to 1.25× either way
+   (the card filters them smoothly), and are painted again at the right step once the zoom rests (ZOOM_REST ms): a
+   pinch otherwise repainted every city at every step, hundreds of pictures a frame, and filled the atlas over and
+   over. ZH.sc is the icon scale held, ZH.f how much a picture is painted smaller (<1) or bigger than it shows. */
+const CSPR_STEP=24,ZOOM_REST=250,ZH={z:0,t:-1e9,sc:0,f:1};
+function zoomHold(sc,G){const t=performance.now();if(cam.z!==ZH.z){ZH.z=cam.z;ZH.t=t;}
+  if(!G||!ZH.sc||t-ZH.t>=ZOOM_REST||sc/ZH.sc>1.25||ZH.sc/sc>1.25)ZH.sc=sc;ZH.f=ZH.sc/sc;}
+// The zoom moved a moment ago: the pictures may be stretched, so a still map is drawn again once it rests (mapStill()).
+const zoomMoving=()=>performance.now()-ZH.tMath.max(1/CSPR_STEP,Math.round(k*ZH.f*CSPR_STEP)/CSPR_STEP);
 // A small picture w×h px at scale k with its anchor at (ax,ay), painted once by paint(g) with the origin on the anchor
-// (k in steps of 1/24, as the cities), then drawn with the anchor at (x,y). Things that bob or pulse are drawn as these
-// at a moving place, so the overlay above the card stays untouched (repainting it costs a whole screen of pixels).
-function stamp(key,w,h,ax,ay,k,x,y,paint){const kq=Math.max(1/24,Math.round(k*24)/24),r=k/kq;
+// (k in steps of 1/24, as the cities; zoomed: k grows with the zoom, and is held while it moves, sprQ()), then drawn with
+// the anchor at (x,y). Things that bob or pulse are drawn as these at a moving place, so the overlay above the card
+// stays untouched (repainting it costs a whole screen of pixels).
+function stamp(key,w,h,ax,ay,k,x,y,paint,zoomed){const kq=zoomed?sprQ(k):Math.max(1/CSPR_STEP,Math.round(k*CSPR_STEP)/CSPR_STEP),r=k/kq;
   const e=spriteEntry(key+'|'+kq,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);});
   blit(e,x-e.ax*r,y-e.ay*r,e.w*r,e.h*r);}
 // Text with an outline, centred on (x,y), as a picture placed on whole device pixels; tw is its width, px its size.
diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js
index f42754e..9448ad9 100644
--- a/src/game/96-map/60-draw.js
+++ b/src/game/96-map/60-draw.js
@@ -36,7 +36,7 @@ function drawFrame(now){
   }
   ctx.setTransform(DPR,0,0,DPR,0,0);
   if(!S)return;
-  const sc=iconScale(),day=S.day;
+  const sc=iconScale(),day=S.day;zoomHold(sc,G);
   // cable systems
   drawCables(ks);
   // links
diff --git a/src/game/96-map/80-cities.js b/src/game/96-map/80-cities.js
index 9b40c4b..ebce4ff 100644
--- a/src/game/96-map/80-cities.js
+++ b/src/game/96-map/80-cities.js
@@ -32,8 +32,7 @@ function cityFarStatic(C,p,down,sel,hov,ph){ctx.strokeStyle='#1E2640';
   if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}}
 // A city's picture is painted once per state and kept as a sprite (citySprite). What moves every frame is painted on top
 // (cityMoving): the lights, the steam, a flashing IX, the hot badges and the offer bubble. The rings and the glow move too,
-// but in steps (cityPhase), so their sprite changes only at a step.
-const CSPR_STEP=24;
+// but in steps (cityPhase), so their sprite changes only at a step; so does its scale (sprQ(), 59-gl-sprites.js).
 // dd is -1 without an attack: the attack's ring at step 0 must not share a sprite with no ring at all.
 function cityPhase(C,p,sel,now){const ph={sel:0,dd:-1,gl:-1};
   if(sel)ph.sel=Math.floor(now/40)%12;                       // dash period 12 px, lineDashOffset -now/40
@@ -94,13 +93,13 @@ function cityMoving(C,p,t,cs,k,sx,sy,now,h,st,hot){const down=st.down,K=k*cs;
     for(let i=0;i<4;i++){const lit=down?false:(((now/(160+i*37))|0)+i)%3!==0,[x,y]=at(-10+i*6.6,1),col=down?'#3B4260':lit?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';dot(x,y,2.1*K,col,1);}
   }
   // A flashing IX: two pictures, one per colour.
-  if(st.ixDraw&&st.ixHot){const on=Math.sin(now/180)>0,ix=p?19:SKY_W[t]/2+4;stamp('ixhot'+(on?1:0),22,22,11,11,K,sx+ix*K,sy+(2-h)*K,()=>{ctx.translate(-ix,h-2);ctx.strokeStyle='#1E2640';cityIX(C,p,t,h,true,on?1:-1);});}
+  if(st.ixDraw&&st.ixHot){const on=Math.sin(now/180)>0,ix=p?19:SKY_W[t]/2+4;stamp('ixhot'+(on?1:0),22,22,11,11,K,sx+ix*K,sy+(2-h)*K,()=>{ctx.translate(-ix,h-2);ctx.strokeStyle='#1E2640';cityIX(C,p,t,h,true,on?1:-1);},true);}
   // Hot badges: the red disc pulses, the ring and the letter over it stay.
   if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const kk of ['r','t','p','c']){if(!hot[kk])continue;const bx=sx-29*K,by=sy+y*K;dot(bx,by,6.5*K,'#FF4D5E',pulse);
-    stamp('hotb|'+HOTL[kk],18,18,9,9,K,bx,by,g=>{g.lineWidth=2;g.strokeStyle='#1E2640';g.beginPath();g.arc(0,0,6.5,0,7);g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(HOTL[kk],0,0.5);});y+=14;}}
+    stamp('hotb|'+HOTL[kk],18,18,9,9,K,bx,by,g=>{g.lineWidth=2;g.strokeStyle='#1E2640';g.beginPath();g.arc(0,0,6.5,0,7);g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(HOTL[kk],0,0.5);},true);y+=14;}}
   // The offer bubble bobs over the city.
   if(st.off)stamp('offer|'+(st.big?2:1),30,28,15,12,K,sx-2*K,sy+(-h-16+Math.sin(now/250)*3)*K,g=>{g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=2.2;g.beginPath();g.ellipse(0,0,11,9,0,0,7);g.fill();g.stroke();
-    g.beginPath();g.moveTo(-3,8);g.lineTo(-5,14);g.lineTo(2,8);g.fill();g.fillStyle=st.big?'#FF4F9A':'#16A866';g.font='900 13px "Baloo 2", sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(st.big?'$$':'$',0,1);});}
+    g.beginPath();g.moveTo(-3,8);g.lineTo(-5,14);g.lineTo(2,8);g.fill();g.fillStyle=st.big?'#FF4F9A':'#16A866';g.font='900 13px "Baloo 2", sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(st.big?'$$':'$',0,1);},true);}
 function drawCity(C,sx,sy,sc,now,lyOverride,dem){
   if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride);
   const hot=(UI.hotMap||{})[C.id];
@@ -109,7 +108,7 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){
   if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc,rq=Math.round(r*4)/4,fill=hasIxAt(C.id)?'#FFD23F':'#FFFFFF',S2=Math.ceil(rq*2+4);
     const e=spriteEntry(['quiet',rq,fill].join('|'),S2,S2,S2/2,S2/2,g=>{g.translate(S2/2,S2/2);g.fillStyle=fill;g.strokeStyle='#1E2640';g.lineWidth=1.6;g.beginPath();g.arc(0,0,rq,0,7);g.fill();g.stroke();});
     blit(e,sx-e.ax,sy+2*sc-e.ay,e.w,e.h);return;}
-  const t=cTier(C.id),cs=p?1:CSC[t],k=sc*(hov?1.15:1),kq=Math.round(k*CSPR_STEP)/CSPR_STEP;
+  const t=cTier(C.id),cs=p?1:CSC[t],k=sc*(hov?1.15:1),kq=sprQ(k);
   const ixn=ixName(C.id),ixDraw=!!ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov),ixHot=!!(ixDraw&&hot&&hot.ix);
   const st={down:!!down,feed:!!(UI.feed&&UI.feed.has(C.id)),sel:!!sel,inc:CM.inc.has(C.id),ixDraw,ixHot,off:CM.off.has(C.id),big:CM.big.has(C.id)};
   const ph=cityPhase(C,p,sel,now),spr=citySprite(C,p,t,cs,kq,ph,st),r=k/kq;
diff --git a/src/game/96-map/88-cable-ships.js b/src/game/96-map/88-cable-ships.js
index f3a4744..881ac69 100644
--- a/src/game/96-map/88-cable-ships.js
+++ b/src/game/96-map/88-cable-ships.js
@@ -30,7 +30,7 @@ function shipSprite(x,y,face,sc,col,now,mode){const bl=mode==='work'&&Math.floor
   c.fillStyle=col;c.strokeStyle='#1E2640';c.lineWidth=1.6;c.lineJoin='round';c.beginPath();c.moveTo(-11,0);c.lineTo(11,0);c.lineTo(8,6);c.lineTo(-9,6);c.closePath();c.fill();c.stroke();
   c.fillStyle='#fff';c.beginPath();c.rect(-7,-7,8,7);c.fill();c.stroke();c.fillStyle='#1E2640';c.fillRect(-5,-5,4,2);
   c.beginPath();c.arc(9,-2,2.6,0,7);c.fillStyle='#FFD23F';c.fill();c.stroke();
-  if(bl){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}});}
+  if(bl){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}},true);}
 function drawShips(ks,now){SHIP_HITS.length=0;if(!S||pzOn()||!S.fleet)return;
   const T=S.day+(UI.speed?clamp(acc/DAY_MS,0,0.999):0),z=cam.z,sc=Math.max(0.85,Math.min(1.5,Math.sqrt(z)))*(lodFar()?0.9:1.05),list=[];
   for(const s of SHIPS){const p=shipAt(s,T);if(p.m==='port'&&z<1.1)continue;list.push({p,s,col:s.club==='prv'?'#7A5CFF':'#FF4D5E'});}
diff --git a/src/game/99-loop.js b/src/game/99-loop.js
index b139bd3..83390ba 100644
--- a/src/game/99-loop.js
+++ b/src/game/99-loop.js
@@ -31,7 +31,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 (the WebGL map has none). */
 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:0,UI.mk?UI.mk.mood:0];
+  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,zoomMoving()];
   let same=v.length===FRAME.length;for(let i=0;i__T,configurable:true});`);
+  return h;
+}
+
+const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+  return (...a)=>{calls.push([k,...a]);return {};};}});
+  const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
+  const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+  GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
+
+// One POP's city pictures painted during frames from zoom z0 to z1 (the clock moving 16 ms a frame), by scale.
+const ZOOM = (z0, z1, n) => `(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const seen=new Set(),bad=[];
+  for(let i=0;i<=${n};i++){cam.z=${z0}+(${z1}-${z0})*i/${n};__T+=16;draw(__T);
+    for(const k of SPRS.keys()){const p=k.split('|');if(p[1]==='city'&&p[2]===id)seen.add(+p[4]);}
+    const k=cityScale(iconScale()),kq=[...SPRS.keys()].filter(x=>x.split('|')[1]==='city'&&x.split('|')[2]===id).map(x=>+x.split('|')[4]);
+    if(kq.length&&!kq.some(q=>Math.max(q/k,k/q)<=1.25*(1+.5/24/0.7)))bad.push(i);}
+  return JSON.stringify({steps:[...seen].sort(),bad});})()`;
+
+test('on the card a zoom keeps each city’s picture for a while, and paints it at the right step once it rests', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  ev(`cam.z=0.6;draw(__T);__T+=1000;draw(__T)`);
+  const r = JSON.parse(ev(ZOOM(0.6, 1.6, 60)));
+  // Without the hold, every 1/24 step between the two scales gets a picture.
+  const plain = ev(`(()=>{const s=new Set();for(let i=0;i<=60;i++){cam.z=0.6+i/60;s.add(Math.round(cityScale(iconScale())*24)/24);}return s.size;})()`);
+  assert.ok(plain >= 10, `the zoom crosses many steps (${plain})`);
+  assert.ok(r.steps.length <= 4, `the city was painted at ${r.steps.length} scales during the zoom (${r.steps}), not ${plain}`);
+  assert.deepEqual(r.bad, [], 'a picture is never stretched more than 1.25× either way (and half a step)');
+  assert.equal(ev('zoomMoving()'), true);
+  ev('__T+=300;draw(__T)');
+  const rest = JSON.parse(ev(`(()=>{const id=S.home,want=Math.round(cityScale(iconScale())*24)/24;
+    return JSON.stringify({f:ZH.f,want,has:[...SPRS.keys()].some(k=>{const p=k.split('|');return p[1]==='city'&&p[2]===id&&+p[4]===want;}),moving:zoomMoving()});})()`));
+  assert.equal(rest.moving, false);
+  assert.equal(rest.f, 1, 'at rest nothing is stretched');
+  assert.equal(rest.has, true, 'the city is painted again at its own step');
+  assert.deepEqual(errors, []);
+});
+
+test('the 2D map paints cities at their own step on every frame of a zoom, as before', () => {
+  const { ev, errors } = open();
+  ev(`mapGl(false);cam.z=0.8;draw(__T);`);
+  const r = JSON.parse(ev(`(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const bad=[];
+    for(let i=0;i<=30;i++){cam.z=0.8+i/30;__T+=16;SPRS.clear();draw(__T);const want=Math.round(cityScale(iconScale())*24)/24;
+      if(ZH.f!==1||![...SPRS.keys()].some(k=>{const p=k.split('|');return p[1]==='city'&&p[2]===id&&+p[4]===want;}))bad.push(i);}
+    return JSON.stringify({bad});})()`));
+  assert.deepEqual(r.bad, []);
+  assert.deepEqual(errors, []);
+});
+
+test('a still map is drawn again when the zoom comes to rest, so the stretched pictures do not stay', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  // Animations off: the loop skips frames while nothing changes.
+  ev(`cam.z=1;draw(__T);mapStill(0,__T);UI.drawnAt=__T;cam.z=1.3;__T+=16;mapStill(0,__T);draw(__T);UI.drawnAt=__T;`);
+  ev(`__T+=16`);
+  assert.equal(ev('mapStill(0,__T)'), true, 'nothing moved since the last frame');
+  ev(`__T+=300`);
+  assert.equal(ev('mapStill(0,__T)'), false, 'the zoom has rested: one more frame');
+  ev(`draw(__T);UI.drawnAt=__T;__T+=16`);
+  assert.equal(ev('ZH.f'), 1);
+  assert.equal(ev('mapStill(0,__T)'), true, 'and then the map stays still again');
+  assert.deepEqual(errors, []);
+});
+
+test('pictures that keep their size whatever the zoom (far-view cities, cones, diggers) are never held or stretched', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{cam.z=1;draw(__T);__T+=1000;cam.z=1;draw(__T);cam.z=1.4;__T+=16;draw(__T);GLS.frame=true;GLS.n=0;ctx=GLX.fx;
+    const f=ZH.f;drawCone(100,100,0);drawBackhoe(200,100,0,false);const D=GLS.data,o=[D[2],D[3],D[SPR_STRIDE+2],D[SPR_STRIDE+3]];
+    const keys=[...SPRS.keys()].filter(k=>['cone','hoe'].includes(k.split('|')[1]));GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify({f,o,keys});})()`));
+  assert.notEqual(r.f, 1, 'the zoom is moving and city pictures are held');
+  assert.deepEqual(r.o, [26, 28, 38, 32], 'drawn at their own size');
+  assert.ok(r.keys.length >= 2 && r.keys.every(k => k.endsWith('|1')), 'painted at scale 1: ' + r.keys);
+  assert.deepEqual(errors, []);
+});

From 3482142ae59c45d5887eb0da0c3a6786f86c103a Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 16:42:03 +0100
Subject: [PATCH 318/491] WebGL map: simplify the coastlines for the zoom

On the card the land was most of a frame's work (the stencil fills twice, the sand, the
edge), and it scales with vertices, not pixels. The land is now built per zoom level
(powers of 2) with each coastline simplified (Douglas-Peucker) so that no point moves
more than 0.25 px at the level's zoom; zooming in takes the finer level at once, zooming
out keeps it until the zoom is 10 % under it. COAST, onLand() and the 2D map are
unchanged.
---
 CHANGELOG.md                           |  1 +
 src/game/96-map/57-webgl-background.js | 38 +++++++++----
 tests/webgl-coast.test.js              | 76 ++++++++++++++++++++++++++
 tests/webgl-map.test.js                |  5 +-
 4 files changed, 108 insertions(+), 12 deletions(-)
 create mode 100644 tests/webgl-coast.test.js

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 946f84e..8811912 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ All notable changes to this project are documented here. The project follows
 - Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the usual map also draws far fewer shapes each frame.
 - Long zooms stay on the graphics card: the pictures of cities and labels are painted on one shared canvas instead of each keeping its own, so the browser no longer runs out of room for them and switches to the slower drawing.
 - Zooming is smoother on big maps: while you zoom, cities and ships keep their picture and are only redrawn sharp once the zoom stops, instead of being repainted at every small step.
+- The graphics card draws the coastlines with fewer points when you zoom out, where the extra detail was smaller than a pixel, so the map costs it a lot less work, which helps phones most.
 
 ## [2.9.1] — 2026-11-04
 
diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js
index d696257..5d5d7b9 100644
--- a/src/game/96-map/57-webgl-background.js
+++ b/src/game/96-map/57-webgl-background.js
@@ -18,15 +18,33 @@ void main(){float d=(length(vq/vr)-1.)*min(vr.x,vr.y),a=clamp(.5-d*uDpr,0.,1.);i
 const CIRC_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aC;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out float vr;
 void main(){vec2 c=(aC.xy-uCam.xy)*uCam.z+uView*.5;float r=aC.z*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vr=r;gl_Position=clip(c+vq,uView,0.);}`;
 const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(length(vq)>vr)discard;o=vec4(1.);}`;
-/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does): the fan for the
-   fills, the coastlines as line segments (paintWorld()'s curves, four segments each) for the sand and the dark edge,
-   and the hills. */
-function glLandGeo(gl,far){const key=far?'far':'all';let G=GLX.land[key];if(G)return G;
-  const keep=far?new Set(LANDP_FAR):null,fan=[],sand=[],edge=[],SAND=glColor('#F8E6A8'),EDGE=glColor('#1E2640');
-  COAST.forEach((ring,ri)=>{if(keep&&!keep.has(LANDP_ALL[ri]))return;const n=ring.length;if(n<3)return;
-    // As smoothPath(): a quadratic curve from the middle of each side to the next, through the corner between them.
-    const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2],P=[];let m=mid(ring[n-1],ring[0]);P.push(m);
-    for(let i=0;i[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(ring[n-1],ring[0]);P.push(m);
+  for(let i=0;i0))return P;const keep=new Uint8Array(n),st=[0,n-1],t2=tol*tol;keep[0]=keep[n-1]=1;
+  while(st.length){const b=st.pop(),a=st.pop(),ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;let m=-1,md=t2;
+    for(let i=a+1;i1?1:t;const ex=ax+t*dx-P[i][0],ey=ay+t*dy-P[i][1],d=ex*ex+ey*ey;if(d>md){md=d;m=i;}}
+    if(m>=0){keep[m]=1;st.push(a,m,m,b);}}
+  const o=[];for(let i=0;icur||z{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return;
+    const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return;
     for(let i=1;i+1{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+  return (...a)=>{calls.push([k,...a]);return {};};}});
+  const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
+  const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
+
+test('a simplified coastline never strays more than the tolerance from the full one', () => {
+  const { ev, errors } = open();
+  const r = JSON.parse(ev(`(()=>{const out=[];let worst=0,rings=0,kept=0,all=0;
+    for(const lv of [-2,-1,0,1,3]){const tol=COAST_TOL/Math.pow(2,lv);
+      COAST.forEach((ring,ri)=>{if(ring.length<3)return;const P=coastPts(ri),Q=coastSimplify(P,tol),at=new Map(P.map((p,i)=>[p,i]));rings++;kept+=Q.length;all+=P.length;
+        if(Q[0]!==P[0]||Q[Q.length-1]!==P[P.length-1])out.push('ends '+ri);
+        for(let j=0;j+1a))out.push('order '+ri);
+          const ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;
+          for(let i=a+1;iworst)worst=d;}}});}
+    return JSON.stringify({bad:out.slice(0,5),worst,rings,share:kept/all});})()`));
+  assert.deepEqual(r.bad, [], 'each ring keeps its ends and its order');
+  assert.ok(r.worst <= 1 + 1e-9, `no point further than the tolerance (worst ${r.worst.toFixed(3)} of it)`);
+  assert.ok(r.rings > 50);
+  assert.ok(r.share < 0.6, `points are left out (${(r.share * 100).toFixed(0)} % kept)`);
+  assert.deepEqual(errors, []);
+});
+
+test('zoomed out the land has a few times fewer segments, and the closer the zoom the more it keeps', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{const full=glLandGeo(GLX.gl,false),n=lv=>glLandGeo(GLX.gl,false,lv).nSeg;
+    return JSON.stringify({full:full.nSeg,fullFan:full.nFan,l_1:n(-1),l0:n(0),l1:n(1),l3:n(3),far:glLandGeo(GLX.gl,true,-1).nSeg,once:glLandGeo(GLX.gl,false,0)===glLandGeo(GLX.gl,false,0),
+      fan:glLandGeo(GLX.gl,false,-1).nFan});})()`));
+  assert.ok(r.l_1 * 3 < r.full, `zoom 0.5–1: ${r.l_1} segments, ${r.full} in full`);
+  assert.ok(r.l_1 < r.l0 && r.l0 < r.l1 && r.l1 <= r.l3 && r.l3 <= r.full, JSON.stringify(r));
+  assert.ok(r.far < r.l_1, 'the far view still leaves out the islets');
+  assert.ok(r.fan * 3 < r.fullFan, 'the fill’s fan shrinks as much');
+  assert.equal(r.once, true, 'each level is built once');
+  assert.deepEqual(errors, []);
+});
+
+test('the zoom level takes the finer level at once and keeps it a little while zooming out', () => {
+  const { ev, errors } = open();
+  const lv = JSON.parse(ev(`(()=>{delete GLX.coastLv;return JSON.stringify([1.5,2.1,1.95,1.85,1.8,0.9,0.95,0.4].map(coastLevel));})()`));
+  assert.deepEqual(lv, [0, 1, 1, 1, 0, -1, -1, -2]);
+  assert.deepEqual(errors, []);
+});
+
+test('each frame on the card fills the land from its zoom level’s geometry; the coastlines and the 2D map stay as they were', () => {
+  const { ev, errors } = open();
+  const coast = ev('JSON.stringify(COAST)');
+  ev(STUB);
+  const fans = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;delete GLX.coastLv;const o=[];
+    for(const z of [0.6,1.4,3.2]){cam.z=z;GLX.gl.calls.length=0;draw(1000);const want=glLandGeo(GLX.gl,lodFar(),coastLevel(z)).nFan;
+      o.push(GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').every(c=>c[3]===want));}return JSON.stringify(o);})()`));
+  assert.deepEqual(fans, [true, true, true]);
+  assert.equal(ev('JSON.stringify(COAST)'), coast, 'COAST is never changed (onLand() reads it)');
+  let built = 0;
+  ev(`mapGl(false);window.__lg=glLandGeo;glLandGeo=function(){__built++;return __lg.apply(this,arguments);};window.__built=0;cam.z=0.6;draw(1016);cam.z=3.2;draw(1032);`);
+  built = ev('__built');
+  assert.equal(built, 0, 'the 2D map does not use it');
+  assert.deepEqual(errors, []);
+});
diff --git a/tests/webgl-map.test.js b/tests/webgl-map.test.js
index 2d70dea..7d41a6e 100644
--- a/tests/webgl-map.test.js
+++ b/tests/webgl-map.test.js
@@ -108,14 +108,15 @@ test('the land is geometry on the card: one fan per coastline, its outlines, its
     const pts=COAST.reduce((a,p)=>a+p.length,0);
     GLX.gl.calls.length=0;cam.z=1.4;draw(1000);
     const fans=GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').map(c=>c[3]);
-    return JSON.stringify({nFan:all.nFan,nSeg:all.nSeg,farSeg:far.nSeg,pts,hills:all.nHill,again:glLandGeo(GLX.gl,false)===all,fans,
+    const lv=glLandGeo(GLX.gl,false,coastLevel(1.4));
+    return JSON.stringify({nFan:all.nFan,nSeg:all.nSeg,farSeg:far.nSeg,pts,hills:all.nHill,again:glLandGeo(GLX.gl,false)===all,fans,lvFan:lv.nFan,
       wl:GLX.gl.calls.some(c=>c[0]==='texImage2D'&&c[6]===WL.cv)});})()`));
   assert.equal(r.nFan % 3, 0, 'whole triangles');
   assert.equal(r.nSeg, r.pts * 4, 'each curve of the coast in four segments');
   assert.ok(r.farSeg < r.nSeg, 'zoomed out, the islets are left out as in 2D');
   assert.equal(r.hills, ev('HILLS.length'));
   assert.ok(r.again, 'built once');
-  assert.ok(r.fans.length >= 2 && r.fans.every(n => n === r.nFan), 'shadow and grass are filled each frame from the same fan');
+  assert.ok(r.fans.length >= 2 && r.fans.every(n => n === r.lvFan), 'shadow and grass are filled each frame from the same fan (the zoom level’s)');
   assert.equal(r.wl, false, 'no picture of the land is uploaded');
   assert.deepEqual(errors, []);
 });

From 87b153db6f9d507deb7958fdf9aa026c6cd5aa50 Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 17:19:27 +0100
Subject: [PATCH 319/491] WebGL map: keep the pictures' keys, the waves and the
 clouds out of the garbage

A frame joined a key for every city, label, quiet dot and stamp it drew, built a closure
to paint each even when the picture was already there, concatenated a prefix onto every
key, made an array per city per copy of the map for its place on screen, and rebuilt
the waves' and the clouds' arrays. Keys are now kept per city (packed into one number for
the yes/no parts), per label text and look, per stamp and scale, and joined again only
when the picture changes; pictures already painted are found before any closure is
made; the card's and the 2D map's pictures are two maps, so keys need no prefix; the
cities' places and the POP lights are computed in place; the waves and the clouds are
written into arrays kept from frame to frame.

Sampled heap profile, TTL save, RTX 4060 Ti: allocations under drawFrame 68 -> 37 MB/s
at x1 and 62 -> 43 MB/s during a pan/zoom sweep; under glBegin 5.4 -> 0.5 MB/s.
---
 CHANGELOG.md                           |  1 +
 src/game/96-map/57-webgl-background.js | 12 ++--
 src/game/96-map/59-gl-sprites.js       | 22 +++++--
 src/game/96-map/60-draw.js             |  4 +-
 src/game/96-map/80-cities.js           | 40 ++++++++----
 tests/webgl-frame-garbage.test.js      | 89 ++++++++++++++++++++++++++
 tests/webgl-sprites.test.js            | 10 +--
 tests/webgl-zoom-sprites.test.js       | 12 ++--
 8 files changed, 153 insertions(+), 37 deletions(-)
 create mode 100644 tests/webgl-frame-garbage.test.js

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8811912..dc7bad2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ All notable changes to this project are documented here. The project follows
 - Long zooms stay on the graphics card: the pictures of cities and labels are painted on one shared canvas instead of each keeping its own, so the browser no longer runs out of room for them and switches to the slower drawing.
 - Zooming is smoother on big maps: while you zoom, cities and ships keep their picture and are only redrawn sharp once the zoom stops, instead of being repainted at every small step.
 - The graphics card draws the coastlines with fewer points when you zoom out, where the extra detail was smaller than a pixel, so the map costs it a lot less work, which helps phones most.
+- The map leaves far less memory behind it on every frame for the browser to clean up while you play.
 
 ## [2.9.1] — 2026-11-04
 
diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js
index 5d5d7b9..ebab529 100644
--- a/src/game/96-map/57-webgl-background.js
+++ b/src/game/96-map/57-webgl-background.js
@@ -74,13 +74,17 @@ function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z));
 const WAVE_COL=glColor('rgba(255,255,255,.45)');
 function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0;
   for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;
-    for(const [x0,cx,cy,x1] of [[x-9+o,x-4.5+o,y-4,x+o],[x+o,x+4.5+o,y+4,x+9+o]]){let px=x0,py=y;
+    // Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame).
+    for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y;
       for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}}
   gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);}
 // The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack.
-function glClouds(gl,now,ks){const A=[];for(const k of ks)for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100+k*W,y=c.y;
-  A.push(x,y,16*c.s,0, x+18*c.s,y-8*c.s,20*c.s,0, x+40*c.s,y,15*c.s,0);}
-  if(!A.length)return;const F=new Float32Array(A),P=GLX.circ;gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cl.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW);
+function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)return;
+  // Written into one array kept from frame to frame, grown when more copies of the map show.
+  if(!GLX.ca||GLX.ca.lengthsprMap().get(key);
 // A picture of w×h CSS px with its anchor at (ax,ay): painted once by paint(g) (the 2D canvas, at the screen's pixel
-// density, which is part of the key), and kept in SPRS. The card's pictures and the 2D map's are kept apart ('g', 'c').
-function spriteEntry(key,w,h,ax,ay,paint){const gpu=GLS.frame&&!!GLX.gl&&!!GLS.prog;key=(gpu?'g':'c')+DPR+'|'+key;let e=SPRS.get(key);if(e)return e;
-  if(SPRS.size>=SPR_MAX)spritesReset();
+// density), and kept by key in SPRS (the card's) or SPRC (the 2D map's).
+function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.get(key);if(e)return e;
+  if(SPRS.size+SPRC.size>=SPR_MAX)spritesReset();
   const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx;
   e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1};
   if(gpu&&pw<=GLS.size&&ph<=GLS.size){const P=glsPad(pw,ph),g=P.g;
@@ -48,7 +53,7 @@ function spriteEntry(key,w,h,ax,ay,paint){const gpu=GLS.frame&&!!GLX.gl&&!!GLS.p
     try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);}
   }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g;
     try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;}e.cv=cv;}
-  SPRS.set(key,e);return e;}
+  M.set(key,e);return e;}
 // Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame.
 function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog||!e.cv)return false;
   try{return glsPut(gl,e,e.cv);}catch(x){throw glErr(x);}}
@@ -85,8 +90,11 @@ const sprQ=k=>Math.max(1/CSPR_STEP,Math.round(k*ZH.f*CSPR_STEP)/CSPR_STEP);
 // (k in steps of 1/24, as the cities; zoomed: k grows with the zoom, and is held while it moves, sprQ()), then drawn with
 // the anchor at (x,y). Things that bob or pulse are drawn as these at a moving place, so the overlay above the card
 // stays untouched (repainting it costs a whole screen of pixels).
+// The full key of a stamp at scale kq, kept per key: it was built again for every stamp on every frame.
+const STK=new Map();
 function stamp(key,w,h,ax,ay,k,x,y,paint,zoomed){const kq=zoomed?sprQ(k):Math.max(1/CSPR_STEP,Math.round(k*CSPR_STEP)/CSPR_STEP),r=k/kq;
-  const e=spriteEntry(key+'|'+kq,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);});
+  let m=STK.get(key);if(!m||m.kq!==kq){if(STK.size>4000)STK.clear();STK.set(key,m={kq,k:key+'|'+kq});}
+  const e=spriteHas(m.k)||spriteEntry(m.k,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);});
   blit(e,x-e.ax*r,y-e.ay*r,e.w*r,e.h*r);}
 // Text with an outline, centred on (x,y), as a picture placed on whole device pixels; tw is its width, px its size.
 function textStamp(t,font,px,tw,fill,stroke,lw,x,y){const W=Math.ceil(tw+lw+4),H=Math.ceil(px*1.5+lw+2);
diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js
index 9448ad9..eea050b 100644
--- a/src/game/96-map/60-draw.js
+++ b/src/game/96-map/60-draw.js
@@ -96,7 +96,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;if(pzHide(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){const sy=(C.y-cam.y)*cam.z+CH/2;if(sy<-60||sy>CH+60)continue;if(C.off&&!cityOn(C.id))continue;if(pzHide(C.id))continue;for(const k of ks){const sx=(C.x+k*W-cam.x)*cam.z+CW/2;if(sx<-60||sx>CW+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=new RGrid(),labs=new RGrid(),hit=(r)=>rects.hits(r);
   const farL=lodFar();
@@ -116,7 +116,7 @@ function drawFrame(now){
     if(ly===null&&prio(v)===1)for(const y of [below,above]){const r={x:v.sx-tw/2,y:y-10,w:tw,h:21};if(!labs.hits(r)){ly=y;rects.push(r);labs.push(r);break;}}
     if(ly===null&&(prio(v)===0||(prio(v)===1&&(v.C.id===S.home||UI.hover===v.C.id)))){ly=below;const r={x:v.sx-tw/2,y:below-10,w:tw,h:21};rects.push(r);labs.push(r);}
     v.ly=ly;}
-  if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,csc,now);pzDrawMarks(ks,now);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,csc,now,v.ly,v.dem);
+  if(pzOn()){for(let i=vis.length-1;i>=0;i--)pzDrawCity(vis[i],csc,now);pzDrawMarks(ks,now);}else for(let i=vis.length-1;i>=0;i--){const v=vis[i];drawCity(v.C,v.sx,v.sy,csc,now,v.ly,v.dem);}
   // cable ships at sea (88-cable-ships.js), over the city labels so a ship leaving port stays in sight
   drawShips(ks,now);
   // Architect runs: what the tubes between two cities are (one trench, or separate paths), above the cities.
diff --git a/src/game/96-map/80-cities.js b/src/game/96-map/80-cities.js
index ebce4ff..3c6eb38 100644
--- a/src/game/96-map/80-cities.js
+++ b/src/game/96-map/80-cities.js
@@ -1,11 +1,15 @@
 // Label widths by text (city labels by id, link labels and far-view labels by text): measuring text every frame is slow.
-const LBLW={},LINKW=new Map(),LBLF=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false};
+const LBLW={},LINKW=new Map(),LBLF=new Map(),FKEY=new Map(),QKEY=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false};
 try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;spritesReset();});}catch(e){}
 // A label on a pill: its text and look never change, so it is painted once (spriteEntry) and drawn as a picture. The
 // centre is x, y; the text sits at y+ty. The pill's box is w×h with corners r; the picture also takes the outline.
+// Keys are kept by text (PILLK), one per look: joining them for every label on every frame was most of the map's garbage.
+const PILLK=new Map();
 function pill(t,font,w,h,r,fill,ink,stroke,lw,x,y,ty){
-  const pad=lw+2,W=Math.ceil(w+pad*2),H=Math.ceil(h+pad*2),key=['pill',t,font,w,h,r,fill,ink,stroke,lw,ty].join('|');
-  const e=spriteEntry(key,W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.fillStyle=fill;g.strokeStyle=stroke;g.lineWidth=lw;
+  const pad=lw+2,W=Math.ceil(w+pad*2),H=Math.ceil(h+pad*2);let L=PILLK.get(t),m=null;
+  if(L)for(let i=0;i4000)PILLK.clear();PILLK.set(t,L=[]);}L.push(m={font,w,h,r,fill,ink,stroke,lw,ty,k:['pill',t,font,w,h,r,fill,ink,stroke,lw,ty].join('|')});}
+  const e=spriteHas(m.k)||spriteEntry(m.k,W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.fillStyle=fill;g.strokeStyle=stroke;g.lineWidth=lw;
     rr(-w/2,-h/2,w,h,r);g.fill();g.stroke();g.fillStyle=ink;g.font=font;g.textAlign='center';g.textBaseline='middle';g.fillText(t,0,ty);});
   // Whole device pixels, so the text stays as sharp as before.
   blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);}
@@ -13,8 +17,10 @@ function pill(t,font,w,h,r,fill,ink,stroke,lw,x,y,ty){
 function drawCityFar(C,sx,sy,sc,now,lyOverride){
   const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
   if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9)dot(sx,sy,12,'rgba(255,77,94,1)',.35+.25*Math.sin(now/200));
-  const t=cTier(C.id),ph=sel?Math.floor(now/40)%8:-1,key=['far',p?1:0,down?1:0,p&&p.site2?1:0,p?(p.routers||1)>=2?1:0:0,t,hov?1:0,hasIxAt(C.id)?1:0,CM.off.has(C.id)?1:0,CM.inc.has(C.id)?1:0,ph].join('|');
-  stamp(key,36,36,18,18,1,sx,sy,()=>cityFarStatic(C,p,down,sel,hov,ph));
+  const t=cTier(C.id),ph=sel?Math.floor(now/40)%8:-1,f=(p?1:0)|(down?2:0)|(p&&p.site2?4:0)|(p&&(p.routers||1)>=2?8:0)|(hov?16:0)|(hasIxAt(C.id)?32:0)|(CM.off.has(C.id)?64:0)|(CM.inc.has(C.id)?128:0);
+  // The key, kept per city and built again only when the picture changes.
+  let m=FKEY.get(C.id);if(!m||m.f!==f||m.t!==t||m.ph!==ph)FKEY.set(C.id,m={f,t,ph,k:'far|'+t+'|'+f+'|'+ph});
+  stamp(m.k,36,36,18,18,1,sx,sy,()=>cityFarStatic(C,p,down,sel,hov,ph));
   if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride;
     pill(t,ctx.font,tw,16,8,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',1.6,sx,ly,1);}
 }
@@ -79,18 +85,25 @@ function cityStatic(C,p,t,cs,k,ph,st){const down=st.down;
   if(st.inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
 }
 // The picture of a city in a given state, at the quantised scale kq: painted once and kept until it is not needed.
-function citySprite(C,p,t,cs,kq,ph,st){
-  const key=['city',C.id,t,kq,st.down?1:0,p?1:0,p&&p.site2?1:0,p&&p.site2&&siteDown(C.id,'b')?1:0,p&&p.ringcut>S.day?1:0,p?(p.routers||1):0,p&&p.gen?1:0,p?(p.rgen||0):0,C.au?1:0,
-    st.ixDraw?1:0,st.ixHot?1:0,ixName(C.id)||'',S.myIx[C.id]?1:0,hasIxAt(C.id)?1:0,!p&&ixQuiet(C.id)?1:0,st.feed?1:0,st.sel?ph.sel:-1,ph.dd,st.inc?1:0].join('|');
+// Its key is kept per city (CKEY) and joined again only when one of its parts changes: the yes/no parts are bits of f.
+const CKEY=new Map();
+function citySprite(C,p,t,cs,kq,ph,st){const id=C.id,
+    f=(st.down?1:0)|(p?2:0)|(p&&p.site2?4:0)|(p&&p.site2&&siteDown(id,'b')?8:0)|(p&&p.ringcut>S.day?16:0)|(p&&p.gen?32:0)|(C.au?64:0)|(st.ixDraw?128:0)|
+      (st.ixHot?256:0)|(S.myIx[id]?512:0)|(hasIxAt(id)?1024:0)|(!p&&ixQuiet(id)?2048:0)|(st.feed?4096:0)|(st.inc?8192:0),
+    ro=p?(p.routers||1):0,rg=p?(p.rgen||0):0,ix=ixName(id)||'',sp=st.sel?ph.sel:-1,dd=ph.dd;
+  let m=CKEY.get(id);
+  if(!m||m.t!==t||m.kq!==kq||m.f!==f||m.ro!==ro||m.rg!==rg||m.ix!==ix||m.sp!==sp||m.dd!==dd)CKEY.set(id,m={t,kq,f,ro,rg,ix,sp,dd,k:['city',id,t,kq,f,ro,rg,ix,sp,dd].join('|')});
+  const e=spriteHas(m.k);if(e)return e;
   const W=Math.ceil(92*kq),H=Math.ceil(84*kq),ax=45*kq,ay=46*kq;
-  return spriteEntry(key,W,H,ax,ay,g=>{g.translate(ax,ay);cityStatic(C,p,t,cs,kq,ph,st);});}
+  return spriteEntry(m.k,W,H,ax,ay,g=>{g.translate(ax,ay);cityStatic(C,p,t,cs,kq,ph,st);});}
 // The parts that move, in the city's frame at the true scale k.
 function cityMoving(C,p,t,cs,k,sx,sy,now,h,st,hot){const down=st.down,K=k*cs;
   if(p){// The POP's own frame is shifted 2 down, and mirrored Down Under (C.au): mp() takes a point of that frame to the city's.
-    const fl=!!C.au,mp=(x,y)=>fl?[-x,-y-2]:[x,y+2],sf=sfOf(R,C.id),at=(x,y)=>{const q=mp(x,y);return [sx+q[0]*K,sy+q[1]*K];};
-    if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const tt=(now/700+i/3)%1,[x,y]=at(6+i*3,-12-tt*18);dot(x,y,(3+tt*4)*K,'rgba(90,98,130,1)',0.55*(1-tt));}}
+    // A point (x,y) of that frame is at sx+(fl?-x:x)*K, sy+(fl?-y-2:y+2)*K (written out: no array per light per frame).
+    const fl=!!C.au,sf=sfOf(R,C.id);
+    if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const tt=(now/700+i/3)%1,x=6+i*3,y=-12-tt*18;dot(sx+(fl?-x:x)*K,sy+(fl?-y-2:y+2)*K,(3+tt*4)*K,'rgba(90,98,130,1)',0.55*(1-tt));}}
     // The four lights: a disc each, lit or not.
-    for(let i=0;i<4;i++){const lit=down?false:(((now/(160+i*37))|0)+i)%3!==0,[x,y]=at(-10+i*6.6,1),col=down?'#3B4260':lit?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';dot(x,y,2.1*K,col,1);}
+    for(let i=0;i<4;i++){const lit=down?false:(((now/(160+i*37))|0)+i)%3!==0,x=-10+i*6.6,col=down?'#3B4260':lit?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';dot(sx+(fl?-x:x)*K,sy+(fl?-3:3)*K,2.1*K,col,1);}
   }
   // A flashing IX: two pictures, one per colour.
   if(st.ixDraw&&st.ixHot){const on=Math.sin(now/180)>0,ix=p?19:SKY_W[t]/2+4;stamp('ixhot'+(on?1:0),22,22,11,11,K,sx+ix*K,sy+(2-h)*K,()=>{ctx.translate(-ix,h-2);ctx.strokeStyle='#1E2640';cityIX(C,p,t,h,true,on?1:-1);},true);}
@@ -106,7 +119,8 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){
   const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
   // No room for its skyline here: a quiet dot, a little bigger for bigger cities, until you zoom in (cityRoom).
   if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc,rq=Math.round(r*4)/4,fill=hasIxAt(C.id)?'#FFD23F':'#FFFFFF',S2=Math.ceil(rq*2+4);
-    const e=spriteEntry(['quiet',rq,fill].join('|'),S2,S2,S2/2,S2/2,g=>{g.translate(S2/2,S2/2);g.fillStyle=fill;g.strokeStyle='#1E2640';g.lineWidth=1.6;g.beginPath();g.arc(0,0,rq,0,7);g.fill();g.stroke();});
+    const qk=rq*8+(fill==='#FFFFFF'?0:1);let key=QKEY.get(qk);if(!key)QKEY.set(qk,key=['quiet',rq,fill].join('|'));
+    const e=spriteHas(key)||spriteEntry(key,S2,S2,S2/2,S2/2,g=>{g.translate(S2/2,S2/2);g.fillStyle=fill;g.strokeStyle='#1E2640';g.lineWidth=1.6;g.beginPath();g.arc(0,0,rq,0,7);g.fill();g.stroke();});
     blit(e,sx-e.ax,sy+2*sc-e.ay,e.w,e.h);return;}
   const t=cTier(C.id),cs=p?1:CSC[t],k=sc*(hov?1.15:1),kq=sprQ(k);
   const ixn=ixName(C.id),ixDraw=!!ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov),ixHot=!!(ixDraw&&hot&&hot.ix);
diff --git a/tests/webgl-frame-garbage.test.js b/tests/webgl-frame-garbage.test.js
new file mode 100644
index 0000000..a672b14
--- /dev/null
+++ b/tests/webgl-frame-garbage.test.js
@@ -0,0 +1,89 @@
+// A frame on the card makes little garbage (src/game/96-map/57-webgl-background.js, 59-gl-sprites.js, 80-cities.js):
+// the keys of the pictures are kept per city and per label and built again only when the picture changes, and the
+// waves and the clouds are written into arrays kept from frame to frame. What is drawn stays the same.
+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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+
+function open() {
+  const h = load({ seed: 777 });
+  h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
+  return h;
+}
+
+const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+  return (...a)=>{calls.push([k,...a]);return {};};}});
+  const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
+  const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+  GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
+
+// Counts the keys joined during one frame (Array#join with '|', as the picture keys are), but the ships' (a handful).
+const JOINS = (body) => `(()=>{let n=0;const j=Array.prototype.join;Array.prototype.join=function(s){if(s==='|'&&this[0]!=='ship')n++;return j.apply(this,arguments);};
+  try{${body}}finally{Array.prototype.join=j;}return n;})()`;
+
+for (const [view, z] of [['near', 1.4], ['far', 0.6]]) {
+  test(`an unchanged frame on the card joins no picture key again (${view} view)`, () => {
+    const { ev, errors } = open();
+    ev(STUB);
+    ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=${z};UI.sel=null;draw(1000);draw(1016);`);
+    const first = ev(JOINS(`SPRS.clear();CKEY.clear();PILLK.clear();FKEY.clear();QKEY.clear();draw(1032);`));
+    const again = ev(JOINS('draw(1048);'));
+    assert.ok(first > 20, `a first frame builds its keys (${first})`);
+    assert.equal(again, 0, 'the next one builds none');
+    assert.deepEqual(errors, []);
+  });
+}
+
+test('a city whose state changes gets a new picture, and its old one back after', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{const id=S.home,C=CITY[id],p=S.pops[id];cam.x=C.x;cam.y=C.y;cam.z=1.4;UI.sel=null;
+    const pic=()=>{draw(1000);return CKEY.get(id).k;};const a=pic();const was=p.down;p.down=S.day+3;const b=pic();p.down=was;const c=pic();
+    UI.sel={type:'city',id};const d=pic();UI.sel=null;
+    const before=CKEY.get(id).k,gen=p.gen;p.gen=!gen;const e=pic();p.gen=gen;
+    return JSON.stringify({a,b,c,d,e,before});})()`));
+  assert.notEqual(r.b, r.a, 'down: another picture');
+  assert.equal(r.c, r.a, 'back up: the same picture');
+  assert.notEqual(r.d, r.a, 'selected: another picture');
+  assert.notEqual(r.e, r.before, 'a generator: another picture');
+  assert.deepEqual(errors, []);
+});
+
+test('labels with the same text but another look are other pictures', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;const f='800 12px "Baloo 2", sans-serif';
+    pill('Lagos',f,50,19,9,'#FFFFFF','#1E2640','#1E2640',2,10,10,.5);pill('Lagos',f,50,19,9,'#FF4F9A','#FFFFFF','#1E2640',2,10,10,.5);pill('Lagos',f,50,19,9,'#FFFFFF','#1E2640','#1E2640',2,10,10,.5);
+    const n=GLS.n,L=PILLK.get('Lagos').length,u=new Set([0,1,2].map(i=>GLS.data[i*SPR_STRIDE+4]+','+GLS.data[i*SPR_STRIDE+5])).size;GLS.frame=false;GLS.n=0;ctx=CTX0;
+    return JSON.stringify({n,L,u});})()`));
+  assert.equal(r.n, 3);
+  assert.equal(r.L, 2, 'two looks kept for one text');
+  assert.equal(r.u, 2, 'two pictures in the atlas, the third label reuses the first');
+  assert.deepEqual(errors, []);
+});
+
+test('the waves and the clouds are what they were, written into arrays kept from frame to frame', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{const ks=[-1,0,1],now=12345,gl=GLX.gl;
+    glWaves(gl,now,ks);const wa=GLX.wa,ph0=now/900,want=[];let m=0,bad=0;
+    for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;for(const [x0,cx,cy,x1] of [[x-9+o,x-4.5+o,y-4,x+o],[x+o,x+4.5+o,y+4,x+9+o]]){let px=x0,py=y;
+      for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y,o2=m*LINE_STRIDE;
+        if(wa[o2]!==Math.fround(px)||wa[o2+1]!==Math.fround(py)||wa[o2+2]!==Math.fround(qx)||wa[o2+3]!==Math.fround(qy))bad++;m++;px=qx;py=qy;}}}
+    glWaves(gl,now+16,ks);const sameW=GLX.wa===wa;
+    glClouds(gl,now,ks);const ca=GLX.ca,A=[];for(const k of ks)for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100+k*W,y=c.y;A.push(x,y,16*c.s,0, x+18*c.s,y-8*c.s,20*c.s,0, x+40*c.s,y,15*c.s,0);}
+    const sent=gl.calls.filter(c=>c[0]==='bufferData').pop()[2],cbad=A.filter((v,i)=>sent[i]!==Math.fround(v)).length;
+    glClouds(gl,now+16,ks);
+    return JSON.stringify({bad,m,sameW,cbad,clen:sent.length,alen:A.length,sameC:GLX.ca===ca});})()`));
+  assert.equal(r.bad, 0, `every wave segment where it was (${r.m} segments)`);
+  assert.equal(r.sameW, true);
+  assert.equal(r.clen, r.alen, 'one record per puff');
+  assert.equal(r.cbad, 0, 'every puff where it was');
+  assert.equal(r.sameC, true, 'the clouds’ array is kept');
+  assert.deepEqual(errors, []);
+});
diff --git a/tests/webgl-sprites.test.js b/tests/webgl-sprites.test.js
index e5d765c..cf7665c 100644
--- a/tests/webgl-sprites.test.js
+++ b/tests/webgl-sprites.test.js
@@ -35,7 +35,7 @@ test('on the card, pictures are painted on one canvas and each goes into the atl
   const r = JSON.parse(ev(`(()=>{const subs=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D'),es=[...SPRS.values()];
     return JSON.stringify({canvases:__canvases,subs:subs.length,sprites:es.length,mine:es.filter(e=>e.cv).length,
       allUp:es.every(e=>e.up),rect:subs.every(c=>c.length===10&&c[9]===GLS_PAD.cv&&c[5]>0&&c[6]>0),
-      fit:subs.every(c=>c[5]<=GLS_PAD.cv.width&&c[6]<=GLS_PAD.cv.height),keys:es.length?[...SPRS.keys()].every(k=>k[0]==='g'):false});})()`));
+      fit:subs.every(c=>c[5]<=GLS_PAD.cv.width&&c[6]<=GLS_PAD.cv.height),keys:es.length>0&&SPRC.size===0});})()`));
   assert.ok(r.sprites > 50, `a zoom paints many pictures (${r.sprites})`);
   assert.ok(r.canvases <= 1, `one canvas for all of them, not one each (${r.canvases} made)`);
   assert.equal(r.mine, 0, 'no picture keeps a canvas of its own');
@@ -53,7 +53,7 @@ test('a full atlas starts again and the picture that did not fit goes into the n
   const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.shy=GLS.size-4;GLS.shx=GLS.size-2;GLS.shh=4;
     const before=SPRS.size;let draws=0;const gd=glsDraw;glsDraw=function(){draws++;};
     const e=spriteEntry('big',40,40,20,20,g=>{g.fillRect(0,0,40,40);});blit(e,10,10,40,40);
-    glsDraw=gd;const r={up:e.up,u0:e.u0,v0:e.v0,kept:SPRS.get('g'+DPR+'|big')===e,size:SPRS.size,n:GLS.n,cv:!!e.cv,shy:GLS.shy};GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify(r);})()`));
+    glsDraw=gd;const r={up:e.up,u0:e.u0,v0:e.v0,kept:SPRS.get('big')===e,size:SPRS.size,n:GLS.n,cv:!!e.cv,shy:GLS.shy};GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify(r);})()`));
   assert.equal(r.up, true, 'the picture is in the atlas');
   assert.equal(r.u0, 0); assert.equal(r.v0, 0);
   assert.equal(r.kept, true, 'and kept under its key after the restart');
@@ -66,7 +66,7 @@ test('a full atlas starts again and the picture that did not fit goes into the n
 test('the 2D map keeps a canvas per picture, and its pictures are not the card’s', () => {
   const { ev, errors } = open();
   ev(`mapGl(false);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
-  const r = JSON.parse(ev(`(()=>{const es=[...SPRS.entries()];return JSON.stringify({n:es.length,cv:es.every(([k,e])=>k[0]==='c'&&e.cv&&e.cv.width===e.pw&&e.cv.height===e.ph),up:es.some(([,e])=>e.up)});})()`));
+  const r = JSON.parse(ev(`(()=>{const es=[...SPRC.entries()];return JSON.stringify({n:es.length,cv:SPRS.size===0&&es.every(([k,e])=>e.cv&&e.cv.width===e.pw&&e.cv.height===e.ph),up:es.some(([,e])=>e.up)});})()`));
   assert.ok(r.n > 10);
   assert.equal(r.cv, true, 'each with its own canvas, at its size');
   assert.equal(r.up, false, 'nothing went to a card');
@@ -82,8 +82,8 @@ test('giving the card up drops its pictures; the 2D map paints its own', () => {
   assert.equal(ev('SPRS.size'), 0, 'no picture without a canvas is left behind');
   assert.equal(ev('GLS.shx+GLS.shy+GLS.shh'), 0, 'the atlas is forgotten');
   ev('draw(1016)');
-  assert.ok(ev('SPRS.size') > 10);
-  assert.equal(ev(`[...SPRS.values()].every(e=>e.cv)`), true, 'the 2D map’s pictures have their canvas');
+  assert.ok(ev('SPRC.size') > 10);
+  assert.equal(ev(`[...SPRC.values()].every(e=>e.cv)`), true, 'the 2D map’s pictures have their canvas');
   assert.ok(ev('ctx===CTX0'));
   assert.deepEqual(errors, []);
 });
diff --git a/tests/webgl-zoom-sprites.test.js b/tests/webgl-zoom-sprites.test.js
index dc8ea40..ae35c7f 100644
--- a/tests/webgl-zoom-sprites.test.js
+++ b/tests/webgl-zoom-sprites.test.js
@@ -27,8 +27,8 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in
 // One POP's city pictures painted during frames from zoom z0 to z1 (the clock moving 16 ms a frame), by scale.
 const ZOOM = (z0, z1, n) => `(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const seen=new Set(),bad=[];
   for(let i=0;i<=${n};i++){cam.z=${z0}+(${z1}-${z0})*i/${n};__T+=16;draw(__T);
-    for(const k of SPRS.keys()){const p=k.split('|');if(p[1]==='city'&&p[2]===id)seen.add(+p[4]);}
-    const k=cityScale(iconScale()),kq=[...SPRS.keys()].filter(x=>x.split('|')[1]==='city'&&x.split('|')[2]===id).map(x=>+x.split('|')[4]);
+    for(const k of SPRS.keys()){const p=k.split('|');if(p[0]==='city'&&p[1]===id)seen.add(+p[3]);}
+    const k=cityScale(iconScale()),kq=[...SPRS.keys()].filter(x=>x.split('|')[0]==='city'&&x.split('|')[1]===id).map(x=>+x.split('|')[3]);
     if(kq.length&&!kq.some(q=>Math.max(q/k,k/q)<=1.25*(1+.5/24/0.7)))bad.push(i);}
   return JSON.stringify({steps:[...seen].sort(),bad});})()`;
 
@@ -45,7 +45,7 @@ test('on the card a zoom keeps each city’s picture for a while, and paints it
   assert.equal(ev('zoomMoving()'), true);
   ev('__T+=300;draw(__T)');
   const rest = JSON.parse(ev(`(()=>{const id=S.home,want=Math.round(cityScale(iconScale())*24)/24;
-    return JSON.stringify({f:ZH.f,want,has:[...SPRS.keys()].some(k=>{const p=k.split('|');return p[1]==='city'&&p[2]===id&&+p[4]===want;}),moving:zoomMoving()});})()`));
+    return JSON.stringify({f:ZH.f,want,has:[...SPRS.keys()].some(k=>{const p=k.split('|');return p[0]==='city'&&p[1]===id&&+p[3]===want;}),moving:zoomMoving()});})()`));
   assert.equal(rest.moving, false);
   assert.equal(rest.f, 1, 'at rest nothing is stretched');
   assert.equal(rest.has, true, 'the city is painted again at its own step');
@@ -56,8 +56,8 @@ test('the 2D map paints cities at their own step on every frame of a zoom, as be
   const { ev, errors } = open();
   ev(`mapGl(false);cam.z=0.8;draw(__T);`);
   const r = JSON.parse(ev(`(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const bad=[];
-    for(let i=0;i<=30;i++){cam.z=0.8+i/30;__T+=16;SPRS.clear();draw(__T);const want=Math.round(cityScale(iconScale())*24)/24;
-      if(ZH.f!==1||![...SPRS.keys()].some(k=>{const p=k.split('|');return p[1]==='city'&&p[2]===id&&+p[4]===want;}))bad.push(i);}
+    for(let i=0;i<=30;i++){cam.z=0.8+i/30;__T+=16;SPRC.clear();draw(__T);const want=Math.round(cityScale(iconScale())*24)/24;
+      if(ZH.f!==1||![...SPRC.keys()].some(k=>{const p=k.split('|');return p[0]==='city'&&p[1]===id&&+p[3]===want;}))bad.push(i);}
     return JSON.stringify({bad});})()`));
   assert.deepEqual(r.bad, []);
   assert.deepEqual(errors, []);
@@ -83,7 +83,7 @@ test('pictures that keep their size whatever the zoom (far-view cities, cones, d
   ev(STUB);
   const r = JSON.parse(ev(`(()=>{cam.z=1;draw(__T);__T+=1000;cam.z=1;draw(__T);cam.z=1.4;__T+=16;draw(__T);GLS.frame=true;GLS.n=0;ctx=GLX.fx;
     const f=ZH.f;drawCone(100,100,0);drawBackhoe(200,100,0,false);const D=GLS.data,o=[D[2],D[3],D[SPR_STRIDE+2],D[SPR_STRIDE+3]];
-    const keys=[...SPRS.keys()].filter(k=>['cone','hoe'].includes(k.split('|')[1]));GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify({f,o,keys});})()`));
+    const keys=[...SPRS.keys()].filter(k=>['cone','hoe'].includes(k.split('|')[0]));GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify({f,o,keys});})()`));
   assert.notEqual(r.f, 1, 'the zoom is moving and city pictures are held');
   assert.deepEqual(r.o, [26, 28, 38, 32], 'drawn at their own size');
   assert.ok(r.keys.length >= 2 && r.keys.every(k => k.endsWith('|1')), 'painted at scale 1: ' + r.keys);

From fb76a1e6fd8f826a1ef5c47b64eb1aff8e5a171e Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 19:08:36 +0100
Subject: [PATCH 320/491] 2D map: draw the pictures with the map's own pen, as
 main did

Cities, markers and labels are now pictures painted once on a canvas of their own. Drawn straight on the map,
main's dashed rings (the selected city, the cities feeding a selected tube, a flood), the cones' tips, a sleeping
POP's "zzz" and a working cable ship's spark took the state the tubes and labels left on the map's canvas: round
line ends and corners, text centred on its middle. A new canvas starts with square ends and text on its baseline, so
the rings came out with square dashes and the "zzz" sat higher. Every picture now starts with that pen (sprPen()),
on the card's shared canvas too.

tests/map-2d.test.js holds the 2D map to main, for players who keep it:
- for the same state, a frame drawn from the kept pictures is, call for call, the frame painted with no cache at
  all: over every state a POP can be in, a city without a POP, random views of the big network with days passing,
  and seeded random games after every move and day (the route-fuzz driver, two pages in lockstep);
- every tube's width, colour, dash and packets follow main's formulas;
- the 2D map never asks for WebGL, never draws a picture without a canvas, keeps one canvas per picture, draws as
  a 2D map after the card is switched off or lost, and paints again at a new pixel density;
- money pop-ups fade as before; every picture starts with the right pen.
Planted bugs (incomplete keys, a stale key memo, the tubes' looks kept without the routing, one shared 2D canvas,
no pen) each fail it. A pixel comparison with main in Chromium (desktop and phone, the fixture, a late-game save and
states from random games) found the pen and nothing else beyond sub-pixel edges.
---
 src/game/96-map/59-gl-sprites.js |   8 +-
 tests/map-2d.test.js             | 308 +++++++++++++++++++++++++++++++
 2 files changed, 314 insertions(+), 2 deletions(-)
 create mode 100644 tests/map-2d.test.js

diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js
index 9ecdf6c..5bb1053 100644
--- a/src/game/96-map/59-gl-sprites.js
+++ b/src/game/96-map/59-gl-sprites.js
@@ -48,12 +48,16 @@ function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.
   e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1};
   if(gpu&&pw<=GLS.size&&ph<=GLS.size){const P=glsPad(pw,ph),g=P.g;
     g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw,ph);ctx=g;
-    try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;g.restore();}
+    try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;g.restore();}
     // A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next.
     try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);}
   }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g;
-    try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;}e.cv=cv;}
+    try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;}e.cv=cv;}
   M.set(key,e);return e;}
+/* A picture starts with the pen the map's own canvas has when it draws cities and markers: the tubes leave it with
+   round line ends and corners, the labels with text centred on its middle. Drawn straight on the map, the dashed rings,
+   the cones' tips and a sleeping POP's "zzz" took those, and a new canvas has others (square ends, text on its baseline). */
+function sprPen(g){g.lineCap='round';g.lineJoin='round';g.textAlign='center';g.textBaseline='middle';}
 // Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame.
 function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog||!e.cv)return false;
   try{return glsPut(gl,e,e.cv);}catch(x){throw glErr(x);}}
diff --git a/tests/map-2d.test.js b/tests/map-2d.test.js
new file mode 100644
index 0000000..450ad59
--- /dev/null
+++ b/tests/map-2d.test.js
@@ -0,0 +1,308 @@
+// The 2D map, for players who keep it (Settings › Map drawing › Always 2D, or no usable graphics card). The WebGL work
+// changed it too: cities, labels and markers are painted once as pictures and reused (59-gl-sprites.js), and each
+// tube's look is worked out once per day's routing (mapLinks(), 55-link-look.js). These tests hold the 2D map to what
+// it drew before:
+// - a frame drawn with the pictures kept from earlier states is, call for call, the frame painted from scratch: no
+//   picture is ever shown for a state it was not painted for (on the big network, and in seeded random games);
+// - every tube's width, colour, dash and packets follow the formulas main's 2D map used, after every move and day;
+// - the 2D map never asks for WebGL, never draws a picture it has no canvas for, and keeps one canvas per picture;
+// - every picture starts with the pen main's map had when it drew the same thing straight on the map (round line
+//   ends, centred text), or its dashed rings and markers would come out differently.
+// The page's clock is set by hand, so nothing depends on how fast the test runs. Comparing pixels with main needs a real
+// browser, which npm test does not use: that was done by hand, in Chromium, for this change.
+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 page = require('../scripts/lib/page');
+const { openPage, playGame, rng } = require('../scripts/lib/route-fuzz');
+
+const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+
+/* In the page: every canvas made from now on records what is drawn on it, and the map's own context records the
+   frame. A picture is known by what was painted on it (a hash of its calls), so a frame's calls say which picture went
+   where. WebGL is not there (getContext gives null for it), and every request for it is counted. */
+const KIT = `window.__M2D=(()=>{
+  const N=v=>typeof v==='number'?String(Math.round(v*1000)/1000):v==null?String(v):typeof v==='function'?'fn':
+    v instanceof HTMLCanvasElement?v.__cid():Array.isArray(v)?'['+v.map(N).join(',')+']':typeof v==='object'?'obj':String(v);
+  const M=['arc','arcTo','beginPath','bezierCurveTo','clearRect','clip','closePath','drawImage','ellipse','fill','fillRect','fillText',
+    'lineTo','moveTo','quadraticCurveTo','rect','resetTransform','restore','rotate','roundRect','save','scale','setLineDash','setTransform',
+    'stroke','strokeRect','strokeText','transform','translate'];
+  // With each call that paints, the state of the context it uses (a picture does not care about the font, say).
+  const IMG=['globalAlpha','globalCompositeOperation'],FILL=[...IMG,'fillStyle'],LINE=[...IMG,'strokeStyle','lineWidth','lineDashOffset','lineJoin','lineCap'],
+    TXT=['font','textAlign','textBaseline'];
+  const PAINT={drawImage:IMG,clearRect:[],fill:FILL,fillRect:FILL,stroke:LINE,strokeRect:LINE,fillText:[...FILL,...TXT],strokeText:[...LINE,...TXT]};
+  const DEF={globalAlpha:1,fillStyle:'#000000',strokeStyle:'#000000',lineWidth:1,font:'10px sans-serif',lineDashOffset:0,lineJoin:'miter',lineCap:'butt',
+    textAlign:'start',textBaseline:'alphabetic',globalCompositeOperation:'source-over'};
+  function rec(c,keep){const Q={h:2166136261,n:0,log:keep?[]:null};
+    const add=s=>{for(let i=0;i>>0;Q.n++;if(Q.log)Q.log.push(s);};
+    for(const m of M)c[m]=function(...a){let s=m+'('+a.map(N).join(',')+')';for(const k of PAINT[m]||[])s+=' '+N(this[k]);add(s);};
+    Object.assign(c,DEF);c.__Q=Q;return c;}
+  const blank=()=>new Proxy({},{get(t,k){if(k in t)return t[k];if(k==='measureText')return s=>({width:String(s).length*7});
+    if(k==='createLinearGradient'||k==='createRadialGradient'||k==='createPattern')return ()=>({addColorStop(){}});
+    if(k==='getImageData')return ()=>({data:new Uint8ClampedArray(4)});if(k==='canvas')return null;return ()=>{};},set(t,k,v){t[k]=v;return true;}});
+  const asked=[];
+  HTMLCanvasElement.prototype.getContext=function(type){asked.push(type);if(type!=='2d')return null;return this.__ctx||(this.__ctx=rec(blank(),false));};
+  HTMLCanvasElement.prototype.__cid=function(){const q=this.__ctx&&this.__ctx.__Q;return q?'cv:'+q.h.toString(36)+'.'+q.n:'cv:?';};
+  rec(CTX0,true);
+  // A picture drawn in a 2D frame without a canvas of its own would simply not show.
+  let lost=0;const blit0=blit;blit=function(e,...a){if(!GLS.frame&&!e.cv)lost++;return blit0(e,...a);};
+  // One frame's calls on the map's canvas, from a known state of the context.
+  function frame(t){const Q=CTX0.__Q;Q.log.length=0;Q.h=2166136261;Q.n=0;Object.assign(CTX0,DEF);draw(t);return Q.log.slice();}
+  function inv(){let dup=0,bad=0;const seen=new Set();
+    for(const e of SPRC.values()){if(!e.cv){bad++;continue;}if(seen.has(e.cv))dup++;seen.add(e.cv);if(e.cv.width!==e.pw||e.cv.height!==e.ph)bad++;}
+    return {webgl:asked.filter(x=>x!=='2d').length,sprs:SPRS.size,glsFrame:GLS.frame,ctx0:ctx===CTX0,glShown:!document.getElementById('mapgl').hidden,
+      pad:!!GLS_PAD.cv,shared:dup,badCanvas:bad,lost};}
+  // Without the cache: every picture is painted again for every call, as if nothing were kept, even within a frame.
+  let nocache=false;const none={get(){},set(){},has:()=>false,size:0},sprMap0=sprMap;sprMap=function(){const m=sprMap0();return nocache?none:m;};
+  /* The same state drawn twice: with the pictures kept from every state before (kept), then painting every picture
+     again (fresh). The land picture is settled first, so both frames find it as it is. */
+  function pair(t){__T+=1000;if(S)worldLayer(cam.z);lost=0;
+    const kept=frame(t),had=SPRC.size;nocache=true;let fresh;try{fresh=frame(t);}finally{nocache=false;}
+    let d=-1;for(let i=0,n=Math.max(kept.length,fresh.length);i1,up=many?grp.filter(x=>!linkDown(x)):null;
+    const 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 w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)));
+    return {w,dash:cut?[8,8]:vx?[2,7]:bld?[10,8]:idle?[4,6]:[],col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),
+      pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0,cut,bld,dark,vx,cap,load,up:up&&up.map(x=>x.id)};}
+  // The kept looks (mapLinks) against groups, geometry and looks worked out again now, the way main did.
+  function looks(){if(!S||!R)return [];const ML=mapLinks(S.day),PI=pairIdx(),LG=linkGroups(),bad=[];
+    if(JSON.stringify(ML.LG.map(g=>g.map(l=>l.id)))!==JSON.stringify(LG.map(g=>g.map(l=>l.id))))return ['the tubes are not grouped as now'];
+    LG.forEach((g,i)=>{const gm=linkGeom(g[0],PI.get(edgeKey(g[0])));if(JSON.stringify(gm.pts)!==JSON.stringify(ML.GM[i].pts))bad.push('geometry of '+g[0].id);
+      const n=ML.looks[i],o=JSON.stringify(ref(g,S.day)),m=JSON.stringify({w:n.w0,dash:LDASH[n.dash],col:n.col,pk:n.pk,cut:n.cut,bld:n.bld,dark:n.dark,vx:n.vx,cap:n.cap,load:n.load,up:n.up&&n.up.map(x=>x.id)});
+      if(o!==m)bad.push(g[0].id+': main '+o+' kept '+m);});
+    return bad.slice(0,3);}
+  /* A view of the map: the camera on a city at a zoom, maybe a city or a tube selected, maybe a city under the
+     pointer, at clock t. u: numbers in [0,1) from the test's own seeded generator. */
+  function view(u){if(!S)return null;const pops=Object.keys(S.pops),at=pops.length&&u[0]<.7?pops[Math.floor(u[1]*pops.length)]:CITIES[Math.floor(u[1]*CITIES.length)].id,C=CITY[at];
+    cam.x=C.x+(u[2]-.5)*80;cam.y=C.y+(u[3]-.5)*60;cam.z=[.45,.7,1,1.6,3.2][Math.floor(u[4]*5)];
+    UI.sel=u[5]<.35?null:u[5]<.6?{type:'city',id:at}:S.links.length?{type:'link',id:S.links[Math.floor(u[6]*S.links.length)].id}:null;
+    UI.hover=u[7]<.3?at:null;return Math.floor(u[8]*20000);}
+  function check(u){const keep={x:cam.x,y:cam.y,z:cam.z,sel:UI.sel,hov:UI.hover};
+    try{const t=view(u);if(t===null)return null;const r=pair(t);r.looks=looks();r.view={at:UI.sel,z:cam.z,t};return r;}
+    finally{cam.x=keep.x;cam.y=keep.y;cam.z=keep.z;UI.sel=keep.sel;UI.hover=keep.hov;}}
+  return {frame,pair,inv,looks,check,view,asked};})();0`;
+
+// What a check returned, as the problems it shows (none: an empty list).
+function problems(r, where) {
+  if (!r) return [];
+  const out = [];
+  if (r.diff) out.push(`${where}: a kept picture differs from a fresh one at call ${r.diff.at}\n  kept:  ${r.diff.kept.join('\n         ')}\n  fresh: ${r.diff.fresh.join('\n         ')}`);
+  for (const l of r.looks || []) out.push(`${where}: ${l}`);
+  if (r.webgl) out.push(`${where}: WebGL asked for ${r.webgl} times`);
+  if (r.lost) out.push(`${where}: ${r.lost} pictures drawn without a canvas`);
+  if (r.shared || r.badCanvas) out.push(`${where}: ${r.shared} pictures share a canvas, ${r.badCanvas} have none or one of the wrong size`);
+  if (r.pad) out.push(`${where}: the card's shared canvas was made`);
+  if (r.sprs || r.glsFrame || !r.ctx0 || r.glShown) out.push(`${where}: card state leaked into 2D ${JSON.stringify({ sprs: r.sprs, glsFrame: r.glsFrame, ctx0: r.ctx0, glShown: r.glShown })}`);
+  return out;
+}
+
+// A card that records what it is asked (jsdom has no WebGL), as in tests/webgl-zoom-sprites.test.js.
+const GLSTUB = `window.__GLSTUB=(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+      return (...a)=>{calls.push(k);return {};};}});
+    const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
+    const fx=document.createElement('canvas').getContext('2d');
+    Object.assign(GLX,{want:true,dead:false,gl,c,f,fx,line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+    GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})();0`;
+
+function open() {
+  const h = load({ seed: 777 });
+  h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
+    window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);`);
+  h.ev(KIT);
+  return h;
+}
+
+test('the 2D map draws the same frame from kept pictures as from fresh ones, whatever happens to a POP', () => {
+  const { ev, errors } = open();
+  const found = [];
+  assert.ok(ev('CW>300&&CH>300'), 'the map has a size');
+  // One city goes through every state its picture can show. After each change the map is looked at from the same
+  // views (every zoom, plain, under the pointer, selected), so a picture kept from an earlier state is found under its
+  // key whenever the key leaves out what changed.
+  const STEPS = [
+    '0',
+    'S.pops[S.home].down=S.day+3',
+    'S.pops[S.home].down=0;S.pops[S.home].routers=2',
+    'S.pops[S.home].gen=1',
+    'S.pops[S.home].rgen=1',
+    'S.pops[S.home].site2=S.pops[S.home].site2||{}',
+    'S.pops[S.home].ringcut=S.day+2',
+    "S.inc.push({id:'t-site',type:'site',ref:S.home,site:'b',until:S.day+5})",
+    'R.ddosHot=Object.assign({},R.ddosHot,{[S.home]:1})',
+    'UI.hotMap={[S.home]:{r:1,t:1,ix:1}}',
+    "S.myIx[S.home]=S.myIx[S.home]||{name:'Test-IX',members:[],next:S.day+4}",
+    'S.pops[S.home].routers=3;S.pops[S.home].rgen=0;S.pops[S.home].gen=0',
+    'delete R.ddosHot[S.home];UI.hotMap=null;S.pops[S.home].ringcut=0',
+    'S.pops[S.home].down=S.day+1',
+    // A city without a POP next to it: an incident there, then an exchange.
+    "S.inc.push({id:'t-x',type:'cut',ref:__OTHER,until:S.day+3})",
+    "S.myIx[__OTHER]={name:'Other-IX',members:[],next:S.day+4}",
+  ];
+  // The other city: the nearest one without a POP.
+  ev("window.__OTHER=CITIES.filter(c=>!S.pops[c.id]&&!c.off).sort((a,b)=>Math.hypot(a.x-CITY[S.home].x,a.y-CITY[S.home].y)-Math.hypot(b.x-CITY[S.home].x,b.y-CITY[S.home].y))[0].id;0");
+  let checks = 0;
+  // u (see view()): centred on the home POP or on the other city, at zoom index z; nothing selected, the city under
+  // the pointer, or selected.
+  const VIEWS = [];
+  for (const city of ['pop', 'other']) for (let z = 0; z < 5; z++) for (const [sel, hov] of [[0.1, 0.9], [0.1, 0.1], [0.5, 0.9]]) VIEWS.push({ city, u: [city === 'pop' ? 0 : 0.9, 0, 0.5, 0.5, z / 5 + 0.01, sel, 0, hov, (z + 1) / 7] });
+  for (const step of STEPS) {
+    ev(step);
+    // Each change is looked at from the city it touches (both at the start).
+    const on = step === '0' ? null : step.includes('__OTHER') ? 'other' : 'pop';
+    VIEWS.forEach(({ city, u }, v) => {
+      if (on && city !== on) return;
+      const at = city === 'pop' ? 'Object.keys(S.pops).indexOf(S.home)/Object.keys(S.pops).length' : 'CITIES.findIndex(c=>c.id===__OTHER)/CITIES.length';
+      ev(`window.__U=${JSON.stringify(u)};__U[1]=${at}+1e-9;0`);
+      found.push(...problems(JSON.parse(ev('JSON.stringify(__M2D.check(__U))')), `after "${step}", view ${v} (${city})`));
+      checks++;
+    });
+  }
+  assert.ok(checks >= 250);
+  assert.deepEqual(found.slice(0, 5), []);
+  assert.deepEqual(errors, []);
+});
+
+test('the 2D map draws the same from kept pictures as from fresh ones, and tubes as main did, over random views of the big network', () => {
+  const { ev, errors } = open();
+  const r = rng(99), found = [];
+  for (let i = 0; i < 60; i++) {
+    // Now and then a day passes (failures and events on), so cuts, builds, floods and offers come and go.
+    if (i % 6 === 5) ev('S.nextFail=S.day;S.nextEvent=S.day;dayTick();compute();');
+    const u = Array.from({ length: 9 }, () => r());
+    found.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `view ${i} (day ${ev('S.day')})`));
+  }
+  assert.deepEqual(found.slice(0, 5), []);
+  assert.deepEqual(errors, []);
+});
+
+test('in seeded random games, after every move and day, the 2D map draws the same from kept pictures and tubes as main did', () => {
+  const file = path.join(os.tmpdir(), `tubes-map2d-${process.pid}.html`);
+  fs.writeFileSync(file, page.assemble().html);
+  try {
+    // A normal game, a sandbox, a scenario and a puzzle (the seeds of tests/route-fuzz.test.js). The big network is the
+    // test above: a whole game of it, routed again after every move on two pages, takes a minute.
+    for (const seed of [20, 23, 27, 26]) {
+      // Two pages of this checkout play the game in lockstep (scripts/lib/route-fuzz.js): drawing the map on both, between
+      // moves, must not make them part (the 2D map must not change the game).
+      const P = { base: openPage(file, 'a'), head: openPage(file, 'b') };
+      for (const p of [P.base, P.head]) p.ev(`window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);${KIT}`);
+      const r = rng(seed * 7919), found = [];
+      let checks = 0;
+      const g = playGame(P, seed, { moves: 40, maxDays: 4, onMove: () => {
+        const u = Array.from({ length: 9 }, () => r());
+        for (const p of [P.base, P.head]) {
+          const out = JSON.parse(p.ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`));
+          if (out) checks++;
+          found.push(...problems(out, `seed ${seed}, page ${p.label}`));
+        }
+      } });
+      assert.equal(g.div, null, `seed ${seed}: the two pages parted: ${JSON.stringify(g.div && { where: g.div.where, last: g.div.last })}`);
+      assert.ok(checks >= 20, `seed ${seed}: the map was checked (${checks})`);
+      assert.deepEqual(found.slice(0, 5), [], `seed ${seed}`);
+      assert.deepEqual(g.errors, [], `seed ${seed}`);
+    }
+  } finally { fs.rmSync(file, { force: true }); }
+});
+
+test('a 2D map without WebGL2 never asks for it again, and its pictures each keep their own canvas', () => {
+  const h = load({ seed: 777 });
+  // Auto mode, in a browser where WebGL2 is not there.
+  h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
+    window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`);
+  h.ev(KIT);
+  h.ev('mapGl(true,false);draw(__T);');
+  const first = JSON.parse(h.ev('JSON.stringify({asked:__M2D.asked.filter(x=>x!=="2d").length,gl:!!GLX.gl,glOn:glOn()})'));
+  assert.equal(first.gl, false);
+  assert.equal(first.glOn, false, 'auto mode draws in 2D');
+  for (let i = 0; i < 20; i++) h.ev(`cam.z=${0.5 + i * 0.15};__T+=16;draw(__T);`);
+  const inv = JSON.parse(h.ev('JSON.stringify(__M2D.inv())'));
+  assert.ok(inv.webgl <= first.asked, `WebGL was asked for again (${inv.webgl} after ${first.asked})`);
+  assert.deepEqual(problems({ ...inv, webgl: 0 }, 'zoom'), []);
+  assert.ok(h.ev('SPRC.size') > 50, 'the pictures are kept');
+  assert.deepEqual(h.errors, []);
+});
+
+test('the 2D map after the card is given up, or switched off, draws as a 2D map that never had one', () => {
+  const { ev, errors } = open();
+  // A card (a recording stand-in) draws a few frames and fills its own pictures.
+  ev(GLSTUB);
+  const views = (tag) => {
+    const out = [];
+    for (let v = 0; v < 8; v++) {
+      const u = [0.2, v / 8, 0.5, 0.5, (v % 5) / 5 + 0.01, v / 8, 0.3, v % 2 ? 0.1 : 0.9, v / 8];
+      out.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `${tag}, view ${v}`));
+    }
+    return out;
+  };
+  // Switched off in the settings, with the card's pictures still kept.
+  for (let i = 0; i < 6; i++) ev(`cam.z=${0.5 + i * 0.4};__T+=16;draw(__T);`);
+  assert.ok(ev('SPRS.size') > 20, 'the card painted its pictures');
+  ev('mapGl(false)');
+  // pad and sprs: the card's own, left from its frames; what matters is that the 2D frames never use them.
+  const off = views('switched off').filter((p) => !/card's shared canvas|card state leaked/.test(p) || /ctx0":false|glShown":true|glsFrame":true/.test(p));
+  assert.deepEqual(off.slice(0, 5), []);
+  // Back on, then the card fails: the session's map stays 2D.
+  ev('mapGl(true);__T+=16;draw(__T);glKill(new Error("test"));');
+  assert.equal(ev('SPRS.size'), 0, 'the card’s pictures are forgotten');
+  const dead = views('given up').filter((p) => !/card's shared canvas/.test(p));
+  assert.deepEqual(dead.slice(0, 5), []);
+  assert.deepEqual(errors, []);
+});
+
+test('the 2D map paints its pictures again for a new pixel density', () => {
+  const { ev, errors } = open();
+  ev('__T+=16;draw(__T);');
+  assert.ok(ev('SPRC.size') > 20);
+  ev('DPR=2;__T+=16;draw(__T);');
+  const bad = JSON.parse(ev('JSON.stringify([...SPRC.values()].filter(e=>e.pw!==Math.ceil(e.w*2)||e.ph!==Math.ceil(e.h*2)).length)'));
+  assert.equal(bad, 0, 'every picture is at the new density');
+  const r = JSON.parse(ev('JSON.stringify(__M2D.check([0,0,0.5,0.5,0.5,0.1,0,0.9,0.3]))'));
+  assert.deepEqual(problems(r, 'at 2×'), []);
+  assert.deepEqual(errors, []);
+});
+
+test('money pop-ups on the 2D map fade out as before', () => {
+  const { ev, errors } = open();
+  const C = 'CITY[S.home]';
+  ev(`cam.x=${C}.x;cam.y=${C}.y;cam.z=1;__T+=16;FLOATS.push({x:${C}.x,y:${C}.y,text:'+$1,234',col:'#16A866',t:__T});`);
+  // At 0, 40% and 80% of its life: drawn at opacity 1-a².
+  const alphas = [];
+  for (const a of [0, 0.4, 0.8]) {
+    const log = JSON.parse(ev(`JSON.stringify(__M2D.frame(FLOATS[FLOATS.length-1].t+${a * 1600}))`));
+    const last = log.filter((s) => s.startsWith('drawImage(')).pop();
+    alphas.push(+last.split(' ')[1]);
+  }
+  assert.deepEqual(alphas, [1, 0.84, 0.36]);
+  ev(`__M2D.frame(FLOATS[FLOATS.length-1].t+1700)`);
+  assert.equal(ev('FLOATS.length'), 0, 'gone after its life');
+  // The same text in two colours at once: two pictures, each in its own colour.
+  ev(`FLOATS.push({x:${C}.x,y:${C}.y,text:'+$500',col:'#16A866',t:5000},{x:${C}.x+40,y:${C}.y,text:'+$500',col:'#FF4D5E',t:5000});`);
+  const r = JSON.parse(ev('JSON.stringify(__M2D.pair(5400))'));
+  assert.deepEqual(problems(r, 'two pop-ups'), []);
+  assert.deepEqual(errors, []);
+});
+
+test('every picture starts with the pen the map had when it drew them itself: round line ends and corners, centred text', () => {
+  const { ev, errors } = open();
+  // Drawn straight on the map, main's dashed rings, cones and "zzz" took the state the tubes and labels left there.
+  let n = 0;
+  const pen = (spoil) => JSON.parse(ev(`(()=>{let o;spriteEntry('t-pen|${n++}',10,10,5,5,g=>{o={cap:g.lineCap,join:g.lineJoin,align:g.textAlign,base:g.textBaseline};
+    ${spoil ? "g.lineCap='butt';g.lineJoin='miter';g.textAlign='start';g.textBaseline='alphabetic';" : ''}});return JSON.stringify(o);})()`));
+  const want = { cap: 'round', join: 'round', align: 'center', base: 'middle' };
+  assert.deepEqual(pen(true), want, 'a 2D picture');
+  assert.deepEqual(pen(false), want, 'the next 2D picture');
+  // On the card one canvas is reused for every picture: each starts from that pen again, whatever the last one did.
+  ev(GLSTUB);
+  ev('GLS.frame=true;');
+  try {
+    assert.deepEqual(pen(true), want, 'a picture on the card');
+    assert.deepEqual(pen(false), want, 'the next picture on the card, on the same canvas');
+    assert.ok(ev('!!GLS_PAD.cv&&SPRS.size>=2'), 'the card’s pictures went through its shared canvas');
+  } finally { ev('GLS.frame=false;'); }
+  assert.deepEqual(errors, []);
+});

From 52c8aaffd6e50c3113af213eb99a98ea295aec8b Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 19:08:42 +0100
Subject: [PATCH 321/491] WebGL map: give the card up for 2D when it runs out
 of memory without saying so

A card short of memory may refuse a texture or a buffer without throwing: the call only leaves OUT_OF_MEMORY for
getError(), which nothing read. Refused, the 64 MB atlas drew every city, label and marker as a black box while the
map stayed on the card (seen in Chromium by refusing it).

The big uploads now read it (glMem()): the atlas, the land for each zoom level, the tubes once a day, the cables.
The atlas tries 2048 px (16 MB) before giving up; any other refusal is the card's error, so draw() gives WebGL up
for the session and draws the same frame again in 2D. getError() is never read on an ordinary frame: each read waits
for the card.

tests/webgl-out-of-memory.test.js: a 4096 px atlas refused gives a 2048 px one; both refused, or the land or the
tubes refused, leave the map in 2D in that frame with no glitch for the player; panning reads no error.
---
 src/game/96-map/56-webgl.js            |  6 ++
 src/game/96-map/57-webgl-background.js |  7 ++-
 src/game/96-map/58-webgl-links.js      |  2 +-
 src/game/96-map/59-gl-sprites.js       | 10 ++--
 tests/webgl-out-of-memory.test.js      | 82 ++++++++++++++++++++++++++
 5 files changed, 99 insertions(+), 8 deletions(-)
 create mode 100644 tests/webgl-out-of-memory.test.js

diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js
index 2819c7d..aa4ee57 100644
--- a/src/game/96-map/56-webgl.js
+++ b/src/game/96-map/56-webgl.js
@@ -20,6 +20,12 @@ function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=docume
 // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame.
 function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;}
 function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);}
+/* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for
+   getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big
+   uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never
+   every frame: each read waits for the card. Up to four flags are read, as one call returns only one. */
+function glMem(gl,what){for(let i=0;i<4;i++){const e=gl.getError();if(!e||e===gl.CONTEXT_LOST_WEBGL)return;
+  if(e===gl.OUT_OF_MEMORY)throw glErr(new Error('the graphics card is out of memory ('+what+')'));}}
 const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n';
 // Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing).
 const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n';
diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js
index ebab529..a528c30 100644
--- a/src/game/96-map/57-webgl-background.js
+++ b/src/game/96-map/57-webgl-background.js
@@ -50,8 +50,9 @@ function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@'
     for(let i=0;i+1new Float32Array(a);
-  return GLX.land[key]={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE,
-    hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};}
+  G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE,
+    hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};
+  glMem(gl,'the land');return GLX.land[key]=G;}
 // Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map.
 function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST);
   gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan);
@@ -94,7 +95,7 @@ function glCables(gl,ks,selC,ar){const key=[selC,ar];
     for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;
       const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0;
       for(let j=0;j+1.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);}
   else o=texture(uTex,vUV)*vC.a;}`;
 function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b;
-  // 4096 px square (64 MB), or what the card allows if that is less (some phones).
-  GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096);
-  GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);
-  gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null);
+  // 4096 px square (64 MB), or what the card allows if that is less (some phones). A card that has not the memory for
+  // it gets 2048 (16 MB: more resets of the atlas, the same map); without even that, the map stays 2D (glMem).
+  GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);glMem(gl,'setup');
+  for(GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096);;GLS.size>>=1){
+    gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null);
+    try{glMem(gl,'the pictures');break;}catch(e){if(GLS.size<=2048)throw e;}}
   for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR);
   for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE);
   GLS.shx=GLS.shy=GLS.shh=0;}
diff --git a/tests/webgl-out-of-memory.test.js b/tests/webgl-out-of-memory.test.js
new file mode 100644
index 0000000..4d49761
--- /dev/null
+++ b/tests/webgl-out-of-memory.test.js
@@ -0,0 +1,82 @@
+// A graphics card short of memory may refuse a texture or a buffer without throwing: the call only leaves
+// OUT_OF_MEMORY for getError(), and the atlas then drew every picture as a black box while the map stayed on the card.
+// The big uploads now read it (glMem(), src/game/96-map/56-webgl.js): the atlas tries 2048 px before giving up, and
+// any other refusal gives the card up for 2D in the same frame. getError() is never read on an ordinary frame (each
+// read waits for the card).
+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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+
+/* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's, and that refuses memory as asked in
+   window.__FAIL: atlas (the texture sizes refused), land (the first static buffer after setup), tubes (the tubes'
+   points). A refusal sets OUT_OF_MEMORY, read once by getError(); the reads are counted. */
+const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__GE=0;window.__ERR=0;
+  const F=window.__FAIL;let setup=true;const c=document.getElementById('mapgl');
+  c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){
+    if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+    if(k==='getExtension')return ()=>({UNMASKED_RENDERER_WEBGL:'REN'});
+    if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096;
+    if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
+    if(k==='getError')return ()=>{__GE++;const e=__ERR;__ERR=0;return e;};
+    if(k==='texImage2D')return (...a)=>{if(a[2]==='RGBA'&&(F.atlas||[]).includes(a[3]))__ERR='OUT_OF_MEMORY';if(a[2]==='RGBA32F'&&F.tubes)__ERR='OUT_OF_MEMORY';};
+    if(k==='bufferData')return (...a)=>{if(a[2]==='STATIC_DRAW'&&F.land&&!setup){F.land=false;__ERR='OUT_OF_MEMORY';}};
+    if(k==='useProgram')return ()=>{setup=false;};
+    return ()=>({});}});})()`;
+
+function open(fail) {
+  const h = load({ seed: 777 });
+  h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
+    window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{};
+    window.__FAIL=${JSON.stringify(fail)};`);
+  h.ev(GL);
+  return h;
+}
+
+test('a card without memory for a 4096 px atlas gets a 2048 px one, and keeps the map', () => {
+  const { ev, errors } = open({ atlas: [4096] });
+  assert.equal(ev('glInit()'), true);
+  assert.equal(ev('GLS.size'), 2048);
+  assert.equal(ev('GLX.dead'), false);
+  assert.deepEqual(errors, []);
+});
+
+test('a card without memory for either atlas leaves the map in 2D', () => {
+  const { ev, errors } = open({ atlas: [4096, 2048] });
+  assert.equal(ev('glInit()'), false);
+  assert.equal(ev('GLX.dead'), true);
+  ev('__T+=16;draw(__T);');
+  assert.equal(ev('glOn()'), false, 'the map is drawn in 2D');
+  assert.equal(ev('document.getElementById("mapgl").hidden'), true);
+  assert.deepEqual(errors, []);
+});
+
+for (const what of ['land', 'tubes']) {
+  test(`a card that refuses the ${what} without throwing gives the map to 2D in the same frame`, () => {
+    const { ev, errors } = open({ [what]: true });
+    assert.equal(ev('glInit()'), true);
+    ev('UI.tickErr=false;__T+=16;draw(__T);');
+    assert.equal(ev('GLX.dead'), true, 'the card is given up');
+    assert.equal(ev('glOn()'), false);
+    assert.equal(ev('document.getElementById("mapgl").hidden'), true);
+    assert.equal(ev('ctx===CTX0&&!GLS.frame'), true);
+    assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player: the frame is drawn again in 2D');
+    // The next frames are plain 2D ones.
+    ev('__T+=16;draw(__T);__T+=16;draw(__T);');
+    assert.deepEqual(errors, []);
+  });
+}
+
+test('an ordinary frame never asks the card for its errors', () => {
+  const { ev, errors } = open({});
+  assert.equal(ev('glInit()'), true);
+  ev('__T+=16;draw(__T);');
+  assert.equal(ev('GLX.dead'), false);
+  assert.ok(ev('__GE') > 0, 'the first frame checked its uploads');
+  ev('__GE=0;for(let i=0;i<30;i++){cam.x+=3;__T+=16;draw(__T);}');
+  assert.equal(ev('__GE'), 0, 'panning sends nothing big, so nothing is read');
+  assert.deepEqual(errors, []);
+});

From cdc7c6d1eb8eafeee6df6948ff5fe00ee44a92c1 Mon Sep 17 00:00:00 2001
From: Antoine <20756073+antt0n@users.noreply.github.com>
Date: Wed, 4 Nov 2026 19:21:23 +0100
Subject: [PATCH 322/491] Settings: one Diagnostic info readout for the screen,
 the map's drawing and its speed
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Settings › Viewport info is now Diagnostic info, and the frame meter of the WebGL work joins it: one readout in a
corner instead of two, for bug reports. It shows:
- what the screen tells the game, as before (sizes, visual viewport, safe areas, standalone, the tab bar);
- what draws the map: WebGL2 and the graphics card's name, or 2D and why (Always 2D, a puzzle, no WebGL2, a
  processor pretending to be a card, a lost context, a card out of memory: glKill() keeps the reason);
- how fast: frames per second, the 95th percentile and slowest frame, draw()'s mean time, the speed and zoom, and on
  the card its segments and packets.
?vp and ?fps open it, ?novp and ?nofps close it, five taps on the date toggle it, and a device that had the frame
meter on keeps it. Its text stays technical and in English: it is pasted into reports. On a 360 px phone it wraps
inside the screen and never takes a tap. The setting's name and description are translated.

tests/diagnostic-info.test.js: the setting, the readout's parts, each reason for 2D, the frame figures, the address
flags and the old setting, the taps, and the phone layout.
---
 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 |   2 +-
 src/game/96-map/10-canvas.js                |  10 --
 src/game/96-map/30-settings.js              |   2 +-
 src/game/96-map/56-webgl.js                 |   2 +-
 src/game/96-map/97-diagnostics.js           |  36 +++++++
 src/game/96-map/97-fps-meter.js             |  11 --
 src/game/99-loop.js                         |   4 +-
 src/i18n/en.js                              |   4 +-
 tests/diagnostic-info.test.js               | 106 ++++++++++++++++++++
 15 files changed, 160 insertions(+), 38 deletions(-)
 create mode 100644 src/game/96-map/97-diagnostics.js
 delete mode 100644 src/game/96-map/97-fps-meter.js
 create mode 100644 tests/diagnostic-info.test.js

diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc7bad2..39252dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ All notable changes to this project are documented here. The project follows
 - Zooming is smoother on big maps: while you zoom, cities and ships keep their picture and are only redrawn sharp once the zoom stops, instead of being repainted at every small step.
 - The graphics card draws the coastlines with fewer points when you zoom out, where the extra detail was smaller than a pixel, so the map costs it a lot less work, which helps phones most.
 - The map leaves far less memory behind it on every frame for the browser to clean up while you play.
+- Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report.
 
 ## [2.9.1] — 2026-11-04
 
diff --git a/site/i18n/de.js b/site/i18n/de.js
index 809873c..66b00a6 100644
--- a/site/i18n/de.js
+++ b/site/i18n/de.js
@@ -1610,7 +1610,6 @@
 "common.vendor_tac":"Hersteller-TAC",
 "common.venus":"Venus",
 "common.via_rs":"über RS",
-"common.viewport_info":"Ansichtsinfo",
 "common.vigilante":"Selbstjustiz",
 "common.walk_away":"Aussteigen",
 "common.wave_lease":"Wave-Miete",
@@ -3916,8 +3915,9 @@
 "settings.auto_draws_the_map_with_your":"Auto zeichnet die Karte mit deiner Grafikkarte, wenn der Browser es erlaubt, damit auch große Netze flüssig bleiben. Immer 2D läuft überall, ist auf großen Karten aber langsamer.",
 "settings.auto_follows_your_device_s_reduce":"Auto folgt der Einstellung „Bewegung reduzieren“ deines Geräts. Aus friert die Karte ein: keine wandernden Pakete, kein Pulsieren, kein schwebender Text.",
 "settings.customers_and_alerts":"Kunden und Warnungen",
+"settings.diagnostic_info":"Diagnoseinfos",
 "settings.display_and_sound":"Anzeige und Ton",
-"settings.for_reporting_layout_bugs_shows_what":"Zum Melden von Layout-Fehlern: zeigt, was dein Bildschirm dem Spiel mitteilt.",
+"settings.for_bug_reports_shows_your_screen":"Für Fehlerberichte: zeigt in einer Ecke die Größe deines Bildschirms, wie die Karte gezeichnet wird (Grafikkarte oder 2D, und warum) und wie schnell.",
 "settings.let_an_ai_agent_drive_this_game":"Eine KI soll dieses Spiel spielen",
 "settings.map_drawing":"Kartendarstellung",
 "settings.n_min":"{n} Min.",
diff --git a/site/i18n/es.js b/site/i18n/es.js
index 9744b6b..c82b48f 100644
--- a/site/i18n/es.js
+++ b/site/i18n/es.js
@@ -1608,7 +1608,6 @@
 "common.vendor_tac":"TAC del fabricante",
 "common.venus":"Venus",
 "common.via_rs":"vía RS",
-"common.viewport_info":"Información del viewport",
 "common.vigilante":"Justiciero",
 "common.walk_away":"Marcharse",
 "common.wave_lease":"Alquiler de onda",
@@ -3914,8 +3913,9 @@
 "settings.auto_draws_the_map_with_your":"Auto dibuja el mapa con tu tarjeta gráfica cuando el navegador lo permite, y así las redes grandes siguen fluidas. Siempre 2D funciona en todas partes, pero va más lento en mapas grandes.",
 "settings.auto_follows_your_device_s_reduce":"Auto sigue el ajuste de reducir movimiento de tu dispositivo. Desactivado congela el mapa: sin paquetes en movimiento, pulsos ni texto flotante.",
 "settings.customers_and_alerts":"Clientes y alertas",
+"settings.diagnostic_info":"Información de diagnóstico",
 "settings.display_and_sound":"Pantalla y sonido",
-"settings.for_reporting_layout_bugs_shows_what":"Para informar de fallos de diseño: muestra lo que tu pantalla le dice al juego.",
+"settings.for_bug_reports_shows_your_screen":"Para informar de fallos: muestra en una esquina el tamaño de tu pantalla, cómo se dibuja el mapa (tarjeta gráfica o 2D, y por qué) y a qué velocidad.",
 "settings.let_an_ai_agent_drive_this_game":"Deja que un agente de IA juegue",
 "settings.map_drawing":"Dibujo del mapa",
 "settings.n_min":"{n} min",
diff --git a/site/i18n/fr.js b/site/i18n/fr.js
index 85ebe05..0999427 100644
--- a/site/i18n/fr.js
+++ b/site/i18n/fr.js
@@ -1608,7 +1608,6 @@
 "common.vendor_tac":"TAC du constructeur",
 "common.venus":"Vénus",
 "common.via_rs":"via RS",
-"common.viewport_info":"Infos viewport",
 "common.vigilante":"Justicier",
 "common.walk_away":"Laisser tomber",
 "common.wave_lease":"Location de longueur d’onde",
@@ -3914,8 +3913,9 @@
 "settings.auto_draws_the_map_with_your":"Auto dessine la carte avec ta carte graphique quand le navigateur le permet, ce qui garde les grands réseaux fluides. Toujours en 2D marche partout mais rame sur les grandes cartes.",
 "settings.auto_follows_your_device_s_reduce":"Auto suit le réglage « réduire les animations » de ton appareil. Inactif fige la carte : plus de paquets en mouvement, de pulsations ni de texte flottant.",
 "settings.customers_and_alerts":"Clients et alertes",
+"settings.diagnostic_info":"Infos de diagnostic",
 "settings.display_and_sound":"Affichage et son",
-"settings.for_reporting_layout_bugs_shows_what":"Pour signaler des bugs de mise en page : montre ce que ton écran dit au jeu.",
+"settings.for_bug_reports_shows_your_screen":"Pour signaler un bug : affiche dans un coin la taille de ton écran, comment la carte est dessinée (carte graphique ou 2D, et pourquoi) et à quelle vitesse.",
 "settings.let_an_ai_agent_drive_this_game":"Laisser un agent IA jouer",
 "settings.map_drawing":"Dessin de la carte",
 "settings.n_min":"{n} min",
diff --git a/site/i18n/it.js b/site/i18n/it.js
index 31ade7b..3855c17 100644
--- a/site/i18n/it.js
+++ b/site/i18n/it.js
@@ -1608,7 +1608,6 @@
 "common.vendor_tac":"TAC del vendor",
 "common.venus":"Venere",
 "common.via_rs":"via RS",
-"common.viewport_info":"Info viewport",
 "common.vigilante":"Giustiziere",
 "common.walk_away":"Lascia perdere",
 "common.wave_lease":"Affitto della wave",
@@ -3914,8 +3913,9 @@
 "settings.auto_draws_the_map_with_your":"Auto disegna la mappa con la tua scheda grafica quando il browser lo consente, così anche le reti grandi restano fluide. Sempre 2D funziona ovunque ma è più lento sulle mappe grandi.",
 "settings.auto_follows_your_device_s_reduce":"Auto segue l’impostazione “riduci movimento” del tuo dispositivo. Off congela la mappa: niente pacchetti in movimento, pulsazioni o testo fluttuante.",
 "settings.customers_and_alerts":"Clienti e avvisi",
+"settings.diagnostic_info":"Info di diagnostica",
 "settings.display_and_sound":"Schermo e audio",
-"settings.for_reporting_layout_bugs_shows_what":"Per segnalare bug di layout: mostra cosa lo schermo dice al gioco.",
+"settings.for_bug_reports_shows_your_screen":"Per segnalare bug: mostra in un angolo le dimensioni dello schermo, come viene disegnata la mappa (scheda grafica o 2D, e perché) e a che velocità.",
 "settings.let_an_ai_agent_drive_this_game":"Lascia giocare un agente IA",
 "settings.map_drawing":"Disegno della mappa",
 "settings.n_min":"{n} min",
diff --git a/site/i18n/pt.js b/site/i18n/pt.js
index b46d71c..9939e1c 100644
--- a/site/i18n/pt.js
+++ b/site/i18n/pt.js
@@ -1608,7 +1608,6 @@
 "common.vendor_tac":"TAC do fabricante",
 "common.venus":"Vênus",
 "common.via_rs":"via RS",
-"common.viewport_info":"Info do viewport",
 "common.vigilante":"Justiceiro",
 "common.walk_away":"Desistir",
 "common.wave_lease":"Aluguel da wave",
@@ -3914,8 +3913,9 @@
 "settings.auto_draws_the_map_with_your":"Auto desenha o mapa com sua placa de vídeo quando o navegador permite, o que mantém redes grandes fluidas. Sempre 2D funciona em qualquer lugar, mas é mais lento em mapas grandes.",
 "settings.auto_follows_your_device_s_reduce":"Auto segue a configuração de reduzir movimento do seu aparelho. Desligado congela o mapa: sem pacotes andando, pulsos ou texto flutuante.",
 "settings.customers_and_alerts":"Clientes e alertas",
+"settings.diagnostic_info":"Informações de diagnóstico",
 "settings.display_and_sound":"Tela e som",
-"settings.for_reporting_layout_bugs_shows_what":"Para reportar bugs de layout: mostra o que sua tela informa ao jogo.",
+"settings.for_bug_reports_shows_your_screen":"Para reportar bugs: mostra em um canto o tamanho da sua tela, como o mapa é desenhado (placa de vídeo ou 2D, e por quê) e a que velocidade.",
 "settings.let_an_ai_agent_drive_this_game":"Deixa um agente de IA jogar",
 "settings.map_drawing":"Desenho do mapa",
 "settings.n_min":"{n} min",
diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js
index fb83f74..a1671dc 100644
--- a/src/game/90-actions/89-game-and-settings.js
+++ b/src/game/90-actions/89-game-and-settings.js
@@ -35,7 +35,7 @@ Object.assign(ACT,{
  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();},
- vpSet:({v})=>{vpOn(v==='on');refreshSettings();},
+ vpSet:({v})=>{diagOn(v==='on');refreshSettings();},
  resetAsk:()=>openModal(`

${tr('game_and_settings.start_a_new_network')}

${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(S?S.name:tr('common.your_network'))})}

${btn(tr('game_and_settings.delete_and_start_over'),'newgame',{},'red big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`), whatsNewShow:()=>whatsNew(true,true), updateNow:()=>{save(true);location.reload();}, diff --git a/src/game/96-map/10-canvas.js b/src/game/96-map/10-canvas.js index e3021cc..ff76dfb 100644 --- a/src/game/96-map/10-canvas.js +++ b/src/game/96-map/10-canvas.js @@ -14,15 +14,5 @@ function fixStandaloneHeight(){const R0=document.documentElement; R0.classList.toggle('iosfix',on);if(on)R0.style.setProperty('--app-h',sh+'px');else R0.style.removeProperty('--app-h');return on?sh:0;} function resize(){const ah=fixStandaloneHeight();DPR=Math.min(2,window.devicePixelRatio||1);CW=innerWidth;CH=ah||innerHeight;cv.width=CW*DPR;cv.height=CH*DPR;} addEventListener('resize',()=>{resize();WL.key=null;renderLeft();fitHud();});resize(); -// Viewport readout for debugging phone layouts: open the game once with ?vp in the address (or the start URL). -function vpDebug(){let el=document.getElementById('vpdbg');if(!el){el=document.createElement('pre');el.id='vpdbg';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none';document.body.appendChild(el); - const pr=document.createElement('div');pr.id='vpprobe';pr.style.cssText='position:fixed;visibility:hidden;padding:env(safe-area-inset-top,0px) 0 env(safe-area-inset-bottom,0px)';document.body.appendChild(pr);} - const pr=document.getElementById('vpprobe'),cs=getComputedStyle(pr),vv=window.visualViewport,de=document.documentElement,tb=document.getElementById('tabbar').getBoundingClientRect(); - el.textContent=`inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height}\nvv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\nstandalone ${navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches)} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}`;} -let VP_T=null;const vpOn=on=>{clearInterval(VP_T);VP_T=null;const el=document.getElementById('vpdbg');if(el)el.remove();if(on){VP_T=setInterval(vpDebug,500);vpDebug();}try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');}catch(e){}}; -if(/[?&]vp\b/.test(location.search))vpOn(true);else if(/[?&]novp\b/.test(location.search))vpOn(false); -try{if(localStorage.getItem('sot-vp')==='1')vpOn(true);}catch(e){} -// Inside an installed app there is no address bar: five quick taps on the date toggle the readout. -{let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];vpOn(!VP_T);}});} // iOS settles the standalone viewport a moment after launch and after rotating. for(const t of [300,1000])setTimeout(()=>{resize();WL.key=null;},t);addEventListener('pageshow',()=>{resize();WL.key=null;}); diff --git a/src/game/96-map/30-settings.js b/src/game/96-map/30-settings.js index 348036a..f3025be 100644 --- a/src/game/96-map/30-settings.js +++ b/src/game/96-map/30-settings.js @@ -33,7 +33,7 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${langPick('langSel')}
- ${seg(tr('common.viewport_info'),'vpSet',VP_T?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_reporting_layout_bugs_shows_what'))} + ${seg(tr('settings.diagnostic_info'),'vpSet',DIAG.on?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_bug_reports_shows_your_screen'))} ${installRow()}
${btn(tr('common.done_8dd3'),'settingsClose',{},'pink')}
`;} const refreshSettings=()=>{if(UI.setOpen)openModal(settingsHtml());}; function animOn(){const m=UI.anim||'auto';if(m==='on')return true;if(m==='off')return false;try{return !matchMedia('(prefers-reduced-motion: reduce)').matches;}catch(e){return true;}} diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js index aa4ee57..3423544 100644 --- a/src/game/96-map/56-webgl.js +++ b/src/game/96-map/56-webgl.js @@ -19,7 +19,7 @@ function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeIte function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;} // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame. function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;} -function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);} +function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);} /* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never diff --git a/src/game/96-map/97-diagnostics.js b/src/game/96-map/97-diagnostics.js new file mode 100644 index 0000000..b5a427e --- /dev/null +++ b/src/game/96-map/97-diagnostics.js @@ -0,0 +1,36 @@ +/* Settings › Diagnostic info: one readout in a corner, for bug reports. What the screen tells the game (for phone + layouts), how the map is drawn (the graphics card or 2D, and why), and how fast: frames per second, the slowest + frames, the time draw() takes. It is also opened with ?vp or ?fps in the address (?novp, ?nofps close it), and, + inside an installed app where there is no address bar, with five quick taps on the date. Its words are technical on + purpose and stay in English: they are pasted into bug reports. */ +const DIAG={on:false,el:null,t:null,fr:[],dr:[],last:0,dms:-1}; +// One frame of the loop (99-loop.js): its interval, and the time draw() took if the map was drawn. +function diagFrame(now){const D=DIAG;if(D.last)D.fr.push(now-D.last);D.last=now;if(D.dms>=0){D.dr.push(D.dms);D.dms=-1;} + if(D.fr.length>600)D.fr.splice(0,300);if(D.dr.length>600)D.dr.splice(0,300);} +// What draws the map, and why it is the 2D canvas when it is. +function diagMap(){if(!S)return 'map: none (title screen)';if(pzOn())return 'map: 2D (puzzle)';if(!GLX.want)return 'map: 2D (Always 2D)'; + if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';} +// Frames since the last readout: per second, the 95th percentile and the slowest, and draw()'s mean. +function diagPerf(){const f=DIAG.fr.splice(0),d=DIAG.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0), + q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-',gl=GLX.shown&&!GLX.dead; + return `${sum?(f.length*1000/sum).toFixed(0):'-'} fps · p95 ${q(.95)} ms · max ${q(1)} ms\ndraw ${d.length?(d.reduce((a,x)=>a+x,0)/d.length).toFixed(1):'-'} ms · x${UI.speed||0} · zoom ${cam.z.toFixed(2)}`+ + (gl?` · ${GLX.nSeg} segments · ${GLX.nPk} packets`:'');} +function diagShow(){const D=DIAG;let el=D.el; + if(!el){el=D.el=document.createElement('pre');el.id='diag';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;max-width:calc(100vw - 32px);background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none;white-space:pre-wrap;overflow-wrap:anywhere'; + // A hidden probe reads the safe areas (the notch, the home bar) as CSS gives them. + const pr=document.createElement('div');pr.id='diagprobe';pr.style.cssText='position:fixed;visibility:hidden;padding:env(safe-area-inset-top,0px) 0 env(safe-area-inset-bottom,0px)';el.appendChild(pr); + D.txt=document.createTextNode('');el.appendChild(D.txt);document.body.appendChild(el);} + const cs=getComputedStyle(document.getElementById('diagprobe')),vv=window.visualViewport,de=document.documentElement,tb=document.getElementById('tabbar').getBoundingClientRect(), + sa=navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches); + D.txt.data=`Series of Tubes ${APP_VERSION} · ${LANG}\n`+ + `inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height} · dpr ${window.devicePixelRatio||1}\n`+ + `vv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\n`+ + `standalone ${sa} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}\n`+ + diagMap()+'\n'+diagPerf();} +// Shows or hides the readout, and remembers it on this device. +function diagOn(on){const D=DIAG;clearInterval(D.t);D.t=null;if(D.el){D.el.remove();D.el=null;}D.on=!!on;D.fr.length=D.dr.length=0;D.last=0;D.dms=-1; + if(on){D.t=setInterval(diagShow,500);diagShow();} + try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');localStorage.removeItem('sot-fps');}catch(e){}} +{const q=location.search;let on=false;try{on=localStorage.getItem('sot-vp')==='1'||localStorage.getItem('sot-fps')==='1';}catch(e){} + if(/[?&](vp|fps)\b/.test(q))on=true;else if(/[?&]no(vp|fps)\b/.test(q))on=false;diagOn(on);} +{let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];diagOn(!DIAG.on);}});} diff --git a/src/game/96-map/97-fps-meter.js b/src/game/96-map/97-fps-meter.js deleted file mode 100644 index 4ad6efd..0000000 --- a/src/game/96-map/97-fps-meter.js +++ /dev/null @@ -1,11 +0,0 @@ -/* A frame meter for measuring the map on a real device: open the game once with ?fps (?nofps hides it again). - Frames per second, the slowest frames, the time draw() takes, and which renderer and graphics card draw the map. */ -const FPSM={on:false,el:null,fr:[],dr:[],last:0,shown:0,dms:-1}; -try{const q=location.search;if(/[?&]fps\b/.test(q))localStorage.setItem('sot-fps','1');else if(/[?&]nofps\b/.test(q))localStorage.removeItem('sot-fps'); - FPSM.on=localStorage.getItem('sot-fps')==='1';}catch(e){} -function fpsNote(now){const M=FPSM;if(M.last)M.fr.push(now-M.last);M.last=now;if(M.dms>=0){M.dr.push(M.dms);M.dms=-1;} - if(now-M.shown<500)return;M.shown=now; - if(!M.el){M.el=document.createElement('pre');M.el.id='fpsm';M.el.style.cssText='position:fixed;right:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none;white-space:pre';document.body.appendChild(M.el);} - const f=M.fr.splice(0),d=M.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0),q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-'; - const gl=GLX.shown&&!GLX.dead; - M.el.textContent=`${sum?(f.length*1000/sum).toFixed(0):0} fps · p95 ${q(.95)} ms · max ${q(1)} ms\ndraw ${d.length?(d.reduce((a,x)=>a+x,0)/d.length).toFixed(1):'-'} ms · ${gl?'WebGL':'2D'} · x${UI.speed||0}`+(gl?`\n${GLX.nSeg} segments · ${GLX.nPk} packets\n${GLX.gpu.slice(0,60)}`:'');} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 83390ba..41f70a8 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -12,8 +12,8 @@ function frame(now){ if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt); 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)){const d0=FPSM.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(FPSM.on)FPSM.dms=performance.now()-d0;} - if(FPSM.on)fpsNote(now); + if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;} + if(DIAG.on)diagFrame(now); } // dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames // do not (src/agent/, a hidden tab), under the frame's own conditions otherwise. diff --git a/src/i18n/en.js b/src/i18n/en.js index b349a32..c4ee816 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1609,7 +1609,6 @@ "common.vendor_tac":"Vendor TAC", "common.venus":"Venus", "common.via_rs":"via RS", -"common.viewport_info":"Viewport info", "common.vigilante":"Vigilante", "common.walk_away":"Walk away", "common.wave_lease":"Wave lease", @@ -3915,8 +3914,9 @@ "settings.auto_draws_the_map_with_your":"Auto draws the map with your graphics card when the browser allows it, which keeps big networks smooth. Always 2D works everywhere but is slower on big maps.", "settings.auto_follows_your_device_s_reduce":"Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.", "settings.customers_and_alerts":"Customers and alerts", +"settings.diagnostic_info":"Diagnostic info", "settings.display_and_sound":"Display and sound", -"settings.for_reporting_layout_bugs_shows_what":"For reporting layout bugs: shows what your screen tells the game.", +"settings.for_bug_reports_shows_your_screen":"For bug reports: shows in a corner your screen's size, how the map is drawn (graphics card or 2D, and why) and how fast.", "settings.let_an_ai_agent_drive_this_game":"Let an AI agent drive this game", "settings.map_drawing":"Map drawing", "settings.n_min":"{n} min", diff --git a/tests/diagnostic-info.test.js b/tests/diagnostic-info.test.js new file mode 100644 index 0000000..324fcf6 --- /dev/null +++ b/tests/diagnostic-info.test.js @@ -0,0 +1,106 @@ +// Settings › Diagnostic info (src/game/96-map/97-diagnostics.js): one readout for bug reports, which replaced the +// separate viewport readout and frame meter. It shows the screen, what draws the map (and why it is 2D), and how fast; +// the setting, ?vp/?fps and five taps on the date open it, and it is remembered on the device. +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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + +function open(opts = {}) { + const h = load({ seed: 777, ...opts }); + h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();console.warn=()=>{};`); + // The readout refreshes on an interval: closing the window stops it, so the test process can end. + h.done = () => h.dom.window.close(); + return h; +} +const text = (ev) => ev('(()=>{const e=document.getElementById("diag");return e?e.textContent:null;})()'); + +test('the setting shows one readout with the screen, the map and its speed, and remembers it', () => { + const h = open(); + const { ev, errors } = h; + try { + assert.equal(text(ev), null, 'off by default'); + ev('ACT.settings()'); + assert.match(ev('$("modal").innerHTML'), new RegExp(ev('tr("settings.diagnostic_info")'))); + ev('ACT.vpSet({v:"on"})'); + const t = text(ev); + for (const part of ['Series of Tubes', 'inner ', 'screen ', 'safe top', 'tabbar', 'map: ', 'fps', 'draw ']) assert.ok(t.includes(part), `shows "${part}"`); + assert.equal(ev('document.querySelectorAll("#diag").length'), 1, 'one readout'); + assert.equal(ev('localStorage.getItem("sot-vp")'), '1'); + ev('ACT.vpSet({v:"off"})'); + assert.equal(text(ev), null); + assert.equal(ev('localStorage.getItem("sot-vp")'), null); + assert.deepEqual(errors, []); + } finally { h.done(); } +}); + +test('it says what draws the map, and why it is the 2D canvas', () => { + const h = open(); + const { ev, errors } = h; + try { + ev('diagOn(true)'); + const map = () => ev('diagMap()'); + ev('mapGl(false,false)'); + assert.equal(map(), 'map: 2D (Always 2D)'); + ev('mapGl(true,false);glKill(new Error("the graphics card is out of memory (the pictures)"))'); + assert.equal(map(), 'map: 2D (the graphics card is out of memory (the pictures))'); + ev('GLX.dead=false;GLX.gl={};GLX.shown=true;GLX.gpu="ANGLE (NVIDIA GeForce GTX 980)"'); + assert.equal(map(), 'map: WebGL2 · ANGLE (NVIDIA GeForce GTX 980)'); + ev('const s=S;S=null;window.__S=s'); + assert.equal(map(), 'map: none (title screen)'); + ev('S=__S;GLX.gl=null;GLX.shown=false'); + assert.deepEqual(errors, []); + } finally { h.done(); } +}); + +test('it measures frames per second, the slowest frames and draw()', () => { + const h = open(); + const { ev, errors } = h; + try { + ev('diagOn(true)'); + // 60 frames, so 59 intervals: 58 of 16 ms and a last one of 50 ms (978 ms in all), each map drawn in 2 ms. + ev('let t=1000;for(let i=0;i<60;i++){t+=i===59?50:16;DIAG.dms=2;diagFrame(t);}diagShow();'); + const t = text(ev); + assert.match(t, /\b60 fps · p95 16 ms · max 50 ms/); + assert.match(t, /draw 2\.0 ms · x0 · zoom /); + assert.deepEqual(errors, []); + } finally { h.done(); } +}); + +test('?fps and ?vp open it, ?nofps closes it, and the old frame meter setting carries over', () => { + for (const [url, storage, want] of [['?fps', {}, true], ['?vp', {}, true], ['?nofps', { 'sot-vp': '1' }, false], ['', { 'sot-fps': '1' }, true], ['', {}, false]]) { + const h = load({ seed: 777, url: 'https://tests.invalid/' + url, storage }); + try { + assert.equal(h.ev('!!document.getElementById("diag")'), want, `${url || 'no flag'} ${JSON.stringify(storage)}`); + assert.equal(h.ev('localStorage.getItem("sot-fps")'), null, 'the old key is gone'); + } finally { h.dom.window.close(); } + } +}); + +test('five quick taps on the date toggle it (an installed app has no address bar)', () => { + const h = open(); + const { ev, errors } = h; + try { + const tap = () => ev('document.getElementById("hDate").click()'); + for (let i = 0; i < 5; i++) tap(); + assert.equal(ev('DIAG.on'), true); + for (let i = 0; i < 5; i++) tap(); + assert.equal(ev('DIAG.on'), false); + assert.deepEqual(errors, []); + } finally { h.done(); } +}); + +test('on a 360 px phone the readout wraps inside the screen instead of running off it', () => { + const h = open(); + const { ev } = h; + try { + ev('diagOn(true)'); + const st = ev('document.getElementById("diag").style.cssText'); + assert.match(st, /max-width: calc\(100vw - 32px\)/); + assert.match(st, /white-space: pre-wrap/); + assert.match(st, /pointer-events: none/, 'it never takes a tap meant for the map'); + } finally { h.done(); } +}); From b03bec267ccc13a019aa8902759134733869f4d4 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:59:05 +0100 Subject: [PATCH 323/491] 2D map: keep the land picture on the graphics card in Firefox on a computer The 2D map paints its land into an offscreen picture. In Firefox that picture was a software canvas (willReadFrequently), because Firefox on Android garbled big paths on its graphics card (#43). Firefox on a computer had it too, and a software canvas is sent to the card again on every frame, at a cost that grows with the picture: the whole world at mid zoom, four screens of it zoomed in. Only Firefox on Android keeps it now (softCanvas()). Measured in Firefox 159 on Windows (RTX 4090, full screen 2560x1440), 2D map, frames per second at zoom 0.6 / 1.1 / 1.6 / 3.2: - big-network fixture, main: 56 / 37 / 34 / 26; with this change: 64 / 49 / 51 / 78; - the 183-POP save, main: 32 / 25 / 25 / 22; with this change: 36 / 26 / 33 / 55. (Measured with the change injected into main's page; the land picture is the same code on this branch.) tests/world-layer-firefox.test.js: which browsers get the software canvas, and that the land is an ordinary one elsewhere. --- CHANGELOG.md | 1 + src/game/96-map/70-world-layer.js | 5 ++++- tests/world-layer-firefox.test.js | 36 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 tests/world-layer-firefox.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 39252dc..32a06d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to this project are documented here. The project follows - Zooming is smoother on big maps: while you zoom, cities and ships keep their picture and are only redrawn sharp once the zoom stops, instead of being repainted at every small step. - The graphics card draws the coastlines with fewer points when you zoom out, where the extra detail was smaller than a pixel, so the map costs it a lot less work, which helps phones most. - The map leaves far less memory behind it on every frame for the browser to clean up while you play. +- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in: its land picture now stays on the graphics card instead of being sent to it again on every frame. Firefox on Android keeps the old way, which avoids its drawing glitches. - Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report. ## [2.9.1] — 2026-11-04 diff --git a/src/game/96-map/70-world-layer.js b/src/game/96-map/70-world-layer.js index 426de70..20a94a8 100644 --- a/src/game/96-map/70-world-layer.js +++ b/src/game/96-map/70-world-layer.js @@ -2,7 +2,10 @@ GPU canvas implementations (Firefox on Android) garble big paths (#43). It is painted into an offscreen image instead: the whole world when that fits in MAXPX, otherwise the visible area plus a margin, repainted when you pan out of it. While a zoom gesture is still moving, the last image is scaled rather than repainted. */ -const SOFT_CANVAS=/Firefox\//.test(navigator.userAgent); +/* Only Firefox on Android gets that image as a software canvas (willReadFrequently). Firefox on a computer drew it + fine on the graphics card, and a software canvas there is sent to the card again on every frame, a cost that grows + with the image: zoomed in, the 2D map ran at half its speed. */ +const softCanvas=ua=>/Android.*Firefox\//.test(ua),SOFT_CANVAS=softCanvas(navigator.userAgent); function wlCovers(z){if(WL.full)return true;const hw=CW/2/z,hh=CH/2/z,w=WL.cv.width/WL.sc,h=WL.cv.height/WL.sc; 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){ diff --git a/tests/world-layer-firefox.test.js b/tests/world-layer-firefox.test.js new file mode 100644 index 0000000..b77ad42 --- /dev/null +++ b/tests/world-layer-firefox.test.js @@ -0,0 +1,36 @@ +// The 2D map's land picture (src/game/96-map/70-world-layer.js) is a software canvas (willReadFrequently) only in +// Firefox on Android, which garbled big paths on its graphics card (#43). Firefox on a computer had it too, and sent +// the whole picture to the card again on every frame: measured in Firefox on Windows, full screen 2560x1440, zoomed in +// the 2D map ran at a third of its speed (zoom 3.2 on the big network: 26 fps, 78 without it). +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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + +test('only Firefox on Android gets the land as a software canvas', () => { + const { ev } = load({ seed: 777 }); + const soft = (ua) => ev(`softCanvas(${JSON.stringify(ua)})`); + // Firefox on Android, phone and tablet. + assert.equal(soft('Mozilla/5.0 (Android 14; Mobile; rv:132.0) Gecko/132.0 Firefox/132.0'), true); + assert.equal(soft('Mozilla/5.0 (Android 13; Tablet; rv:128.0) Gecko/128.0 Firefox/128.0'), true); + // Firefox on a computer, and the other browsers. + assert.equal(soft('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0'), false); + assert.equal(soft('Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0'), false); + assert.equal(soft('Mozilla/5.0 (Macintosh; Intel Mac OS X 14.5; rv:131.0) Gecko/20100101 Firefox/131.0'), false); + assert.equal(soft('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36'), false); + assert.equal(soft('Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/130.0 Mobile/15E148 Safari/605.1.15'), false); +}); + +test('elsewhere the land picture is an ordinary canvas, which the browser may keep on the graphics card', () => { + const { ev, errors } = load({ seed: 777 }); + ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();mapGl(false,false); + window.__opts=[];const gc=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(t,o){__opts.push(o||null);return gc.call(this,t,o);}; + WL.cv=null;WL.key=null;cam.z=1.6;worldLayer(cam.z);`); + assert.equal(ev('SOFT_CANVAS'), false); + assert.ok(ev('!!WL.cv'), 'the land was painted'); + assert.equal(ev('__opts.some(o=>o&&o.willReadFrequently)'), false); + assert.deepEqual(errors, []); +}); From fe109cff844fb26888807a64235b66ed5482573e Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:04:48 +0100 Subject: [PATCH 324/491] WebGL map: fill overlapping coastlines as land, as the 2D map does The card filled the land by an odd/even count over all the coastlines at once, so two coasts that overlap cancelled out into sea: Timor, drawn by two coastlines, lost most of its inside and its shadow when zoomed in. The 2D map fills each coast on its own. The fan now turns every coast the same way and the stencil counts windings (+1 and -1 by the triangles' facing, filled where not zero), which is the 2D canvas's nonzero rule: an overlap counts 2 and stays land. Same number of draws. --- src/game/96-map/57-webgl-background.js | 16 +++++++--- tests/webgl-coast.test.js | 44 ++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js index a528c30..544b8ed 100644 --- a/src/game/96-map/57-webgl-background.js +++ b/src/game/96-map/57-webgl-background.js @@ -41,11 +41,16 @@ function coastSimplify(P,tol){const n=P.length;if(n<4||!(tol>0))return P;const k // around a power of 2 does not switch back and forth. function coastLevel(z){const want=Math.floor(Math.log2(Math.max(z,1/64))),cur=GLX.coastLv; if(cur===undefined||want>cur||z{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return; const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return; - for(let i=1;i+1{let w=0;const s=(ax,ay,bx,by)=>(bx-ax)*(y-ay)-(by-ay)*(x-ax); + for(let i=0;i0&&d2>0&&d3>0)w++;else if(d1<0&&d2<0&&d3<0)w--;}return w;};`; + +test('two overlapping coastlines leave their overlap filled (Timor), at every zoom', () => { + const { ev, errors } = open(); + ev(WIND); + const r = JSON.parse(ev(`(()=>{const pt=[1692,600],o={both:[58,154].map(i=>inPoly(...pt,coastPts(i)))}; + for(const lv of [undefined,-1,0,1,2,3,4,5]){const tol=lv===undefined?0:COAST_TOL/Math.pow(2,lv),fan=[]; + COAST.forEach((ring,ri)=>{if(ring.length<3)return;const P=coastSimplify(coastPts(ri),tol);if(P.length>=4)coastFan(P,fan);}); + o['lv'+lv]=__wind(fan,...pt);} + return JSON.stringify(o);})()`)); + assert.deepEqual(r.both, [true, true], 'the point is inside both of Timor’s coastlines'); + for (const lv of [undefined, -1, 0, 1, 2, 3, 4, 5]) assert.equal(r['lv' + lv], 2, `level ${lv}: counted twice, so land (an odd/even count gave 0, sea)`); + assert.deepEqual(errors, []); +}); + +test('every coastline counts +1 inside, whichever way it was drawn', () => { + const { ev, errors } = open(); + ev(WIND); + const r = JSON.parse(ev(`(()=>{const sq=(x,y,s,cw)=>{const p=[[x,y],[x+s,y],[x+s,y+s],[x,y+s]];return cw?p.reverse():p;}; + const fan=[];coastFan(sq(0,0,10,false),fan);coastFan(sq(5,5,10,true),fan); + return JSON.stringify({a:__wind(fan,2,1),both:__wind(fan,8,6),b:__wind(fan,12,13),out:__wind(fan,20,20)});})()`)); + assert.deepEqual(r, { a: 1, both: 2, b: 1, out: 0 }, 'one square turned each way: the overlap is 2, not 0'); + assert.deepEqual(errors, []); +}); + +test('the card fills the land where the winding count is not zero, and leaves the stencil at zero', () => { + const { ev, errors } = open(); + ev(STUB); + const c = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;GLX.gl.calls.length=0;draw(1000); + return JSON.stringify(GLX.gl.calls.filter(c=>/^stencil/.test(c[0])).map(c=>c.join(' ')));})()`)); + assert.ok(c.includes('stencilOpSeparate FRONT KEEP KEEP INCR_WRAP') && c.includes('stencilOpSeparate BACK KEEP KEEP DECR_WRAP'), 'counts windings, +1 one way and -1 the other'); + assert.ok(c.includes('stencilFunc NOTEQUAL 0 255'), 'fills where the count is not zero, on all 8 bits'); + assert.ok(c.includes('stencilOp ZERO ZERO ZERO'), 'and sets it back to zero'); + assert.ok(!c.some(s => /INVERT/.test(s)), 'no odd/even count left'); + assert.deepEqual(errors, []); +}); From 123b3d00eabc66d8b0e1137e83362f3a93b650c2 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:06:11 +0100 Subject: [PATCH 325/491] WebGL map: give the card up for 2D when it refuses a picture without saying so The atlas, the land, the tubes and the cables read getError() after they are sent, but a picture sent into the atlas (texSubImage2D) was marked as sent at once: a card short of memory that only set OUT_OF_MEMORY left it kept and drawn from an atlas that never got it. A frame that sent new pictures now asks once, at its end and before drawing them; a refusal gives the map to 2D in the same frame and forgets the card's pictures. A frame that only reuses the atlas still asks nothing. --- src/game/96-map/59-gl-sprites.js | 13 ++++++---- tests/webgl-out-of-memory.test.js | 40 ++++++++++++++++++++++++++----- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js index c6f3bb8..615c48e 100644 --- a/src/game/96-map/59-gl-sprites.js +++ b/src/game/96-map/59-gl-sprites.js @@ -5,7 +5,7 @@ const SPR_MAX=1400,SPR_STRIDE=13; // The card's pictures (SPRS) and the 2D map's (SPRC), by key; both at the screen's pixel density SPR_DPR. const SPRS=new Map(),SPRC=new Map();let SPR_DPR=0; -const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0}; +const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0}; /* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */ const SPR_VS=GL_HEAD+`layout(location=0) in vec4 aP;layout(location=1) in vec4 aUV;layout(location=2) in vec4 aC;layout(location=3) in float aK; @@ -30,7 +30,7 @@ function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4 // Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it). function spritesReset(){glsDrawNow();SPRS.clear();SPRC.clear();GLS.shx=GLS.shy=GLS.shh=0;} // The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten. -function spritesDrop(){GLS.n=0;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} +function spritesDrop(){GLS.n=GLS.up=0;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} /* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. */ @@ -70,7 +70,7 @@ function glsPut(gl,e,src){const pw=e.pw,ph=e.ph,A=GLS.size;if(pw>A||ph>A)return gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true); // Only the picture's corner of the source: the pad is bigger than most pictures. gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); - Object.assign(e,{up:true,u0:x/A,v0:y/A,u1:(x+pw)/A,v1:(y+ph)/A});return true;} + GLS.up++;Object.assign(e,{up:true,u0:x/A,v0:y/A,u1:(x+pw)/A,v1:(y+ph)/A});return true;} // The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace. function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;} // Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas. @@ -116,5 +116,8 @@ function glsDraw(gl,n){gl.useProgram(GLS.prog.p);gl.bindVertexArray(GLS.vao);gl. gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex); gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST); gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);gl.bindVertexArray(null);} -// The end of a frame on the card: the pictures go up over the tubes. The frame is over even if that draw fails. -function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;glsDrawNow();} +/* The end of a frame on the card: the pictures go up over the tubes. The frame is over even if that draw fails. + A frame that sent new pictures first asks the card if it took them (once, however many): a card short of memory + may refuse one without throwing, and the picture would be kept as sent. It then gives the map to 2D (glMem() throws, + draw() draws the frame again there and glKill() forgets the card's pictures). A frame that only reuses the atlas asks nothing. */ +function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;const up=GLS.up;GLS.up=0;if(up&&GLX.gl)glMem(GLX.gl,'the pictures');glsDrawNow();} diff --git a/tests/webgl-out-of-memory.test.js b/tests/webgl-out-of-memory.test.js index 4d49761..b43f4e0 100644 --- a/tests/webgl-out-of-memory.test.js +++ b/tests/webgl-out-of-memory.test.js @@ -13,12 +13,16 @@ const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json' /* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's, and that refuses memory as asked in window.__FAIL: atlas (the texture sizes refused), land (the first static buffer after setup), tubes (the tubes' - points). A refusal sets OUT_OF_MEMORY, read once by getError(); the reads are counted. */ -const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__GE=0;window.__ERR=0; - const F=window.__FAIL;let setup=true;const c=document.getElementById('mapgl'); + points), sprites (every picture sent into the atlas). A refusal sets OUT_OF_MEMORY, read once by getError(); the + reads are counted. It also counts the pictures sent (__SUB), what is deleted (__DEL) and the context let go (__LOST). */ +const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__GE=0;window.__ERR=0;window.__SUB=0;window.__DEL=[];window.__LOST=0;window.__LOSTEV=0; + const F=window.__FAIL;let setup=true,lost=false;const c=document.getElementById('mapgl');c.addEventListener('webglcontextlost',()=>{__LOSTEV++;}); c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){ if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k; - if(k==='getExtension')return ()=>({UNMASKED_RENDERER_WEBGL:'REN'}); + if(k==='getExtension')return (n)=>n==='WEBGL_lose_context'?{loseContext:()=>{__LOST++;lost=true;c.dispatchEvent(new window.Event('webglcontextlost'));}}:{UNMASKED_RENDERER_WEBGL:'REN'}; + if(k==='isContextLost')return ()=>lost||!!window.__lostNow; + if(k==='deleteTexture'||k==='deleteBuffer')return (x)=>{__DEL.push(x);}; + if(k==='texSubImage2D')return ()=>{__SUB++;if(F.sprites)__ERR='OUT_OF_MEMORY';}; if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096; if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true; if(k==='getError')return ()=>{__GE++;const e=__ERR;__ERR=0;return e;}; @@ -76,7 +80,31 @@ test('an ordinary frame never asks the card for its errors', () => { ev('__T+=16;draw(__T);'); assert.equal(ev('GLX.dead'), false); assert.ok(ev('__GE') > 0, 'the first frame checked its uploads'); - ev('__GE=0;for(let i=0;i<30;i++){cam.x+=3;__T+=16;draw(__T);}'); - assert.equal(ev('__GE'), 0, 'panning sends nothing big, so nothing is read'); + // Panning brings new cities into view, whose pictures are sent: only those frames ask, once each. + const pan = JSON.parse(ev(`(()=>{let quiet=0,asked=0,sent=0,most=0;for(let i=0;i<30;i++){const s=__SUB,g=__GE;cam.x+=3;__T+=16;draw(__T); + if(__SUB===s){quiet++;if(__GE>g)asked++;}else{sent++;most=Math.max(most,__GE-g);}}return JSON.stringify({quiet,asked,sent,most});})()`)); + assert.ok(pan.quiet > 0, 'some frames send no picture'); + assert.equal(pan.asked, 0, 'a frame that sends nothing big reads nothing'); + assert.ok(pan.most <= 4, 'a frame that sends pictures asks once (getError() read up to four flags), not once per picture'); + ev('__GE=0;for(let i=0;i<10;i++){__T+=16;draw(__T);}'); + assert.equal(ev('__GE'), 0, 'a still map reads nothing'); + assert.deepEqual(errors, []); +}); + +/* A picture the card refused without throwing (texSubImage2D only leaves OUT_OF_MEMORY) was kept as sent, and drawn + from an atlas that never got it. The frame now checks its new pictures before drawing them, and gives the map to 2D + in that same frame: no picture is kept as sent. */ +test('a picture the card refuses without throwing gives the map to 2D in the same frame', () => { + const { ev, errors } = open({ sprites: true }); + assert.equal(ev('glInit()'), true); + ev('UI.tickErr=false;const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;__T+=16;draw(__T);'); + assert.ok(ev('__SUB') > 0, 'pictures were sent'); + assert.equal(ev('GLX.dead'), true, 'the card is given up'); + assert.equal(ev('SPRS.size'), 0, 'no picture is kept as sent to the card'); + assert.equal(ev('glOn()'), false); + assert.equal(ev('document.getElementById("mapgl").hidden'), true); + assert.ok(ev('SPRC.size') > 0, 'the same frame was drawn again in 2D, with its own pictures'); + assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player'); + ev('__T+=16;draw(__T);'); assert.deepEqual(errors, []); }); From 10ef838e8718825304c35e34251710ca7579b7a5 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:07:25 +0100 Subject: [PATCH 326/491] WebGL map: free what the card holds when it is given up for good Given up while its context still lived (memory refused, a setup failing half-way), the card kept the atlas (64 MB at 4096 px), the tubes' points and the rest while the 2D map began painting its own pictures. glKill() now deletes the biggest and lets the context go (WEBGL_lose_context, where the browser has it), unless the browser already lost it; glInit() keeps the context from the start so a failed setup is let go too, and the loss event of a context let go on purpose does not give the card up a second time. Always 2D still keeps the card for later. --- src/game/96-map/56-webgl.js | 16 +++++++++---- tests/webgl-out-of-memory.test.js | 38 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js index 3423544..981aba4 100644 --- a/src/game/96-map/56-webgl.js +++ b/src/game/96-map/56-webgl.js @@ -8,7 +8,7 @@ Puzzles, and any browser without WebGL2 or whose context fails or is lost, keep the 2D map. So does WebGL drawn by the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */ -const GLX={want:true,dead:false,gl:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; +const GLX={want:true,dead:false,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){} // Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark). const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i; @@ -19,7 +19,15 @@ function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeIte function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;} // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame. function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;} -function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);} +function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true; + const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);} +/* The card given up for good (not Always 2D, which keeps it for later) still held what was sent to it, the atlas alone + 64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go + (WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps + the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */ +function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf); + const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){} + GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;} /* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never @@ -42,13 +50,13 @@ function glVao(gl,sizes,div=1,data=null){const v=gl.createVertexArray(),b=gl.cre function glInit(){if(GLX.gl)return true;if(GLX.dead)return false; try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers'); const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'}); - if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2'); + if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl; try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){} if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu); const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)}; // The tubes' points for the packets: floats read with texelFetch, never filtered. const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST); - c.addEventListener('webglcontextlost',e=>{e.preventDefault();glKill('the graphics context was lost');UI.drawnAt=0;}); + c.addEventListener('webglcontextlost',e=>{e.preventDefault();if(GLX.dead)return;glKill('the graphics context was lost');UI.drawnAt=0;}); glsInit(gl); // The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every // frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself. diff --git a/tests/webgl-out-of-memory.test.js b/tests/webgl-out-of-memory.test.js index b43f4e0..b09577c 100644 --- a/tests/webgl-out-of-memory.test.js +++ b/tests/webgl-out-of-memory.test.js @@ -108,3 +108,41 @@ test('a picture the card refuses without throwing gives the map to 2D in the sam ev('__T+=16;draw(__T);'); assert.deepEqual(errors, []); }); + +/* Given up for good while the context still lives (memory refused), the card kept the atlas (64 MB at 4096 px) and the + rest while the 2D map began painting its own pictures. glKill() now deletes the biggest and lets the context go. */ +test('giving the card up for good frees what it holds and lets the context go, and the frame is drawn in 2D', () => { + const { ev, errors } = open({ tubes: true }); + assert.equal(ev('glInit()'), true); + ev('window.__atlas=GLS.tex;window.__tubes=GLX.tex;window.__buf=GLS.buf;'); + ev('UI.tickErr=false;__T+=16;draw(__T);'); + assert.equal(ev('GLX.dead'), true); + assert.equal(ev('__DEL.includes(__atlas)&&__DEL.includes(__tubes)&&__DEL.includes(__buf)'), true, 'the atlas, the tubes’ points and the pictures’ buffer are deleted'); + assert.equal(ev('__LOST'), 1, 'the context is let go'); + assert.equal(ev('__LOSTEV'), 1, 'its loss event came once'); + assert.equal(ev('GLS.tex===null&&GLS.buf===null&&GLX.tex===null&&GLX.gl===null&&GLX.ctx===null'), true, 'nothing on the card is referenced'); + assert.equal(ev('GLX.why'), 'the graphics card is out of memory (the tubes)', 'the loss it caused does not replace the reason'); + assert.equal(ev('!!UI.tickErr'), false, 'the frame was drawn again in 2D'); + ev('__T+=16;draw(__T);'); + assert.deepEqual(errors, []); +}); + +test('a setup that fails half-way lets its context go too', () => { + const { ev, errors } = open({ atlas: [4096, 2048] }); + assert.equal(ev('glInit()'), false); + assert.equal(ev('__LOST'), 1); + assert.equal(ev('GLX.ctx'), null); + assert.deepEqual(errors, []); +}); + +test('a context the browser lost is not let go a second time', () => { + const { ev, errors } = open({}); + assert.equal(ev('glInit()'), true); + ev('__T+=16;draw(__T);'); + ev('window.__lostNow=true;document.getElementById("mapgl").dispatchEvent(new window.Event("webglcontextlost"));'); + assert.equal(ev('GLX.dead'), true); + assert.equal(ev('GLX.why'), 'the graphics context was lost'); + assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did'); + ev('__T+=16;draw(__T);'); + assert.deepEqual(errors, []); +}); From d57b3ae10f4d379dc64033756a126eab95611c10 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:56:58 +0100 Subject: [PATCH 327/491] WebGL map: say how the land's stencil counts, and what the land costs the card --- src/game/96-map/57-webgl-background.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js index 544b8ed..5055126 100644 --- a/src/game/96-map/57-webgl-background.js +++ b/src/game/96-map/57-webgl-background.js @@ -4,8 +4,8 @@ const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends const SEA_TOP=glPm('#62CBEA'),SEA_BOT=glPm('#43AED6'),CLOUD_COL=glPm('rgba(255,255,255,.55)'); const LAND_SHADOW=glPm('rgba(20,90,130,.35)'),LAND_GRASS=glPm('#9BDA6C'),HILL_COL=glPm('#86CB5B'),HILL_SHINE=glPm('rgba(255,255,255,.18)'); -// The land's fill: a fan of triangles per coastline, counted in the stencil (each pixel flips once per triangle over -// it, so what is inside ends odd), then one cover where the stencil is odd. uOff shifts it in CSS px (the shadow). +// The land's fill: a fan of triangles per coastline, counted in the stencil (how many times the coasts wind round each +// pixel: glLandFill()), then one cover where the count is not zero. uOff shifts it in CSS px (the shadow). const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam; void main(){gl_Position=clip((aV-uCam.xy)*uCam.z+uView*.5+uOff,uView,0.);}`; const FAN_FS=GL_HEAD+`out vec4 o;void main(){o=vec4(0.);}`; @@ -22,7 +22,9 @@ const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(len lv (powers of 2): the fan for the fills, the coastlines as line segments (paintWorld()'s curves, four segments each) for the sand and the dark edge, and the hills. Zoomed out a coastline has far more points than pixels, and its vertices were most of the card's work: at level lv it is simplified so that no point moves more than COAST_TOL px at - the level's zoom (Douglas-Peucker). Without lv, the whole coastline. COAST and onLand() are not touched. */ + the level's zoom (Douglas-Peucker). Without lv, the whole coastline. COAST and onLand() are not touched. + Each level stays on the card once built (GLX.land, freed with the card): from 0.4 MB zoomed out to 3 MB at the + closest zoom, about 15 MB if a game visits every zoom, so zooming back never builds one again mid-gesture. */ const COAST_TOL=0.25,COASTP=[]; // A coastline as paintWorld() draws it (smoothPath(): a quadratic curve from the middle of each side to the next, // through the corner between them), four segments per curve; the first point is repeated at the end. From 57546ea18e417caaf4d7b3fea958bc4a3b51f7fa Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:00:34 +0100 Subject: [PATCH 328/491] 2D map: hold its pictures to 48 MB, letting go of those unused the longest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 2D map keeps a canvas per picture, and the list was capped only by its length (1 400). A long zoom on a big network paints every city again at each step of its scale, so a pinch from 0.6 to 3.2 and back held 181 MB of pictures (the TTL save: 179 MB) where one frame uses 2 to 23 MB. At the end of a frame over 48 MB, the pictures it did not use go, those unused the longest first, down to 36 MB, and each canvas let go is emptied (0×0) so its pixels are freed without waiting for the collector. The frame's own pictures are never let go, so a screen that needs more keeps what it needs. Finding a picture now marks it as used. Measured in jsdom on the same pinch (1280×800 at 2×): 43 MB at most (TTL: 40 MB); 4 781 pictures painted against 4 083 (TTL: 5 549 against 6 030); at most 321 painted in one frame, the same as before (the zoom's own steps). The card's atlas is unchanged: it has its own fixed size. --- src/game/96-map/59-gl-sprites.js | 23 +++++++--- src/game/96-map/60-draw.js | 4 +- tests/map-2d-sprite-budget.test.js | 68 ++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 7 deletions(-) create mode 100644 tests/map-2d-sprite-budget.test.js diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js index 615c48e..ad1d91e 100644 --- a/src/game/96-map/59-gl-sprites.js +++ b/src/game/96-map/59-gl-sprites.js @@ -5,6 +5,18 @@ const SPR_MAX=1400,SPR_STRIDE=13; // The card's pictures (SPRS) and the 2D map's (SPRC), by key; both at the screen's pixel density SPR_DPR. const SPRS=new Map(),SPRC=new Map();let SPR_DPR=0; +/* The 2D map's pictures each keep a canvas, so they are also held to a size: a long zoom on a big network paints every + city again at each step, and the list (only capped at SPR_MAX) held up to 180 MB of them where a frame shows 2 to + 23 MB. At the end of a frame over SPRC_BUDGET bytes, the pictures it did not use go, those unused the longest first, + down to 3/4 of the budget (so this happens once in a while, not every frame). The frame's own are always kept: a + screen that needs more than the budget keeps what it needs. A canvas let go is emptied (0×0) at once, which frees + its pixels without waiting for the collector. The card's atlas has its own fixed size (GLS.size). + SPR_F counts frames (draw()); finding or drawing a picture marks it as used in this one (e.f). */ +const SPRC_BUDGET=48*1048576;let SPRC_B=0,SPR_F=0; +const sprFree=e=>{if(e.cv){e.cv.width=e.cv.height=0;e.cv=null;}}; +function sprcTrim(){if(SPRC_B<=SPRC_BUDGET)return;const old=[];for(const [k,e] of SPRC)if(e.fa[0]-b[0]);const goal=SPRC_BUDGET*0.75; + for(const [,k,e] of old){if(SPRC_B<=goal)break;SPRC.delete(k);SPRC_B-=e.pw*e.ph*4;sprFree(e);}} const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0}; /* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */ @@ -28,7 +40,7 @@ function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4 for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE); GLS.shx=GLS.shy=GLS.shh=0;} // Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it). -function spritesReset(){glsDrawNow();SPRS.clear();SPRC.clear();GLS.shx=GLS.shy=GLS.shh=0;} +function spritesReset(){glsDrawNow();for(const e of SPRC.values())sprFree(e);SPRS.clear();SPRC.clear();SPRC_B=0;GLS.shx=GLS.shy=GLS.shh=0;} // The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten. function spritesDrop(){GLS.n=GLS.up=0;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} /* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a @@ -41,20 +53,21 @@ function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('ca // Where this frame's pictures are kept: the card's or the 2D map's. A new pixel density starts both again. function sprMap(){if(DPR!==SPR_DPR){SPR_DPR=DPR;spritesReset();}return GLS.frame&&!!GLX.gl&&!!GLS.prog?SPRS:SPRC;} // The picture already painted under key, if any: callers ask first, so a picture drawn every frame costs no closure. -const spriteHas=key=>sprMap().get(key); +const spriteHas=key=>{const e=sprMap().get(key);if(e)e.f=SPR_F;return e;}; // A picture of w×h CSS px with its anchor at (ax,ay): painted once by paint(g) (the 2D canvas, at the screen's pixel // density), and kept by key in SPRS (the card's) or SPRC (the 2D map's). -function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.get(key);if(e)return e; +function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.get(key);if(e){e.f=SPR_F;return e;} if(SPRS.size+SPRC.size>=SPR_MAX)spritesReset(); const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx; - e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1}; + e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1,f:SPR_F}; if(gpu&&pw<=GLS.size&&ph<=GLS.size){const P=glsPad(pw,ph),g=P.g; g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw,ph);ctx=g; try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;g.restore();} // A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next. try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);} }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g; - try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;}e.cv=cv;} + try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;}e.cv=cv; + if(M===SPRC)SPRC_B+=pw*ph*4;} M.set(key,e);return e;} /* A picture starts with the pen the map's own canvas has when it draws cities and markers: the tubes leave it with round line ends and corners, the labels with text centred on its middle. Drawn straight on the map, the dashed rings, diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index eea050b..6709e30 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -1,8 +1,8 @@ /* A frame. An error from the card itself (glErr()) gives WebGL up for this session and draws the same frame again in 2D, once; any other error goes on to the loop's tickErr(). Either way the 2D context and the sprite queue are reset. */ -function draw(now){for(let pass=0;;pass++){let err=null;DFC=new Map(); +function draw(now){for(let pass=0;;pass++){let err=null;DFC=new Map();SPR_F++; try{drawFrame(now);}catch(e){err=e;} - try{glsFrameEnd();}catch(e){if(!err)err=e;}finally{DFC=null;GLS.frame=false;GLS.n=0;ctx=CTX0;} + try{glsFrameEnd();}catch(e){if(!err)err=e;}finally{DFC=null;GLS.frame=false;GLS.n=0;ctx=CTX0;sprcTrim();} if(!err)return;if(!err.glErr||pass)throw err;glKill(err);}} // Rectangles on a 64 px grid: a new one is compared only with the few that share its cells (a plain list made the // label placement quadratic in the number of cities). diff --git a/tests/map-2d-sprite-budget.test.js b/tests/map-2d-sprite-budget.test.js new file mode 100644 index 0000000..217508f --- /dev/null +++ b/tests/map-2d-sprite-budget.test.js @@ -0,0 +1,68 @@ +// The 2D map keeps a canvas per picture (59-gl-sprites.js). A long zoom on a big network paints every city again at +// each step, and the list, capped only by its length, held up to 180 MB of pictures where a frame shows at most 23 MB. +// It is now held to SPRC_BUDGET bytes: past it, the pictures no frame used since the one before are let go, and those +// in use are always kept. The page's clock is set by hand, so nothing depends on how fast the test runs. +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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + +// The big network on a 1280×800 screen at 2× in 2D. Canvases are counted as they are made; their contexts take any call. +function open() { + const h = load({ seed: 777 }); + h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute(); + window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false,false); + DPR=2;CW=1280;CH=800;cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=0.6;window.__cv=0; + const ce=document.createElement.bind(document);document.createElement=function(t){const e=ce(t);if(String(t).toLowerCase()==='canvas')__cv++;return e;}; + HTMLCanvasElement.prototype.getContext=function(){return this.__c||(this.__c=new Proxy({},{get(t,k){if(k in t)return t[k]; + if(k==='measureText')return s=>({width:String(s).length*7});if(k==='createLinearGradient')return ()=>({addColorStop(){}});return ()=>{};},set(t,k,v){t[k]=v;return true;}}));}; + window.__bytes=()=>{let b=0;for(const e of SPRC.values())b+=e.pw*e.ph*4;return b;}; + // What the last frame drew: its pictures and their bytes. + window.__used=()=>{let n=0,b=0;for(const e of SPRC.values())if(e.f===SPR_F){n++;b+=e.pw*e.ph*4;}return {n,b};};`); + return h; +} +// A pinch from 0.6 to 3.2 and back in 180 frames of 16 ms: the most bytes held, and the most a frame used. +const PINCH = `(()=>{let held=0,used=0,drift=0;for(let i=0;i<=180;i++){const f=i<=90?i/90:(180-i)/90;cam.z=0.6*Math.pow(3.2/0.6,f);__T+=16;draw(__T); + const b=__bytes();held=Math.max(held,b);used=Math.max(used,__used().b);drift=Math.max(drift,Math.abs(b-SPRC_B));}return JSON.stringify({held,used,drift});})()`; + +test('a long zoom on the 2D map holds its pictures to the budget, plus what one frame needs', () => { + const { ev, errors } = open(); + const r = JSON.parse(ev(PINCH)); + const MB = 1048576, budget = ev('SPRC_BUDGET'); + assert.equal(r.drift, 0, 'the bytes counted are the bytes held'); + assert.ok(r.used > 5 * MB, `a frame uses a real share of it (${(r.used / MB).toFixed(1)} MB)`); + // After a frame, over the budget only if that frame alone needs more. + assert.ok(r.held <= Math.max(budget, r.used), `held ${(r.held / MB).toFixed(1)} MB, budget ${budget / MB} MB`); + assert.ok(r.held < 80 * MB, `far under the 180 MB it held before (${(r.held / MB).toFixed(1)} MB)`); + assert.deepEqual(errors, []); +}); + +test('the pictures a frame uses are never let go, and a still map paints nothing new', () => { + const { ev, errors } = open(); + ev(PINCH); + // Every picture the last frame drew is still kept (it was used, so it cannot have been let go). + ev('window.__keep=[];const b0=blit;blit=function(e,...a){__keep.push(e);return b0(e,...a);};__T+=16;draw(__T);blit=b0;'); + assert.ok(ev('__keep.length') > 50); + assert.equal(ev('__keep.every(e=>[...SPRC.values()].includes(e))'), true, 'every picture of the frame is kept'); + // The same view again and again: everything comes from the kept pictures. + ev('window.__c0=__cv;for(let i=0;i<5;i++){__T+=16;draw(__T);}'); + assert.equal(ev('__cv-__c0'), 0, 'no picture painted again'); + assert.deepEqual(errors, []); +}); + +test('under the budget nothing is let go', () => { + const { ev, errors } = open(); + ev('cam.z=1.1;__T+=16;draw(__T);window.__n=SPRC.size;window.__b=SPRC_B;'); + assert.ok(ev('__b') < ev('SPRC_BUDGET')); + // A small pan: new pictures come in, none goes. + ev('for(let i=0;i<10;i++){cam.x+=4;__T+=16;draw(__T);}'); + assert.ok(ev('SPRC.size') >= ev('__n'), 'the list only grew'); + assert.equal(ev('SPRC_B'), ev('__bytes()')); + // A reset (a new pixel density) forgets the bytes with the pictures. + ev('DPR=1;__T+=16;draw(__T);'); + assert.equal(ev('SPRC_B'), ev('__bytes()')); + assert.deepEqual(errors, []); +}); From 351b3aa5222762f843abd22cb4692169d7c58f2d Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:04:45 +0100 Subject: [PATCH 329/491] WebGL map: take a lost context back, and let it go for Always 2D The first loss of the WebGL context gave the card up for the session. A context can come back (a driver reset; on a phone, sometimes just leaving the app), so a phone that went to another app came back to the slower 2D map until the page was reloaded. Always 2D, chosen in Settings, kept the context and its 64 MB atlas for a map drawn in 2D. A loss now leaves the 2D map drawing while the context is away (glLost(): the event is cancelled so the browser may give it back), and everything on the card is built again on the same context when it comes back (glRestored(), glForget(): glInit() runs as for the first frame). A card lost more than GL_LOSSES (2) times is given up for the session, so a card that keeps failing does not keep the map switching. Always 2D lets the context go through WEBGL_lose_context and Auto asks for it back, the same path, never counted as a loss; a context the browser gives back after the player chose Always 2D is let go again. Without the extension, and for the GPU benchmark's switches (mapGl(on,false)), the context is kept as before. The listeners and the overlay's wrappers are set once. Diagnostic info says when the map waits for a lost context. Tests: webgl-context-restore (7), and the loss test of webgl-out-of-memory now waits for the context instead of giving it up. --- src/game/96-map/56-webgl.js | 31 ++++-- src/game/96-map/97-diagnostics.js | 2 +- tests/diagnostic-info.test.js | 4 +- tests/webgl-context-restore.test.js | 145 ++++++++++++++++++++++++++++ tests/webgl-out-of-memory.test.js | 7 +- 5 files changed, 177 insertions(+), 12 deletions(-) create mode 100644 tests/webgl-context-restore.test.js diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js index 981aba4..26fae66 100644 --- a/src/game/96-map/56-webgl.js +++ b/src/game/96-map/56-webgl.js @@ -5,29 +5,46 @@ Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used. - Puzzles, and any browser without WebGL2 or whose context fails or is lost, keep the 2D map. So does WebGL drawn by + Puzzles, and any browser without WebGL2 or whose context fails, keep the 2D map; a lost context, until it is back. So does WebGL drawn by the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */ -const GLX={want:true,dead:false,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; +const GLX={want:true,dead:false,lost:false,sleep:false,losses:0,lose:null,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){} // Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark). const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i; const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit(); // Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not. +// Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back. function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){} - if(!on)glShow(false);GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;} + if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}} + GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;} function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;} // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame. function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;} function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true; const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);} -/* The card given up for good (not Always 2D, which keeps it for later) still held what was sent to it, the atlas alone +/* The card given up for good (not Always 2D: glSleep()) still held what was sent to it, the atlas alone 64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go (WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */ function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf); const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){} GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;} +/* A lost context comes back. The browser may lose it (a driver reset; on a phone, sometimes just leaving the app) and + give it back (webglcontextrestored): the 2D map draws meanwhile, and everything on the card is built again on the + same context, as for the first frame. A card lost more than GL_LOSSES times is given up for the session, so a card + that keeps failing does not keep the map switching. Always 2D lets the context go the same way (WEBGL_lose_context) + and Auto asks for it back, so 64 MB of atlas and the rest are not held for a map that is not drawn. */ +const GL_LOSSES=2; +// Forgets what was on the card (the context itself is kept): glInit() builds it all again. +function glForget(){GLX.gl=null;spritesDrop();GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;Object.assign(GLX,{tex:null,land:{},ckey:null,key:[]});glShow(false);UI.drawnAt=0;} +function glLost(e){if(GLX.dead)return;e.preventDefault();if(GLX.lost)return; // let go by Always 2D (glSleep()) + if(++GLX.losses>GL_LOSSES){glKill('the graphics context was lost '+GLX.losses+' times');return;} + GLX.lost=true;glForget();} +function glRestored(){if(GLX.dead)return;GLX.lost=false;glForget();if(!GLX.want)glSleep();} +// Always 2D: lets the context go, unless the browser has it already (its restore then finds Always 2D and lets it go). +function glSleep(){const L=GLX.lose;if(!GLX.ctx||GLX.dead||!L||typeof L.restoreContext!=='function')return; + if(GLX.lost){GLX.sleep=true;return;}glForget();GLX.sleep=GLX.lost=true;try{L.loseContext();}catch(e){GLX.sleep=GLX.lost=false;}} /* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never @@ -47,21 +64,21 @@ function glVao(gl,sizes,div=1,data=null){const v=gl.createVertexArray(),b=gl.cre gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW); let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;}); gl.bindVertexArray(null);return {v,b};} -function glInit(){if(GLX.gl)return true;if(GLX.dead)return false; +function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false; try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers'); const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'}); if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl; + if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}} try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){} if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu); const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)}; // The tubes' points for the packets: floats read with texelFetch, never filtered. const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST); - c.addEventListener('webglcontextlost',e=>{e.preventDefault();if(GLX.dead)return;glKill('the graphics context was lost');UI.drawnAt=0;}); glsInit(gl); // The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every // frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself. const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype; - for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};} + if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}} const V=s=>glVao(gl,s); Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;} catch(e){glKill(e);return false;}} diff --git a/src/game/96-map/97-diagnostics.js b/src/game/96-map/97-diagnostics.js index b5a427e..d80320f 100644 --- a/src/game/96-map/97-diagnostics.js +++ b/src/game/96-map/97-diagnostics.js @@ -9,7 +9,7 @@ function diagFrame(now){const D=DIAG;if(D.last)D.fr.push(now-D.last);D.last=now; if(D.fr.length>600)D.fr.splice(0,300);if(D.dr.length>600)D.dr.splice(0,300);} // What draws the map, and why it is the 2D canvas when it is. function diagMap(){if(!S)return 'map: none (title screen)';if(pzOn())return 'map: 2D (puzzle)';if(!GLX.want)return 'map: 2D (Always 2D)'; - if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';} + if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';if(GLX.lost)return 'map: 2D (graphics context lost, waiting for it back)';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';} // Frames since the last readout: per second, the 95th percentile and the slowest, and draw()'s mean. function diagPerf(){const f=DIAG.fr.splice(0),d=DIAG.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0), q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-',gl=GLX.shown&&!GLX.dead; diff --git a/tests/diagnostic-info.test.js b/tests/diagnostic-info.test.js index 324fcf6..2713149 100644 --- a/tests/diagnostic-info.test.js +++ b/tests/diagnostic-info.test.js @@ -47,7 +47,9 @@ test('it says what draws the map, and why it is the 2D canvas', () => { assert.equal(map(), 'map: 2D (Always 2D)'); ev('mapGl(true,false);glKill(new Error("the graphics card is out of memory (the pictures)"))'); assert.equal(map(), 'map: 2D (the graphics card is out of memory (the pictures))'); - ev('GLX.dead=false;GLX.gl={};GLX.shown=true;GLX.gpu="ANGLE (NVIDIA GeForce GTX 980)"'); + ev('GLX.dead=false;GLX.lost=true'); + assert.equal(map(), 'map: 2D (graphics context lost, waiting for it back)'); + ev('GLX.lost=false;GLX.gl={};GLX.shown=true;GLX.gpu="ANGLE (NVIDIA GeForce GTX 980)"'); assert.equal(map(), 'map: WebGL2 · ANGLE (NVIDIA GeForce GTX 980)'); ev('const s=S;S=null;window.__S=s'); assert.equal(map(), 'map: none (title screen)'); diff --git a/tests/webgl-context-restore.test.js b/tests/webgl-context-restore.test.js new file mode 100644 index 0000000..734fa03 --- /dev/null +++ b/tests/webgl-context-restore.test.js @@ -0,0 +1,145 @@ +// A WebGL context can be lost and given back: a driver reset, or on a phone sometimes just leaving the app. The map +// gave the card up for the session at the first loss, so a phone that went to another app came back to the slower 2D +// map until the page was reloaded. It now draws in 2D while the context is away, and builds everything on the card +// again when the browser gives it back (webglcontextrestored), up to GL_LOSSES times a session. Settings › Map drawing +// › Always 2D lets the context go the same way (WEBGL_lose_context), and Auto asks for it back, so a map drawn in 2D +// does not hold 64 MB of atlas on the card. Switching for the GPU benchmark (mapGl(on,false)) keeps the context. +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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + +/* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's. It can be lost by the "browser" + (__browserLose(), __browserRestore()) or through WEBGL_lose_context (counted in __LOST and __RESTORE; without it when + window.__noExt). Events come at once, which the real ones do not: the code must not rely on either order. Textures + made are counted (__TEX), so a rebuild shows. */ +const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__LOST=0;window.__RESTORE=0;window.__TEX=0; + let lost=false;const c=document.getElementById('mapgl'),fire=t=>c.dispatchEvent(new window.Event(t,{cancelable:true})); + window.__browserLose=()=>{lost=true;fire('webglcontextlost');};window.__browserRestore=()=>{lost=false;fire('webglcontextrestored');}; + const ext={loseContext:()=>{__LOST++;if(lost)return;lost=true;fire('webglcontextlost');},restoreContext:()=>{__RESTORE++;if(!lost)return;lost=false;fire('webglcontextrestored');}}; + const gl=new Proxy({},{get(t,k){ + if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k; + if(k==='getExtension')return (n)=>n==='WEBGL_lose_context'?(window.__noExt?null:ext):{UNMASKED_RENDERER_WEBGL:'REN'}; + if(k==='isContextLost')return ()=>lost; + if(k==='createTexture')return ()=>{__TEX++;return {};}; + if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096; + if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true; + if(k==='getError')return ()=>0; + return ()=>({});}}); + c.getContext=(t)=>t==='webgl2'?gl:null;})()`; + +function open(storage) { + const h = load({ seed: 777, storage }); + h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute(); + window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{}; + const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`); + h.ev(GL); + return h; +} +const frame = (ev) => ev('__T+=16;draw(__T);JSON.stringify({gl:!!GLX.gl&&GLX.shown,dead:GLX.dead,lost:GLX.lost,sprs:SPRS.size,sprc:SPRC.size,err:!!UI.tickErr})'); + +test('a context the browser loses draws the map in 2D, then on the card again once it is back', () => { + const { ev, errors } = open(); + assert.equal(JSON.parse(frame(ev)).gl, true, 'drawn on the card'); + ev('UI.tickErr=false;__browserLose();'); + let f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead, f.lost, f.err], [false, false, true, false], 'in 2D while it is away, without a glitch'); + assert.equal(f.sprs, 0, 'the card’s pictures are forgotten (its atlas went with the context)'); + assert.ok(f.sprc > 0, 'the 2D map paints its own'); + assert.equal(ev('document.getElementById("mapgl").hidden'), true); + ev('window.__t0=__TEX;window.__built=0;const gb=glBuild;glBuild=function(){__built++;return gb.apply(this,arguments);};__browserRestore();'); + f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'back on the card'); + assert.ok(ev('__TEX-__t0') >= 2, 'the atlas and the tubes’ points are made again'); + assert.equal(ev('__built'), 1, 'the tubes are built again'); + assert.ok(f.sprs > 0, 'the pictures are sent again'); + assert.equal(ev('GLX.losses'), 1); + assert.deepEqual(errors, []); +}); + +test(`a card lost more than GL_LOSSES times is given up for the session`, () => { + const { ev, errors } = open(); + frame(ev); + const n = ev('GL_LOSSES'); + for (let i = 0; i < n; i++) { ev('__browserLose()'); frame(ev); ev('__browserRestore()'); assert.equal(JSON.parse(frame(ev)).gl, true, `back after loss ${i + 1}`); } + ev('__browserLose()'); + let f = JSON.parse(frame(ev)); + assert.equal(f.dead, true, 'given up'); + assert.match(ev('GLX.why'), /lost 3 times/); + assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did'); + // A late restore does not bring it back. + ev('__browserRestore()'); + f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead], [false, true]); + assert.deepEqual(errors, []); +}); + +test('Always 2D lets the context go, Auto takes it back, and neither counts as a loss', () => { + const { ev, errors } = open(); + frame(ev); + ev("ACT.mapSet({v:'2d'})"); + assert.equal(ev('__LOST'), 1, 'the context is let go'); + assert.equal(ev('GLX.gl===null&&GLS.tex===null&&SPRS.size===0'), true, 'nothing on the card is held'); + let f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead], [false, false]); + assert.equal(ev('localStorage.getItem("sot-map")'), '2d'); + ev("ACT.mapSet({v:'auto'})"); + assert.equal(ev('__RESTORE'), 1, 'asked back'); + f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'on the card again'); + assert.equal(ev('GLX.losses'), 0, 'the player’s choice is not a failure'); + // Back and forth: still fine, still not counted. + for (let i = 0; i < 4; i++) { ev("ACT.mapSet({v:'2d'})"); frame(ev); ev("ACT.mapSet({v:'auto'})"); } + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.equal(ev('GLX.losses'), 0); + assert.deepEqual(errors, []); +}); + +test('a context the browser gives back after the player chose Always 2D is let go again', () => { + const { ev, errors } = open(); + frame(ev); + ev('__browserLose()'); + ev("ACT.mapSet({v:'2d'})"); + assert.equal(ev('__LOST'), 0, 'already lost: nothing to let go yet'); + ev('__browserRestore()'); + assert.equal(ev('__LOST'), 1, 'let go as soon as it is back'); + assert.equal(JSON.parse(frame(ev)).gl, false); + ev("ACT.mapSet({v:'auto'})"); + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.deepEqual(errors, []); +}); + +test('the GPU benchmark switches maps without letting the context go', () => { + const { ev, errors } = open(); + frame(ev); + ev('mapGl(false,false)'); + assert.equal(JSON.parse(frame(ev)).gl, false); + ev('mapGl(true,false)'); + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.equal(ev('__LOST+__RESTORE'), 0); + assert.deepEqual(errors, []); +}); + +test('without WEBGL_lose_context, Always 2D keeps the context, as before', () => { + const { ev, errors } = open(); + ev('window.__noExt=true'); + frame(ev); + ev("ACT.mapSet({v:'2d'})"); + assert.equal(JSON.parse(frame(ev)).gl, false); + assert.equal(ev('!!GLX.gl'), true, 'kept for later'); + ev("ACT.mapSet({v:'auto'})"); + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.deepEqual(errors, []); +}); + +test('a game started with Always 2D never makes a context', () => { + const { ev, errors } = open({ 'sot-map': '2d' }); + ev('window.__made=0;const gc=document.getElementById("mapgl").getContext;document.getElementById("mapgl").getContext=t=>{__made++;return gc(t);};'); + frame(ev); + ev("ACT.settings({})"); + assert.equal(ev('__made'), 0); + assert.deepEqual(errors, []); +}); diff --git a/tests/webgl-out-of-memory.test.js b/tests/webgl-out-of-memory.test.js index b09577c..fb54011 100644 --- a/tests/webgl-out-of-memory.test.js +++ b/tests/webgl-out-of-memory.test.js @@ -135,13 +135,14 @@ test('a setup that fails half-way lets its context go too', () => { assert.deepEqual(errors, []); }); +// A context the browser lost may come back (tests/webgl-context-restore.test.js): it is waited for, not let go. test('a context the browser lost is not let go a second time', () => { const { ev, errors } = open({}); assert.equal(ev('glInit()'), true); ev('__T+=16;draw(__T);'); - ev('window.__lostNow=true;document.getElementById("mapgl").dispatchEvent(new window.Event("webglcontextlost"));'); - assert.equal(ev('GLX.dead'), true); - assert.equal(ev('GLX.why'), 'the graphics context was lost'); + ev('window.__lostNow=true;document.getElementById("mapgl").dispatchEvent(new window.Event("webglcontextlost",{cancelable:true}));'); + assert.equal(ev('GLX.dead'), false, 'waiting for it to come back'); + assert.equal(ev('GLX.lost&&!glOn()'), true, 'the 2D map draws meanwhile'); assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did'); ev('__T+=16;draw(__T);'); assert.deepEqual(errors, []); From b7a9ec3e3cd976f49edb2b99b38b982b97b02890 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:05:11 +0100 Subject: [PATCH 330/491] Settings: say whether the card can draw the map without setting it up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings › Map drawing said "This browser cannot" by calling glInit(), so opening Settings on the title screen or in a puzzle, where the map is drawn in 2D, made the WebGL context and its 64 MB atlas. It now says what is known without asking the card (glCan()): a card given up or a browser without WebGL2 cannot; a card not tried yet counts as able. A card that turns out to be the processor's is still named once the game draws its first frame, in Diagnostic info and in Settings. Test in webgl-context-restore. --- src/game/96-map/30-settings.js | 2 +- src/game/96-map/56-webgl.js | 3 +++ tests/webgl-context-restore.test.js | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/game/96-map/30-settings.js b/src/game/96-map/30-settings.js index f3025be..b2874fd 100644 --- a/src/game/96-map/30-settings.js +++ b/src/game/96-map/30-settings.js @@ -30,7 +30,7 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${tr('settings.display_and_sound')} ${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))} - ${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glInit()?' '+tr('settings.this_browser_cannot_so_the_map'):''))} + ${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glCan()?' '+tr('settings.this_browser_cannot_so_the_map'):''))} ${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])}
${langPick('langSel')}
${seg(tr('settings.diagnostic_info'),'vpSet',DIAG.on?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_bug_reports_shows_your_screen'))} diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js index 26fae66..7f4196d 100644 --- a/src/game/96-map/56-webgl.js +++ b/src/game/96-map/56-webgl.js @@ -13,6 +13,9 @@ try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){} // Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark). const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i; const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit(); +// Whether the card can draw the map, as far as is known without asking it: Settings says so without making a context +// (on the title screen or in a puzzle that made the 64 MB atlas for a map drawn in 2D). A card not tried yet counts as able. +const glCan=()=>!GLX.dead&&typeof WebGL2RenderingContext!=='undefined'; // Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not. // Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back. function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){} diff --git a/tests/webgl-context-restore.test.js b/tests/webgl-context-restore.test.js index 734fa03..ea46ea2 100644 --- a/tests/webgl-context-restore.test.js +++ b/tests/webgl-context-restore.test.js @@ -143,3 +143,21 @@ test('a game started with Always 2D never makes a context', () => { assert.equal(ev('__made'), 0); assert.deepEqual(errors, []); }); + +// Settings said whether the card could draw the map by setting it up: opening them on the title screen or in a puzzle +// made the context and its 64 MB atlas for a map drawn in 2D. It now says what is known without asking the card. +test('opening Settings never makes a context, and still says when the card cannot', () => { + const { ev, errors } = open(); + ev('window.WebGL2RenderingContext=function(){};window.__made=0;const c=document.getElementById("mapgl"),gc=c.getContext;c.getContext=t=>{__made++;return gc(t);};'); + const note = () => ev("settingsHtml().includes(tr('settings.this_browser_cannot_so_the_map'))"); + ev('const s=S;S=null;window.__S=s;'); + assert.equal(note(), false, 'title screen: a card not tried yet counts as able'); + ev('S=__S;'); + assert.equal(note(), false); + assert.equal(ev('__made'), 0, 'no context made by Settings'); + ev('glKill(new Error("no graphics card, only SwiftShader"))'); + assert.equal(note(), true, 'a card given up: Settings says so'); + ev('delete window.WebGL2RenderingContext;GLX.dead=false;'); + assert.equal(note(), true, 'no WebGL2 in this browser: Settings says so'); + assert.deepEqual(errors, []); +}); From c652bce7d299d895d95ba1db5f604cf50e0a29b8 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:06:07 +0100 Subject: [PATCH 331/491] Diagnostic info: say how often the map was drawn, and drop a key no release had The loop runs at the screen's rate even when a still map is not drawn again, so the readout's "fps" said 60 or 240 on a map that was not being drawn at all, which a bug report would take for the map's speed. It now also says how often the map was drawn ("map drawn N/s"). The sot-fps setting it carried over only ever existed on this branch, never in a release, so it is no longer read or removed; ?fps and ?nofps still open and close the readout. --- src/game/96-map/97-diagnostics.js | 9 +++++---- tests/diagnostic-info.test.js | 13 +++++++------ 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/game/96-map/97-diagnostics.js b/src/game/96-map/97-diagnostics.js index d80320f..7098b72 100644 --- a/src/game/96-map/97-diagnostics.js +++ b/src/game/96-map/97-diagnostics.js @@ -10,10 +10,11 @@ function diagFrame(now){const D=DIAG;if(D.last)D.fr.push(now-D.last);D.last=now; // What draws the map, and why it is the 2D canvas when it is. function diagMap(){if(!S)return 'map: none (title screen)';if(pzOn())return 'map: 2D (puzzle)';if(!GLX.want)return 'map: 2D (Always 2D)'; if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';if(GLX.lost)return 'map: 2D (graphics context lost, waiting for it back)';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';} -// Frames since the last readout: per second, the 95th percentile and the slowest, and draw()'s mean. +// Frames since the last readout: per second, the 95th percentile and the slowest, and draw()'s mean. The loop runs at +// the screen's rate even when a still map is not drawn again (mapStill()), so how often it was drawn is shown too. function diagPerf(){const f=DIAG.fr.splice(0),d=DIAG.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0), q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-',gl=GLX.shown&&!GLX.dead; - return `${sum?(f.length*1000/sum).toFixed(0):'-'} fps · p95 ${q(.95)} ms · max ${q(1)} ms\ndraw ${d.length?(d.reduce((a,x)=>a+x,0)/d.length).toFixed(1):'-'} ms · x${UI.speed||0} · zoom ${cam.z.toFixed(2)}`+ + return `${sum?(f.length*1000/sum).toFixed(0):'-'} fps · map drawn ${sum?(d.length*1000/sum).toFixed(0):'-'}/s · p95 ${q(.95)} ms · max ${q(1)} ms\ndraw ${d.length?(d.reduce((a,x)=>a+x,0)/d.length).toFixed(1):'-'} ms · x${UI.speed||0} · zoom ${cam.z.toFixed(2)}`+ (gl?` · ${GLX.nSeg} segments · ${GLX.nPk} packets`:'');} function diagShow(){const D=DIAG;let el=D.el; if(!el){el=D.el=document.createElement('pre');el.id='diag';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;max-width:calc(100vw - 32px);background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none;white-space:pre-wrap;overflow-wrap:anywhere'; @@ -30,7 +31,7 @@ function diagShow(){const D=DIAG;let el=D.el; // Shows or hides the readout, and remembers it on this device. function diagOn(on){const D=DIAG;clearInterval(D.t);D.t=null;if(D.el){D.el.remove();D.el=null;}D.on=!!on;D.fr.length=D.dr.length=0;D.last=0;D.dms=-1; if(on){D.t=setInterval(diagShow,500);diagShow();} - try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');localStorage.removeItem('sot-fps');}catch(e){}} -{const q=location.search;let on=false;try{on=localStorage.getItem('sot-vp')==='1'||localStorage.getItem('sot-fps')==='1';}catch(e){} + try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');}catch(e){}} +{const q=location.search;let on=false;try{on=localStorage.getItem('sot-vp')==='1';}catch(e){} if(/[?&](vp|fps)\b/.test(q))on=true;else if(/[?&]no(vp|fps)\b/.test(q))on=false;diagOn(on);} {let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];diagOn(!DIAG.on);}});} diff --git a/tests/diagnostic-info.test.js b/tests/diagnostic-info.test.js index 2713149..722ddd8 100644 --- a/tests/diagnostic-info.test.js +++ b/tests/diagnostic-info.test.js @@ -63,21 +63,22 @@ test('it measures frames per second, the slowest frames and draw()', () => { const { ev, errors } = h; try { ev('diagOn(true)'); - // 60 frames, so 59 intervals: 58 of 16 ms and a last one of 50 ms (978 ms in all), each map drawn in 2 ms. - ev('let t=1000;for(let i=0;i<60;i++){t+=i===59?50:16;DIAG.dms=2;diagFrame(t);}diagShow();'); + // 60 frames, so 59 intervals: 58 of 16 ms and a last one of 50 ms (978 ms in all); the map drawn on every other + // one (a still map is not drawn again), in 2 ms: 30 in 978 ms, 31 a second. + ev('let t=1000;for(let i=0;i<60;i++){t+=i===59?50:16;if(i%2)DIAG.dms=2;diagFrame(t);}diagShow();'); const t = text(ev); - assert.match(t, /\b60 fps · p95 16 ms · max 50 ms/); + assert.match(t, /\b60 fps · map drawn 31\/s · p95 16 ms · max 50 ms/); assert.match(t, /draw 2\.0 ms · x0 · zoom /); assert.deepEqual(errors, []); } finally { h.done(); } }); -test('?fps and ?vp open it, ?nofps closes it, and the old frame meter setting carries over', () => { - for (const [url, storage, want] of [['?fps', {}, true], ['?vp', {}, true], ['?nofps', { 'sot-vp': '1' }, false], ['', { 'sot-fps': '1' }, true], ['', {}, false]]) { +test('?fps and ?vp open it, ?nofps closes it, and it stays open on this device', () => { + for (const [url, storage, want] of [['?fps', {}, true], ['?vp', {}, true], ['?nofps', { 'sot-vp': '1' }, false], ['', { 'sot-vp': '1' }, true], ['', {}, false]]) { const h = load({ seed: 777, url: 'https://tests.invalid/' + url, storage }); try { assert.equal(h.ev('!!document.getElementById("diag")'), want, `${url || 'no flag'} ${JSON.stringify(storage)}`); - assert.equal(h.ev('localStorage.getItem("sot-fps")'), null, 'the old key is gone'); + assert.equal(h.ev('localStorage.getItem("sot-vp")'), want ? '1' : null, 'remembered as one setting'); } finally { h.dom.window.close(); } } }); From 32f330b1c389a808b078961ddaa48814bd7b1f50 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:09:59 +0100 Subject: [PATCH 332/491] WebGL map: check the pictures sent to the card at most once a second A frame that sent pictures read getError() to know whether the card took them. In every browser WebGL runs in another process, and each read waits for it to finish everything sent so far, uploads included: a wait on the main thread on exactly the frames that already cost the most (a pan or a zoom sends pictures on most frames, up to 321 in one). The card keeps an error until it is read, so one read a second still finds a refusal: the pictures are now checked at most every GL_MEM_EVERY (1 000) ms, and a picture refused in between shows at worst as a dark box until then, after which the map goes to 2D as before. The first pictures sent into a new atlas are still checked at once, where a card that allocates it lazily refuses. The cost could not be timed here (no Vulkan driver on this machine for Chromium to reach the graphics card); the change bounds it whatever it is. Tests: webgl-out-of-memory reads at most twice in two seconds of panning, and a refusal after the first check gives the map to 2D within a second. --- src/game/96-map/59-gl-sprites.js | 20 +++++++++++------ tests/webgl-out-of-memory.test.js | 37 +++++++++++++++++++++++-------- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js index ad1d91e..309c1d7 100644 --- a/src/game/96-map/59-gl-sprites.js +++ b/src/game/96-map/59-gl-sprites.js @@ -17,7 +17,7 @@ const sprFree=e=>{if(e.cv){e.cv.width=e.cv.height=0;e.cv=null;}}; function sprcTrim(){if(SPRC_B<=SPRC_BUDGET)return;const old=[];for(const [k,e] of SPRC)if(e.fa[0]-b[0]);const goal=SPRC_BUDGET*0.75; for(const [,k,e] of old){if(SPRC_B<=goal)break;SPRC.delete(k);SPRC_B-=e.pw*e.ph*4;sprFree(e);}} -const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0}; +const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0,upq:false,memT:-1e9}; /* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */ const SPR_VS=GL_HEAD+`layout(location=0) in vec4 aP;layout(location=1) in vec4 aUV;layout(location=2) in vec4 aC;layout(location=3) in float aK; @@ -38,11 +38,11 @@ function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4 try{glMem(gl,'the pictures');break;}catch(e){if(GLS.size<=2048)throw e;}} for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR); for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE); - GLS.shx=GLS.shy=GLS.shh=0;} + GLS.shx=GLS.shy=GLS.shh=0;GLS.memT=-1e9;GLS.upq=false;} // Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it). function spritesReset(){glsDrawNow();for(const e of SPRC.values())sprFree(e);SPRS.clear();SPRC.clear();SPRC_B=0;GLS.shx=GLS.shy=GLS.shh=0;} // The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten. -function spritesDrop(){GLS.n=GLS.up=0;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} +function spritesDrop(){GLS.n=GLS.up=0;GLS.upq=false;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} /* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. */ @@ -130,7 +130,13 @@ function glsDraw(gl,n){gl.useProgram(GLS.prog.p);gl.bindVertexArray(GLS.vao);gl. gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST); gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);gl.bindVertexArray(null);} /* The end of a frame on the card: the pictures go up over the tubes. The frame is over even if that draw fails. - A frame that sent new pictures first asks the card if it took them (once, however many): a card short of memory - may refuse one without throwing, and the picture would be kept as sent. It then gives the map to 2D (glMem() throws, - draw() draws the frame again there and glKill() forgets the card's pictures). A frame that only reuses the atlas asks nothing. */ -function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;const up=GLS.up;GLS.up=0;if(up&&GLX.gl)glMem(GLX.gl,'the pictures');glsDrawNow();} + Pictures sent are checked (did the card take them?): a card short of memory may refuse one without throwing, and the + picture would be kept as sent. It then gives the map to 2D (glMem() throws, draw() draws the frame again there and + glKill() forgets the card's pictures). Each read waits for the card to finish everything sent so far, so it is done + at most once every GL_MEM_EVERY ms: the card keeps an error until it is read, so a later read still finds it, and a + picture refused in between shows at worst as a dark box for that time. The first pictures sent into a new atlas are + checked at once (a card that allocates it lazily refuses there). A frame that only reuses the atlas asks nothing. */ +const GL_MEM_EVERY=1000; +function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;if(GLS.up)GLS.upq=true;GLS.up=0; + if(GLS.upq&&GLX.gl){const t=performance.now();if(t-GLS.memT>=GL_MEM_EVERY){GLS.memT=t;GLS.upq=false;glMem(GLX.gl,'the pictures');}} + glsDrawNow();} diff --git a/tests/webgl-out-of-memory.test.js b/tests/webgl-out-of-memory.test.js index fb54011..75a7bc5 100644 --- a/tests/webgl-out-of-memory.test.js +++ b/tests/webgl-out-of-memory.test.js @@ -1,8 +1,8 @@ // A graphics card short of memory may refuse a texture or a buffer without throwing: the call only leaves // OUT_OF_MEMORY for getError(), and the atlas then drew every picture as a black box while the map stayed on the card. // The big uploads now read it (glMem(), src/game/96-map/56-webgl.js): the atlas tries 2048 px before giving up, and -// any other refusal gives the card up for 2D in the same frame. getError() is never read on an ordinary frame (each -// read waits for the card). +// any other refusal gives the card up for 2D in the same frame, or for a picture within a second. getError() is never +// read on an ordinary frame, and at most once a second while pictures are sent (each read waits for the card). const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); @@ -80,13 +80,17 @@ test('an ordinary frame never asks the card for its errors', () => { ev('__T+=16;draw(__T);'); assert.equal(ev('GLX.dead'), false); assert.ok(ev('__GE') > 0, 'the first frame checked its uploads'); - // Panning brings new cities into view, whose pictures are sent: only those frames ask, once each. - const pan = JSON.parse(ev(`(()=>{let quiet=0,asked=0,sent=0,most=0;for(let i=0;i<30;i++){const s=__SUB,g=__GE;cam.x+=3;__T+=16;draw(__T); - if(__SUB===s){quiet++;if(__GE>g)asked++;}else{sent++;most=Math.max(most,__GE-g);}}return JSON.stringify({quiet,asked,sent,most});})()`)); - assert.ok(pan.quiet > 0, 'some frames send no picture'); - assert.equal(pan.asked, 0, 'a frame that sends nothing big reads nothing'); - assert.ok(pan.most <= 4, 'a frame that sends pictures asks once (getError() read up to four flags), not once per picture'); - ev('__GE=0;for(let i=0;i<10;i++){__T+=16;draw(__T);}'); + // Panning brings new cities into view, whose pictures are sent: they are checked at most once a second (each read + // waits for the card), the first time a second after the first frame's check. + const pan = JSON.parse(ev(`(()=>{let sent=0,reads=0,most=0,at=[];for(let i=0;i<120;i++){const s=__SUB,g=__GE;cam.x+=3;__T+=16;draw(__T); + if(__SUB>s)sent++;if(__GE>g){reads++;at.push(i);}most=Math.max(most,__GE-g);}return JSON.stringify({sent,reads,most,at});})()`)); + assert.ok(pan.sent > 5, 'frames send pictures'); + assert.ok(pan.reads >= 1 && pan.reads <= 2, `about two seconds of panning read the errors once or twice, not once per frame that sends (${JSON.stringify(pan)})`); + assert.ok(pan.most <= 4, 'one check reads at most four flags'); + // The pan's last pictures are still to be checked: once, on the next frame a second on. Then a still map reads nothing. + ev('__GE=0;__T+=1100;draw(__T);'); + assert.ok(ev('__GE') <= 4, 'the pictures left over are checked once'); + ev('__GE=0;for(let i=0;i<10;i++){__T+=1100;draw(__T);}'); assert.equal(ev('__GE'), 0, 'a still map reads nothing'); assert.deepEqual(errors, []); }); @@ -109,6 +113,21 @@ test('a picture the card refuses without throwing gives the map to 2D in the sam assert.deepEqual(errors, []); }); +// The card keeps an error until it is read: a picture refused between two checks is found by the next one. +test('a picture refused after the first check gives the map to 2D within a second', () => { + const { ev, errors } = open({}); + assert.equal(ev('glInit()'), true); + ev('UI.tickErr=false;const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;__T+=16;draw(__T);'); + assert.equal(ev('GLX.dead'), false); + ev('__FAIL.sprites=true;'); + const n = ev('(()=>{let i=0;for(;i<120&&!GLX.dead;i++){cam.x+=5;__T+=16;draw(__T);}return i;})()'); + assert.equal(ev('GLX.dead'), true, 'given up'); + assert.ok(n * 16 <= 1000 + 32, `within a second (${n} frames)`); + assert.equal(ev('SPRS.size'), 0, 'no picture is kept as sent'); + assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player'); + assert.deepEqual(errors, []); +}); + /* Given up for good while the context still lives (memory refused), the card kept the atlas (64 MB at 4096 px) and the rest while the 2D map began painting its own pictures. glKill() now deletes the biggest and lets the context go. */ test('giving the card up for good frees what it holds and lets the context go, and the frame is drawn in 2D', () => { From 8c2000f6b1241b3b856e59d163c9c865532e5ff9 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:10:29 +0100 Subject: [PATCH 333/491] CHANGELOG: one bullet per change players will see The WebGL work had eight bullets, so with upstream's three the app's What's new (five bullets) showed only two of ours, and four described fixes to the WebGL map itself, which no release has had: a zoom that lost the context, the cities repainted at every step of a zoom, the coastlines' points, the garbage per frame. What a player gets from them goes into the first bullet (smooth zooms, the coastlines, Always 2D freeing the card, a lost card coming back), which leaves four, each with the pull request's number. --- CHANGELOG.md | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32a06d4..57e00c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,14 +9,10 @@ All notable changes to this project are documented here. The project follows - The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. - Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid. - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in. -- The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same; Settings › Map drawing › Always 2D keeps the old drawing, and browsers without WebGL2 or without a usable graphics card keep it on their own, as does a game whose graphics card fails while you play. -- Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the usual map also draws far fewer shapes each frame. -- Long zooms stay on the graphics card: the pictures of cities and labels are painted on one shared canvas instead of each keeping its own, so the browser no longer runs out of room for them and switches to the slower drawing. -- Zooming is smoother on big maps: while you zoom, cities and ships keep their picture and are only redrawn sharp once the zoom stops, instead of being repainted at every small step. -- The graphics card draws the coastlines with fewer points when you zoom out, where the extra detail was smaller than a pixel, so the map costs it a lot less work, which helps phones most. -- The map leaves far less memory behind it on every frame for the browser to clean up while you play. -- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in: its land picture now stays on the graphics card instead of being sent to it again on every frame. Firefox on Android keeps the old way, which avoids its drawing glitches. -- Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report. +- The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same, and zoomed out the card draws the coastlines with fewer points where the extra detail was smaller than a pixel, which helps phones most. Settings › Map drawing › Always 2D keeps the old drawing and frees what the graphics card held, and browsers without WebGL2 or without a usable graphics card keep it on their own. If the graphics card stops for a moment (on a phone, switching apps can do that), the map is drawn in 2D until it is back, and stays in 2D for a game where it keeps failing. (#281) +- Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the map also draws far fewer shapes each frame. (#281) +- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in: its land picture now stays on the graphics card instead of being sent to it again on every frame. Firefox on Android keeps the old way, which avoids its drawing glitches. (#281) +- Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report. (#281) ## [2.9.1] — 2026-11-04 From c3e1dd93485aa38c93dfbdda2c738c9c98648490 Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:59:38 +0100 Subject: [PATCH 334/491] WebGL map: keep each picture in a clear border in the atlas The card blends the texels around the point it reads, so a picture drawn off whole pixels, or stretched while a zoom moves, read half a texel past its edge: its neighbour in the atlas, or a picture left from before the last reset. The map showed thin coloured lines along the edges of cities and labels. Each picture now goes in with a clear one-texel border, and painting on the pad is clipped to the picture so the border stays clear. --- src/game/96-map/59-gl-sprites.js | 27 ++++++++++------ tests/webgl-sprites.test.js | 53 +++++++++++++++++++++++++++++++- 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js index 309c1d7..997e7a1 100644 --- a/src/game/96-map/59-gl-sprites.js +++ b/src/game/96-map/59-gl-sprites.js @@ -45,7 +45,11 @@ function spritesReset(){glsDrawNow();for(const e of SPRC.values())sprFree(e);SPR function spritesDrop(){GLS.n=GLS.up=0;GLS.upq=false;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} /* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context - and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. */ + and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. + Each picture goes in with a clear border of GLS_GAP px: the card blends the texels around the point it reads, so a + picture drawn off whole pixels or a little stretched read half a texel past its edge, and showed a thin line of its + neighbour in the atlas (or of a picture from before the last reset, which leaves the texture as it was). */ +const GLS_GAP=1; const GLS_PAD={cv:null,g:null}; function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('canvas');P.cv.width=P.cv.height=256;} if(P.cv.width=SPR_MAX)spritesReset(); const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx; e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1,f:SPR_F}; - if(gpu&&pw<=GLS.size&&ph<=GLS.size){const P=glsPad(pw,ph),g=P.g; - g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw,ph);ctx=g; - try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;g.restore();} + const G=GLS_GAP; + if(gpu&&pw+2*G<=GLS.size&&ph+2*G<=GLS.size){const P=glsPad(pw+2*G,ph+2*G),g=P.g; + // Clipped to the picture, as its own canvas would be, so the border stays clear. + g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw+2*G,ph+2*G);g.beginPath();g.rect(G,G,pw,ph);g.clip();ctx=g; + try{g.setTransform(DPR,0,0,DPR,G,G);sprPen(g);paint(g);}finally{ctx=saved;g.restore();} // A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next. try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);} }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g; @@ -74,16 +80,19 @@ function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M. the cones' tips and a sleeping POP's "zzz" took those, and a new canvas has others (square ends, text on its baseline). */ function sprPen(g){g.lineCap='round';g.lineJoin='round';g.textAlign='center';g.textBaseline='middle';} // Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame. -function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog||!e.cv)return false; - try{return glsPut(gl,e,e.cv);}catch(x){throw glErr(x);}} -function glsPut(gl,e,src){const pw=e.pw,ph=e.ph,A=GLS.size;if(pw>A||ph>A)return false; +function glsEnsure(e){if(e.up)return true;const gl=GLX.gl,G=GLS_GAP;if(!gl||!GLS.prog||!e.cv)return false; + if(e.pw+2*G>GLS.size||e.ph+2*G>GLS.size)return false; + const P=glsPad(e.pw+2*G,e.ph+2*G),g=P.g;g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,e.pw+2*G,e.ph+2*G);g.drawImage(e.cv,G,G); + try{return glsPut(gl,e,P.cv);}catch(x){throw glErr(x);}} +// src holds the picture at (GLS_GAP,GLS_GAP), in a clear border that goes into the atlas with it. +function glsPut(gl,e,src){const G=GLS_GAP,pw=e.pw+2*G,ph=e.ph+2*G,A=GLS.size;if(pw>A||ph>A)return false; if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;} if(GLS.shy+ph>A){spritesReset();return false;} const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph); gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true); - // Only the picture's corner of the source: the pad is bigger than most pictures. + // Only the picture's corner of the source (with its border): the pad is bigger than most pictures. gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); - GLS.up++;Object.assign(e,{up:true,u0:x/A,v0:y/A,u1:(x+pw)/A,v1:(y+ph)/A});return true;} + GLS.up++;Object.assign(e,{up:true,u0:(x+G)/A,v0:(y+G)/A,u1:(x+pw-G)/A,v1:(y+ph-G)/A});return true;} // The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace. function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;} // Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas. diff --git a/tests/webgl-sprites.test.js b/tests/webgl-sprites.test.js index cf7665c..95d4874 100644 --- a/tests/webgl-sprites.test.js +++ b/tests/webgl-sprites.test.js @@ -47,6 +47,57 @@ test('on the card, pictures are painted on one canvas and each goes into the atl assert.deepEqual(errors, []); }); +// The card blends the texels around the point it reads: a picture drawn off whole pixels, or stretched while a zoom +// moves, read half a texel past its edge, and the map showed thin coloured lines around cities (its neighbour in the +// atlas, or a picture from before the last reset). So each picture goes in with a clear border, and never touches another. +test('on the card, every picture sits in the atlas in a clear border of its own', () => { + const { ev, errors } = open(); + ev(STUB); + // What the pad is asked to do for each picture: cleared, clipped to the picture, painted inside the border. + ev(`(()=>{const P=glsPad(1,1),g=P.g;window.__pad=[];for(const k of ['clearRect','rect','setTransform'])g[k]=(...a)=>__pad.push([k,...a]);})()`); + ev(ZOOM); + const r = JSON.parse(ev(`(()=>{const A=GLS.size,G=GLS_GAP,es=[...SPRS.values()].filter(e=>e.up); + const R=es.map(e=>({x0:Math.round(e.u0*A),y0:Math.round(e.v0*A),x1:Math.round(e.u1*A),y1:Math.round(e.v1*A),e})); + const exact=R.every(q=>q.x1-q.x0===q.e.pw&&q.y1-q.y0===q.e.ph); + const inside=R.every(q=>q.x0>=G&&q.y0>=G&&q.x1+G<=A&&q.y1+G<=A); + let touch=0;for(let i=0;ic[0]==='texSubImage2D').slice(-es.length); + const sent=subs.every(c=>R.some(q=>c[3]===q.x0-G&&c[4]===q.y0-G&&c[5]===q.e.pw+2*G&&c[6]===q.e.ph+2*G)); + // Each picture: clearRect(0,0,W,H), then rect(G,G,W-2G,H-2G) for the clip, then the transform that paints inside it. + const at=__pad.flatMap((c,i)=>c[0]==='clearRect'?[i]:[]),nx=(i,k)=>__pad[i+k]||[]; + return JSON.stringify({n:es.length,exact,inside,touch,sent,G, + cleared:at.length>=es.length&&at.every(i=>nx(i,0)[1]===0&&nx(i,0)[2]===0), + clipped:at.every(i=>{const c=nx(i,0),q=nx(i,1);return q[0]==='rect'&&q[1]===G&&q[2]===G&&q[3]===c[3]-2*G&&q[4]===c[4]-2*G;}), + offset:at.every(i=>{const q=nx(i,2);return q[0]==='setTransform'&&q[5]===G&&q[6]===G;})});})()`)); + assert.ok(r.n > 50, `a zoom paints many pictures (${r.n})`); + assert.ok(r.G >= 1, 'a border of at least one texel'); + assert.equal(r.exact, true, 'the picture’s own texels are read, no more'); + assert.equal(r.inside, true, 'with room for its border inside the atlas'); + assert.equal(r.touch, 0, 'no two pictures (with their borders) overlap or touch'); + assert.equal(r.sent, true, 'each was sent with its border'); + assert.equal(r.cleared, true, 'the pad is cleared from its corner, border included'); + assert.equal(r.clipped, true, 'painting is clipped to the picture, so the border stays clear'); + assert.equal(r.offset, true, 'and starts inside the border'); + assert.deepEqual(errors, []); +}); + +test('a picture with its own canvas goes into the atlas in a clear border too', () => { + const { ev, errors } = open(); + ev(STUB); + const r = JSON.parse(ev(`(()=>{const e=spriteEntry('own',20,10,10,5,g=>{g.fillRect(0,0,20,10);}); + const P=glsPad(1,1),g=P.g,log=[];g.clearRect=(...a)=>log.push(['clear',...a]);g.drawImage=(cv,x,y)=>log.push(['draw',cv===e.cv,x,y]); + const ok=glsEnsure(e),A=GLS.size,G=GLS_GAP,s=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D').pop(); + return JSON.stringify({cv:!!e.cv,ok,log,G,u0:e.u0*A,v0:e.v0*A,u1:e.u1*A,v1:e.v1*A,pw:e.pw,ph:e.ph,sent:s.slice(3,7),pad:s[9]===P.cv});})()`)); + assert.equal(r.cv, true, 'painted outside a card frame, so with its own canvas'); + assert.equal(r.ok, true); + assert.deepEqual(r.log, [['clear', 0, 0, r.pw + 2 * r.G, r.ph + 2 * r.G], ['draw', true, r.G, r.G]], 'copied into a cleared pad, inside the border'); + assert.deepEqual([r.u0, r.v0, r.u1, r.v1], [r.G, r.G, r.G + r.pw, r.G + r.ph]); + assert.deepEqual(r.sent, [0, 0, r.pw + 2 * r.G, r.ph + 2 * r.G]); + assert.equal(r.pad, true); + assert.deepEqual(errors, []); +}); + test('a full atlas starts again and the picture that did not fit goes into the new one at once', () => { const { ev, errors } = open(); ev(STUB); @@ -55,7 +106,7 @@ test('a full atlas starts again and the picture that did not fit goes into the n const e=spriteEntry('big',40,40,20,20,g=>{g.fillRect(0,0,40,40);});blit(e,10,10,40,40); glsDraw=gd;const r={up:e.up,u0:e.u0,v0:e.v0,kept:SPRS.get('big')===e,size:SPRS.size,n:GLS.n,cv:!!e.cv,shy:GLS.shy};GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify(r);})()`)); assert.equal(r.up, true, 'the picture is in the atlas'); - assert.equal(r.u0, 0); assert.equal(r.v0, 0); + assert.equal(r.u0, 1 / 4096, 'at the start of the new atlas, past its clear border'); assert.equal(r.v0, 1 / 4096); assert.equal(r.kept, true, 'and kept under its key after the restart'); assert.equal(r.size, 1, 'the old pictures are gone'); assert.equal(r.n, 1, 'drawn this frame'); From 72f4bb54f3c0f4be67d5d8e19fcc42f3d9b7575f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 02:09:52 +0000 Subject: [PATCH 335/491] Scrubbed clean traffic no longer shows as DDoS junk on links (#289) What a scrubbing center sends back to its target is the target's own traffic, but compute() carried it under the junk bucket, so a small flood at a big customer showed up as hundreds of gigabits of DDoS junk on the backbone. It now has its own bucket, shown as scrubbed clean traffic in the link panel. --- 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/80-simulation/30-compute.js | 11 +++++---- src/game/93-ui/70-link-panels.js | 2 +- src/i18n/en.js | 1 + tests/ddos-scrub-clean.test.js | 36 ++++++++++++++++++++++++++++ 10 files changed, 50 insertions(+), 6 deletions(-) create mode 100644 tests/ddos-scrub-clean.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index b10e1f4..52c0c25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project are documented here. The project follows - The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. - Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid. - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in. +- Clean traffic that a scrubbing center sends back to a customer under attack no longer shows as DDoS junk on your backbone links; a link now lists it as scrubbed clean traffic, so a small flood no longer looks like hundreds of gigabits of junk (#289). ## [2.9.1] — 2026-11-04 - Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten. diff --git a/site/i18n/de.js b/site/i18n/de.js index 3ffe669..28039ea 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1498,6 +1498,7 @@ "common.scenario_specialist":"Szenario-Spezialist", "common.scenarios":"Szenarien", "common.script_kiddie":"Script Kiddie", +"common.scrubbed_traffic":"Sauberer Traffic vom Scrubbing", "common.scrubbing_centers":"Scrubbing-Center", "common.see_who":"Wer?", "common.selective":"Selektiv", diff --git a/site/i18n/es.js b/site/i18n/es.js index e90856f..d03e88d 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1496,6 +1496,7 @@ "common.scenario_specialist":"Especialista en escenarios", "common.scenarios":"Escenarios", "common.script_kiddie":"Script kiddie", +"common.scrubbed_traffic":"Tráfico limpio del scrubbing", "common.scrubbing_centers":"Centros de depuración", "common.see_who":"Ver quién", "common.selective":"Selectiva", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 2c7461a..5d93c0c 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1496,6 +1496,7 @@ "common.scenario_specialist":"Spécialiste des scénarios", "common.scenarios":"Scénarios", "common.script_kiddie":"Script kiddie", +"common.scrubbed_traffic":"Trafic nettoyé par le scrubbing", "common.scrubbing_centers":"Centres de scrubbing", "common.see_who":"Voir qui", "common.selective":"Sélective", diff --git a/site/i18n/it.js b/site/i18n/it.js index 3381ff8..59a264d 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1496,6 +1496,7 @@ "common.scenario_specialist":"Specialista di scenari", "common.scenarios":"Scenari", "common.script_kiddie":"Script Kiddie", +"common.scrubbed_traffic":"Traffico pulito dallo scrubbing", "common.scrubbing_centers":"Centri di scrubbing", "common.see_who":"Vedi chi", "common.selective":"Selettiva", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index e021902..eda0475 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1496,6 +1496,7 @@ "common.scenario_specialist":"Especialista em cenários", "common.scenarios":"Cenários", "common.script_kiddie":"Script Kiddie", +"common.scrubbed_traffic":"Tráfego limpo do scrubbing", "common.scrubbing_centers":"Centros de scrubbing", "common.see_who":"Ver quem", "common.selective":"Seletiva", diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 5353c91..d414a57 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -13,7 +13,7 @@ class EgSums{constructor(t){this.t=t;}get(k){const s=this.t.g.get(k);return s=== threads, so it sends these plain pieces (R.efp, R.flc) and the page rebuilds the same lazy R. */ function efBuild(R2,L,ACN,ACD,NKN,NC,NN){const efg={};for(const [id,i,t] of L){let rec=null;efg[id]=new EgSums(t); Object.defineProperty(R2.ef,id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,s] of t.g)rec.eg[k]=t.v[s]; - for(const j of t.n)rec.net[j=1;if(CORE)for(const c of pops){const i=CIDX[c];PASS[i]=corePass(c);OUT[i]=inCore(c)?0:1;} const nodeTake=(i,a)=>{NRES[i]-=a;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;}; const TNA=new Float64Array(TSL.size*NN),TNS=new Uint8Array(TSL.size*NN),TNK=[],TORD=[]; - const NKN=NN+2,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[]; + const NKN=NN+3,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[]; // t.g gives each egress a slot in t.v, so adding to it allocates nothing (a Map of numbers boxes every new sum). const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),v:[],n:[],d:[]};EL.push(l);}const s=t.g.get(eg);if(s===undefined){t.g.set(eg,t.v.length);t.v.push(0+a);}else t.v[s]+=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;}; @@ -172,12 +172,13 @@ function compute(){RW.gen++; // Same answer as diversePaths(), which would rebuild today's live links for every customer. if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}}})(); /* Floods ride the backbone ahead of everyone's traffic (25-ddos-flood.js). haul: up to g from city A to POP B over the - shortest path, as far as links and routers have room. */ + shortest path, as far as links and routers have room. What a scrubbing center sends back is the target's own clean + traffic, counted apart from the junk (#289). */ const msOf=(A,B)=>{const Bi=CIDX[B],Ai=CIDX[A];return SPD[B]&&SPD[B][Ai]n+e.lat,0):0;}; let JK=0;const haul=(A,B,g,ek,from,clean)=>{if(!(g>0))return 0;const Ai=CIDX[A],Bi=CIDX[B];if(!SPD[B]||!(SPD[B][Ai]{const key=src*NC+dst,c0=teCache.get(key); diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 8fcd742..4e488d9 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -61,7 +61,7 @@ function trafficSection(l){ if(!rec){return h+`

${tr('link_panels.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]); - const col=id=>id==='junk'?'#FF4D5E':id==='l2vpn'?'#7B61FF':NET[id].col,nm=id=>id==='junk'?tr('common.ddos_junk'):id==='l2vpn'?tr('common.l2vpn_customers'):NET[id].name; + const col=id=>id==='junk'?'#FF4D5E':id==='l2vpn'?'#7B61FF':id==='scrub'?'#22C47A':NET[id].col,nm=id=>id==='junk'?tr('common.ddos_junk'):id==='l2vpn'?tr('common.l2vpn_customers'):id==='scrub'?tr('common.scrubbed_traffic'):NET[id].name; h+=`${n>1?`

${tr('link_panels.totals_for_all_n_links_between',{n})}

`:''}
${nets.map(([id,v])=>``).join('')}
`; h+=`

${tr('common.content_from')}

`+nets.slice(0,6).map(([id,v])=>`
${esc(nm(id))}${fmtG(v)} · ${pct(v/tot)}
`).join(''); const egs=Object.entries(rec.eg).sort((a,b)=>b[1]-a[1]); diff --git a/src/i18n/en.js b/src/i18n/en.js index 0c5865c..d0eedb7 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1497,6 +1497,7 @@ "common.scenario_specialist":"Scenario Specialist", "common.scenarios":"Scenarios", "common.script_kiddie":"Script Kiddie", +"common.scrubbed_traffic":"Scrubbed clean traffic", "common.scrubbing_centers":"Scrubbing centers", "common.see_who":"See who", "common.selective":"Selective", diff --git a/tests/ddos-scrub-clean.test.js b/tests/ddos-scrub-clean.test.js new file mode 100644 index 0000000..a226100 --- /dev/null +++ b/tests/ddos-scrub-clean.test.js @@ -0,0 +1,36 @@ +// #289: the clean traffic a scrubbing center sends back to its target is the target's own traffic, not the flood. +// On a link it must not show as DDoS junk, which made a 12 G attack look like hundreds of gigs of junk on the backbone. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('#289 scrubbed traffic coming back to the target is not counted as DDoS junk on the backbone', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1})"); + ev("ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});closeModal()"); + // A big customer (200 G port) hit by a small 12 G flood, with a 10T scrubbing center in Amsterdam always on. + ev("S.biz.push({id:'h',type:'host',name:'Big Host',city:'fra',bw:200,rate:100,mood:80,since:0,reqs:[]});S.scrubs=[{city:'ams',tier:2}];S.scrubMode='always'"); + ev("S.ev.ddos={id:'atk',city:'fra',tgt:'h',vec:'dns',gbps:12,start:S.day,until:S.day+2,bh:false};compute()"); + const m = JSON.parse(ev("(()=>{const m=ddosReport(ddosAll()[0]);return JSON.stringify({pulled:m.pulled,cleaned:m.cleaned,over:m.over})})()")); + assert.equal(m.pulled, 12, 'the whole flood is pulled to the scrubbing center'); + assert.equal(m.over, 0, 'and cleaned in full'); + const net = JSON.parse(ev("JSON.stringify(R.ef[edgeKey(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))].net)")); + assert.ok(!(net.junk > 1e-6), `no junk on the link: ${JSON.stringify(net)}`); + assert.ok(net.scrub > 50, `the clean traffic is shown as such: ${JSON.stringify(net)}`); + const h = ev("trafficSection(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))"); + assert.doesNotMatch(h, /DDoS junk/); + assert.match(h, new RegExp(ev("tr('common.scrubbed_traffic')"))); + assert.deepEqual(errors, []); +}); + +test('#289 a flood that does ride the backbone is still DDoS junk', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40"); + ev("ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'ams',net:'cog',tier:1})"); + ev("S.biz.push({id:'g',type:'game',name:'Lag Lords',city:'fra',bw:10,rate:100,mood:80,since:0,reqs:[]})"); + ev("S.ev.ddos={id:'atk',city:'fra',tgt:'g',vec:'ack',gbps:20,start:S.day,until:S.day+2,bh:false};compute()"); + const net = JSON.parse(ev("JSON.stringify(R.ef[edgeKey(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))].net)")); + assert.ok(net.junk > 1, `junk on the link: ${JSON.stringify(net)}`); + assert.ok(!(net.scrub > 0)); + assert.deepEqual(errors, []); +}); From 45ffdba8ae643f14a0ff0f56b9b8bbf36cb879dc Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 07:31:17 +0100 Subject: [PATCH 336/491] =?UTF-8?q?Sweden=20beyond=20Stockholm:=20Gothenbu?= =?UTF-8?q?rg,=20Malm=C3=B6=20and=20Haparanda=20(closes=20#206)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Gothenburg between Oslo and Copenhagen on Netnod's exchange, Malmö across the Øresund on SONIX, and Haparanda where GlobalConnect's fibre crosses the land border to Finland. A Nordic fibre carrier sells transit along that route; Tele2, Telenor and Arelion reach the new cities. --- 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 +++ site/scenarios/weekly/2026-W46.json | 2 +- src/game/20-world/40-city-coords.js | 3 ++ src/game/20-world/50-cities.js | 5 +++ src/game/20-world/55-city-pdb.js | 3 ++ src/game/30-networks/10-networks.js | 2 +- src/game/30-networks/30-long-tail.js | 2 +- src/game/30-networks/32-homegrown-eyeballs.js | 3 +- src/i18n/en.js | 4 +++ tests/gameplay-rules.test.js | 2 +- tests/sweden.test.js | 34 +++++++++++++++++++ 16 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 tests/sweden.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 52c0c25..7a359ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Sweden gets Gothenburg, Malmö and Haparanda (#206). Gothenburg sits between Oslo and Copenhagen with its own exchange, Malmö faces Copenhagen across the Øresund, and Haparanda on the Finnish border is where the fibre crosses over land to Finland, with no exchange yet for you to found one. A Nordic fibre carrier sells transit along that route from Berlin to the border, and Swedish home networks reach the new cities. - The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. - Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid. - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in. diff --git a/site/i18n/de.js b/site/i18n/de.js index 28039ea..4448902 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -689,6 +689,7 @@ "cities.a_tiny_country_at_the_mouth":"Ein winziges Land am Eingang zum Roten Meer, wo ein Dutzend Kabel zwischen Europa, Asien und Afrika an Land gehen. Die Preise sind entsprechend.", "cities.a_tiny_surfing_town_in_cornwall":"Ein winziger Surferort in Cornwall, an dem ein erstaunlicher Teil des transatlantischen Internets an Land geht. Die Klippen sind voller Glasfaser.", "cities.a_weather_station_and_a_port":"Eine Wetterstation und ein Hafen an der Mündung des Jenissei. Das Polar-Express-Kabel sollte hier anlanden; es kam nie an. Verlege dein eigenes.", +"cities.across_the_oresund_from_copenhagen":"Gegenüber von Kopenhagen am Öresund: eine berühmte Brücke und darunter jede Menge Leitungen.", "cities.afghanistan_buys_its_internet_from_four":"Afghanistan kauft sein Internet bei vier Nachbarn ein, Usbekistan, Iran, Pakistan und sogar Armenien, über Glasfaser durch die Berge.", "cities.africa_s_westernmost_capital_where":"Afrikas westlichste Hauptstadt, wo die Hälfte der Kabel entlang der Küste eine Pause einlegt. Die Atlantikbrise ist Gratis-Kühlung.", "cities.agribusiness_capital_and_home_of":"Hauptstadt des Agrobusiness und Heimat der Sertanejo-Musik. Jeder Lkw, Traktor und Silo will einen Anschluss.", @@ -823,6 +824,7 @@ "cities.oil_gas_and_hurricanes_the":"Öl, Gas und Hurrikans. Die Generatoren hier sind auf eine Woche ausgelegt, und das war auch nötig.", "cities.oman_s_capital_just_outside_the":"Omans Hauptstadt, knapp außerhalb der Straße von Hormus, wo die Hälfte der Kabel von Europa nach Asien unterwegs Halt macht.", "cities.on_an_island_so_every_link":"Auf einer Insel, also ist jeder Link nach draußen ein Seekabel.", +"cities.on_the_finnish_border_twinned_with":"Zwillingsstadt von Tornio auf der anderen Flussseite: Hier überquert der Landweg zwischen Schweden und Finnland die Grenze.", "cities.one_cable_and_a_whole_country":"Ein Kabel für ein ganzes Land: Gambia hängt an ACE, ein einziger Schnitt kann fast alles offline nehmen.", "cities.one_foot_in_europe_one_in":"Ein Fuß in Europa, einer in Asien. Jede Landroute zwischen beiden führt hier durch.", "cities.one_network_for_the_whole_country":"Ein Netz für das ganze Land, und seine einzigen sichtbaren Nachbarn sind Satelliten.", @@ -857,6 +859,7 @@ "cities.startups_techno_and_a_surprising":"Startups, Techno und überraschend viele Rechenzentren in alten Brauereien.", "cities.subsea_cables_to_africa_and_asia":"Seekabel nach Afrika und Asien landen hier an.", "cities.suriname_s_first_cable_comes_ashore":"Surinames erstes Kabel kommt in Totness an Land, zwei Stunden westlich an der Küste, und läuft weiter nach Guyana und Trinidad.", +"cities.swedens_west_coast_where_the_fibre":"Schwedens Westküste, auf halbem Weg zwischen Oslo und Kopenhagen: Hier läuft die Glasfaser zwischen Schweden und Norwegen durch.", "cities.switzerland_s_federal_city_governs_from":"Die Bundesstadt der Schweiz regiert von hier und peert in Zürich, eine Stunde die Strecke hinauf.", "cities.tahiti_in_french_polynesia_a_cable":"Tahiti, in Französisch-Polynesien. Ein Kabel führt nach Norden nach Hawaii, und das neue von Chile nach Australien hält hier: das Sprungbrett zwischen Südamerika und Ozeanien.", "cities.tango_steak_and_a_very":"Tango, Steak und eine sehr treue Schar lokaler ISPs.", @@ -2427,6 +2430,7 @@ "homegrown_eyeballs.the_gambia_s_state_telco_and":"Gambias staatliche Telco und Hüterin seiner einzigen Kabellandestation.", "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_nordic_fibre_carrier_whose_superfibre":"Der nordische Glasfaser-Carrier, dessen Superfaser von Berlin bis hinauf an die finnische Grenze reicht. Vorsicht vor Baggern.", "homegrown_eyeballs.the_one_network_of_north_korea":"Das einzige Netz Nordkoreas, das meistens zu den Sternen hinaufschaut.", "homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"Der andere Mobilfunkriese der Philippinen, unterwegs durch den ganzen Archipel.", "homegrown_eyeballs.the_republic_of_congo_s_state":"Der Staatscarrier der Republik Kongo: WACS in Pointe-Noire, ein Backbone hinauf nach Brazzaville und ein Sprung über den Fluss nach Kinshasa.", diff --git a/site/i18n/es.js b/site/i18n/es.js index d03e88d..4619591 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -687,6 +687,7 @@ "cities.a_tiny_country_at_the_mouth":"Un país minúsculo en la boca del Mar Rojo donde llega a tierra una docena de cables entre Europa, Asia y África. Cobra en consecuencia.", "cities.a_tiny_surfing_town_in_cornwall":"Un pueblo surfero diminuto en Cornualles por donde llega a tierra una parte notable del internet transatlántico. Los acantilados están llenos de fibra.", "cities.a_weather_station_and_a_port":"Una estación meteorológica y un puerto en la desembocadura del Yeniséi. El cable Polar Express debía llegar aquí; nunca llegó. Tiende el tuyo.", +"cities.across_the_oresund_from_copenhagen":"Al otro lado del Øresund desde Copenhague: un puente famoso y un montón de tubos debajo.", "cities.afghanistan_buys_its_internet_from_four":"Afganistán compra su internet a cuatro vecinos, Uzbekistán, Irán, Pakistán e incluso Armenia, por fibra a través de las montañas.", "cities.africa_s_westernmost_capital_where":"La capital más occidental de África, donde la mitad de los cables costa abajo paran a descansar. La brisa atlántica es refrigeración gratis.", "cities.agribusiness_capital_and_home_of":"Capital del agronegocio y cuna de la música sertaneja. Cada camión, tractor y silo quiere conexión.", @@ -821,6 +822,7 @@ "cities.oil_gas_and_hurricanes_the":"Petróleo, gas y huracanes. Los generadores de aquí están dimensionados para una semana, y la han necesitado.", "cities.oman_s_capital_just_outside_the":"La capital de Omán, justo a la salida del estrecho de Ormuz, donde la mitad de los cables de Europa a Asia hacen escala.", "cities.on_an_island_so_every_link":"En una isla, así que todo enlace hacia fuera es un cable submarino.", +"cities.on_the_finnish_border_twinned_with":"Hermanada con Tornio al otro lado del río: aquí cruza la ruta terrestre entre Suecia y Finlandia.", "cities.one_cable_and_a_whole_country":"Un cable para todo un país: Gambia depende de ACE, así que un solo corte puede dejar casi todo offline.", "cities.one_foot_in_europe_one_in":"Un pie en Europa, otro en Asia. Toda ruta terrestre entre ambas pasa por aquí.", "cities.one_network_for_the_whole_country":"Una sola red para todo el país, y sus únicos vecinos visibles son satélites.", @@ -855,6 +857,7 @@ "cities.startups_techno_and_a_surprising":"Startups, techno y un número sorprendente de centros de datos en antiguas cervecerías.", "cities.subsea_cables_to_africa_and_asia":"Aquí aterrizan cables submarinos hacia África y Asia.", "cities.suriname_s_first_cable_comes_ashore":"El primer cable de Surinam llega a tierra en Totness, dos horas al oeste por la costa, y sigue hasta Guyana y Trinidad.", +"cities.swedens_west_coast_where_the_fibre":"La costa oeste de Suecia, a medio camino entre Oslo y Copenhague: por aquí pasa la fibra entre Suecia y Noruega.", "cities.switzerland_s_federal_city_governs_from":"La ciudad federal de Suiza gobierna desde aquí y hace peering desde Zúrich, a una hora por la vía.", "cities.tahiti_in_french_polynesia_a_cable":"Tahití, en la Polinesia Francesa. Un cable sube al norte hasta Hawái, y el nuevo de Chile a Australia para aquí: el trampolín entre Sudamérica y Oceanía.", "cities.tango_steak_and_a_very":"Tango, asado y una multitud muy fiel de ISP locales.", @@ -2425,6 +2428,7 @@ "homegrown_eyeballs.the_gambia_s_state_telco_and":"La telco estatal de Gambia y guardiana de su única estación de amarre de cable.", "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_nordic_fibre_carrier_whose_superfibre":"El operador de fibra nórdico cuya superfibra va desde Berlín hasta la frontera finlandesa. Cuidado con las excavadoras.", "homegrown_eyeballs.the_one_network_of_north_korea":"La única red de Corea del Norte, casi siempre mirando las estrellas.", "homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"El otro gigante móvil de Filipinas, recorriendo el archipiélago.", "homegrown_eyeballs.the_republic_of_congo_s_state":"El operador estatal de la República del Congo: WACS en Pointe-Noire, una troncal hasta Brazzaville y un salto al otro lado del río hasta Kinsasa.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 5d93c0c..980158b 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -687,6 +687,7 @@ "cities.a_tiny_country_at_the_mouth":"Un pays minuscule à l’entrée de la mer Rouge, où atterrissent une douzaine de câbles entre l’Europe, l’Asie et l’Afrique. Il facture en conséquence.", "cities.a_tiny_surfing_town_in_cornwall":"Une petite ville de surf en Cornouailles où atterrit une part remarquable de l’Internet transatlantique. Les falaises sont pleines de fibre.", "cities.a_weather_station_and_a_port":"Une station météo et un port à l’embouchure de l’Ienisseï. Le câble Polar Express devait atterrir ici ; il n’est jamais arrivé. Pose le tien.", +"cities.across_the_oresund_from_copenhagen":"En face de Copenhague, de l'autre côté de l'Øresund : un pont célèbre, et beaucoup de tuyaux dessous.", "cities.afghanistan_buys_its_internet_from_four":"L’Afghanistan achète son internet à quatre voisins, l’Ouzbékistan, l’Iran, le Pakistan et même l’Arménie, par fibre à travers les montagnes.", "cities.africa_s_westernmost_capital_where":"La capitale la plus à l’ouest de l’Afrique, où la moitié des câbles qui longent la côte font une pause. La brise atlantique, c’est du free cooling.", "cities.agribusiness_capital_and_home_of":"Capitale de l’agrobusiness et berceau de la musique sertaneja. Chaque camion, tracteur et silo veut une connexion.", @@ -821,6 +822,7 @@ "cities.oil_gas_and_hurricanes_the":"Pétrole, gaz et ouragans. Ici, les groupes électrogènes sont dimensionnés pour une semaine, et ça a déjà servi.", "cities.oman_s_capital_just_outside_the":"La capitale d’Oman, juste à la sortie du détroit d’Ormuz, où la moitié des câbles entre l’Europe et l’Asie fait escale.", "cities.on_an_island_so_every_link":"Sur une île, donc chaque lien qui en part est un câble sous-marin.", +"cities.on_the_finnish_border_twinned_with":"Jumelée avec Tornio, de l'autre côté de la rivière : la route terrestre entre la Suède et la Finlande passe ici.", "cities.one_cable_and_a_whole_country":"Un câble pour tout un pays : la Gambie dépend d’ACE, et une seule coupure peut mettre presque tout hors ligne.", "cities.one_foot_in_europe_one_in":"Un pied en Europe, un en Asie. Toutes les routes terrestres entre les deux passent par ici.", "cities.one_network_for_the_whole_country":"Un seul réseau pour tout le pays, et ses seuls voisins visibles sont des satellites.", @@ -855,6 +857,7 @@ "cities.startups_techno_and_a_surprising":"Startups, techno et un nombre surprenant de datacenters dans d’anciennes brasseries.", "cities.subsea_cables_to_africa_and_asia":"Les câbles sous-marins vers l’Afrique et l’Asie atterrissent ici.", "cities.suriname_s_first_cable_comes_ashore":"Le premier câble du Suriname touche terre à Totness, à deux heures à l’ouest sur la côte, et continue vers le Guyana et Trinidad.", +"cities.swedens_west_coast_where_the_fibre":"La côte ouest de la Suède, à mi-chemin entre Oslo et Copenhague : la fibre entre la Suède et la Norvège passe par ici.", "cities.switzerland_s_federal_city_governs_from":"La ville fédérale suisse gouverne d’ici et peere depuis Zurich, à une heure de train.", "cities.tahiti_in_french_polynesia_a_cable":"Tahiti, en Polynésie française. Un câble remonte vers Hawaï, et le nouveau, du Chili à l’Australie, s’y arrête : le gué entre l’Amérique du Sud et l’Océanie.", "cities.tango_steak_and_a_very":"Tango, steak et une foule très fidèle de FAI locaux.", @@ -2425,6 +2428,7 @@ "homegrown_eyeballs.the_gambia_s_state_telco_and":"La télécom publique de Gambie, gardienne de son unique station d’atterrissement.", "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_nordic_fibre_carrier_whose_superfibre":"L'opérateur de fibre nordique dont la superfibre va de Berlin jusqu'à la frontière finlandaise. Attention aux pelleteuses.", "homegrown_eyeballs.the_one_network_of_north_korea":"L’unique réseau de Corée du Nord, la tête surtout dans les étoiles.", "homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"L’autre géant mobile des Philippines, qui parcourt tout l’archipel.", "homegrown_eyeballs.the_republic_of_congo_s_state":"L'opérateur public de la République du Congo : WACS à Pointe-Noire, un backbone jusqu'à Brazzaville et un saut de l'autre côté du fleuve vers Kinshasa.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 59a264d..e0f2ee8 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -687,6 +687,7 @@ "cities.a_tiny_country_at_the_mouth":"Un paese minuscolo all’imbocco del Mar Rosso dove approdano una dozzina di cavi tra Europa, Asia e Africa. E si fa pagare di conseguenza.", "cities.a_tiny_surfing_town_in_cornwall":"Una cittadina di surfisti in Cornovaglia dove approda una fetta notevole dell’internet transatlantica. Le scogliere sono piene di fibra.", "cities.a_weather_station_and_a_port":"Una stazione meteo e un porto alla foce dello Enisej. Il cavo Polar Express doveva approdare qui; non è mai arrivato. Posane uno tu.", +"cities.across_the_oresund_from_copenhagen":"Di fronte a Copenaghen, oltre l'Øresund: un ponte famoso e un sacco di tubi sotto.", "cities.afghanistan_buys_its_internet_from_four":"L’Afghanistan compra il suo internet da quattro vicini, Uzbekistan, Iran, Pakistan e perfino Armenia, su fibra attraverso le montagne.", "cities.africa_s_westernmost_capital_where":"La capitale più a ovest dell’Africa, dove metà dei cavi lungo la costa si fermano a riposare. La brezza atlantica è free cooling.", "cities.agribusiness_capital_and_home_of":"Capitale dell’agribusiness e patria della musica sertanejo. Ogni camion, trattore e silo vuole una connessione.", @@ -821,6 +822,7 @@ "cities.oil_gas_and_hurricanes_the":"Petrolio, gas e uragani. I generatori qui sono dimensionati per una settimana, e ce n’è stato bisogno.", "cities.oman_s_capital_just_outside_the":"La capitale dell’Oman, appena fuori dallo Stretto di Hormuz, dove metà dei cavi dall’Europa all’Asia fa tappa.", "cities.on_an_island_so_every_link":"È su un’isola, quindi ogni link in uscita è un cavo sottomarino.", +"cities.on_the_finnish_border_twinned_with":"Gemellata con Tornio, oltre il fiume: qui passa la via di terra tra Svezia e Finlandia.", "cities.one_cable_and_a_whole_country":"Un cavo per un intero paese: il Gambia dipende da ACE, quindi un solo taglio può mandarne offline quasi tutto.", "cities.one_foot_in_europe_one_in":"Un piede in Europa, uno in Asia. Ogni rotta terrestre tra le due passa di qui.", "cities.one_network_for_the_whole_country":"Una sola rete per tutto il paese, e i suoi unici vicini visibili sono satelliti.", @@ -855,6 +857,7 @@ "cities.startups_techno_and_a_surprising":"Startup, techno e un numero sorprendente di data center in vecchi birrifici.", "cities.subsea_cables_to_africa_and_asia":"Qui approdano i cavi sottomarini per l’Africa e l’Asia.", "cities.suriname_s_first_cable_comes_ashore":"Il primo cavo del Suriname approda a Totness, due ore a ovest lungo la costa, e prosegue verso la Guyana e Trinidad.", +"cities.swedens_west_coast_where_the_fibre":"La costa ovest della Svezia, a metà strada tra Oslo e Copenaghen: qui passa la fibra tra Svezia e Norvegia.", "cities.switzerland_s_federal_city_governs_from":"La città federale svizzera governa da qui e fa peering da Zurigo, un’ora di treno più su.", "cities.tahiti_in_french_polynesia_a_cable":"Tahiti, nella Polinesia Francese. Un cavo corre a nord verso le Hawaii, e quello nuovo dal Cile all’Australia fa tappa qui: il trampolino tra il Sud America e l’Oceania.", "cities.tango_steak_and_a_very":"Tango, bistecca e una folla fedelissima di ISP locali.", @@ -2425,6 +2428,7 @@ "homegrown_eyeballs.the_gambia_s_state_telco_and":"La telco statale del Gambia e custode del suo unico approdo di cavo.", "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_nordic_fibre_carrier_whose_superfibre":"L'operatore di fibra nordico la cui superfibra va da Berlino fino al confine finlandese. Occhio alle ruspe.", "homegrown_eyeballs.the_one_network_of_north_korea":"L’unica rete della Corea del Nord, quasi sempre con lo sguardo tra le stelle.", "homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"L’altro gigante mobile delle Filippine, in giro per l’arcipelago.", "homegrown_eyeballs.the_republic_of_congo_s_state":"L'operatore statale della Repubblica del Congo: WACS a Pointe-Noire, una dorsale fino a Brazzaville e un salto oltre il fiume fino a Kinshasa.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index eda0475..a96a9e1 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -687,6 +687,7 @@ "cities.a_tiny_country_at_the_mouth":"Um país minúsculo na entrada do Mar Vermelho, onde uma dúzia de cabos entre Europa, Ásia e África chega à terra. E cobra por isso.", "cities.a_tiny_surfing_town_in_cornwall":"Uma cidadezinha de surfe na Cornualha onde uma fatia impressionante da internet transatlântica chega à terra. Os penhascos estão cheios de fibra.", "cities.a_weather_station_and_a_port":"Uma estação meteorológica e um porto na foz do Ienissei. O cabo Polar Express deveria chegar aqui; nunca chegou. Lance o seu.", +"cities.across_the_oresund_from_copenhagen":"Do outro lado do Øresund, em frente a Copenhaga: uma ponte famosa, e muitos tubos por baixo.", "cities.afghanistan_buys_its_internet_from_four":"O Afeganistão compra sua internet de quatro vizinhos, Uzbequistão, Irã, Paquistão e até a Armênia, por fibra através das montanhas.", "cities.africa_s_westernmost_capital_where":"A capital mais ocidental da África, onde metade dos cabos da costa para descansar. A brisa do Atlântico é refrigeração de graça.", "cities.agribusiness_capital_and_home_of":"Capital do agronegócio e terra do sertanejo. Todo caminhão, trator e silo quer uma conexão.", @@ -821,6 +822,7 @@ "cities.oil_gas_and_hurricanes_the":"Petróleo, gás e furacões. Os geradores aqui são dimensionados para uma semana, e já precisaram disso.", "cities.oman_s_capital_just_outside_the":"A capital de Omã, logo na saída do Estreito de Ormuz, onde metade dos cabos da Europa para a Ásia faz uma parada.", "cities.on_an_island_so_every_link":"Fica numa ilha, então todo link pra fora é cabo submarino.", +"cities.on_the_finnish_border_twinned_with":"Geminada com Tornio, do outro lado do rio: a rota terrestre entre a Suécia e a Finlândia passa por aqui.", "cities.one_cable_and_a_whole_country":"Um cabo para um país inteiro: a Gâmbia depende do ACE, então um único corte pode deixar quase tudo offline.", "cities.one_foot_in_europe_one_in":"Um pé na Europa, outro na Ásia. Toda rota terrestre entre as duas passa por aqui.", "cities.one_network_for_the_whole_country":"Uma rede para o país inteiro, e seus únicos vizinhos visíveis são satélites.", @@ -855,6 +857,7 @@ "cities.startups_techno_and_a_surprising":"Startups, techno e um número surpreendente de data centers em cervejarias antigas.", "cities.subsea_cables_to_africa_and_asia":"Cabos submarinos para a África e a Ásia chegam aqui.", "cities.suriname_s_first_cable_comes_ashore":"O primeiro cabo do Suriname chega à terra em Totness, duas horas a oeste pela costa, e segue para a Guiana e Trinidad.", +"cities.swedens_west_coast_where_the_fibre":"A costa oeste da Suécia, a meio caminho entre Oslo e Copenhaga: a fibra entre a Suécia e a Noruega passa por aqui.", "cities.switzerland_s_federal_city_governs_from":"A cidade federal da Suíça governa daqui e faz peering a partir de Zurique, a uma hora de trem.", "cities.tahiti_in_french_polynesia_a_cable":"O Taiti, na Polinésia Francesa. Um cabo segue ao norte para o Havaí, e o novo do Chile à Austrália para aqui: o trampolim entre a América do Sul e a Oceania.", "cities.tango_steak_and_a_very":"Tango, carne e uma turma muito fiel de provedores locais.", @@ -2425,6 +2428,7 @@ "homegrown_eyeballs.the_gambia_s_state_telco_and":"A telco estatal da Gâmbia e guardiã da sua única estação de cabo.", "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_nordic_fibre_carrier_whose_superfibre":"O operador de fibra nórdico cuja superfibra vai de Berlim até à fronteira finlandesa. Cuidado com as escavadoras.", "homegrown_eyeballs.the_one_network_of_north_korea":"A única rede da Coreia do Norte, quase sempre olhando para as estrelas.", "homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"O outro gigante móvel das Filipinas, a percorrer o arquipélago.", "homegrown_eyeballs.the_republic_of_congo_s_state":"A operadora estatal da República do Congo: WACS em Pointe-Noire, um backbone até Brazzaville e um salto do outro lado do rio até Kinshasa.", diff --git a/site/scenarios/weekly/2026-W46.json b/site/scenarios/weekly/2026-W46.json index 1c03f83..ae2a07a 100644 --- a/site/scenarios/weekly/2026-W46.json +++ b/site/scenarios/weekly/2026-W46.json @@ -1 +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":182,"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}} +{"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":170,"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/src/game/20-world/40-city-coords.js b/src/game/20-world/40-city-coords.js index 5969b8e..0b57f2d 100644 --- a/src/game/20-world/40-city-coords.js +++ b/src/game/20-world/40-city-coords.js @@ -141,6 +141,7 @@ const CITY_LL={ "geo":[-58.16,6.8], "gid":[29.93,-3.43], "gnd":[-61.75,12.05], + "got":[11.97,57.71], "gua":[-90.51,14.63], "gum":[144.75,13.47], "gyd":[49.87,40.41], @@ -159,6 +160,7 @@ const CITY_LL={ "hln":[-112.03,46.59], "hnl":[-157.86,21.31], "hou":[-95.37,29.76], + "hpa":[24.14,65.89], "hre":[31.05,-17.83], "hyd":[78.49, 17.39], "icn":[126.98,37.57], @@ -231,6 +233,7 @@ const CITY_LL={ "mla":[14.51,35.9], "mle":[73.51,4.18], "mmk":[33.08,68.97], + "mmx":[13.0,55.6], "mnl":[120.98,14.6], "mos":[37.62,55.76], "mpm":[32.57,-25.97], diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index bd8f4e2..ec41e1c 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -416,6 +416,10 @@ const CITIES=[ {id:'rba',name:'Rabat',x:0,y:0,land:'af',reg:'AF',cc:'MA',capital:true,P:85,ix:'',dc:'Hassan Tower DC'}, // Brazzaville, across the river from Kinshasa {id:'bzv',name:'Brazzaville',x:0,y:0,land:'af',reg:'AF',cc:'CG',capital:true,P:40,ix:'Saka-Saka-IX',dc:'Corniche Colo'}, + // Sweden beyond Stockholm (#206): Gothenburg between Oslo and Copenhagen, Malmö across the Øresund, Haparanda on the land border with Finland + {id:'got',name:'Gothenburg',x:0,y:0,land:'eu',reg:'EU',cc:'SE',P:120,ix:'Feske-IX',dc:'Fish Church Colo',note:tr('cities.swedens_west_coast_where_the_fibre')}, + {id:'mmx',name:'Malmö',x:0,y:0,land:'eu',reg:'EU',cc:'SE',P:70,ix:'Haj-IX',dc:'Turning Torso Racks',note:tr('cities.across_the_oresund_from_copenhagen')}, + {id:'hpa',name:'Haparanda',x:0,y:0,land:'eu',reg:'EU',cc:'SE',P:5,ix:'',dc:'Border Twin Racks',note:tr('cities.on_the_finnish_border_twinned_with')}, ]; // Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat. const CITY_NUDGE={ @@ -471,6 +475,7 @@ const CITY_NUDGE={ mde:[-1.7,-1.9], mgf:[-5.8,-4.4], mia:[-.6,.4], + mmx:[6,2], mtl:[.8,0], mvd:[2.2,-4.3], nat:[-1.5,-3.3], diff --git a/src/game/20-world/55-city-pdb.js b/src/game/20-world/55-city-pdb.js index 3edf3e1..df12bc0 100644 --- a/src/game/20-world/55-city-pdb.js +++ b/src/game/20-world/55-city-pdb.js @@ -146,6 +146,7 @@ const CITY_PDB={ geo:[0,2,8], // est. gid:[0,0,9], // est. gnd:[0,2,11], // est. + got:[8,45,1011], // est. gua:[5,16,103], gum:[6,28,11], gyd:[7,15,131], @@ -164,6 +165,7 @@ const CITY_PDB={ hln:[0,0,33300], // est. hnl:[7,33,33300], hou:[21,173,33300], + hpa:[0,2,1011], // est. hre:[1,0,37], hyd:[17,152,6412], icn:[37,201,1197], @@ -236,6 +238,7 @@ const CITY_PDB={ mla:[3,10,43], // est. mle:[1,3,15], // est. mmk:[2,4,6683], // est. + mmx:[4,18,1011], // est. mnl:[17,352,750], mos:[49,632,6683], mpm:[7,20,36], diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index 6c80020..d2b9ae1 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -2,7 +2,7 @@ const NETS=[ {id:'lvl',name:'Level Tree',asn:3535,type:'t1',pol:'restrictive',share:.07,price:9,col:'#7B61FF',pops:['syd','hfx','bda','hnl','bde','man','edi','svg','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','cph','osl','tor','lax','mex','mtl','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','bio','rio','bue','scl','bog','lim','pan','waw','prg','vie','bud','buh','ist','kcy','cal','van','ott','bru','bet','ham','muc','cpq','gdl','mty','qro','was','mgm','lit','sac','hfd','dov','tlh','boi','spi','ind','dsm','top','fft','btr','aug','anp','lan','stp','jan','jef','hln','lnk','csn','con','ttn','saf','alb','rdu','bis','cmh','okc','sle','har','pvd','cae','pir','bna','aus','mpv','ric','olm','crw','msn','cys'],ix:[],blurb:tr('networks.grew_from_a_seedling_into_a')}, {id:'ntt',name:'Not That Telecom',asn:2941,type:'t1',pol:'restrictive',share:.06,price:8,col:'#4B3FC4',pops:['hnl','gum','man','mil','atn','den','bos','hou','phx','jkt','mnl','lax','dxb','icn','sea','sjc','dal','ash','nyc','lon','ams','fra','sin','hkg','tok','syd','tpe','del','maa','blr','hyd','osa','kul','bkk','sgn','kcy','dus','fuk'],ix:[],blurb:tr('networks.huge_in_asia_which_telecom_not')}, - {id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['pdl','tci','svg','edi','man','mil','rom','pmo','ath','ber','osl','cph','hel','beg','sof','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','mrs','hkg','sin','tpe','tll','waw','vie','bud','buh','prg','kyv','van','bru','ham','muc','dus','krs','ebj','rix','zag','bts'],ix:[],blurb:tr('networks.nordic_backbone_that_tells_you')}, + {id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['pdl','tci','svg','edi','man','mil','rom','pmo','ath','ber','osl','cph','hel','beg','sof','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','mrs','hkg','sin','tpe','tll','waw','vie','bud','buh','prg','kyv','van','bru','ham','muc','dus','krs','ebj','rix','zag','bts','got','mmx','hpa'],ix:[],blurb:tr('networks.nordic_backbone_that_tells_you')}, {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','bio','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','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','pvd','hfd','har','msn','zag','vno','bts','lju','brn','pry'],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','bio','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','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','dsm','msn','boi','yeg','ywg','yxe','yqb','tia','zag','vno','skp','bts','lju','pnh','wlg'],ix:'ALL',blurb:tr('networks.will_peer_with_anyone_anywhere')}, diff --git a/src/game/30-networks/30-long-tail.js b/src/game/30-networks/30-long-tail.js index 7bf3000..2f2e5c4 100644 --- a/src/game/30-networks/30-long-tail.js +++ b/src/game/30-networks/30-long-tail.js @@ -81,7 +81,7 @@ NETS.push( {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')}); + {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','got','mmx'],ix:['osl','svg','got'],blurb:tr('long_tail.norway_s_incumbent_neither_yes_nor')}); NETS.push( {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')}, diff --git a/src/game/30-networks/32-homegrown-eyeballs.js b/src/game/30-networks/32-homegrown-eyeballs.js index bbc8a97..a883165 100644 --- a/src/game/30-networks/32-homegrown-eyeballs.js +++ b/src/game/30-networks/32-homegrown-eyeballs.js @@ -55,6 +55,7 @@ NETS.push( {id:'frs',name:'Oh Yas Sénégal',asn:37649,type:'eye',cc:['SN','KM'],pol:'open',share:.0008,up:['tat','tly'],col:'#FFD100',pops:['dkr','hah'],ix:['dkr'],blurb:tr('homegrown_eyeballs.senegal_s_number_two_freshly_renamed')}, {id:'fsm',name:'Island-Hop Micronesia',asn:10130,type:'t2',cc:'FM',pol:'open',share:.0001,price:14,up:['gtg'],col:'#0072CE',pops:['pni','gum'],ix:[],blurb:tr('homegrown_eyeballs.micronesia_s_only_telco_noodling_across')}, {id:'gbt',name:'Gabon Tele-Calm',asn:16058,type:'t2',cc:'GA',pol:'open',share:.0004,price:11,up:['mrc','tng'],col:'#F7941D',pops:['lbv','cas'],ix:['lbv'],blurb:tr('homegrown_eyeballs.gabon_s_old_telco_now_part')}, + {id:'gdc',name:'Global Disconnect',asn:31027,type:'t2',pol:'open',share:.0008,price:5,up:['tly','cog'],col:'#00B2A9',pops:['sto','got','mmx','hpa','cph','osl','hel','ber'],ix:['sto','got','cph','osl','hel'],blurb:tr('homegrown_eyeballs.the_nordic_fibre_carrier_whose_superfibre')}, {id:'get',name:'GET-ESA Going',asn:37173,type:'t2',cc:'GQ',pol:'open',share:.0002,price:14,up:['agc'],col:'#3E9A3D',pops:['ssg','dla'],ix:[],blurb:tr('homegrown_eyeballs.equatorial_guinea_s_state_telco_finally')}, {id:'glb',name:'Globe-Trotter Telecom',asn:4775,type:'t2',cc:'PH',pol:'selective',minIx:3,minPni:15,share:.006,price:6,up:['ntt','tat'],col:'#0056A2',pops:['mnl','ceb','dvo','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('homegrown_eyeballs.the_philippines_other_mobile_giant_roaming')}, {id:'gmt',name:'Gam-Tell',asn:25250,type:'t2',cc:'GM',pol:'open',share:.0003,price:12,up:['skl','cog'],col:'#0072BC',pops:['bjl','dkr'],ix:['bjl'],blurb:tr('homegrown_eyeballs.the_gambia_s_state_telco_and')}, @@ -140,7 +141,7 @@ NETS.push( {id:'tjt',name:'Tojik Tock',asn:51346,type:'t2',cc:'TJ',pol:'open',share:.0004,price:12,up:['rtc','uzt'],col:'#00843D',pops:['dyu'],ix:['dyu'],blurb:tr('homegrown_eyeballs.tajikistan_s_state_telco_counting_the')}, {id:'tks',name:'Slove-Nice Telekom',asn:5603,type:'t2',cc:'SI',pol:'selective',minIx:2,minPni:10,share:.001,price:9,up:['lvl','skl','cog'],col:'#0066B3',pops:['lju','vie'],ix:['lju'],blurb:tr('homegrown_eyeballs.slovenia_s_state_telco_very_nice')}, {id:'tkt',name:'Darvaza Telecom',asn:20661,type:'t2',cc:'TM',pol:'selective',minIx:1,minPni:8,share:.0003,price:15,up:['rtc','uzt'],col:'#007A33',pops:['asb'],ix:[],blurb:tr('homegrown_eyeballs.turkmenistan_s_one_gateway_named_after')}, - {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:'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','got','mmx'],ix:['sto','got'],blurb:tr('homegrown_eyeballs.sweden_s_challenger_that_took_on')}, {id:'tlv',name:'Tell-Ya Lietuva',asn:8764,type:'eye',cc:'LT',pol:'selective',minIx:2,minPni:10,share:.0012,up:['tly','cog'],col:'#990AE3',pops:['vno','sto'],ix:['vno'],blurb:tr('homegrown_eyeballs.telia_s_lithuanian_arm_still_telling')}, {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:'tnw',name:'Telekom Networks Mal-away',asn:37294,type:'eye',cc:'MW',pol:'open',share:.0005,up:['liq','mtx'],col:'#00A0DF',pops:['llw'],ix:['llw'],blurb:tr('homegrown_eyeballs.malawi_s_own_mobile_network_never')}, diff --git a/src/i18n/en.js b/src/i18n/en.js index d0eedb7..40031a8 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -688,6 +688,7 @@ "cities.a_tiny_country_at_the_mouth":"A tiny country at the mouth of the Red Sea where a dozen cables between Europe, Asia and Africa come ashore. It charges accordingly.", "cities.a_tiny_surfing_town_in_cornwall":"A tiny surfing town in Cornwall where a remarkable share of the transatlantic internet comes ashore. The cliffs are full of fiber.", "cities.a_weather_station_and_a_port":"A weather station and a port at the mouth of the Yenisei. The Polar Express cable was meant to land here; it never arrived. Lay your own.", +"cities.across_the_oresund_from_copenhagen":"Across the Øresund from Copenhagen: one famous bridge, and a lot of pipes under it.", "cities.afghanistan_buys_its_internet_from_four":"Afghanistan buys its internet from four neighbours, Uzbekistan, Iran, Pakistan and even Armenia, over fibre through the mountains.", "cities.africa_s_westernmost_capital_where":"Africa’s westernmost capital, where half the cables down the coast stop for a rest. The Atlantic breeze is free cooling.", "cities.agribusiness_capital_and_home_of":"Agribusiness capital and home of sertanejo music. Every truck, tractor and silo wants a connection.", @@ -822,6 +823,7 @@ "cities.oil_gas_and_hurricanes_the":"Oil, gas and hurricanes. The generators here are sized for a week, and they have needed it.", "cities.oman_s_capital_just_outside_the":"Oman’s capital, just outside the Strait of Hormuz, where half the cables from Europe to Asia stop on the way.", "cities.on_an_island_so_every_link":"On an island, so every link off it is a subsea cable.", +"cities.on_the_finnish_border_twinned_with":"Twinned with Tornio across the river: the land route between Sweden and Finland crosses here.", "cities.one_cable_and_a_whole_country":"One cable and a whole country: The Gambia hangs on ACE, so a single cut can take most of it offline.", "cities.one_foot_in_europe_one_in":"One foot in Europe, one in Asia. Every land route between them crosses here.", "cities.one_network_for_the_whole_country":"One network for the whole country, and its only visible neighbours are satellites.", @@ -856,6 +858,7 @@ "cities.startups_techno_and_a_surprising":"Startups, techno and a surprising number of data centers in old breweries.", "cities.subsea_cables_to_africa_and_asia":"Subsea cables to Africa and Asia land here.", "cities.suriname_s_first_cable_comes_ashore":"Suriname's first cable comes ashore at Totness, two hours west along the coast, and goes on to Guyana and Trinidad.", +"cities.swedens_west_coast_where_the_fibre":"Sweden's west coast, halfway between Oslo and Copenhagen: the fibre between Sweden and Norway runs through here.", "cities.switzerland_s_federal_city_governs_from":"Switzerland's federal city governs from here and peers from Zurich, an hour up the line.", "cities.tahiti_in_french_polynesia_a_cable":"Tahiti, in French Polynesia. A cable runs north to Hawaii, and the new one from Chile to Australia stops here: the stepping stone between South America and Oceania.", "cities.tango_steak_and_a_very":"Tango, steak and a very loyal crowd of local ISPs.", @@ -2426,6 +2429,7 @@ "homegrown_eyeballs.the_gambia_s_state_telco_and":"The Gambia's state telco and the keeper of its one cable landing.", "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_nordic_fibre_carrier_whose_superfibre":"The Nordic fibre carrier whose superfibre runs from Berlin all the way up to the Finnish border. Mind the diggers.", "homegrown_eyeballs.the_one_network_of_north_korea":"The one network of North Korea, mostly gazing at the stars.", "homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"The Philippines’ other mobile giant, roaming the archipelago.", "homegrown_eyeballs.the_republic_of_congo_s_state":"The Republic of the Congo's state carrier: WACS at Pointe-Noire, a backbone up to Brazzaville and a hop across the river to Kinshasa.", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 4996006..e40b5fa 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -104,7 +104,7 @@ const EXCEPTIONS = { // 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', 'Bell Aliant', 'BICS', 'Cogent', 'GTT', 'Hurricane Electric', 'Level 3', 'Level3', 'Liquid', 'Liquid Intelligent Technologies', 'Lumen', 'Northwestel', 'NTT', 'Orange', 'PCCW', 'SaskTel', 'Seacom', 'Singtel', 'Sparkle', 'Tata', 'Tata Communications', 'Telia', 'Telxius', 'Tusass', 'Vodafone', 'Zayo', + 'AT&T', 'Bell Aliant', 'BICS', 'Cogent', 'GlobalConnect', 'GTT', 'Hurricane Electric', 'Level 3', 'Level3', 'Liquid', 'Liquid Intelligent Technologies', 'Lumen', 'Northwestel', 'NTT', 'Orange', 'PCCW', 'SaskTel', 'Seacom', 'Singtel', 'Sparkle', 'Tata', 'Tata Communications', 'Telia', 'Telxius', 'Tusass', '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 diff --git a/tests/sweden.test.js b/tests/sweden.test.js new file mode 100644 index 0000000..e5ef896 --- /dev/null +++ b/tests/sweden.test.js @@ -0,0 +1,34 @@ +// #206: Sweden beyond Stockholm. Gothenburg sits between Oslo and Copenhagen, Malmö across the Øresund from +// Copenhagen, and Haparanda on the land border with Finland, where the fibre crosses to Tornio. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('#206 Gothenburg, Malmö and Haparanda are Swedish cities with transit, and Gothenburg and Malmö have exchanges', () => { + const { ev, errors } = load(); + for (const c of ['got', 'mmx', 'hpa']) { + assert.equal(ev(`CITY.${c}.cc`), 'SE', `${c} is in Sweden`); + assert.ok(ev(`NETS.some(n=>n.price&&n.pops.includes('${c}'))`), `${c} sells transit`); + } + assert.ok(ev("!!CITY.got.ix&&!!CITY.mmx.ix"), 'Netnod Gothenburg and SONIX Malmö'); + assert.equal(ev('CITY.hpa.ix'), '', 'Haparanda waits for a player-founded exchange'); + assert.ok(ev("CITY.got.P>CITY.mmx.P&&CITY.mmx.P>CITY.hpa.P&&CITY.sto.P>CITY.got.P"), 'sized like the real cities'); + // Swedish homes get their own networks in the new cities, not only in Stockholm. + for (const n of ['tlt', 'tnr']) for (const c of ['got', 'mmx']) assert.ok(ev(`NET.${n}.pops.includes('${c}')`), `${n} in ${c}`); + assert.deepEqual(errors, []); +}); + +test('#206 Gothenburg sits between Oslo and Copenhagen, Malmö next to Copenhagen, and Haparanda reaches Finland over land', () => { + const { ev, errors } = load(); + ev('ACT.start({})'); + const km = (a, b) => ev(`kmBetween('${a}','${b}')`); + assert.ok(km('got', 'osl') < km('cph', 'osl') && km('got', 'cph') < km('cph', 'osl'), 'Oslo to Copenhagen can stop in Gothenburg'); + assert.ok(km('mmx', 'cph') < 40, 'the Øresund is short'); + for (const [a, b] of [['mmx', 'cph'], ['got', 'osl'], ['hpa', 'hel']]) assert.equal(ev(`isSub('${a}','${b}')`), false, `${a}–${b} over land`); + // The carrier whose fibre crosses the border there sells transit on both sides. + assert.ok(ev("NET.gdc.price>0&&NET.gdc.pops.includes('hpa')&&NET.gdc.pops.includes('hel')")); + ev("S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'got'});ACT.buyTransit({city:'got',net:'gdc',tier:1});compute()"); + assert.ok(ev("S.transit.some(t=>t.city==='got'&&t.net==='gdc')"), 'a POP in Gothenburg can buy transit there'); + ev('cam.x=CITY.mmx.x;cam.y=CITY.mmx.y;cam.z=5;draw(0)'); + assert.deepEqual(errors, []); +}); From b8d313b0299e29e8443da4ca573ea0c7bcb8d490 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 06:50:19 +0000 Subject: [PATCH 337/491] Alien waves priced against their fiber; crews halve a build at most (#203) An alien wave rented for about as much as leasing the whole fiber, so a route sold out to its market earned 11 to 35 times its lease and the gear paid back in one to three months. A wave now rents for 30% of the fiber's monthly cost (lease plus amplifiers), and each one sold between the same two cities goes cheaper, down to 40% of the first: a full route earns 2 to 6 times its lease. Signed contracts keep their price. Gameplay rule F6. Extra crews could bring any land build to the next day. They now cut it to half its planned time at most, and the button says when it would be done. Gameplay rule F7. A typed order (the agent API) could end a wave, dark fiber or cable in a city the map does not show, and opened a POP there. --- .claude/skills/gameplay-rules/SKILL.md | 2 + CHANGELOG.md | 3 + 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/agent/20-commands.js | 4 +- src/game/10-catalog/60-reach-and-subsea.js | 4 +- src/game/60-features/37-fiber-broker.js | 8 ++- src/game/80-simulation/50-sanitize.js | 2 +- src/game/80-simulation/60-requirements.js | 2 +- src/game/90-actions/60-links.js | 2 +- src/game/90-actions/87-fiber-and-hardware.js | 6 +- src/game/90-actions/90-action-helpers.js | 2 + src/game/93-ui/70-link-panels.js | 2 +- src/i18n/en.js | 3 +- tests/alien-wave-rent.test.js | 67 ++++++++++++++++++++ tests/cable-ships.test.js | 2 +- tests/gameplay-rules.test.js | 25 ++++++++ tests/issues.test.js | 2 +- tests/subsea-upgrade-timing.test.js | 13 +++- 22 files changed, 144 insertions(+), 20 deletions(-) create mode 100644 tests/alien-wave-rent.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index b258991..5622736 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -66,6 +66,8 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | 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. | | F5 | Capacity you rent to other carriers never outgrows the route's market: a broker listing sells over time as carriers between the two cities want it, and neither it nor a random offer sells past what both cities' eyeballs support (a landing town counts the big city it serves). | Rent that scales with your own glass and not with demand is a money machine (#203). | +| F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). | +| F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). | ## DDoS diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a359ca..e1dc2b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ All notable changes to this project are documented here. The project follows - Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid. - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in. - Clean traffic that a scrubbing center sends back to a customer under attack no longer shows as DDoS junk on your backbone links; a link now lists it as scrubbed clean traffic, so a small flood no longer looks like hundreds of gigabits of junk (#289). +- Alien waves you rent out on your dark fiber are now priced against the fiber itself: a wave costs a share of what leasing and lighting that fiber would cost the buyer, and each wave sold between the same two cities goes a little cheaper than the last. A route sold out to its market now earns a few times its lease, not dozens, and contracts already signed keep their price (#203). +- Extra crews can now cut a fiber build on land to half its planned time at most, since permits and rights of way do not speed up; the button shows the day it would be done (#203). +- A link ordered by typing both ends (the AI tools) can no longer end in a city the map does not show (#203). ## [2.9.1] — 2026-11-04 - Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten. diff --git a/site/i18n/de.js b/site/i18n/de.js index 4448902..159a8d4 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2637,6 +2637,7 @@ "link_panels.abandon_the_fiber":"Glasfaser aufgeben", "link_panels.add_parallel_link":"Parallelen Link hinzufügen", "link_panels.additional_traffic_lost":"Zusätzlich verlorener Traffic", +"link_panels.all_crews_done_in_n_days_price":{"one":"Alle Trupps: fertig in {n} Tag {price}","other":"Alle Trupps: fertig in {n} Tagen {price}"}, "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_n_days":"Lizenz beantragen {price} + {mo}/Monat · ~{n} Tage", "link_panels.at_this_pop_net_s_traffic_always":"In diesem POP nimmt der Verkehr zu {net} immer diesen Port. POPs ohne einen nehmen ihren nächsten Transit-Port.", @@ -2653,6 +2654,7 @@ "link_panels.connected_but_tight":"Verbunden, aber knapp.", "link_panels.cost_on_this_link_w_allowed":"Kosten auf diesem Link: {w}. Erlaubt: {lo} bis {hi}.", "link_panels.cost_the_exact_number_whatever_the":"Kosten: genau diese Zahl, egal wie lang der Link ist.", +"link_panels.crews_can_halve_a_build_at_most":"Genehmigungen und Wegerechte geben das Tempo vor: Mehr Trupps halbieren die geplante Bauzeit höchstens, schneller geht es nicht.", "link_panels.dark_fiber_kind_km_km":"Dark Fiber · {kind} · {km} km", "link_panels.de_kicks_personalised_pricing_p_of":"Personalisierte DE-KICKS-Preise: {p} % von dem, was ein normaler IX verlangen würde (Aktion, noch {n} Tage).", "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Personalisierte DE-KICKS-Preise: {p} % von dem, was ein normaler IX verlangen würde.", @@ -2660,7 +2662,6 @@ "link_panels.each_channel_is_a_pair_of":"Jeder Kanal ist ein Paar Optiken, eine pro Ende. ZR+-Optiken stecken direkt in deinen Routern. Transponder sitzen in einem Shelf.", "link_panels.enters_your_network_at":"Kommt in dein Netz bei", "link_panels.every_pop_carries_net_s_traffic":"Jeder POP leitet den Verkehr zu {net} durch dein Netz bis zu diesem Port.", -"link_panels.finish_in_1_day_price":"In 1 Tag fertigstellen {price}", "link_panels.foreign_networks_need_a_local_joint":"Ausländische Netze brauchen ein lokales Joint Venture und eine Betriebslizenz, um hier Infrastruktur zu bauen.", "link_panels.found_your_own_ix_cost_mo":"Eigenen IX gründen {cost} + {mo}/Monat", "link_panels.full_links_during_the_test":"Volle Links während des Tests", diff --git a/site/i18n/es.js b/site/i18n/es.js index 4619591..6b51464 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2635,6 +2635,7 @@ "link_panels.abandon_the_fiber":"Abandonar la fibra", "link_panels.add_parallel_link":"Añadir enlace paralelo", "link_panels.additional_traffic_lost":"Tráfico perdido adicional", +"link_panels.all_crews_done_in_n_days_price":{"one":"Todas las cuadrillas: listo en {n} día {price}","other":"Todas las cuadrillas: listo en {n} días {price}"}, "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_n_days":"Solicitar una licencia {price} + {mo}/mes · ~{n} días", "link_panels.at_this_pop_net_s_traffic_always":"En este POP, el tráfico de {net} siempre usa este puerto. Los POP que no tienen uno usan su puerto de tránsito más cercano.", @@ -2651,6 +2652,7 @@ "link_panels.connected_but_tight":"Conectado, pero justo.", "link_panels.cost_on_this_link_w_allowed":"Coste en este enlace: {w}. Permitido: de {lo} a {hi}.", "link_panels.cost_the_exact_number_whatever_the":"Coste: el número exacto, sea cual sea la distancia.", +"link_panels.crews_can_halve_a_build_at_most":"Los permisos y los derechos de paso marcan el ritmo: más cuadrillas reducen una obra como mucho a la mitad del tiempo previsto.", "link_panels.dark_fiber_kind_km_km":"Fibra oscura · {kind} · {km} km", "link_panels.de_kicks_personalised_pricing_p_of":"Precio personalizado de DE-KICKS: {p} % de lo que cobraría un IX normal (promo, quedan {n} días).", "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Precio personalizado de DE-KICKS: {p} % de lo que cobraría un IX normal.", @@ -2658,7 +2660,6 @@ "link_panels.each_channel_is_a_pair_of":"Cada canal es un par de ópticas, una por extremo. Las ópticas ZR+ se enchufan directo a tus routers. Los transpondedores van en un estante.", "link_panels.enters_your_network_at":"Entra en tu red por", "link_panels.every_pop_carries_net_s_traffic":"Cada POP lleva el tráfico de {net} por tu red hasta este puerto.", -"link_panels.finish_in_1_day_price":"Terminar en 1 día {price}", "link_panels.foreign_networks_need_a_local_joint":"Las redes extranjeras necesitan una empresa conjunta local y una licencia de operación para construir infraestructura aquí.", "link_panels.found_your_own_ix_cost_mo":"Funda tu propio IX {cost} + {mo}/mes", "link_panels.full_links_during_the_test":"Enlaces llenos durante la prueba", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 980158b..c530438 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2635,6 +2635,7 @@ "link_panels.abandon_the_fiber":"Abandonner la fibre", "link_panels.add_parallel_link":"Ajouter un lien parallèle", "link_panels.additional_traffic_lost":"Trafic perdu en plus", +"link_panels.all_crews_done_in_n_days_price":{"one":"Toutes les équipes : fini en {n} jour {price}","other":"Toutes les équipes : fini en {n} jours {price}"}, "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_n_days":"Demander une licence {price} + {mo}/mois · ~{n} jours", "link_panels.at_this_pop_net_s_traffic_always":"Dans ce POP, le trafic de {net} passe toujours par ce port. Les POP qui n’en ont pas utilisent leur port de transit le plus proche.", @@ -2651,6 +2652,7 @@ "link_panels.connected_but_tight":"Connecté, mais de justesse.", "link_panels.cost_on_this_link_w_allowed":"Coût sur ce lien : {w}. Autorisé : de {lo} à {hi}.", "link_panels.cost_the_exact_number_whatever_the":"Coût : le nombre exact, quelle que soit la distance.", +"link_panels.crews_can_halve_a_build_at_most":"Les permis et les droits de passage imposent le rythme : plus d’équipes réduisent un chantier à la moitié de sa durée prévue, pas moins.", "link_panels.dark_fiber_kind_km_km":"Fibre noire · {kind} · {km} km", "link_panels.de_kicks_personalised_pricing_p_of":"Tarif personnalisé DE-KICKS : {p} % de ce que facturerait un IX normal (promo, encore {n} jours).", "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Tarif personnalisé DE-KICKS : {p} % de ce que facturerait un IX normal.", @@ -2658,7 +2660,6 @@ "link_panels.each_channel_is_a_pair_of":"Chaque canal, c’est une paire d’optiques, une à chaque bout. Les optiques ZR+ se branchent directement dans tes routeurs. Les transpondeurs vivent sur une étagère.", "link_panels.enters_your_network_at":"Entre dans ton réseau à", "link_panels.every_pop_carries_net_s_traffic":"Chaque POP achemine le trafic de {net} à travers ton réseau jusqu’à ce port.", -"link_panels.finish_in_1_day_price":"Terminer en 1 jour {price}", "link_panels.foreign_networks_need_a_local_joint":"Les réseaux étrangers ont besoin d’une coentreprise locale et d’une licence d’opérateur pour construire ici.", "link_panels.found_your_own_ix_cost_mo":"Fonder ton propre IX {cost} + {mo}/mois", "link_panels.full_links_during_the_test":"Liens saturés pendant le test", diff --git a/site/i18n/it.js b/site/i18n/it.js index e0f2ee8..e37fafe 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2635,6 +2635,7 @@ "link_panels.abandon_the_fiber":"Abbandona la fibra", "link_panels.add_parallel_link":"Aggiungi link parallelo", "link_panels.additional_traffic_lost":"Ulteriore traffico perso", +"link_panels.all_crews_done_in_n_days_price":{"one":"Tutte le squadre: finito in {n} giorno {price}","other":"Tutte le squadre: finito in {n} giorni {price}"}, "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_n_days":"Richiedi una licenza {price} + {mo}/mese · ~{n} giorni", "link_panels.at_this_pop_net_s_traffic_always":"In questo POP il traffico di {net} usa sempre questa porta. I POP che non ne hanno una usano la porta di transit più vicina.", @@ -2651,6 +2652,7 @@ "link_panels.connected_but_tight":"Connesso, ma al limite.", "link_panels.cost_on_this_link_w_allowed":"Costo su questo link: {w}. Ammessi: da {lo} a {hi}.", "link_panels.cost_the_exact_number_whatever_the":"Costo: il numero esatto, a prescindere dalla distanza.", +"link_panels.crews_can_halve_a_build_at_most":"Permessi e servitù di passaggio dettano i tempi: con più squadre un cantiere dura al massimo la metà del previsto, non di meno.", "link_panels.dark_fiber_kind_km_km":"Dark fiber · {kind} · {km} km", "link_panels.de_kicks_personalised_pricing_p_of":"Prezzi personalizzati DE-KICKS: {p}% di quanto chiederebbe un IX normale (promo, ancora {n} giorni).", "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Prezzi personalizzati DE-KICKS: {p}% di quanto chiederebbe un IX normale.", @@ -2658,7 +2660,6 @@ "link_panels.each_channel_is_a_pair_of":"Ogni canale è una coppia di ottiche, una per estremità. Le ottiche ZR+ si infilano direttamente nei tuoi router. I transponder stanno su uno scaffale.", "link_panels.enters_your_network_at":"Entra nella tua rete a", "link_panels.every_pop_carries_net_s_traffic":"Ogni POP instrada il traffico di {net} attraverso la tua rete fino a questa porta.", -"link_panels.finish_in_1_day_price":"Termina in 1 giorno {price}", "link_panels.foreign_networks_need_a_local_joint":"Per costruire infrastrutture qui, le reti straniere hanno bisogno di una joint venture locale e di una licenza operativa.", "link_panels.found_your_own_ix_cost_mo":"Fonda il tuo IX {cost} + {mo}/mese", "link_panels.full_links_during_the_test":"Collegamenti saturi durante il test", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a96a9e1..06e7c30 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2635,6 +2635,7 @@ "link_panels.abandon_the_fiber":"Abandonar a fibra", "link_panels.add_parallel_link":"Adicionar link paralelo", "link_panels.additional_traffic_lost":"Tráfego perdido a mais", +"link_panels.all_crews_done_in_n_days_price":{"one":"Todas as equipes: pronto em {n} dia {price}","other":"Todas as equipes: pronto em {n} dias {price}"}, "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_n_days":"Pedir licença {price} + {mo}/mês · ~{n} dias", "link_panels.at_this_pop_net_s_traffic_always":"Neste POP, o tráfego de {net} sempre usa esta porta. POPs sem uma usam a porta de transit mais próxima.", @@ -2651,6 +2652,7 @@ "link_panels.connected_but_tight":"Conectado, mas no limite.", "link_panels.cost_on_this_link_w_allowed":"Custo neste link: {w}. Permitido: de {lo} a {hi}.", "link_panels.cost_the_exact_number_whatever_the":"Custo: o número exato, seja qual for a distância.", +"link_panels.crews_can_halve_a_build_at_most":"Licenças e servidões de passagem ditam o ritmo: mais equipes encurtam uma obra no máximo à metade do prazo previsto.", "link_panels.dark_fiber_kind_km_km":"Dark fiber · {kind} · {km} km", "link_panels.de_kicks_personalised_pricing_p_of":"Preço personalizado DE-KICKS: {p}% do que um IX normal cobraria (promo, faltam {n} dias).", "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"Preço personalizado DE-KICKS: {p}% do que um IX normal cobraria.", @@ -2658,7 +2660,6 @@ "link_panels.each_channel_is_a_pair_of":"Cada canal é um par de ópticas, uma em cada ponta. Ópticas ZR+ encaixam direto nos seus routers. Transponders ficam numa prateleira.", "link_panels.enters_your_network_at":"Entra na sua rede em", "link_panels.every_pop_carries_net_s_traffic":"Cada POP leva o tráfego de {net} pela sua rede até esta porta.", -"link_panels.finish_in_1_day_price":"Concluir em 1 dia {price}", "link_panels.foreign_networks_need_a_local_joint":"Redes estrangeiras precisam de uma joint venture local e de uma licença de operação para construir infraestrutura aqui.", "link_panels.found_your_own_ix_cost_mo":"Fundar seu próprio IX {cost} + {mo}/mês", "link_panels.full_links_during_the_test":"Links lotados durante o teste", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 7c58a63..a725106 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -179,8 +179,8 @@ const API_CMD={ quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:subUpgradeCost(l,a.k),days:SUB_UPGRADES[a.k].days}:{};}, doc:'Add premium submarine terminals or extra optical engineering to your own subsea cable. Level 4+, once each.'}, crews:{args:[['id','entityId'],['all','boolean',false]],watch:['links.#id'], - quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};const n=a.all?crewSteps(l):1;return {setup:n*crewCost(l),days:30*n};}, - doc:'Pay for more crews on a cable build: 30 days off per step. Only while more than a day of construction remains.'}, + quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};const n=a.all?crewSteps(l):Math.min(1,crewSteps(l));return {setup:n*crewCost(l),days:n?l.ready-Math.max(crewFloor(l),l.ready-30*n):0};}, + doc:'Pay for more crews on a cable build: 30 days off per step, down to half of the planned build at most.'}, addCh:{args:[['id','entityId'],['o','opticId']],watch:['links.#id'], quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:chCost(l,a.o),blocked:[chWhy(l,a.o)].filter(Boolean)}:{};}, doc:'Light one channel on a dark-fiber span with a given optic; uses a spare from the shelf if you have one.'}, diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index e4bb4b1..305027c 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -22,7 +22,9 @@ function setCableReady(l,ready,day=S.day){const shift=ready-l.ready; } // Crews hurry a build on land. At sea only a cable ship does (85-incidents/50-cable-ships.js). const crewCost=l=>Math.round(15000+l.km*6); -const crewSteps=l=>Math.max(0,Math.ceil((l.ready-S.day-1)/30)); +// Permits and rights of way set the pace: crews cut at most half of the planned build (#203). +const crewFloor=l=>Math.max(S.day+1,Number.isFinite(l.day)?l.day+Math.ceil(dfBuildDays(l.km)/2):0); +const crewSteps=l=>Math.max(0,Math.ceil((l.ready-crewFloor(l))/30)); // Old saves lack purchase dates. Only shorten dates beyond any valid remaining // commissioning window. Credit elapsed time since the actual cable finish; // recent purchases and installed upgrades stay untouched. diff --git a/src/game/60-features/37-fiber-broker.js b/src/game/60-features/37-fiber-broker.js index a0f0275..e208f6f 100644 --- a/src/game/60-features/37-fiber-broker.js +++ b/src/game/60-features/37-fiber-broker.js @@ -15,6 +15,12 @@ const brMarket=(a,b)=>clamp(Math.round(Math.sqrt(brWeight(a)*brWeight(b))/BR_DIV function brSold(a,b){const k=edgeKey({a,b});let n=0;const ls=new Set(S.links.filter(l=>l.kind==='df'&&edgeKey(l)===k).map(l=>l.id)); for(const x of S.biz)if(ls.has(x.link))n+=x.type==='wwave'?(x.slots||0):x.type==='dfpair'?BR_PAIR:0;return n;} const brFree=l=>Math.max(0,brMarket(l.a,l.b)-brSold(l.a,l.b)); +/* What a carrier pays for one alien wave (#203): a share of what the fiber itself costs a month (lease plus amplifiers), + since a buyer would not pay more than leasing and lighting it. Each wave sold between the two cities makes the next + one cheaper, down to 40% of the first once the route's market is full: a full route earns a few times its lease. */ +const WW_SHARE=0.3,WW_FALL=0.6; +function wwRate(l,n,cut=1){const F=dfLeaseMo(l.km)+ampCount(l.km)*AMP_MO,M=brMarket(l.a,l.b),s=brSold(l.a,l.b);let r=0; + for(let i=0;i0)&&!(L.p>0))delete l.list;}} // A sale: a new carrier on this fiber, or more waves for one that already rents here. function brSell(l,t,n){const T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;}; - const o=fiberOffer(t,l,nm,0.9);if(t==='wwave'){o.slots=n;o.rate=Math.round(waveMo(l.km,false,2)*0.55*n*0.9);o.what=wwWhat(l,n);} + const o=fiberOffer(t,l,nm,0.9);if(t==='wwave'){o.slots=n;o.rate=wwRate(l,n,0.9);o.what=wwWhat(l,n);} const more=t==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===l.id&&b.name===o.name); if(more){more.slots=(more.slots||0)+n;more.rate+=o.rate;more.what=wwWhat(l,more.slots);}else S.biz.push(offerCustomer(o)); toast(tr('broker.sold',{name:esc(o.name),what:esc(t==='wwave'?wwWhat(l,n):o.what),price:fmt$(o.rate)}),'good'); diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 6d25862..394874d 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -21,7 +21,7 @@ function sanitize(s){ 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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}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)||!cablePair(l.cable,l.a,l.b)))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;}); + s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}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)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */ diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js index 97ebd4d..ca97bd6 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -77,5 +77,5 @@ const freeCh=(l,u)=>chMax(l)-(l.ch||[]).length-soldSlots(l,u),pairFree=(l,u)=>!! const wwWhat=(l,n)=>trn('requirements.n_400g_alien_wave_on_your',n,{a:CITY[l.a].name,b:CITY[l.b].name}); function fiberOffer(t,l,nm,cut=1){ if(t==='wwave'){const slots=1+Math.floor(Math.random()*Math.min(4,freeCh(l))); - return {id:uid(),city:l.a,city2:l.b,link:l.id,slots,what:wwWhat(l,slots),name:nm(),type:t,bw:1,rate:Math.round(waveMo(l.km,false,2)*0.55*slots*cut),reqs:[],exp:S.day+30};} + return {id:uid(),city:l.a,city2:l.b,link:l.id,slots,what:wwWhat(l,slots),name:nm(),type:t,bw:1,rate:wwRate(l,slots,cut),reqs:[],exp:S.day+30};} return {id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('requirements.a_spare_fiber_pair_in_your',{a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*0.9*cut),reqs:[],exp:S.day+30};} diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index 6864da7..d9d1ffe 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -15,7 +15,7 @@ Object.assign(ACT,{ foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name; S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();}, buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); - if(!linkFromOk(a)||((cnCity(a)||cnCity(b))&&!cnOk()))return; + if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return; if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;} const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;} {const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b)); diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index 39c333d..0413443 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -7,14 +7,14 @@ Object.assign(ACT,{ 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||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a))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; + orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(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};popStdApply(b);} 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}`,id=uid(),ship=layName({id}),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}); const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false; 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||noTalk(p.a,p.b))return;const {a,b}=p;if(!dfAllowed(a,b)||!linkFromOk(a))return;const sc=isSub(a,b)?subDfCable(a,b):null,km=sc?sc.km:kmBetween(a,b); + orderDf:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(!dfAllowed(a,b)||!linkFromOk(a)||!linkToOk(b))return;const sc=isSub(a,b)?subDfCable(a,b):null,km=sc?sc.km:kmBetween(a,b); 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};popStdApply(b);} @@ -37,6 +37,6 @@ Object.assign(ACT,{ seaRush:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l)return;const k=prepSteps(l);if(!k)return;const n=all?k:1;if(!spend(n*prepCost(l)))return;const ready=Math.max(prepFloor(l),l.ready-PREP_STEP*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('cable_ships.the_factory_runs_a_night_shift',saved,{n:saved}),'good');sfx('build');after();}, layShip:({id})=>{const l=S.links.find(x=>x.id===id);const q=l&&layQuote(l);if(!q||!spend(q.cost))return;l.ship2=1;setCableReady(l,l.ready-q.save); toast(trn('cable_ships.second_lay_ship_booked',q.save,{ship:esc(layName(l,1)),n:q.save}),'good');sfx('coin');after();}, - crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.sub||l.ready<=S.day+1)return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(S.day+1,l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('fiber_and_hardware.more_crews_on_site_construction_is',saved,{n:saved}),'good');after();}, + crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.sub||!crewSteps(l))return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(crewFloor(l),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 86afee0..bed742e 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -12,6 +12,8 @@ function dfAllowed(a,b){if(noTalk(a,b))return false;if(isSub(a,b))return !!subDf // A link starts at one of your POPs. The map only drags one from a POP, but a typed order (the agent API) names both ends. function linkFromWhy(a){return S.pops[a]?'':tr('action_helpers.you_have_no_pop_in_city',{city:CITY[a].name});} function linkFromOk(a){const w=linkFromWhy(a);if(w){toast(w,'bad');sfx('err');}return !w;} +// ...and ends at a city you could build a POP in (#203): a typed order can name one the map does not show. +function linkToOk(b){if(S.pops[b]||cityOn(b))return true;toast(popOffWhy(b),'bad');sfx('err');return false;} // A retired small city (off: true) takes no new POP; the nearest open city in its country stands in for it. function popOffWhy(c){const C=CITY[c],near=CITIES.filter(o=>!o.off&&o.cc===C.cc).sort((x,y)=>kmBetween(c,x.id)-kmBetween(c,y.id))[0]; return tr('action_helpers.city_is_off_the_map_small',{city:C.name,near:near?near.name:''});} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 4e488d9..0880551 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -115,7 +115,7 @@ 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}

`; if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); - 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&&l.sub?layPanel(l):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')}

`;} + 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&&l.sub?layPanel(l):l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash${!crewSteps(l)&&l.ready>S.day+1?`

${tr('link_panels.crews_can_halve_a_build_at_most')}

`:''}`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

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

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${shipNote(inc)}${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)}
${seatPanel(l)}${l.own&&l.sub?`
${tr('common.cable_design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''} diff --git a/src/i18n/en.js b/src/i18n/en.js index 40031a8..ad8a9de 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2636,6 +2636,7 @@ "link_panels.abandon_the_fiber":"Abandon the fiber", "link_panels.add_parallel_link":"Add parallel link", "link_panels.additional_traffic_lost":"Additional traffic lost", +"link_panels.all_crews_done_in_n_days_price":{"one":"All the crews: done in {n} day {price}","other":"All the crews: done in {n} days {price}"}, "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_n_days":"Apply for a license {price} + {mo}/mo · ~{n} days", "link_panels.at_this_pop_net_s_traffic_always":"At this POP, {net}'s traffic always uses this port. POPs without one use their nearest transit port.", @@ -2652,6 +2653,7 @@ "link_panels.connected_but_tight":"Connected, but tight.", "link_panels.cost_on_this_link_w_allowed":"Cost on this link: {w}. Allowed: {lo} to {hi}.", "link_panels.cost_the_exact_number_whatever_the":"Cost: the exact number, whatever the distance.", +"link_panels.crews_can_halve_a_build_at_most":"Permits and rights of way set the pace: extra crews can cut a build to half its planned time, no further.", "link_panels.dark_fiber_kind_km_km":"Dark fiber · {kind} · {km} km", "link_panels.de_kicks_personalised_pricing_p_of":"DE-KICKS personalised pricing: {p}% of what a normal IX would charge (promo, {n} days left).", "link_panels.de_kicks_personalised_pricing_p_of_3d4f":"DE-KICKS personalised pricing: {p}% of what a normal IX would charge.", @@ -2659,7 +2661,6 @@ "link_panels.each_channel_is_a_pair_of":"Each channel is a pair of optics, one per end. ZR+ optics plug straight into your routers. Transponders sit on a shelf.", "link_panels.enters_your_network_at":"Enters your network at", "link_panels.every_pop_carries_net_s_traffic":"Every POP carries {net}'s traffic across your network to this port.", -"link_panels.finish_in_1_day_price":"Finish in 1 day {price}", "link_panels.foreign_networks_need_a_local_joint":"Foreign networks need a local joint venture and an operating license to build infrastructure here.", "link_panels.found_your_own_ix_cost_mo":"Found your own IX {cost} + {mo}/mo", "link_panels.full_links_during_the_test":"Full links during the test", diff --git a/tests/alien-wave-rent.test.js b/tests/alien-wave-rent.test.js new file mode 100644 index 0000000..9bd353e --- /dev/null +++ b/tests/alien-wave-rent.test.js @@ -0,0 +1,67 @@ +// #203: renting out alien waves was a money machine. A wave is now priced against what the fiber itself costs, and gets +// cheaper as a route fills; extra crews cut a build to half its planned time at most; a typed order cannot end a link +// in a city the map does not show. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const fiber = (ev, id, a, b, km) => ev(`S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:true,sys:'cl',ch:[],km:${km},ready:0,day:0,cut:0,mo:1,trench:'own:${id}',pairs:1})`); +const sell = (ev, id) => ev(`(()=>{const l=S.links.find(x=>x.id==='${id}'),r=wwRate(l,1);S.biz.push({id:uid(),type:'wwave',link:l.id,slots:1,rate:r,city:l.a,city2:l.b,name:'n'+S.biz.length,bw:1,mood:80,since:0,reqs:[]});return r})()`); + +test('#203 an alien wave rents for a share of the fiber, and each one sold on a route makes the next cheaper', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.biz=[];S.offers=[];for(const c of ['lon','nyc'])if(!S.pops[c])ACT.buildPop({city:c})"); + fiber(ev, 'f', 'lon', 'nyc', 5570); + const F = ev('dfLeaseMo(5570)+ampCount(5570)*AMP_MO'), M = ev("brMarket('lon','nyc')"); + const rates = []; + for (let i = 0; i < M; i++) rates.push(sell(ev, 'f')); + assert.ok(rates[0] <= 0.3 * F + 1, `the first wave costs at most 30% of the fiber: ${rates[0]} vs ${F}`); + for (let i = 1; i < rates.length; i++) assert.ok(rates[i] <= rates[i - 1], 'never dearer than the one before'); + assert.ok(rates.at(-1) < rates[0] * 0.45, 'the last waves of a full route go cheap'); + const full = rates.reduce((a, b) => a + b, 0); + assert.ok(full / F > 2 && full / F < 8, `a full route earns a few times its lease, not dozens: ${(full / F).toFixed(1)}×`); + // The old price: one wave cost about as much as the whole fiber, and a full route earned ~29× its lease. + assert.ok(full < ev(`Math.round(waveMo(5570,false,2)*0.55)*${M}`) / 3); + // A random offer and a broker sale on the same route follow the same price. + fiber(ev, 'g', 'lon', 'nyc', 5570); + ev("S.biz=[]"); + assert.equal(ev("(()=>{let n=0;const o=fiberOffer('wwave',S.links.find(l=>l.id==='g'),()=>'x');return o.rate===wwRate(S.links.find(l=>l.id==='g'),o.slots)})()"), true); + assert.deepEqual(errors, []); +}); + +test('#203 extra crews cut a build to half its planned time, no further', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;for(const c of ['fra','waw'])if(!S.pops[c])ACT.buildPop({city:c})"); + const km = Math.round(ev("kmBetween('fra','waw')")), days = ev(`dfBuildDays(${km})`); + ev(`S.links.push({id:'b',a:'fra',b:'waw',kind:'df',own:true,sys:'roadm',ch:[],km:${km},ready:S.day+${days},day:S.day,cut:0,mo:1,trench:'own:b',pairs:1});after();UI.sel={type:'link',id:'b'};renderPanel()`); + const start = ev('S.day'); + assert.match(ev("document.getElementById('panelBody').textContent"), new RegExp(`All the crews: done in ${Math.ceil(days / 2)} days`)); + const cash = ev('S.cash'); + ev("ACT.crews({id:'b',all:1})"); + assert.equal(ev("S.links.find(l=>l.id==='b').ready"), start + Math.ceil(days / 2), 'half the planned build'); + assert.ok(ev('S.cash') < cash); + const c2 = ev('S.cash'); + ev("ACT.crews({id:'b'});ACT.crews({id:'b',all:1})"); + assert.equal(ev('S.cash'), c2, 'no more crews to buy'); + ev('renderPanel()'); + const crews = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')]; + assert.ok(crews.length && crews.every((b) => b.disabled)); + assert.match(ev("document.getElementById('panelBody').textContent"), /half its planned time/); + // Phone: the panel still renders with the note. + ev("window.innerWidth=360;renderAll()"); + assert.deepEqual(errors, []); +}); + +test('#203 a dark fiber, cable or wave cannot be ordered to a city the map does not show', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6"); + ev("ACT.buildPop({city:'sao'})"); + const home = 'sao', off = ev("(()=>{const c=CITIES.find(c=>c.off&&!cityOn(c.id)&&dfAllowed('sao',c.id));return c?c.id:null})()"); + assert.ok(off, 'there is a hidden city to try'); + const pops = ev('Object.keys(S.pops).length'); + ev(`UI.pending={a:'${home}',b:'${off}'};UI.dfSrc='lease';UI.dfSys='lite';ACT.orderDf()`); + ev(`UI.pending={a:'${home}',b:'${off}'};ACT.buildLink({tier:0})`); + assert.equal(ev('Object.keys(S.pops).length'), pops, 'no POP appears there'); + assert.equal(ev(`S.links.some(l=>l.b==='${off}'||l.a==='${off}')`), false); + assert.deepEqual(errors, []); +}); diff --git a/tests/cable-ships.test.js b/tests/cable-ships.test.js index 5d00697..aea5daa 100644 --- a/tests/cable-ships.test.js +++ b/tests/cable-ships.test.js @@ -187,7 +187,7 @@ test('your own subsea cable: survey and factory first, then a lay ship; a second assert.match(panel(), /Survey, permits and the cable factory/); assert.match(panel(), /Laying starts in 560 days/); assert.match(panel(), /Book a second lay ship/); - assert.doesNotMatch(panel(), /Hire extra crews|Finish in 1 day/); + assert.doesNotMatch(panel(), /Hire extra crews|All the crews/); const cash = ev('S.cash'); ev("ACT.crews({id:'own'})"); assert.equal(ev('S.cash'), cash, 'no crews at sea'); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index e40b5fa..bc0a0e1 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -412,6 +412,31 @@ test('F5: rented capacity never outgrows the route\'s market (#203)', () => { assert.deepEqual(g.errors, []); }); +test('F6: an alien wave is priced against its fiber, and a full route earns a few times its lease (#203)', () => { + const g = load(); + g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.biz=[];S.offers=[]"); + for (const [a, b] of [['lon', 'par'], ['lon', 'nyc'], ['fra', 'sin'], ['nyc', 'sjc'], ['jed', 'gdx']]) { + const r = JSON.parse(g.ev(`(()=>{const l={id:'f6${a}${b}',a:'${a}',b:'${b}',kind:'df',own:true,sys:'cl',ch:[],km:Math.round(kmBetween('${a}','${b}')),ready:0,day:0,cut:0,mo:1,pairs:2};S.links.push(l); + const F=dfLeaseMo(l.km)+ampCount(l.km)*AMP_MO,M=brMarket(l.a,l.b),rs=[]; + for(let i=0;i x + y, 0); + assert.ok(full < 8 * r.F, `F6: ${a}-${b} full route ${(full / r.F).toFixed(1)}× its lease`); + } + assert.deepEqual(g.errors, []); +}); + +test('F7: extra crews cut a build on land to half its planned time at most (#203)', () => { + const g = load(); + g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e11;S.lvl=4;for(const c of ['fra','mad'])if(!S.pops[c])ACT.buildPop({city:c})"); + const km = Math.round(g.ev("kmBetween('fra','mad')")), days = g.ev(`dfBuildDays(${km})`), d0 = g.ev('S.day'); + g.ev(`S.links.push({id:'f7',a:'fra',b:'mad',kind:'df',own:true,sys:'roadm',ch:[],km:${km},ready:S.day+${days},day:S.day,cut:0,mo:1,trench:'own:f7',pairs:1});ACT.crews({id:'f7',all:1});for(let i=0;i<50;i++)ACT.crews({id:'f7'})`); + assert.ok(g.ev("S.links.find(l=>l.id==='f7').ready") - d0 >= days / 2, 'F7: never under half the planned build'); + assert.deepEqual(g.errors, []); +}); + // D1–D4: DDoS as networks see it (#242). tests/ddos-model.test.js plays each one in detail. const ddFra = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.rgen=RG.findIndex(r=>r.fsN===8);S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:10,rate:1,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'D',city:'fra',bw:5,rate:1,mood:80,since:0,reqs:[]});compute()"); const ddHit = (ev, g) => ev(`S.ev.ddos={id:'x',city:'fra',tgt:'g',vec:'dns',gbps:${g},start:S.day,until:S.day+2,bh:false};compute()`); diff --git a/tests/issues.test.js b/tests/issues.test.js index 09271f2..c2e22ad 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -1267,7 +1267,7 @@ test('#51 a dark fiber shows what is rented out, and spare capacity can be liste ev("for(let i=0;i<120&&!S.biz.some(b=>b.link==='df1');i++)brTick();renderPanel()"); const b = JSON.parse(ev("JSON.stringify(S.biz.find(x=>x.link==='df1'))")); assert.equal(b.type, 'wwave'); - assert.equal(b.rate, ev(`Math.round(waveMo(450,false,2)*0.55*${b.slots}*0.9)`), 'the usual alien-wave price minus the broker'); + assert.equal(b.rate, ev(`(()=>{const F=dfLeaseMo(450)+ampCount(450)*AMP_MO,M=brMarket('fra','ams');let r=0;for(let i=0;i<${b.slots};i++)r+=F*WW_SHARE*(1-WW_FALL*Math.min(1,i/M));return Math.round(r*0.9)})()`), 'the alien-wave price, priced against the fiber, minus the broker'); assert.ok(txt().includes(b.name), 'the customer is listed on the fiber'); assert.match(txt(), new RegExp(`Free channels\\s*${62 - b.slots} / 64`)); assert.equal(ev("S.links[0].list?S.links[0].list.w:0"), 4 - b.slots, 'the listing shrinks by what sold'); diff --git a/tests/subsea-upgrade-timing.test.js b/tests/subsea-upgrade-timing.test.js index 77a7bde..30e26b2 100644 --- a/tests/subsea-upgrade-timing.test.js +++ b/tests/subsea-upgrade-timing.test.js @@ -8,6 +8,12 @@ function setup(ev, sub = true) { S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:${sub},sys:'roadm',km:15000,ch:[],day:100,ready:1000,cut:0,mo:1}];`); } +// Crews cut a land build to half its planned time at most (#203): plan these builds long enough that crews can still +// bring them to tomorrow, so the tests below check the price and the one-click purchase. +function plannedLong(ev) { + ev('S.links[0].day=101-Math.ceil(dfBuildDays(S.links[0].km)/2)'); +} + function dates(ev) { return JSON.parse(ev('JSON.stringify([S.links[0].ready,S.links[0].subterminal,S.links[0].subengineering])')); } @@ -126,6 +132,7 @@ test('one-click completion on land costs the same as repeated crew hires', () => const { ev, dom, errors } = load(); try { setup(ev, false); + plannedLong(ev); ev("UI.sel={type:'link',id:'cable'};renderPanel()"); const button = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all); assert.ok(button && !button.disabled, 'one-click option is available'); @@ -140,6 +147,7 @@ test('one-click completion on land costs the same as repeated crew hires', () => ev("ACT.crews({id:'cable',all:1})"); assert.equal(ev('S.cash'), bulkCash, 'repeat submission cannot charge again'); setup(ev, false); + plannedLong(ev); ev("for(let i=0;i<30;i++)ACT.crews({id:'cable'})"); assert.equal(ev('S.links[0].ready'), bulkReady); assert.equal(ev('S.cash'), bulkCash); @@ -156,6 +164,7 @@ test('one-click completion is atomic when unaffordable and handles short or comp const { ev, dom } = load(); try { setup(ev, false); + plannedLong(ev); 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); @@ -177,7 +186,9 @@ test('owned ground fiber exposes the one-click button and uses the same crew pri const { ev, dom, errors } = load(); try { setup(ev); - ev("ACT.buildPop({city:'ams'});Object.assign(S.links[0],{a:'fra',b:'ams',sub:false,km:800,ready:191});UI.sel={type:'link',id:'cable'};renderPanel()"); + ev("ACT.buildPop({city:'ams'});Object.assign(S.links[0],{a:'fra',b:'ams',sub:false,km:800,ready:191})"); + plannedLong(ev); + ev("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.ok(bulk && !bulk.disabled, 'ground construction has the same one-click control'); assert.ok(bulk.textContent.includes(ev('fmt$(3*(15000+800*6))')), '91 days remaining requires three hires'); From 8841fdacb98897313c4e3b30121b4a080d302915 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 08:15:46 +0100 Subject: [PATCH 338/491] Customers come and go: contracts, renewals at the market price, growth, haggles and leaving (#178) Every customer now signs for a term (enterprise and hosting 1-3 years, wholesale and circuits 2-5, fiber pairs 10-20). When it ends most renew at today's bandwidth price, happy ones often grow to the next size, a few with competitors around ask for a discount 30 days ahead (match, meet halfway or let go in Deals; no answer matches), and some leave: unhappy ones because of the service, others acquired, bust, insourced, moved (they stay if you have a POP there), multihomed, project ended, a cheaper bid, or now and then one of the odder reasons (never more than one every 60 days). The bandwidth market is flat for six months, then about 10% cheaper a year, slowed by dearer hardware, moving in a slow three-year cycle and pushed up during a shortage. New offers and renewals are priced in it; one renewal moves a price at most 25% down or 10% up. Nothing happens in a first term. Rolls are hashes of the customer and its term, never Math.random, so seeded games keep their stream. Old saves get renewals spread over the next year. Happy customers of a year or more send a referral about every six weeks. The dashboard's Customers tab shows customers won and lost each month and why, renewals due and the market; customer rows show the contract end. The differential fuzz now leaves out state fields only this checkout has, so a new feature's state does not fail the comparison with main while everything both games share must still match. --- CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 2 +- scripts/lib/fuzz-page.js | 13 +- scripts/lib/route-fuzz.js | 6 +- site/i18n/de.js | 78 +++++++ site/i18n/es.js | 78 +++++++ site/i18n/fr.js | 78 +++++++ site/i18n/it.js | 78 +++++++ site/i18n/pt.js | 78 +++++++ src/agent/20-commands.js | 6 + src/agent/30-docs.js | 5 +- src/game/10-catalog/30-supply-chain.js | 1 + src/game/60-features/37-fiber-broker.js | 2 +- src/game/80-simulation/50-sanitize.js | 4 +- .../80-simulation/75-customer-lifecycle.js | 148 ++++++++++++++ src/game/88-days/10-day-tick.js | 4 +- src/game/90-actions/50-customers.js | 12 +- src/game/93-ui/40-hud-and-panels.js | 6 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/94-dashboard/30-customers.js | 2 +- src/game/94-dashboard/60-dashboard.js | 2 +- src/i18n/en.js | 78 +++++++ tests/customer-lifecycle.test.js | 190 ++++++++++++++++++ tests/save-size.test.js | 4 +- 24 files changed, 859 insertions(+), 19 deletions(-) create mode 100644 src/game/80-simulation/75-customer-lifecycle.js create mode 100644 tests/customer-lifecycle.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e1dc2b2..bbfce26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Customers now sign contracts, and when one ends they renew, grow, haggle or leave, not always because of you (#178). Most renew at today's bandwidth price, which falls about 10% a year but rises when hardware is short; happy customers often take a bigger size, and some ask for a discount you can match, meet halfway or turn down in Deals. Others are acquired, go bust, build their own network, move away (they stay if you have a POP where they go), split their traffic with a second provider or end their project, and now and then one leaves for a stranger reason. Nothing changes during a customer's first contract, renewals in an old save are spread over the next year, your happiest long-time customers send you referrals, and the NOC dashboard shows customers won and lost each month and why. - Sweden gets Gothenburg, Malmö and Haparanda (#206). Gothenburg sits between Oslo and Copenhagen with its own exchange, Malmö faces Copenhagen across the Øresund, and Haparanda on the Finnish border is where the fibre crosses over land to Finland, with no exchange yet for you to found one. A Nordic fibre carrier sells transit along that route from Berlin to the border, and Swedish home networks reach the new cities. - The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. - Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f067aa0..1dbb155 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,7 +33,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `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 desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | -| `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service | +| `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service | | `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) | | `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` | | `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers | diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 71d5ca5..2070d32 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -154,8 +154,15 @@ return r + '\n' + fl + '\n' + pf; }; const parts = () => { const o = {}; if (!R) return o; for (const k of Object.keys(R)) o[k] = JSON.stringify(R[k]); o.fl = R.fl ? JSON.stringify(R.fl) : ''; return o; }; - const sDigest = () => JSON.stringify(S); - const sParts = () => { const o = {}; for (const k of Object.keys(S)) o[k] = JSON.stringify(S[k]); return o; }; + // A field only this checkout's game has (a new feature's state, on S or on its customers and offers) cannot match main + // yet: the driver passes those (drop) and they are left out; every field both games have must still match. + const sKeys = () => ({ top: Object.keys(S), items: [...new Set([...(S.biz || []), ...(S.offers || [])].flatMap((x) => Object.keys(x)))] }); + const sDrop = (drop) => { if (!drop || (!drop.top.length && !drop.items.length)) return S; const o = {}; + for (const k of Object.keys(S)) if (!drop.top.includes(k)) o[k] = S[k]; + for (const k of ['biz', 'offers']) if (Array.isArray(o[k])) o[k] = o[k].map((x) => { const y = {}; for (const f of Object.keys(x)) if (!drop.items.includes(f)) y[f] = x[f]; return y; }); + return o; }; + const sDigest = (drop) => JSON.stringify(sDrop(drop)); + const sParts = (drop) => { const s = sDrop(drop), o = {}; for (const k of Object.keys(s)) o[k] = JSON.stringify(s[k]); return o; }; /* After a move: what the move routed (a), routing again from the same state (b: on this checkout's page the kept tables are used), and routing from that state with the cache off (c: RC.on=false where there is an RC). b and c route from the same previous R; c's R is kept, as a plain compute would. */ @@ -170,5 +177,5 @@ if (keep) UI.rkR = R; return { a, b, c }; }; - window.__fz = { direct, lists, start, state, screen, press, close, poke, day, routing, parts, sDigest, sParts, check, errs, modalOpen }; + window.__fz = { direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen }; })(); diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index b5b5eb2..bbc1683 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -78,8 +78,10 @@ function playGame(pages, seed, opts = {}) { const [x, y] = both('check'); for (const k of ['a', 'b', 'c']) if (x[k] !== y[k]) { fail(where + ': routing (' + k + ') base vs head', { diff: firstDiff(base.call('parts'), head.call('parts')) }); return false; } if (y.b !== y.c) { fail(where + ': head cached vs uncached', { diff: 'R from the kept tables differs from a fresh route' }); return false; } - const [s1, s2] = both('sDigest'); - if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(base.call('sParts'), head.call('sParts')) }); return false; } + // Fields only this checkout's game has are left out on both sides (see sKeys in fuzz-page.js). + const [k1, k2] = both('sKeys'), drop = { top: k2.top.filter((k) => !k1.top.includes(k)), items: k2.items.filter((k) => !k1.items.includes(k)) }; + const [s1, s2] = both('sDigest', drop); + if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(base.call('sParts', drop), head.call('sParts', drop)) }); return false; } return true; }; diff --git a/site/i18n/de.js b/site/i18n/de.js index 159a8d4..248b069 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2605,6 +2605,84 @@ "lease_swaps.your_fiber_here_has_room_for":"Deine Glasfaser hier hat Platz für {free} weitere Kanäle, für den Umzug dieser Mieten brauchst du aber {n}. Beleuchte zuerst ein weiteres Faserpaar oder rüste das Line System auf.", "lease_swaps.your_own_cable_up_up_front":"Dein eigenes Kabel: {up} vorab, {mo}/Monat, etwa {n} Tage Bauzeit.", "lease_swaps.your_own_fiber_up_up_front":"Deine eigene Glasfaser: {up} vorab, {mo}/Monat, etwa {n} Tage Bauzeit.", +"lifecycle.acquired_stays_bigger":"{name} wurde übernommen und bleibt bei dir, größer: jetzt {bw}.", +"lifecycle.bandwidth_market":"Bandbreitenmarkt", +"lifecycle.bandwidth_prices":"Bandbreitenpreise", +"lifecycle.contract_until":"Vertrag bis {date}", +"lifecycle.haggle":"{name} ({city}) will für {price}/Monat verlängern, {p} weniger. Die Konkurrenz bietet mit. Antworte in den Deals innerhalb von {n} Tagen.", +"lifecycle.last_12_months":"letzte 12 Monate", +"lifecycle.left_acquired":"{name} wurde übernommen, und der Käufer zieht alles auf sein eigenes Netz um.", +"lifecycle.left_bust":"{name} ist pleite. Der Hype ist ohne sie weitergezogen.", +"lifecycle.left_cheaper":"{name} hat ein günstigeres Angebot der Konkurrenz in {city} angenommen.", +"lifecycle.left_insourced":"{name} ist groß genug für ein eigenes Backbone und peert künftig mit dir, statt zu kaufen.", +"lifecycle.left_moved":"{name} ist aus {city} weggezogen, an einen Ort ohne deinen POP.", +"lifecycle.left_multihomed":"{name} hat seinen ganzen Verkehr zu einem zweiten Anbieter verlegt.", +"lifecycle.left_odd":"{name} hat nicht verlängert. {why}", +"lifecycle.left_project_ended":"Das Projekt von {name} ist vorbei, und die Leitung geht mit.", +"lifecycle.left_unhappy":"{name} hat nicht verlängert: Der Service hat sie zu oft im Stich gelassen.", +"lifecycle.let_go":"{name} ist weg. Der Vertrag lief ohnehin aus.", +"lifecycle.let_them_go":"Ziehen lassen", +"lifecycle.lost":"Verloren", +"lifecycle.market_above":"{p} über deinem Start", +"lifecycle.market_as_start":"wie bei deinem Start", +"lifecycle.market_below":"{p} unter deinem Start", +"lifecycle.match":"Mitgehen", +"lifecycle.matched":"{name} hat zum gewünschten Preis verlängert.", +"lifecycle.meet_halfway":"In der Mitte treffen", +"lifecycle.meet_no":"{name} hat das Angebot der Konkurrenz genommen und ist weg.", +"lifecycle.meet_yes":"{name} hat dein Angebot angenommen und für {price}/Monat verlängert.", +"lifecycle.moved_stays":"{name} ist von {from} nach {to} gezogen, wo du einen POP hast, und bleibt also.", +"lifecycle.multihomed_keeps":"{name} hat die Hälfte seines Verkehrs zu einem zweiten Anbieter verlegt. Dir bleiben {bw}.", +"lifecycle.n_grew":{"one":"1 gewachsen","other":"{n} gewachsen"}, +"lifecycle.n_more":{"one":"…und 1 weiterer.","other":"…und {n} weitere."}, +"lifecycle.n_renewed":{"one":"1 Vertrag zu heutigen Preisen verlängert ({p}).","other":"{n} Verträge zu heutigen Preisen verlängert ({p})."}, +"lifecycle.next_30_days":"nächste 30 Tage", +"lifecycle.nobody_left_yet":"Bisher ist niemand gegangen.", +"lifecycle.odd_4g_dongle":"Die ganze Firma läuft jetzt über eine SaaS-App an einem 4G-Stick. Es funktioniert prima, und das ist das Schlimmste.", +"lifecycle.odd_95th":"Ihr CFO hat 95. Perzentil auf der Rechnung gesehen und glaubt, du berechnest die 95 schlimmsten Tage.", +"lifecycle.odd_alphabetical":"Ihr Rebranding-Budget ist aufgebraucht, also sparen sie alphabetisch, und du warst zuerst dran.", +"lifecycle.odd_asn_six":"Ihr neuer CTO traut nur ASNs mit genau drei Siebenen.", +"lifecycle.odd_bad_holiday":"Sie haben herausgefunden, dass du ihre Pakete durch eine Stadt leitest, in der sie mal einen miesen Urlaub hatten.", +"lifecycle.odd_bought_thrice":"Sie wurden von einer Firma gekauft, die von einer Firma gekauft wurde, die schon ein Netz hat. Niemand weiß, wer das Sagen hat.", +"lifecycle.odd_center":"Sie haben gelesen, dass Latenz zählt, und ziehen näher an die Mitte des Internets. Sie glauben, die liegt auf einem Feld auf dem Land.", +"lifecycle.odd_communities":"Sie sind zu einem Anbieter gewechselt, dessen BGP-Communities besser dokumentiert sind. Es gibt zwei davon.", +"lifecycle.odd_dead_beef":"Sie wollten eine IPv6-Adresse, die ihren Namen in Hex buchstabiert. :dead:beef war schon vergeben.", +"lifecycle.odd_espresso":"Die neue Espressomaschine im Büro lässt die Sicherung fliegen. Sie geben dem Router die Schuld, also dir.", +"lifecycle.odd_fewer_vendors":"Der neue CEO will weniger Lieferanten. Du warst der einzige. Jetzt haben sie keinen und sind begeistert.", +"lifecycle.odd_goat_farmer":"Die Person, die bei dir unterschrieben hat, ist Ziegenbäuerin geworden, und die Nachfolge macht alles anders.", +"lifecycle.odd_holiday_card":"Deine Weihnachtskarte kam pünktlich an. Das hat sie misstrauisch gemacht.", +"lifecycle.odd_landlord":"Ihr Vermieter kassiert pro Kabel durch die Wand, und deins ist dick und auffällig.", +"lifecycle.odd_looking_glass":"Dein Looking Glass war eine Stunde weg, und ihr NOC-Leiter hat das persönlich genommen.", +"lifecycle.odd_mate":"Dein Account Manager hat ihren Account Manager in einer Mail Kumpel genannt. Sie sind keine Kumpel.", +"lifecycle.odd_quadrant":"Ein Berater hat eine Folie mit einem Quadranten gemacht, und du warst im falschen.", +"lifecycle.odd_raccoon":"Ein Waschbär ist in ihren einzigen Schrank gezogen und scheint mit dem Cross-Connect eines anderen Carriers glücklicher.", +"lifecycle.odd_rdns":"Dein Reverse-DNS für ihre IP lautet customer-cheapskate-04. Jemand aus ihrem Team hat es bemerkt.", +"lifecycle.odd_space":"Sie haben auf eine KI-native, blockchainbasierte Satellite-first-Strategie umgeschwenkt, und deine Faser ist nicht im All.", +"lifecycle.odd_spreadsheet_cell":"Neue Regel im Einkauf: Jeder Lieferantenname muss ohne Umbruch in eine Tabellenzelle passen.", +"lifecycle.odd_the_cloud":"Sie ziehen alles in die Cloud. Die Cloud ist ein Rack zwei Straßen weiter, angebunden von dir. Sie haben es noch nicht gemerkt.", +"lifecycle.odd_too_many_feet":"Ihr Praktikant hat zum Angeben ein Traceroute gemacht, 14 Hops gesehen und erklärt, das seien zu viele Füße.", +"lifecycle.odd_wireguard":"Sie gehen komplett remote. Alle 40 Leute fahren WireGuard aus ihren Küchen, und die Büroleitung ist nur noch für die Pflanzen.", +"lifecycle.odd_wrong_blue":"Die neue Büroleitung will alle Kabel in derselben Farbe, und deins ist das falsche Blau.", +"lifecycle.referred_by":"Empfohlen von {name}, einem deiner zufriedensten Kunden.", +"lifecycle.renewal_haggle":"Verlängerung am {date}: wird verhandelt", +"lifecycle.renewals":"Verlängerungen", +"lifecycle.renewals_soon":"Verlängerungen", +"lifecycle.renewed_and_grew":"{name} hat verlängert und auf {bw} aufgestockt ({city}).", +"lifecycle.unanswered_matches":"Ohne Antwort bis Vertragsende gehst du auf ihren Preis ein.", +"lifecycle.wants_price":"Zahlt {was}/Monat, will für {price}/Monat ({p} weniger) verlängern.", +"lifecycle.why_acquired":"Übernommen", +"lifecycle.why_bust":"Pleite", +"lifecycle.why_cheaper_bid":"Günstigeres Angebot", +"lifecycle.why_insourced":"Eigenes Netz gebaut", +"lifecycle.why_moved":"Weggezogen", +"lifecycle.why_multihomed":"Zu einem zweiten Anbieter", +"lifecycle.why_other":"Andere Gründe", +"lifecycle.why_project_ended":"Projekt beendet", +"lifecycle.why_they_left":"Warum sie gingen", +"lifecycle.why_unhappy":"Unzufrieden mit dem Service", +"lifecycle.won":"Gewonnen", +"lifecycle.won_and_lost":"Gewonnene und verlorene Kunden", +"lifecycle.won_and_lost_note":"Verträge laufen ein bis fünf Jahre, Faserpaare zehn bis zwanzig. Läuft einer aus, verlängern die meisten zum heutigen Marktpreis, und zufriedene wachsen oft. Manche gehen, und nicht immer deinetwegen.", "link_modal.building_into_mainland_china_needs_a":"Für den Ausbau nach Festlandchina brauchst du ein Joint Venture und eine Betriebslizenz. Öffne {city}, um sie zu beantragen.", "link_modal.cross_border_circuits_into_mainland":"Grenzüberschreitende Verbindungen nach Festlandchina verkaufen nur lizenzierte Carrier, zum dreifachen Preis. Normale verlieren an der Grenze etwa 20 % des Traffics.", "link_modal.diverse_route_40_survives_cuts_alone":"Redundante Route +40 % · übersteht Schnitte allein", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6b51464..2bcc245 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2603,6 +2603,84 @@ "lease_swaps.your_fiber_here_has_room_for":"Tu fibra de aquí tiene sitio para {free} canales más, y mover estos alquileres necesita {n}. Ilumina otro par de fibra o mejora antes el sistema de línea.", "lease_swaps.your_own_cable_up_up_front":"Tu propio cable: {up} por adelantado, {mo}/mes, unos {n} días de obra.", "lease_swaps.your_own_fiber_up_up_front":"Tu propia fibra: {up} por adelantado, {mo}/mes, unos {n} días de obra.", +"lifecycle.acquired_stays_bigger":"{name} fue adquirida y se queda contigo, más grande: ahora {bw}.", +"lifecycle.bandwidth_market":"Mercado de ancho de banda", +"lifecycle.bandwidth_prices":"Precios del ancho de banda", +"lifecycle.contract_until":"contrato hasta {date}", +"lifecycle.haggle":"{name} ({city}) quiere {price}/mes para renovar, un {p} menos. La competencia está pujando. Responde en Ofertas en {n} días.", +"lifecycle.last_12_months":"últimos 12 meses", +"lifecycle.left_acquired":"{name} fue adquirida, y el comprador lo pasa todo a su propia red.", +"lifecycle.left_bust":"{name} quebró. El hype siguió sin ellos.", +"lifecycle.left_cheaper":"{name} aceptó una oferta más barata de un competidor en {city}.", +"lifecycle.left_insourced":"{name} creció lo bastante para montar su propia red troncal, y ahora hará peering contigo en vez de comprar.", +"lifecycle.left_moved":"{name} se mudó de {city} a un lugar donde no tienes POP.", +"lifecycle.left_multihomed":"{name} pasó todo su tráfico a un segundo proveedor.", +"lifecycle.left_odd":"{name} no renovó. {why}", +"lifecycle.left_project_ended":"El proyecto de {name} terminó, y el circuito se va con él.", +"lifecycle.left_unhappy":"{name} no renovó: el servicio les falló demasiadas veces.", +"lifecycle.let_go":"{name} se fue. Su contrato terminaba de todos modos.", +"lifecycle.let_them_go":"Dejarlos ir", +"lifecycle.lost":"Perdidos", +"lifecycle.market_above":"{p} por encima de cuando empezaste", +"lifecycle.market_as_start":"como cuando empezaste", +"lifecycle.market_below":"{p} por debajo de cuando empezaste", +"lifecycle.match":"Igualar", +"lifecycle.matched":"{name} renovó al precio que pidió.", +"lifecycle.meet_halfway":"Partir la diferencia", +"lifecycle.meet_no":"{name} aceptó la oferta de la competencia y se fue.", +"lifecycle.meet_yes":"{name} aceptó tu oferta y renovó por {price}/mes.", +"lifecycle.moved_stays":"{name} se mudó de {from} a {to}, donde tienes POP, así que se queda.", +"lifecycle.multihomed_keeps":"{name} pasó la mitad de su tráfico a un segundo proveedor. Te quedas con {bw}.", +"lifecycle.n_grew":{"one":"1 creció","other":"{n} crecieron"}, +"lifecycle.n_more":{"one":"…y 1 más.","other":"…y {n} más."}, +"lifecycle.n_renewed":{"one":"1 contrato renovado a precios de hoy ({p}).","other":"{n} contratos renovados a precios de hoy ({p})."}, +"lifecycle.next_30_days":"próximos 30 días", +"lifecycle.nobody_left_yet":"Todavía no se ha ido nadie.", +"lifecycle.odd_4g_dongle":"Toda la empresa funciona ahora con una app SaaS por un pincho 4G. Funciona bien, que es lo peor.", +"lifecycle.odd_95th":"Su director financiero vio percentil 95 en la factura y cree que les cobras los 95 peores días.", +"lifecycle.odd_alphabetical":"Se les acabó el presupuesto del rebranding, así que recortan gastos por orden alfabético, y tú salías primero.", +"lifecycle.odd_asn_six":"Su nuevo CTO solo se fía de los ASN con exactamente tres sietes.", +"lifecycle.odd_bad_holiday":"Descubrieron que enrutas sus paquetes por una ciudad donde una vez tuvieron unas malas vacaciones.", +"lifecycle.odd_bought_thrice":"Los compró una empresa a la que compró una empresa que ya tiene red. Nadie sabe quién manda.", +"lifecycle.odd_center":"Leyeron que la latencia importa, así que se mudan más cerca del centro de internet. Creen que está en un campo en las afueras.", +"lifecycle.odd_communities":"Se pasaron a un proveedor cuyas comunidades BGP están mejor documentadas. Tiene dos.", +"lifecycle.odd_dead_beef":"Querían una dirección IPv6 que deletreara su nombre en hexadecimal. :dead:beef ya estaba ocupada.", +"lifecycle.odd_espresso":"La nueva cafetera de la oficina hace saltar los plomos. Le echan la culpa al router, así que a ti.", +"lifecycle.odd_fewer_vendors":"El nuevo CEO quiere menos proveedores. Tú eras el único. Ahora no tienen ninguno y están encantados.", +"lifecycle.odd_goat_farmer":"La persona que firmó contigo se fue a criar cabras, y su sustituto hace las cosas de otra manera.", +"lifecycle.odd_holiday_card":"Tu tarjeta de felicitación llegó a tiempo. Eso les hizo sospechar.", +"lifecycle.odd_landlord":"Su casero cobra por cada cable que atraviesa la pared, y el tuyo es grueso y llamativo.", +"lifecycle.odd_looking_glass":"Tu looking glass estuvo caído una hora, y su jefe de NOC se lo tomó como algo personal.", +"lifecycle.odd_mate":"Tu gestor de cuenta llamó colega a su gestor de cuenta en un correo. No son colegas.", +"lifecycle.odd_quadrant":"Un consultor hizo una diapositiva con un cuadrante, y tú estabas en el equivocado.", +"lifecycle.odd_raccoon":"Un mapache se instaló en su único armario, y parece más contento con el cross-connect de otro operador.", +"lifecycle.odd_rdns":"Tu DNS inverso para su IP dice customer-cheapskate-04. Alguien de su equipo se dio cuenta.", +"lifecycle.odd_space":"Giraron a una estrategia nativa de IA, respaldada por blockchain y con el satélite primero, y tu fibra no está en el espacio.", +"lifecycle.odd_spreadsheet_cell":"Nueva norma de compras: el nombre de cada proveedor debe caber en una celda sin saltar de línea.", +"lifecycle.odd_the_cloud":"Lo están pasando todo a la nube. La nube es un rack a dos calles, conectado por ti. Aún no se han dado cuenta.", +"lifecycle.odd_too_many_feet":"Su becario hizo un traceroute para lucirse, vio 14 saltos y declaró que eran demasiados pies.", +"lifecycle.odd_wireguard":"Se pasan al teletrabajo total. Los 40 empleados usarán WireGuard desde sus cocinas, y la línea de la oficina es solo para las plantas.", +"lifecycle.odd_wrong_blue":"La nueva responsable de oficina quiere todos los cables del mismo color, y el tuyo es del azul equivocado.", +"lifecycle.referred_by":"Recomendado por {name}, uno de tus clientes más contentos.", +"lifecycle.renewal_haggle":"renovación el {date}: negociando", +"lifecycle.renewals":"Renovaciones", +"lifecycle.renewals_soon":"Renovaciones", +"lifecycle.renewed_and_grew":"{name} renovó y creció a {bw} ({city}).", +"lifecycle.unanswered_matches":"Si no respondes antes de que acabe el contrato, igualas su precio.", +"lifecycle.wants_price":"Paga {was}/mes, quiere {price}/mes ({p} menos) para renovar.", +"lifecycle.why_acquired":"Adquiridos", +"lifecycle.why_bust":"Quebraron", +"lifecycle.why_cheaper_bid":"Oferta más barata", +"lifecycle.why_insourced":"Montaron su propia red", +"lifecycle.why_moved":"Se mudaron", +"lifecycle.why_multihomed":"Se fueron a otro proveedor", +"lifecycle.why_other":"Otros motivos", +"lifecycle.why_project_ended":"Proyecto terminado", +"lifecycle.why_they_left":"Por qué se fueron", +"lifecycle.why_unhappy":"Descontentos con el servicio", +"lifecycle.won":"Ganados", +"lifecycle.won_and_lost":"Clientes ganados y perdidos", +"lifecycle.won_and_lost_note":"Los contratos duran de uno a cinco años, los pares de fibra de diez a veinte. Cuando uno termina, la mayoría renueva al precio de mercado de hoy y los contentos suelen crecer. Algunos se van, y no siempre por tu culpa.", "link_modal.building_into_mainland_china_needs_a":"Construir en China continental necesita una empresa conjunta y una licencia de operación. Abre {city} para solicitarla.", "link_modal.cross_border_circuits_into_mainland":"Los circuitos transfronterizos hacia China continental solo los venden operadores con licencia, a 3× el precio. Los normales pierden cerca del 20 % del tráfico en la frontera.", "link_modal.diverse_route_40_survives_cuts_alone":"Ruta diversa +40 % · sobrevive a cortes sola", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c530438..eefbefc 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2603,6 +2603,84 @@ "lease_swaps.your_fiber_here_has_room_for":"Ta fibre ici a de la place pour {free} canaux de plus, et transférer ces locations en demande {n}. Allume d’abord une autre paire de fibres ou mets à niveau le système de ligne.", "lease_swaps.your_own_cable_up_up_front":"Ton propre câble : {up} d’entrée, {mo}/mois, environ {n} jours de travaux.", "lease_swaps.your_own_fiber_up_up_front":"Ta propre fibre : {up} d’entrée, {mo}/mois, environ {n} jours de travaux.", +"lifecycle.acquired_stays_bigger":"{name} a été rachetée et reste chez vous, en plus gros : {bw} désormais.", +"lifecycle.bandwidth_market":"Marché de la bande passante", +"lifecycle.bandwidth_prices":"Prix de la bande passante", +"lifecycle.contract_until":"contrat jusqu'au {date}", +"lifecycle.haggle":"{name} ({city}) veut {price}/mois pour renouveler, soit {p} de moins. La concurrence fait des offres. Répondez dans Offres d'ici {n} jours.", +"lifecycle.last_12_months":"12 derniers mois", +"lifecycle.left_acquired":"{name} a été rachetée, et l'acheteur bascule tout sur son propre réseau.", +"lifecycle.left_bust":"{name} a fait faillite. La hype est passée à autre chose sans eux.", +"lifecycle.left_cheaper":"{name} a accepté une offre moins chère d'un concurrent à {city}.", +"lifecycle.left_insourced":"{name} est devenue assez grande pour construire son propre backbone, et fera du peering avec vous au lieu d'acheter.", +"lifecycle.left_moved":"{name} a quitté {city} pour un endroit où vous n'avez pas de POP.", +"lifecycle.left_multihomed":"{name} a basculé tout son trafic chez un second fournisseur.", +"lifecycle.left_odd":"{name} n'a pas renouvelé. {why}", +"lifecycle.left_project_ended":"Le projet de {name} est terminé, et le circuit part avec.", +"lifecycle.left_unhappy":"{name} n'a pas renouvelé : le service les a trop souvent déçus.", +"lifecycle.let_go":"{name} est partie. Son contrat arrivait à échéance de toute façon.", +"lifecycle.let_them_go":"Les laisser partir", +"lifecycle.lost":"Perdus", +"lifecycle.market_above":"{p} au-dessus de vos débuts", +"lifecycle.market_as_start":"comme à vos débuts", +"lifecycle.market_below":"{p} en dessous de vos débuts", +"lifecycle.match":"S'aligner", +"lifecycle.matched":"{name} a renouvelé au prix demandé.", +"lifecycle.meet_halfway":"Couper la poire en deux", +"lifecycle.meet_no":"{name} a pris l'offre du concurrent et est partie.", +"lifecycle.meet_yes":"{name} a accepté votre offre et renouvelé à {price}/mois.", +"lifecycle.moved_stays":"{name} a déménagé de {from} à {to}, où vous avez un POP : elle reste.", +"lifecycle.multihomed_keeps":"{name} a basculé la moitié de son trafic chez un second fournisseur. Il vous reste {bw}.", +"lifecycle.n_grew":{"one":"1 a grossi","other":"{n} ont grossi"}, +"lifecycle.n_more":{"one":"…et 1 autre.","other":"…et {n} autres."}, +"lifecycle.n_renewed":{"one":"1 contrat renouvelé aux prix du jour ({p}).","other":"{n} contrats renouvelés aux prix du jour ({p})."}, +"lifecycle.next_30_days":"30 prochains jours", +"lifecycle.nobody_left_yet":"Personne n'est encore parti.", +"lifecycle.odd_4g_dongle":"Toute l'entreprise tourne désormais sur une appli SaaS via une clé 4G. Ça marche très bien, et c'est le pire.", +"lifecycle.odd_95th":"Leur directeur financier a vu 95e centile sur la facture et croit que vous facturez les 95 pires jours.", +"lifecycle.odd_alphabetical":"Leur budget de changement d'image est épuisé, alors ils réduisent les coûts par ordre alphabétique, et vous êtes arrivé en premier.", +"lifecycle.odd_asn_six":"Leur nouveau CTO ne fait confiance qu'aux ASN qui contiennent exactement trois 7.", +"lifecycle.odd_bad_holiday":"Ils ont découvert que vous faites passer leurs paquets par une ville où ils ont passé de mauvaises vacances.", +"lifecycle.odd_bought_thrice":"Ils ont été rachetés par une entreprise rachetée par une entreprise qui a déjà un réseau. Personne ne sait qui commande.", +"lifecycle.odd_center":"Ils ont lu que la latence compte, alors ils se rapprochent du centre d'Internet. Ils pensent qu'il est dans un champ à la campagne.", +"lifecycle.odd_communities":"Ils sont passés chez un fournisseur dont les communautés BGP sont mieux documentées. Il y en a deux.", +"lifecycle.odd_dead_beef":"Ils voulaient une adresse IPv6 qui épelle leur nom en hexadécimal. :dead:beef était déjà prise.", +"lifecycle.odd_espresso":"La nouvelle machine à espresso du bureau fait sauter le disjoncteur. Ils accusent le routeur, donc vous.", +"lifecycle.odd_fewer_vendors":"Le nouveau PDG veut moins de fournisseurs. Vous étiez le seul. Ils n'en ont plus aucun, et sont ravis.", +"lifecycle.odd_goat_farmer":"La personne qui avait signé avec vous est partie élever des chèvres, et son remplaçant fait les choses autrement.", +"lifecycle.odd_holiday_card":"Votre carte de vœux est arrivée à l'heure. Ça les a rendus méfiants.", +"lifecycle.odd_landlord":"Leur propriétaire facture chaque câble qui traverse le mur, et le vôtre est épais et voyant.", +"lifecycle.odd_looking_glass":"Votre looking glass a été en panne une heure, et leur chef de NOC l'a pris personnellement.", +"lifecycle.odd_mate":"Votre chargé de compte a appelé leur chargé de compte mon pote dans un e-mail. Ils ne sont pas potes.", +"lifecycle.odd_quadrant":"Un consultant a fait une diapo avec un quadrant, et vous étiez dans le mauvais.", +"lifecycle.odd_raccoon":"Un raton laveur s'est installé dans leur unique baie, et il semble préférer le cross-connect d'un autre opérateur.", +"lifecycle.odd_rdns":"Votre DNS inverse pour leur IP indique customer-cheapskate-04. Quelqu'un de leur équipe l'a remarqué.", +"lifecycle.odd_space":"Ils ont pivoté vers une stratégie IA-native, adossée à la blockchain et satellite d'abord, et votre fibre n'est pas dans l'espace.", +"lifecycle.odd_spreadsheet_cell":"Nouvelle règle des achats : le nom de chaque fournisseur doit tenir dans une cellule de tableur sans retour à la ligne.", +"lifecycle.odd_the_cloud":"Ils migrent tout vers le cloud. Le cloud est une baie à deux rues de là, raccordée par vous. Ils ne l'ont pas encore remarqué.", +"lifecycle.odd_too_many_feet":"Leur stagiaire a lancé un traceroute pour frimer, a vu 14 sauts et a déclaré que ça faisait trop de pieds.", +"lifecycle.odd_wireguard":"Ils passent en télétravail complet. Les 40 salariés utiliseront WireGuard depuis leur cuisine, et la ligne du bureau ne sert plus qu'aux plantes.", +"lifecycle.odd_wrong_blue":"La nouvelle responsable des locaux veut tous les câbles de la même couleur, et le vôtre n'est pas le bon bleu.", +"lifecycle.referred_by":"Recommandé par {name}, l'un de vos clients les plus satisfaits.", +"lifecycle.renewal_haggle":"renouvellement le {date} : en négociation", +"lifecycle.renewals":"Renouvellements", +"lifecycle.renewals_soon":"Renouvellements", +"lifecycle.renewed_and_grew":"{name} a renouvelé et passe à {bw} ({city}).", +"lifecycle.unanswered_matches":"Sans réponse avant la fin du contrat, vous vous alignez sur leur prix.", +"lifecycle.wants_price":"Paie {was}/mois, veut {price}/mois ({p} de moins) pour renouveler.", +"lifecycle.why_acquired":"Rachetés", +"lifecycle.why_bust":"Faillite", +"lifecycle.why_cheaper_bid":"Offre moins chère", +"lifecycle.why_insourced":"Ont construit leur réseau", +"lifecycle.why_moved":"Ont déménagé", +"lifecycle.why_multihomed":"Partis chez un second fournisseur", +"lifecycle.why_other":"Autres raisons", +"lifecycle.why_project_ended":"Projet terminé", +"lifecycle.why_they_left":"Pourquoi ils sont partis", +"lifecycle.why_unhappy":"Mécontents du service", +"lifecycle.won":"Gagnés", +"lifecycle.won_and_lost":"Clients gagnés et perdus", +"lifecycle.won_and_lost_note":"Les contrats durent de un à cinq ans, les paires de fibre de dix à vingt. À l'échéance, la plupart renouvellent au prix du marché du jour et les clients satisfaits grossissent souvent. Certains partent, et pas toujours à cause de vous.", "link_modal.building_into_mainland_china_needs_a":"Construire en Chine continentale exige une coentreprise et une licence d’opérateur. Ouvre {city} pour faire la demande.", "link_modal.cross_border_circuits_into_mainland":"Les circuits transfrontaliers vers la Chine continentale ne sont vendus que par des opérateurs titulaires d’une licence, à 3× le prix. Les circuits normaux perdent environ 20 % du trafic à la frontière.", "link_modal.diverse_route_40_survives_cuts_alone":"Chemin diversifié +40 % · survit seul aux coupures", diff --git a/site/i18n/it.js b/site/i18n/it.js index e37fafe..e75fe8d 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2603,6 +2603,84 @@ "lease_swaps.your_fiber_here_has_room_for":"La tua fibra qui ha spazio per altri {free} canali, e spostare questi affitti ne richiede {n}. Prima accendi un'altra coppia di fibre o aggiorna il line system.", "lease_swaps.your_own_cable_up_up_front":"Il tuo cavo: {up} subito, {mo}/mese, circa {n} giorni di lavori.", "lease_swaps.your_own_fiber_up_up_front":"La tua fibra: {up} subito, {mo}/mese, circa {n} giorni di lavori.", +"lifecycle.acquired_stays_bigger":"{name} è stata acquisita e resta con te, più grande: ora {bw}.", +"lifecycle.bandwidth_market":"Mercato della banda", +"lifecycle.bandwidth_prices":"Prezzi della banda", +"lifecycle.contract_until":"contratto fino al {date}", +"lifecycle.haggle":"{name} ({city}) vuole {price}/mese per rinnovare, il {p} in meno. La concorrenza fa offerte. Rispondi nelle Offerte entro {n} giorni.", +"lifecycle.last_12_months":"ultimi 12 mesi", +"lifecycle.left_acquired":"{name} è stata acquisita, e chi l'ha comprata sposta tutto sulla propria rete.", +"lifecycle.left_bust":"{name} è fallita. L'hype è andato avanti senza di loro.", +"lifecycle.left_cheaper":"{name} ha accettato un'offerta più economica di un concorrente a {city}.", +"lifecycle.left_insourced":"{name} è diventata abbastanza grande da costruirsi la propria dorsale, e farà peering con te invece di comprare.", +"lifecycle.left_moved":"{name} si è trasferita da {city} in un posto dove non hai un POP.", +"lifecycle.left_multihomed":"{name} ha spostato tutto il suo traffico su un secondo fornitore.", +"lifecycle.left_odd":"{name} non ha rinnovato. {why}", +"lifecycle.left_project_ended":"Il progetto di {name} è finito, e il circuito se ne va con lui.", +"lifecycle.left_unhappy":"{name} non ha rinnovato: il servizio li ha delusi troppe volte.", +"lifecycle.let_go":"{name} se n'è andata. Il contratto scadeva comunque.", +"lifecycle.let_them_go":"Lasciarli andare", +"lifecycle.lost":"Persi", +"lifecycle.market_above":"{p} sopra a quando hai iniziato", +"lifecycle.market_as_start":"come quando hai iniziato", +"lifecycle.market_below":"{p} sotto a quando hai iniziato", +"lifecycle.match":"Accettare", +"lifecycle.matched":"{name} ha rinnovato al prezzo richiesto.", +"lifecycle.meet_halfway":"Venirsi incontro", +"lifecycle.meet_no":"{name} ha preso l'offerta del concorrente e se n'è andata.", +"lifecycle.meet_yes":"{name} ha accettato la tua offerta e rinnovato a {price}/mese.", +"lifecycle.moved_stays":"{name} si è trasferita da {from} a {to}, dove hai un POP, quindi resta.", +"lifecycle.multihomed_keeps":"{name} ha spostato metà del traffico su un secondo fornitore. A te restano {bw}.", +"lifecycle.n_grew":{"one":"1 è cresciuto","other":"{n} sono cresciuti"}, +"lifecycle.n_more":{"one":"…e 1 altro.","other":"…e altri {n}."}, +"lifecycle.n_renewed":{"one":"1 contratto rinnovato ai prezzi di oggi ({p}).","other":"{n} contratti rinnovati ai prezzi di oggi ({p})."}, +"lifecycle.next_30_days":"prossimi 30 giorni", +"lifecycle.nobody_left_yet":"Finora non se n'è andato nessuno.", +"lifecycle.odd_4g_dongle":"Tutta l'azienda ora gira su un'app SaaS con una chiavetta 4G. Funziona benissimo, ed è la parte peggiore.", +"lifecycle.odd_95th":"Il loro CFO ha visto 95° percentile in fattura e pensa che fatturi i 95 giorni peggiori.", +"lifecycle.odd_alphabetical":"Il budget del rebranding è finito, quindi tagliano i costi in ordine alfabetico, e tu eri il primo.", +"lifecycle.odd_asn_six":"Il loro nuovo CTO si fida solo degli ASN con esattamente tre 7.", +"lifecycle.odd_bad_holiday":"Hanno scoperto che instradi i loro pacchetti attraverso una città dove una volta hanno fatto una brutta vacanza.", +"lifecycle.odd_bought_thrice":"Li ha comprati un'azienda comprata da un'azienda che ha già una rete. Nessuno sa chi comanda.", +"lifecycle.odd_center":"Hanno letto che la latenza conta, quindi si avvicinano al centro di internet. Pensano che sia in un campo in campagna.", +"lifecycle.odd_communities":"Sono passati a un fornitore con le community BGP meglio documentate. Ne ha due.", +"lifecycle.odd_dead_beef":"Volevano un indirizzo IPv6 che scrivesse il loro nome in esadecimale. :dead:beef era già preso.", +"lifecycle.odd_espresso":"La nuova macchina dell'espresso dell'ufficio fa saltare la corrente. Danno la colpa al router, quindi a te.", +"lifecycle.odd_fewer_vendors":"Il nuovo CEO vuole meno fornitori. Eri l'unico. Ora non ne hanno nessuno, e sono felicissimi.", +"lifecycle.odd_goat_farmer":"La persona che aveva firmato con te è andata ad allevare capre, e chi l'ha sostituita fa le cose diversamente.", +"lifecycle.odd_holiday_card":"Il tuo biglietto di auguri è arrivato in tempo. Questo li ha insospettiti.", +"lifecycle.odd_landlord":"Il loro padrone di casa fa pagare ogni cavo che passa nel muro, e il tuo è spesso e vistoso.", +"lifecycle.odd_looking_glass":"Il tuo looking glass è stato giù per un'ora, e il loro capo NOC l'ha presa sul personale.", +"lifecycle.odd_mate":"Il tuo account manager ha chiamato il loro account manager amico in un'email. Non sono amici.", +"lifecycle.odd_quadrant":"Un consulente ha fatto una slide con un quadrante, e tu eri in quello sbagliato.", +"lifecycle.odd_raccoon":"Un procione si è trasferito nel loro unico armadio, e sembra più felice con il cross-connect di un altro operatore.", +"lifecycle.odd_rdns":"Il tuo DNS inverso per il loro IP dice customer-cheapskate-04. Qualcuno del loro team se n'è accorto.", +"lifecycle.odd_space":"Hanno virato su una strategia AI-native, basata su blockchain e satellite-first, e la tua fibra non è nello spazio.", +"lifecycle.odd_spreadsheet_cell":"Nuova regola degli acquisti: il nome di ogni fornitore deve stare in una cella senza andare a capo.", +"lifecycle.odd_the_cloud":"Stanno spostando tutto nel cloud. Il cloud è un rack a due strade di distanza, collegato da te. Non se ne sono ancora accorti.", +"lifecycle.odd_too_many_feet":"Il loro stagista ha lanciato un traceroute per fare scena, ha visto 14 hop e ha dichiarato che erano troppi piedi.", +"lifecycle.odd_wireguard":"Passano al lavoro tutto da remoto. I 40 dipendenti useranno WireGuard dalle loro cucine, e la linea dell'ufficio serve solo alle piante.", +"lifecycle.odd_wrong_blue":"Il nuovo responsabile dell'ufficio vuole tutti i cavi dello stesso colore, e il tuo è del blu sbagliato.", +"lifecycle.referred_by":"Consigliato da {name}, uno dei tuoi clienti più contenti.", +"lifecycle.renewal_haggle":"rinnovo il {date}: si tratta", +"lifecycle.renewals":"Rinnovi", +"lifecycle.renewals_soon":"Rinnovi", +"lifecycle.renewed_and_grew":"{name} ha rinnovato ed è salita a {bw} ({city}).", +"lifecycle.unanswered_matches":"Senza risposta entro la fine del contratto, accetti il loro prezzo.", +"lifecycle.wants_price":"Paga {was}/mese, vuole {price}/mese ({p} in meno) per rinnovare.", +"lifecycle.why_acquired":"Acquisiti", +"lifecycle.why_bust":"Falliti", +"lifecycle.why_cheaper_bid":"Offerta più economica", +"lifecycle.why_insourced":"Rete propria", +"lifecycle.why_moved":"Trasferiti", +"lifecycle.why_multihomed":"Passati a un secondo fornitore", +"lifecycle.why_other":"Altri motivi", +"lifecycle.why_project_ended":"Progetto finito", +"lifecycle.why_they_left":"Perché se ne sono andati", +"lifecycle.why_unhappy":"Scontenti del servizio", +"lifecycle.won":"Acquisiti", +"lifecycle.won_and_lost":"Clienti acquisiti e persi", +"lifecycle.won_and_lost_note":"I contratti durano da uno a cinque anni, le coppie di fibra da dieci a venti. Alla scadenza quasi tutti rinnovano al prezzo di mercato di oggi, e i clienti contenti spesso crescono. Alcuni se ne vanno, e non sempre per colpa tua.", "link_modal.building_into_mainland_china_needs_a":"Per costruire nella Cina continentale servono una joint venture e una licenza operativa. Apri {city} per fare domanda.", "link_modal.cross_border_circuits_into_mainland":"I circuiti transfrontalieri verso la Cina continentale li vendono solo carrier con licenza, a 3× il prezzo. Quelli normali perdono circa il 20% del traffico al confine.", "link_modal.diverse_route_40_survives_cuts_alone":"Percorso diverso +40% · sopravvive da solo ai tagli", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 06e7c30..2145d01 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2603,6 +2603,84 @@ "lease_swaps.your_fiber_here_has_room_for":"Sua fibra aqui tem espaço para mais {free} canais, e mover esses aluguéis exige {n}. Acenda outro par de fibras ou atualize o line system primeiro.", "lease_swaps.your_own_cable_up_up_front":"Seu próprio cabo: {up} à vista, {mo}/mês, cerca de {n} dias de obra.", "lease_swaps.your_own_fiber_up_up_front":"Sua própria fibra: {up} à vista, {mo}/mês, cerca de {n} dias de obra.", +"lifecycle.acquired_stays_bigger":"{name} foi comprada e continua com você, maior: agora {bw}.", +"lifecycle.bandwidth_market":"Mercado de banda", +"lifecycle.bandwidth_prices":"Preços de banda", +"lifecycle.contract_until":"contrato até {date}", +"lifecycle.haggle":"{name} ({city}) quer {price}/mês para renovar, {p} a menos. A concorrência está dando lances. Responda em Negócios em até {n} dias.", +"lifecycle.last_12_months":"últimos 12 meses", +"lifecycle.left_acquired":"{name} foi comprada, e o comprador leva tudo para a própria rede.", +"lifecycle.left_bust":"{name} faliu. O hype seguiu em frente sem eles.", +"lifecycle.left_cheaper":"{name} aceitou uma proposta mais barata de um concorrente em {city}.", +"lifecycle.left_insourced":"{name} cresceu o bastante para montar o próprio backbone, e vai fazer peering com você em vez de comprar.", +"lifecycle.left_moved":"{name} saiu de {city} para um lugar onde você não tem POP.", +"lifecycle.left_multihomed":"{name} passou todo o tráfego para um segundo provedor.", +"lifecycle.left_odd":"{name} não renovou. {why}", +"lifecycle.left_project_ended":"O projeto de {name} acabou, e o circuito vai junto.", +"lifecycle.left_unhappy":"{name} não renovou: o serviço falhou com eles vezes demais.", +"lifecycle.let_go":"{name} foi embora. O contrato estava acabando de qualquer jeito.", +"lifecycle.let_them_go":"Deixar ir", +"lifecycle.lost":"Perdidos", +"lifecycle.market_above":"{p} acima do começo", +"lifecycle.market_as_start":"como no começo", +"lifecycle.market_below":"{p} abaixo do começo", +"lifecycle.match":"Igualar", +"lifecycle.matched":"{name} renovou pelo preço que pediu.", +"lifecycle.meet_halfway":"Meio-termo", +"lifecycle.meet_no":"{name} aceitou a proposta do concorrente e foi embora.", +"lifecycle.meet_yes":"{name} aceitou sua proposta e renovou por {price}/mês.", +"lifecycle.moved_stays":"{name} mudou de {from} para {to}, onde você tem POP, então fica.", +"lifecycle.multihomed_keeps":"{name} passou metade do tráfego para um segundo provedor. Você fica com {bw}.", +"lifecycle.n_grew":{"one":"1 cresceu","other":"{n} cresceram"}, +"lifecycle.n_more":{"one":"…e mais 1.","other":"…e mais {n}."}, +"lifecycle.n_renewed":{"one":"1 contrato renovado aos preços de hoje ({p}).","other":"{n} contratos renovados aos preços de hoje ({p})."}, +"lifecycle.next_30_days":"próximos 30 dias", +"lifecycle.nobody_left_yet":"Ninguém saiu ainda.", +"lifecycle.odd_4g_dongle":"A empresa inteira agora roda num app SaaS por um modem 4G. Funciona bem, e essa é a pior parte.", +"lifecycle.odd_95th":"O diretor financeiro deles viu percentil 95 na fatura e acha que você cobra os 95 piores dias.", +"lifecycle.odd_alphabetical":"O orçamento do rebranding acabou, então estão cortando custos em ordem alfabética, e você apareceu primeiro.", +"lifecycle.odd_asn_six":"O novo CTO deles só confia em ASNs com exatamente três setes.", +"lifecycle.odd_bad_holiday":"Descobriram que você roteia os pacotes deles por uma cidade onde tiveram umas férias ruins.", +"lifecycle.odd_bought_thrice":"Foram comprados por uma empresa que foi comprada por uma empresa que já tem rede. Ninguém sabe quem manda.", +"lifecycle.odd_center":"Leram que latência importa, então estão se mudando para perto do centro da internet. Acham que fica num campo no interior.", +"lifecycle.odd_communities":"Mudaram para um provedor cujas comunidades BGP são mais bem documentadas. São duas.", +"lifecycle.odd_dead_beef":"Queriam um endereço IPv6 que soletrasse o nome deles em hexadecimal. :dead:beef já estava em uso.", +"lifecycle.odd_espresso":"A nova máquina de espresso do escritório derruba o disjuntor. Eles culpam o roteador, então culpam você.", +"lifecycle.odd_fewer_vendors":"O novo CEO quer menos fornecedores. Você era o único. Agora eles não têm nenhum, e estão felizes.", +"lifecycle.odd_goat_farmer":"A pessoa que assinou com você saiu para criar cabras, e quem entrou no lugar faz tudo diferente.", +"lifecycle.odd_holiday_card":"Seu cartão de fim de ano chegou na hora. Isso os deixou desconfiados.", +"lifecycle.odd_landlord":"O proprietário cobra por cabo que atravessa a parede, e o seu é grosso e chamativo.", +"lifecycle.odd_looking_glass":"Seu looking glass ficou fora do ar por uma hora, e o chefe do NOC deles levou para o lado pessoal.", +"lifecycle.odd_mate":"Seu gerente de conta chamou o gerente de conta deles de parceiro num e-mail. Eles não são parceiros.", +"lifecycle.odd_quadrant":"Um consultor fez um slide com um quadrante, e você estava no errado.", +"lifecycle.odd_raccoon":"Um guaxinim se mudou para o único rack deles, e parece mais feliz com o cross-connect de outra operadora.", +"lifecycle.odd_rdns":"Seu DNS reverso para o IP deles diz customer-cheapskate-04. Alguém da equipe deles percebeu.", +"lifecycle.odd_space":"Mudaram para uma estratégia nativa de IA, baseada em blockchain e satélite em primeiro lugar, e sua fibra não está no espaço.", +"lifecycle.odd_spreadsheet_cell":"Nova regra de compras: o nome de cada fornecedor tem que caber numa célula da planilha sem quebrar linha.", +"lifecycle.odd_the_cloud":"Estão levando tudo para a nuvem. A nuvem é um rack a duas ruas dali, conectado por você. Eles ainda não perceberam.", +"lifecycle.odd_too_many_feet":"O estagiário deles rodou um traceroute para se exibir, viu 14 saltos e declarou que eram pés demais.", +"lifecycle.odd_wireguard":"Vão trabalhar 100% remoto. Os 40 funcionários vão usar WireGuard da cozinha, e a linha do escritório fica só para as plantas.", +"lifecycle.odd_wrong_blue":"A nova gerente do escritório quer todos os cabos da mesma cor, e o seu é do azul errado.", +"lifecycle.referred_by":"Indicado por {name}, um dos seus clientes mais felizes.", +"lifecycle.renewal_haggle":"renovação em {date}: negociando", +"lifecycle.renewals":"Renovações", +"lifecycle.renewals_soon":"Renovações", +"lifecycle.renewed_and_grew":"{name} renovou e cresceu para {bw} ({city}).", +"lifecycle.unanswered_matches":"Sem resposta até o fim do contrato, você iguala o preço deles.", +"lifecycle.wants_price":"Paga {was}/mês, quer {price}/mês ({p} a menos) para renovar.", +"lifecycle.why_acquired":"Comprados", +"lifecycle.why_bust":"Faliram", +"lifecycle.why_cheaper_bid":"Proposta mais barata", +"lifecycle.why_insourced":"Montaram a própria rede", +"lifecycle.why_moved":"Mudaram", +"lifecycle.why_multihomed":"Foram para outro provedor", +"lifecycle.why_other":"Outros motivos", +"lifecycle.why_project_ended":"Projeto encerrado", +"lifecycle.why_they_left":"Por que saíram", +"lifecycle.why_unhappy":"Insatisfeitos com o serviço", +"lifecycle.won":"Conquistados", +"lifecycle.won_and_lost":"Clientes conquistados e perdidos", +"lifecycle.won_and_lost_note":"Os contratos duram de um a cinco anos, os pares de fibra de dez a vinte. Quando um termina, a maioria renova pelo preço de mercado de hoje e os clientes felizes costumam crescer. Alguns saem, e nem sempre por sua causa.", "link_modal.building_into_mainland_china_needs_a":"Construir na China continental exige uma joint venture e uma licença de operação. Abra {city} para solicitar.", "link_modal.cross_border_circuits_into_mainland":"Circuitos transfronteiriços para a China continental só são vendidos por operadoras licenciadas, a 3× o preço. Os comuns perdem cerca de 20% do tráfego na fronteira.", "link_modal.diverse_route_40_survives_cuts_alone":"Rota diversa +40% · sobrevive a cortes sozinha", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index a725106..fd80aa6 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -218,6 +218,12 @@ const API_CMD={ doc:'Sign a pending offer. Rejected without a POP in every city it needs, without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, decline:{args:[['id','entityId']], doc:'Throw an offer away.'}, + renewMatch:{args:[['id','entityId']],watch:['biz.#id'], + doc:'Answer a renewal haggle (a customer with hag): renew at the price they asked. Unanswered, this happens on its own when the term ends.'}, + renewMeet:{args:[['id','entityId']],watch:['biz.#id'], + doc:'Answer a renewal haggle by meeting halfway between their price and today\'s market price. They accept about two times in three; otherwise they leave.'}, + renewLet:{args:[['id','entityId']], + doc:'Answer a renewal haggle by letting the customer go now.'}, dropBiz:{args:[['id','entityId']],confirm:'double', doc:'Terminate a signed customer. Rejected once an event contract\'s event has started.'}, setRoute:{args:[['id','entityId'],['m','routeMode']],watch:['biz.#id'], diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 72af161..50e5df8 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -32,8 +32,9 @@ const API_STATE_DOC={ pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'}, caches:{type:'array',doc:'CDN cache boxes: city, net, building.'}, nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, - biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates.'}, - offers:{type:'array',doc:'Pending customer offers, each expiring on a day.'}, + biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates (te: the day the term ends, mk: the bandwidth market it was priced in, hag: an open renewal haggle {rate, until}).'}, + offers:{type:'array',doc:'Pending customer offers, each expiring on a day (mk: the bandwidth market they were priced in; refN: the customer who referred them).'}, + cl:{type:'map',doc:'Customer lifecycle (#178): odd (the day of the last unusual departure) and mo, one entry a month of customers won, renewed, grown, haggling and lost by reason.'}, done:{type:'map',doc:'Goals landed, by goal id → day.'}, ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'}, diff --git a/src/game/10-catalog/30-supply-chain.js b/src/game/10-catalog/30-supply-chain.js index 8fc363b..14128da 100644 --- a/src/game/10-catalog/30-supply-chain.js +++ b/src/game/10-catalog/30-supply-chain.js @@ -17,6 +17,7 @@ function hwShockStart(){const k=pick(Object.keys(HW_SHOCK)),n=45+Math.floor(Math 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')}
+
${tr('lifecycle.bandwidth_prices')}${mktTxt()}
${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})}
`:''} ${l?`
${tr('common.price_lock')}${tr('supply_chain.until_date_at_p',{date:dateStr(l.until),p:pct(l.mul-1)})}
` :`

${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`}
`;} diff --git a/src/game/60-features/37-fiber-broker.js b/src/game/60-features/37-fiber-broker.js index e208f6f..d419095 100644 --- a/src/game/60-features/37-fiber-broker.js +++ b/src/game/60-features/37-fiber-broker.js @@ -31,6 +31,6 @@ function brTick(){for(const l of S.links){const L=l.list;if(!L||l.kind!=='df'||! function brSell(l,t,n){const T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;}; const o=fiberOffer(t,l,nm,0.9);if(t==='wwave'){o.slots=n;o.rate=wwRate(l,n,0.9);o.what=wwWhat(l,n);} const more=t==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===l.id&&b.name===o.name); - if(more){more.slots=(more.slots||0)+n;more.rate+=o.rate;more.what=wwWhat(l,more.slots);}else S.biz.push(offerCustomer(o)); + if(more){more.slots=(more.slots||0)+n;more.rate+=o.rate;more.what=wwWhat(l,more.slots);}else S.biz.push(clSign(offerCustomer(o))); toast(tr('broker.sold',{name:esc(o.name),what:esc(t==='wwave'?wwWhat(l,n):o.what),price:fmt$(o.rate)}),'good'); floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 394874d..c318652 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -55,7 +55,9 @@ function sanitize(s){ for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('common.your_ix')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);} const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity)); const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;}; - {const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>unpackBiz(fixBiz(b),ids));}s.offers=s.offers.filter(okBiz).map(fixBiz); + {const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz); + // Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally. + for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s); // Sponsorships and capacity conferences (#168): registrations are true or 'sp', the glow and the pending deals are checked. 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};} diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js new file mode 100644 index 0000000..30e8625 --- /dev/null +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -0,0 +1,148 @@ +/* ---------- Customers come and go (#178) ---------- + Every customer signs for a term. When it ends, most renew at today's market price, happy ones often grow, a few haggle + for a discount, and some leave for reasons that are not your fault (or, when they were unhappy, because they were). + Nothing changes during a customer's first term. Every roll is a hash of the customer and its term, never + Math.random, so seeded games and tests keep their random stream. */ + +/* The bandwidth market: what a Gbps sells for, 1 when you start. Flat for the first six months, then about 10% cheaper + a year (transit really does fall: 11–17% a year in the big hubs), slowed by dearer hardware, moving up and down in a + slow three-year cycle, and pushed up while a shortage lasts. Without the market rule it stays at 1. */ +const MK_YR=0.10,MK_FREE=180,MK_FLOOR=0.3,MK_SHOCK={opt:1.15,rt:1.1,build:1.08}; +function mktBase(d){if(d<=MK_FREE)return 1;const y=(d-MK_FREE)/365; + return Math.max(MK_FLOOR,Math.pow(1-MK_YR,y)*Math.sqrt(hwTrend(d))*(1+0.06*Math.sin(2*Math.PI*y/3)));} +function mkt(){if(!S||!rule('market'))return 1;const s=hwShock();return mktBase(S.day)*(s?MK_SHOCK[s.k]||1:1);} + +// Terms in months: enterprise and hosting 1–3 years, wholesale and circuits 2–5, IRUs and fiber pairs 10–20. +const CL_TERMS={ip:[12,24,36],whole:[24,36,48,60],iru:[120,180,240]}; +// Events, capacity deals and scripted scenario customers have their own endings. +const clKind=t=>{const T=BIZ_T[t];if(!T||T.event||T.cap)return null;if(t==='dfpair'||t==='pairs')return 'iru';return T.l2||T.fiber||t==='isp'||t==='gpu'?'whole':'ip';}; +const clOn=b=>!!b&&!b.scripted&&!!clKind(b.type); +// A stable roll in [0,1) for this customer, this term and this question. +const clR=(b,q)=>(hstr(((S&&S.asn)||0)+'|'+b.id+'|'+b.te+'|'+q)%100000)/100000; +const clPick=(a,b,q)=>a[Math.floor(clR(b,q)*a.length)]; +function clTerm(b,from){const m=clPick(CL_TERMS[clKind(b.type)],{id:b.id,te:from},'term');return from+Math.round(m*365/12);} +// What this customer's contract would be priced at today: its price moved by the market since it was signed. +// A renewal moves at most 25% down or 10% up at once, so an old save is not repriced in one go. +const clFair=b=>rule('market')&&b.mk>0?Math.round(b.rate*clamp(mkt()/b.mk,0.75,1.1)):b.rate; +// Competition where the customer is: carriers selling transit there (a fiber or circuit customer counts both ends). +const clComp=b=>{const cs=bCities(b);let n=0;for(const n2 of NETS)if(cs.some(c=>sellsAt(n2,c)))n++;return n;}; + +// Why they leave when it is not your fault: which reasons fit which customers. Moved and multihomed may keep them. +const CL_WHY={ + acq:{l:N_('lifecycle.why_acquired'),left:N_('lifecycle.left_acquired'),ok:()=>true}, + bust:{l:N_('lifecycle.why_bust'),left:N_('lifecycle.left_bust'),ok:t=>['gpu','stream','game','cgame','metav','ai','agi','hft','provedor','dia','host','mars'].includes(t)}, + insrc:{l:N_('lifecycle.why_insourced'),left:N_('lifecycle.left_insourced'),ok:t=>['isp','hyper','onramp','provedor','edu','sov','aiwan','stream'].includes(t)}, + moved:{l:N_('lifecycle.why_moved'),left:N_('lifecycle.left_moved'),ok:t=>{const T=BIZ_T[t];return !T.l2&&!T.fiber&&!T.nni;}}, + multi:{l:N_('lifecycle.why_multihomed'),left:N_('lifecycle.left_multihomed'),ok:t=>{const T=BIZ_T[t];return !T.l2&&!T.fiber;}}, + ended:{l:N_('lifecycle.why_project_ended'),left:N_('lifecycle.left_project_ended'),ok:t=>{const T=BIZ_T[t];return T.l2||T.fiber||t==='bulk';}}, + cheap:{l:N_('lifecycle.why_cheaper_bid'),left:N_('lifecycle.left_cheaper'),ok:()=>true}, + sad:{l:N_('lifecycle.why_unhappy'),ok:()=>false}, + odd:{l:N_('lifecycle.why_other'),ok:()=>false}, +}; +// The other reasons: now and then (never more than once every two months) a customer leaves for one of these. +const CL_ODD=[N_('lifecycle.odd_asn_six'),N_('lifecycle.odd_bad_holiday'),N_('lifecycle.odd_rdns'),N_('lifecycle.odd_too_many_feet'),N_('lifecycle.odd_dead_beef'),N_('lifecycle.odd_looking_glass'), + N_('lifecycle.odd_communities'),N_('lifecycle.odd_quadrant'),N_('lifecycle.odd_spreadsheet_cell'),N_('lifecycle.odd_fewer_vendors'),N_('lifecycle.odd_the_cloud'),N_('lifecycle.odd_bought_thrice'), + N_('lifecycle.odd_alphabetical'),N_('lifecycle.odd_goat_farmer'),N_('lifecycle.odd_mate'),N_('lifecycle.odd_95th'),N_('lifecycle.odd_holiday_card'),N_('lifecycle.odd_raccoon'),N_('lifecycle.odd_espresso'), + N_('lifecycle.odd_landlord'),N_('lifecycle.odd_wrong_blue'),N_('lifecycle.odd_space'),N_('lifecycle.odd_4g_dongle'),N_('lifecycle.odd_center'),N_('lifecycle.odd_wireguard')]; +const CL_ODD_GAP=60,CL_HAG_MAX=3,CL_MONTHS=24; + +// The month's tally for the dashboard: won, renewed, grew, haggled and who left why. +function clNote(k,why){const C=S.cl||(S.cl={odd:-1e9,mo:[]}),c=cal(S.day),m=c.y*12+c.m;let e=C.mo[C.mo.length-1]; + if(!e||e.m!==m){e={m,won:0,ren:0,grew:0,hag:0,lost:{}};C.mo.push(e);if(C.mo.length>CL_MONTHS)C.mo.shift();} + if(k==='lost')e.lost[why]=(e.lost[why]||0)+1;else e[k]=(e[k]||0)+1;} +// A new customer: its first term and the market it signed in. +function clSign(b){if(!clOn(b))return b;b.mk=b.mk>0?b.mk:mkt();b.te=clTerm(b,S.day);clNote('won');return b;} +function clRenew(b,rate){b.rate=Math.max(0,Math.round(rate));b.mk=mkt();delete b.hag;delete b.hr;b.te=clTerm(b,b.te);} +function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);} +const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ '); + +// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. +function clGrow(b){const T=BIZ_T[b.type];if(T.fiber)return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=up||b.bw*2;return true;} +// Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says. +function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))}; + if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;} + const C=S.cl;if(d-C.odd>=CL_ODD_GAP&&clR(b,'odd')<0.25){C.odd=d;clGone(b,'odd');out.lost.push(tr('lifecycle.left_odd',{...v,why:tr(clPick(CL_ODD,b,'oddline'))}));return;} + const ks=Object.keys(CL_WHY).filter(k=>CL_WHY[k].ok(b.type)),k=clPick(ks,b,'why'); + if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;} + if(k==='moved'){const reg=CITY[b.city].reg,to=Object.keys(S.pops).filter(c=>c!==b.city&&CITY[c].reg===reg&&bizCity(c)).sort(); + const c2=to.length&&clR(b,'stay')<0.5?clPick(to,b,'to'):null; + if(c2){const from=CITY[b.city].name;b.city=c2;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.moved_stays',{name:v.name,from:esc(from),to:esc(CITY[c2].name)}));return;}} + if(k==='multi'&&b.bw>=2){const keep=(T.opts||[]).filter(x=>x<=b.bw/2).pop()||b.bw/2;b.bw=keep;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.multihomed_keeps',{...v,bw:fmtG(b.bw)}));return;} + clGone(b,k);out.lost.push(tr(CL_WHY[k].left,v));} + +/* A day of contracts, after the moods. 30 days before a term ends a customer with competitors around may ask for a + discount (at most three open at a time); at the end, the rest renew, grow or leave. An unanswered haggle renews at + the asked price. */ +function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0); + const pat=rule('moods')==='patient'?0.5:1; + for(const b of S.biz.slice()){if(!b.te||!clOn(b))continue; + if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;} + if(d=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(0.8+0.12*clR(b,'ask'))); + if(ask>0&&ask=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}} + clRenew(b,clFair(b));clNote('ren');out.ren++;} + clNews(out);clReferral(d);} +// What the day says: haggles one by one (they want an answer), the rest in a few lines so a big network is not a wall of toasts. +function clNews(out){ + for(const b of out.hag){const was=bizMo(b),now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate; + toast(tr('lifecycle.haggle',{name:esc(b.name),city:esc(clWhere(b)),price:fmt$(now),p:pct(1-now/Math.max(1,was)),n:b.hag.until-S.day}),'',[{l:tr('common.deals'),act:'leftTab',args:{t:'deals'}}],{a:'cust',v:b.id});} + const few=(list,kind)=>{for(const t of list.slice(0,3))toast(t,kind);if(list.length>3)toast(trn('lifecycle.n_more',list.length-3),kind);}; + few(out.ok,'good');few(out.lost,''); + if(out.ren)toast(trn('lifecycle.n_renewed',out.ren,{p:mktTxt()}),'');} +const mktTxt=()=>{const m=mkt();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});}; + +/* Growth by word of mouth: about every six weeks the happiest long-standing customer (a year or more, 90%+ happy) + tells someone like them, who shows up in Deals asking for the smallest size at today's price. */ +const CL_REF=['dia','game','host','isp','stream','edu','scrub','provedor','gpu','cgame','metav']; +function clReferral(d){if(d%45!==0||S.offers.length>=6)return; + const b=S.biz.filter(x=>clOn(x)&&CL_REF.includes(x.type)&&x.mood>=90&&d-(x.since||0)>=365&&bizCity(x.city)&&lvl()>=(BIZ_T[x.type].lv||1)).sort((a,c)=>c.mood-a.mood||(a.since||0)-(c.since||0)||(a.ido.ref===b.id))return;const T=BIZ_T[b.type],list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));if(!list.length)return; + const name=clPick(list,{id:b.id,te:d},'refname');useName(name); + S.offers.push({id:uid(),city:b.city,city2:null,name,type:b.type,bw:(T.opts||[1])[0],rate:Math.round((CITY[b.city].au?T.rate*AU_ARPU:T.rate)*mkt()),mk:mkt(),reqs:[],exp:d+40,ref:b.id,refN:b.name});} +// New offers are priced at today's market (spawnOffer and friends price at 1; this moves them). +function mktPrice(from){const m=mkt();for(let i=from;iS?S.biz.reduce((a,b)=>a+(b.hag?1:0),0):0; +// The renewals waiting for an answer, at the top of Deals. +function clDealsHtml(){const hs=S.biz.filter(b=>b.hag).sort((a,b)=>a.hag.until-b.hag.until);if(!hs.length)return ''; + return `

${tr('lifecycle.renewals')}

${tr('lifecycle.unanswered_matches')}

`+hs.map(b=>{const now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate,was=bizMo(b); + return `
${esc(b.name)}
${esc(BIZ_T[b.type].l)} · ${esc(clWhere(b))} · ${tr('ui.n_d_left',{n:b.hag.until-S.day})}
+
${tr('lifecycle.wants_price',{was:fmt$(was),price:fmt$(now),p:pct(1-now/Math.max(1,was))})}
+
${btn(tr('lifecycle.match'),'renewMatch',{id:b.id},'green sm')}${btn(tr('lifecycle.meet_halfway'),'renewMeet',{id:b.id},'sm')}${btn(tr('lifecycle.let_them_go'),'renewLet',{id:b.id},'ghost sm')}
`;}).join('');} +// The contract line on a customer row. +const clTermTxt=b=>clOn(b)&&b.te?(b.hag?tr('lifecycle.renewal_haggle',{date:dateStr(b.te)}):tr('lifecycle.contract_until',{date:dateStr(b.te)})):''; + +/* Dashboard: customers won and lost per month (and why), renewals coming up, and the bandwidth market. */ +function clPanel(){const C=S.cl||{mo:[]},mo=C.mo.slice(-12);const soon=S.biz.filter(b=>clOn(b)&&b.te&&b.te-S.day<=30&&b.te>=S.day).length; + const sum=k=>mo.reduce((a,e)=>a+(k==='lost'?Object.values(e.lost).reduce((x,y)=>x+y,0):e[k]||0),0),why={};for(const e of mo)for(const k in e.lost)why[k]=(why[k]||0)+e.lost[k]; + let h=`

${tr('lifecycle.won_and_lost')}

${tr('lifecycle.won_and_lost_note')}

+
${tr('lifecycle.won')}
${sum('won')}
${tr('lifecycle.last_12_months')}
+
${tr('lifecycle.lost')}
${sum('lost')}
${trn('lifecycle.n_grew',sum('grew'))}
+
${tr('lifecycle.renewals_soon')}
${soon}
${tr('lifecycle.next_30_days')}
+
${tr('lifecycle.bandwidth_market')}
${Math.round(mkt()*100)}
${mktTxt()}
`; + if(mo.length){const max=Math.max(1,...mo.map(e=>Math.max(e.won,Object.values(e.lost).reduce((x,y)=>x+y,0)))),W=600,H=120,mid=H/2,bw=W/12; + let g=``; + mo.forEach((e,i)=>{const lost=Object.values(e.lost).reduce((x,y)=>x+y,0),x=(i+12-mo.length)*bw+bw*0.2,w=bw*0.6,hw=(mid-12)*e.won/max,hl=(mid-12)*lost/max; + g+=`${MONTHS[e.m%12]} · ${tr('lifecycle.won')} ${e.won}${MONTHS[e.m%12]} · ${tr('lifecycle.lost')} ${lost}${MONTHS[e.m%12]}`;}); + h+=`${g}`;} + const ks=Object.keys(why).sort((a,b)=>why[b]-why[a]); + h+=ks.length?`

${tr('lifecycle.why_they_left')}

`+ks.map(k=>`
${tr(CL_WHY[k]?CL_WHY[k].l:CL_WHY.odd.l)}${why[k]}
`).join(''):`

${tr('lifecycle.nobody_left_yet')}

`; + return h+`
`;} + +/* Saves from before contracts: renewals spread over the next year (from the customer's id, so they do not all fall on + one day), and the market they signed in from the day they signed. */ +function clFix(s,b){if(b.scripted||!clKind(b.type)){delete b.te;delete b.mk;delete b.hag;delete b.hr;return b;} + const day=Math.max(0,Math.floor(+s.day||0)),ok=v=>typeof v==='number'&&isFinite(v); + if(!ok(b.te)||b.teday+365*21)b.te=day+30+hstr('te|'+b.id)%335;b.te=Math.floor(b.te); + if(!ok(b.mk)||b.mk<=0||b.mk>5)b.mk=mktBase(Math.max(0,Math.floor(+b.since||0))); + if(b.hag&&(typeof b.hag!=='object'||!ok(b.hag.rate)||b.hag.rate<0||!ok(b.hag.until)))delete b.hag;else if(b.hag)b.hag={rate:Math.round(b.hag.rate),until:Math.floor(Math.min(b.hag.until,b.te))}; + if(b.hr!==undefined&&b.hr!==b.te)delete b.hr;return b;} +function clFixState(s){const C=s.cl&&typeof s.cl==='object'&&!Array.isArray(s.cl)?s.cl:{},o={odd:typeof C.odd==='number'&&isFinite(C.odd)?C.odd:-1e9,mo:[]}; + if(Array.isArray(C.mo))for(const e of C.mo.slice(-CL_MONTHS)){if(!e||typeof e!=='object'||!Number.isInteger(e.m))continue;const n=v=>Math.max(0,Math.min(1e7,Math.floor(+v)||0)),lost={}; + if(e.lost&&typeof e.lost==='object')for(const k in e.lost)if(own(CL_WHY,k))lost[k]=n(e.lost[k]);o.mo.push({m:e.m,won:n(e.won),ren:n(e.ren),grew:n(e.grew),hag:n(e.hag),lost});} + s.cl=o;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 945c8bb..f421ab8 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -57,6 +57,8 @@ function dayPost(d){ toast(tr('day_tick.name_is_furious_fix_service_in',{name:esc(b.name),city:CITY[b.city].name})+(why?`
${esc(why)}`:'')+(paused?`
${tr('common.game_paused')}`:''),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');} else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('day_tick.name_is_getting_unhappy_happiness_p',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`
${esc(why)}`:''),'',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);}} if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;} + // contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js) + clDay(d); // own IX members join for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.lengthn.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg))); @@ -67,7 +69,7 @@ function dayPost(d){ // offers S.offers=S.offers.filter(o=>o.exp>d); brTick(); - if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1))spawnOffer(); + if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)){const n0=S.offers.length;spawnOffer();mktPrice(n0);} // 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(); diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index 53d9aee..87b7d94 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -12,8 +12,18 @@ 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(customer); + S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;S.biz.push(clSign(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();}, }); +/* The renewal haggle (#178, 75-customer-lifecycle.js): match their price, meet halfway (they take it about two times + in three), or let them go. */ +function clHagOf(id){const b=S.biz.find(x=>x.id===id);return b&&b.hag?b:null;} +Object.assign(ACT,{ + renewMatch:({id})=>{const b=clHagOf(id);if(!b)return;clRenew(b,b.hag.rate);clNote('ren');toast(tr('lifecycle.matched',{name:esc(b.name)}),'good');sfx('coin');after();}, + renewMeet:({id})=>{const b=clHagOf(id);if(!b)return;const mid=Math.round((b.hag.rate+clFair(b))/2); + if(clR(b,'meet')<0.65){clRenew(b,mid);clNote('ren');toast(tr('lifecycle.meet_yes',{name:esc(b.name),price:fmt$(BIZ_T[b.type].fiber?b.rate:b.bw*b.rate)}),'good');sfx('coin');} + else{clGone(b,'cheap');toast(tr('lifecycle.meet_no',{name:esc(b.name)}),'bad');sfx('err');}after();}, + renewLet:({id})=>{const b=clHagOf(id);if(!b)return;clGone(b,'cheap');toast(tr('lifecycle.let_go',{name:esc(b.name)}),'');after();}, +}); diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 70042c6..9408436 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -32,7 +32,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?``:''}`],['nets',`${tr('common.networks')}`]]; + const tabs=[['goals',`${tr('common.goals')}${ndone}/${GOALS.length}`],['deals',`${tr('common.deals')}${S.offers.length+clHags()?`${S.offers.length+clHags()}`:''}`],['noc',`NOC${S.inc.length?``:''}`],['nets',`${tr('common.networks')}`]]; $('leftTabs').innerHTML=tabs.map(([k,l])=>``).join('')+(innerWidth<760?``:''); let h=''; if(UI.left==='goals'){ @@ -42,11 +42,11 @@ function renderLeft(){checkLayer(); 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()+seatSection(); + h+=clDealsHtml()+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)}`:''}
${spotWhy(o)}${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)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${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',{},'')}${btn(`⚙️ ${tr('routing.routing_and_ddos')}${S.te&&!coreTE()?'':''}`,'routingOpen',{},'')}
`; diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index b12a20b..4452395 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -37,7 +37,7 @@ function cityPanel(c){ h+=`

${tr('common.business_customers')}

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

${tr('city_panel.no_businesses_yet_offers_pop_up')}

`; - 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('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('city_panel.fiber_is_down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('common.needs_a_scrubbing_center')+'':''}${S.day-(b.since||0)<15?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('common.happiness_p',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.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)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('city_panel.fiber_is_down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('common.needs_a_scrubbing_center')+'':''}${S.day-(b.since||0)<15?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('common.happiness_p',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}
`; h+=`
`+offersHere(c); }else if(UI.tab==='up'){ h+=portNote(c)+latNote(c); diff --git a/src/game/94-dashboard/30-customers.js b/src/game/94-dashboard/30-customers.js index 8ff718e..600820a 100644 --- a/src/game/94-dashboard/30-customers.js +++ b/src/game/94-dashboard/30-customers.js @@ -30,5 +30,5 @@ 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('common.happiness')],['mo',tr('common.per_month')],['name',tr('common.name')],['city',tr('common.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('common.price_mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('common.happiness_p',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('common.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('common.price_mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}${clTermTxt(b)?' · '+clTermTxt(b):''}
${bRisk(b)}${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('common.happiness_p',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('common.open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); return h+listMore('cust',rows.length,n=>trn('customers.n_more_customer',n))+`
`;} diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 4ea4fae..16aecdb 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 e={c:0,p:0,ix:0,t:0};let w=0;for(const n of NETS)if(n.tail){const x=R.netEg[n.id];if(x)for(const k in e)e[k]+=x[k]||0;w+=R.demTo[n.id]||0;}nets.push(row({id:'_tail',name:tr('dashboard.the_long_tail_n_small_networks',{n:NETS.filter(n=>n.tail).length}),asn:'many',type:'eye',col:'#8A93B8'},e,w));} for(let i=nets.length-1;i>=0;i--)if(!(nets[i].t>0.01||(!filt&&nets[i].want>0.01)))nets.splice(i,1); {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==='cust')h+=clPanel()+custSection(); 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')}

${chartLegend('mix')}
${[['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('')} diff --git a/src/i18n/en.js b/src/i18n/en.js index ad8a9de..cd6de57 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2604,6 +2604,84 @@ "lease_swaps.your_fiber_here_has_room_for":"Your fiber here has room for {free} more channels, and moving these leases needs {n}. Light another fiber pair or upgrade the line system first.", "lease_swaps.your_own_cable_up_up_front":"Your own cable: {up} up front, {mo}/mo, about {n} days to build.", "lease_swaps.your_own_fiber_up_up_front":"Your own fiber: {up} up front, {mo}/mo, about {n} days to build.", +"lifecycle.acquired_stays_bigger":"{name} was acquired and stays with you, bigger: now {bw}.", +"lifecycle.bandwidth_market":"Bandwidth market", +"lifecycle.bandwidth_prices":"Bandwidth prices", +"lifecycle.contract_until":"contract until {date}", +"lifecycle.haggle":"{name} ({city}) wants {price}/mo to renew, {p} less. Competitors are bidding. Answer in Deals within {n} days.", +"lifecycle.last_12_months":"last 12 months", +"lifecycle.left_acquired":"{name} was acquired, and the buyer moves everything onto its own network.", +"lifecycle.left_bust":"{name} went bust. The hype moved on without them.", +"lifecycle.left_cheaper":"{name} took a cheaper bid from a competitor in {city}.", +"lifecycle.left_insourced":"{name} got big enough to build its own backbone, and will peer with you instead of buying.", +"lifecycle.left_moved":"{name} moved away from {city}, somewhere you have no POP.", +"lifecycle.left_multihomed":"{name} moved all its traffic to a second provider.", +"lifecycle.left_odd":"{name} did not renew. {why}", +"lifecycle.left_project_ended":"{name}'s project is over, and the circuit goes with it.", +"lifecycle.left_unhappy":"{name} did not renew: the service let them down too often.", +"lifecycle.let_go":"{name} is gone. Their contract was up anyway.", +"lifecycle.let_them_go":"Let them go", +"lifecycle.lost":"Lost", +"lifecycle.market_above":"{p} above when you started", +"lifecycle.market_as_start":"as when you started", +"lifecycle.market_below":"{p} below when you started", +"lifecycle.match":"Match", +"lifecycle.matched":"{name} renewed at the price they asked.", +"lifecycle.meet_halfway":"Meet halfway", +"lifecycle.meet_no":"{name} took the competitor's bid and left.", +"lifecycle.meet_yes":"{name} took your offer and renewed at {price}/mo.", +"lifecycle.moved_stays":"{name} moved from {from} to {to}, where you have a POP, so it stays.", +"lifecycle.multihomed_keeps":"{name} moved half its traffic to a second provider. You keep {bw}.", +"lifecycle.n_grew":{"one":"1 grew","other":"{n} grew"}, +"lifecycle.n_more":{"one":"…and 1 more.","other":"…and {n} more."}, +"lifecycle.n_renewed":{"one":"1 contract renewed at today's prices ({p}).","other":"{n} contracts renewed at today's prices ({p})."}, +"lifecycle.next_30_days":"next 30 days", +"lifecycle.nobody_left_yet":"Nobody has left yet.", +"lifecycle.odd_4g_dongle":"Their whole company now runs on one SaaS app over a 4G dongle. It works fine, which is the worst part.", +"lifecycle.odd_95th":"Their CFO saw 95th percentile on the invoice and thinks you charge for the 95 worst days.", +"lifecycle.odd_alphabetical":"Their rebrand budget ran out, so they are cutting costs alphabetically, and you came up first.", +"lifecycle.odd_asn_six":"Their new CTO only trusts ASNs with exactly three 7s in them.", +"lifecycle.odd_bad_holiday":"They found out you route their packets through a city they once had a bad holiday in.", +"lifecycle.odd_bought_thrice":"They were bought by a company that was bought by a company that already has a network. Nobody knows who is in charge.", +"lifecycle.odd_center":"They read that latency matters, so they are moving closer to the center of the internet. They think it is in a field in the countryside.", +"lifecycle.odd_communities":"They switched to a provider whose BGP communities are better documented. There are two of them.", +"lifecycle.odd_dead_beef":"They wanted an IPv6 address that spells their name in hex. :dead:beef was taken.", +"lifecycle.odd_espresso":"The office's new espresso machine trips the breaker. They blame the router, so they blame you.", +"lifecycle.odd_fewer_vendors":"The new CEO wants fewer vendors. You were the only one. They now have none, and are delighted.", +"lifecycle.odd_goat_farmer":"The person who signed with you left to become a goat farmer, and their replacement is doing things differently.", +"lifecycle.odd_holiday_card":"Your holiday card arrived on time. That made them suspicious.", +"lifecycle.odd_landlord":"Their landlord charges per cable through the wall, and yours is thick and showy.", +"lifecycle.odd_looking_glass":"Your looking glass was down for an hour, and their NOC lead took it personally.", +"lifecycle.odd_mate":"Your account manager called their account manager mate in an email. They are not mates.", +"lifecycle.odd_quadrant":"A consultant made a slide with a quadrant, and you were in the wrong one.", +"lifecycle.odd_raccoon":"A raccoon moved into their only cabinet, and it seems happier with another carrier's cross-connect.", +"lifecycle.odd_rdns":"Your reverse DNS for their IP says customer-cheapskate-04. Someone on their team noticed.", +"lifecycle.odd_space":"They pivoted to an AI-native, blockchain-backed, satellite-first strategy, and your fiber is not in space.", +"lifecycle.odd_spreadsheet_cell":"Procurement's new rule: every vendor's name must fit in one spreadsheet cell without wrapping.", +"lifecycle.odd_the_cloud":"They are moving everything to the cloud. The cloud is a rack two streets away, connected by you. They haven't noticed yet.", +"lifecycle.odd_too_many_feet":"Their intern ran a traceroute to show off, saw 14 hops and declared it too many feet.", +"lifecycle.odd_wireguard":"They are going fully remote. All 40 staff will run WireGuard from their kitchens, and the office line is just for the plants.", +"lifecycle.odd_wrong_blue":"The new office manager wants every cable the same colour, and yours is the wrong blue.", +"lifecycle.referred_by":"Referred by {name}, one of your happiest customers.", +"lifecycle.renewal_haggle":"renewal on {date}: haggling", +"lifecycle.renewals":"Renewals", +"lifecycle.renewals_soon":"Renewals", +"lifecycle.renewed_and_grew":"{name} renewed and grew to {bw} ({city}).", +"lifecycle.unanswered_matches":"No answer by the end of the contract means you match their price.", +"lifecycle.wants_price":"Pays {was}/mo, wants {price}/mo ({p} less) to renew.", +"lifecycle.why_acquired":"Acquired", +"lifecycle.why_bust":"Went bust", +"lifecycle.why_cheaper_bid":"Took a cheaper bid", +"lifecycle.why_insourced":"Built their own network", +"lifecycle.why_moved":"Moved away", +"lifecycle.why_multihomed":"Went to a second provider", +"lifecycle.why_other":"Other reasons", +"lifecycle.why_project_ended":"Project ended", +"lifecycle.why_they_left":"Why they left", +"lifecycle.why_unhappy":"Unhappy with the service", +"lifecycle.won":"Won", +"lifecycle.won_and_lost":"Customers won and lost", +"lifecycle.won_and_lost_note":"Contracts run one to five years, fiber pairs ten to twenty. When one ends, most customers renew at today's market price and happy ones often grow. Some leave, and not always because of you.", "link_modal.building_into_mainland_china_needs_a":"Building into mainland China needs a joint venture and an operating license. Open {city} to apply.", "link_modal.cross_border_circuits_into_mainland":"Cross-border circuits into mainland China are sold only by licensed carriers, at 3× the price. Regular ones lose about 20% of traffic at the border.", "link_modal.diverse_route_40_survives_cuts_alone":"Diverse route +40% · survives cuts alone", diff --git a/tests/customer-lifecycle.test.js b/tests/customer-lifecycle.test.js new file mode 100644 index 0000000..8fef686 --- /dev/null +++ b/tests/customer-lifecycle.test.js @@ -0,0 +1,190 @@ +// Customers come and go (#178): contract terms, renewals at the market price, growth, haggles, leaving for reasons that +// are not your fault, referrals, the bandwidth market, and old saves. Every roll is a hash of the customer and its +// term, so these tests pick ids that land where they need to and never depend on luck. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});compute()"; +// A signed customer, as an accepted offer makes it. +const sign = (ev, o) => ev(`(()=>{const b=clSign(offerCustomer(Object.assign({id:'c'+Math.random().toString(36).slice(2),city:'ams',city2:null,name:'Test Co',type:'dia',bw:5,rate:600,reqs:[],exp:S.day+40},${JSON.stringify(o || {})})));S.biz.push(b);return b.id;})()`); +const B = (ev, id, k) => ev(`S.biz.find(b=>b.id===${JSON.stringify(id)})${k ? '.' + k : ''}`); +// An id whose roll for question q (at term end te) is below p, or at least p when above is true. +const idFor = (ev, q, p, te, above = false) => ev(`(()=>{for(let i=0;i<20000;i++){const id='x'+i,r=clR({id,te:${te}},'${q}');if(${above ? 'r>=' : 'r<'}${p})return id;}})()`); + +test('every customer signs for a term that fits what it buys; events and scripted customers have none', () => { + const { ev, errors } = load(); + ev(start); + const months = (type) => { const id = sign(ev, { type, bw: 1, rate: 100 }); return Math.round((B(ev, id, 'te') - ev('S.day')) * 12 / 365); }; + for (const t of ['dia', 'host', 'game']) assert.ok([12, 24, 36].includes(months(t)), `${t}: one to three years`); + for (const t of ['l2vpn', 'isp']) assert.ok([24, 36, 48, 60].includes(months(t)), `${t}: two to five years`); + assert.ok([120, 180, 240].includes(months('dfpair')), 'fiber pairs: ten to twenty years'); + const ev1 = sign(ev, { type: 'event', start: ev('S.day') + 20, dur: 4, fee: 1000 }); + assert.equal(B(ev, ev1, 'te'), undefined, 'an event has its own ending'); + assert.equal(B(ev, sign(ev, {}), 'mk'), 1, 'signed in the market of the day'); + assert.equal(ev("S.cl.mo[S.cl.mo.length-1].won"), 7, 'and counted as won this month'); + assert.deepEqual(errors, []); +}); + +test('nothing happens during a first term, and a renewal reprices to the market at most 25% at once', () => { + const { ev, errors } = load(); + ev(start); + const te = ev('S.day') + 365; + const id = idFor(ev, 'leave', 0.9, te, true); + ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'Steady Co',type:'dia',bw:5,rate:600,reqs:[],mood:100,since:S.day,te:${te},mk:2})`); + ev(`for(let i=0;i<364;i++)clDay(S.day+i)`); + assert.equal(B(ev, id, 'rate'), 600, 'first term: same price, still here'); + ev(`S.biz.find(b=>b.id==='${id}').mood=100;clDay(${te})`); + assert.ok(B(ev, id), 'renewed'); + const rate = B(ev, id, 'rate'); + assert.ok(rate === 450 || B(ev, id, 'bw') > 5, `the market halved, but one renewal moves the price 25% at most (${rate})`); + assert.ok(B(ev, id, 'te') > te, 'a new term starts where the old one ended'); + assert.deepEqual(errors, []); +}); + +test('the lifecycle never draws from Math.random, so seeded games keep their stream', () => { + const { ev, errors } = load(); + ev(start); + for (let i = 0; i < 40; i++) sign(ev, { name: 'Co ' + i, type: i % 3 ? 'dia' : 'l2vpn', city2: i % 3 ? null : 'lon' }); + ev('for(const b of S.biz)b.te=S.day+31'); + ev('window.__r=0;const r0=Math.random;Math.random=()=>{__r++;return r0();};for(let i=0;i<40;i++)clDay(S.day+i);Math.random=r0'); + assert.equal(ev('__r'), 0); + assert.ok(ev("S.cl.mo.reduce((a,e)=>a+e.ren+e.grew+Object.values(e.lost).reduce((x,y)=>x+y,0),0)") > 0, 'contracts did end'); + assert.deepEqual(errors, []); +}); + +test('happy customers renew or grow; an unhappy one leaves, and says it was the service', () => { + const { ev, errors } = load(); + ev(start); + const te = ev('S.day') + 10; + const stay = idFor(ev, 'leave', 0.5, te, true), grow = ev(`(()=>{for(let i=0;i<20000;i++){const id='g'+i;if(clR({id,te:${te}},'leave')>=0.5&&clR({id,te:${te}},'grow')<0.3)return id;}})()`); + const sad = idFor(ev, 'leave', 0.3, te); + for (const [id, mood] of [[stay, 100], [grow, 100], [sad, 20]]) ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:2,rate:600,reqs:[],mood:${mood},since:S.day-400,te:${te},mk:1})`); + ev(`clDay(${te})`); + assert.ok(B(ev, stay), 'renewed'); + assert.equal(B(ev, grow, 'bw'), 5, 'grew to the next size their type sells'); + assert.equal(B(ev, sad), undefined, 'the unhappy one left'); + assert.equal(ev("S.cl.mo[S.cl.mo.length-1].lost.sad"), 1); + assert.match(ev('S.log[0].t+S.log[1].t+S.log[2].t'), /did not renew: the service let them down/); + assert.deepEqual(errors, []); +}); + +test('leaving that is not your fault: only reasons that fit the customer, and the odd ones at most every two months', () => { + const { ev, errors } = load(); + ev(start); + const r = JSON.parse(ev(`(()=>{const seen={};S.day=1000;S.cl={odd:-1e9,mo:[]}; + for(let i=0;i<3000;i++){const t=['dia','l2vpn','dfpair','isp','gpu'][i%5],b={id:'q'+i,city:'ams',city2:BIZ_T[t].l2||BIZ_T[t].fiber?'lon':null,name:'Q'+i,type:t,bw:4,rate:100,reqs:[],mood:90,since:0,te:S.day,mk:1}; + if(clR(b,'leave')>=(0.04+0.08*Math.min(1,clComp(b)/6)+0.35*0.01))continue;S.biz=[b];const before=JSON.stringify(S.cl.mo);clDay(S.day); + const e=S.cl.mo[S.cl.mo.length-1];for(const k in e.lost)(seen[k]=seen[k]||new Set()).add(t);S.cl.mo=[];S.day+=7;} + const out={};for(const k in seen)out[k]=[...seen[k]];return JSON.stringify(out);})()`)); + for (const k of Object.keys(r)) assert.ok(['acq', 'bust', 'insrc', 'moved', 'multi', 'ended', 'cheap', 'odd'].includes(k), k); + assert.ok(!(r.ended || []).includes('dia'), 'an internet customer has no project circuit to end'); + assert.ok(!(r.moved || []).some(t => t === 'l2vpn' || t === 'dfpair'), 'circuits and fiber do not move away'); + assert.ok(!(r.bust || []).includes('dfpair')); + // The odd reasons: never twice within 60 days. + const gaps = JSON.parse(ev(`(()=>{S.day=5000;S.cl={odd:-1e9,mo:[]};const days=[];for(let d=0;d<400;d++){for(let i=0;i<6;i++){const b={id:'o'+d+'_'+i,city:'ams',city2:null,name:'O',type:'dia',bw:1,rate:100,reqs:[],mood:90,since:0,te:S.day,mk:1};S.biz=[b];const o=S.cl.odd;clDay(S.day);if(S.cl.odd!==o)days.push(S.day);}S.day++;}return JSON.stringify(days);})()`)); + assert.ok(gaps.length >= 3, `odd reasons do come (${gaps.length} in 400 days)`); + assert.ok(gaps.every((d, i) => !i || d - gaps[i - 1] >= 60), 'at most one every 60 days'); + assert.deepEqual(errors, []); +}); + +test('a haggle: 30 days ahead, in Deals; match, meet halfway, let go, or no answer matches their price', () => { + const { ev, errors } = load(); + ev(start); + const te = ev('S.day') + 30; + const id = idFor(ev, 'hag', 0.05, te); + ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'Haggle Co',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:${te},mk:1})`); + ev(`clDay(S.day)`); + const hag = JSON.parse(ev(`JSON.stringify(S.biz.find(b=>b.id==='${id}').hag)`)); + assert.ok(hag && hag.rate < 600 && hag.rate >= 480 && hag.until === te, `asks 8–20% off until the term ends (${JSON.stringify(hag)})`); + ev("UI.left='deals';renderLeft()"); + const deals = ev("document.getElementById('leftBody')?document.getElementById('leftBody').innerHTML:document.getElementById('left').innerHTML"); + assert.match(deals, /data-act="renewMatch"/); + assert.match(deals, /data-act="renewMeet"/); + assert.match(deals, /data-act="renewLet"/); + assert.match(ev("document.getElementById('leftTabs').innerHTML"), /cnt">\d/, 'counted on the Deals tab'); + ev(`ACT.renewMatch({id:'${id}'})`); + assert.equal(B(ev, id, 'rate'), hag.rate, 'matched'); + assert.equal(B(ev, id, 'hag'), undefined); + // No answer: renews at the asked price when the term ends. + ev(`(()=>{const b=S.biz.find(b=>b.id==='${id}');b.hag={rate:500,until:S.day+5};})()`); + ev(`for(let i=0;i<6;i++)clDay(S.day+i)`); + assert.equal(B(ev, id, 'rate'), 500); + ev(`(()=>{const b=S.biz.find(b=>b.id==='${id}');b.hag={rate:400,until:S.day+5};})()`); + ev(`ACT.renewLet({id:'${id}'})`); + assert.equal(B(ev, id), undefined, 'let go'); + assert.deepEqual(errors, []); +}); + +test('the bandwidth market: flat for six months, then cheaper each year, up in a shortage, 1 without the market rule', () => { + const { ev, errors } = load(); + ev(start); + assert.equal(ev('mktBase(0)'), 1); + assert.equal(ev('mktBase(180)'), 1); + const y1 = ev('mktBase(180+365)'), y3 = ev('mktBase(180+3*365)'); + assert.ok(y1 < 0.97 && y1 > 0.85, `a year on: ${y1}`); + assert.ok(y3 < y1 && y3 > 0.6, `three years on: ${y3}`); + assert.ok(ev('mktBase(180+40*365)') >= 0.3, 'never below the floor'); + ev('S.day=900'); + const calm = ev('mkt()'); + ev("S.hw={shock:{k:'opt',until:S.day+30,mul:1.5}}"); + assert.ok(ev('mkt()') > calm * 1.1, 'a laser shortage pushes bandwidth prices up'); + ev("S.rules=Object.assign({},S.rules||RULE_DEF,{market:false})"); + assert.equal(ev('mkt()'), 1); + assert.deepEqual(errors, []); +}); + +test('word of mouth: a happy customer of a year or more brings a referral at the smallest size and today\'s price', () => { + const { ev, errors } = load(); + ev(start); + ev("S.day=900;S.offers=[];S.biz.push({id:'fan',city:'ams',city2:null,name:'Big Fan Ltd',type:'host',bw:40,rate:60,reqs:[],mood:100,since:100,te:2000,mk:1})"); + ev('clReferral(899)'); + assert.equal(ev('S.offers.length'), 0, 'about every six weeks, not every day'); + ev('clReferral(900)'); + const o = JSON.parse(ev('JSON.stringify(S.offers[0])')); + assert.equal(o.type, 'host'); + assert.equal(o.bw, 10, 'the smallest size'); + assert.equal(o.refN, 'Big Fan Ltd'); + assert.equal(o.rate, Math.round(60 * ev('mkt()'))); + ev("UI.left='deals';renderLeft()"); + assert.match(ev("document.getElementById('left').innerHTML"), /Referred by Big Fan Ltd/); + assert.deepEqual(errors, []); +}); + +test('old saves: renewals spread over the next year, the market from the signing day, broken fields repaired', () => { + const { ev, errors } = load(); + ev(start); + const s = JSON.parse(ev('JSON.stringify(packSave(S))')); + s.day = 1500; + s.biz = []; + for (let i = 0; i < 200; i++) s.biz.push({ id: 'old' + i, city: 'ams', name: 'Old ' + i, type: i % 2 ? 'dia' : 'host', bw: 5, rate: 600, mood: 90, since: 200 }); + s.biz.push({ id: 'bad', city: 'ams', name: 'Bad', type: 'dia', bw: 5, rate: 600, mood: 90, since: 200, te: 'soon', mk: -3, hag: { rate: 'x' } }); + s.cl = { odd: 'never', mo: [{ m: 30, won: 3, lost: { acq: 1, nonsense: 5 } }, 'junk'] }; + const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})))`)); + const tes = out.biz.map(b => b.te - 1500); + assert.ok(tes.every(t => t >= 30 && t <= 365), 'within the next year, never on day one'); + assert.ok(new Set(tes).size > 100, 'spread out, not one wave'); + const bad = out.biz.find(b => b.id === 'bad'); + assert.equal(bad.hag, undefined); + assert.ok(bad.mk > 0 && bad.mk === ev('mktBase(200)'), 'the market of the day it signed'); + assert.deepEqual(out.cl, { odd: -1e9, mo: [{ m: 30, won: 3, ren: 0, grew: 0, hag: 0, lost: { acq: 1 } }] }); + assert.deepEqual(errors, []); +}); + +test('the dashboard shows customers won and lost, why, renewals coming up and the market; rows show the contract', () => { + const { ev, errors } = load(); + ev(start); + const id = sign(ev, {}); + ev("clNote('lost','bust');clNote('lost','odd');clNote('grew')"); + ev("ACT.dash({});UI.dtab='cust';renderDash()"); + const h = ev("document.getElementById('dash').innerHTML"); + assert.match(h, /Customers won and lost/); + assert.match(h, /Went bust/); + assert.match(h, /Other reasons/); + assert.match(h, /Bandwidth market/); + assert.match(h, /contract until/); + ev(`selectCity('ams');UI.tab='cust';renderPanel()`); + assert.match(ev("document.getElementById('panel').innerHTML"), /contract until/); + assert.ok(B(ev, id)); + assert.deepEqual(errors, []); +}); diff --git a/tests/save-size.test.js b/tests/save-size.test.js index 4f4c544..1607493 100644 --- a/tests/save-size.test.js +++ b/tests/save-size.test.js @@ -39,7 +39,9 @@ const bigBiz = "ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buildPop "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<300;i++){const slots=1+i%4;S.biz.push({id:'w'+i,city:'fra',city2:'ams',reqs:[],latMax:null,route:'normal',name:'Carrier '+i,type:'wwave',bw:1,rate:4000,mood:100-i%9*1.37,since:i,sites:null,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots),pm:i%2?100:99,warned:i%5===0,warn60:false});}" + "S.biz.push({id:'l2',city:'fra',city2:'ams',reqs:['diverse'],latMax:3.2,route:'fast',name:'Fast Co',type:'hft',bw:5,rate:900,mood:80,since:0,sites:null,slots:0,pm:81,warned:false,warn60:true});" + - "S.biz.push({id:'d1',city:'fra',city2:null,reqs:[],latMax:null,route:'normal',name:'Plain Co',type:'dia',bw:5,rate:600,mood:100,since:0,sites:null,slots:0});compute()"; + "S.biz.push({id:'d1',city:'fra',city2:null,reqs:[],latMax:null,route:'normal',name:'Plain Co',type:'dia',bw:5,rate:600,mood:100,since:0,sites:null,slots:0});" + + // Signed customers carry a contract (#178): when the term ends and the market it was priced in. + "for(const b of S.biz)if(clOn(b)){b.te=400;b.mk=1;}compute()"; const sorted = "JSON.stringify(S.biz.map(b=>Object.keys(b).sort().map(k=>[k,b[k]])))"; test('#176 saves leave customer defaults out, and loading puts them back exactly', () => { From 0cdbef97fe08d968130bc9799df85b207b62ddf3 Mon Sep 17 00:00:00 2001 From: Christopher Hawker Date: Thu, 5 Nov 2026 18:26:44 +1100 Subject: [PATCH 339/491] A dashboard tab listing the cities with no POP yet The dashboard shows what you have built, not what you haven't. The new tab lists every city you could still open, with its eyeballs, exchange and price, and sorts, filters by region and pages like the other long lists. Open selects the city on the map, so a build still goes through the city panel and its warnings. The tab also works in the NOC window. --- CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 2 +- scripts/lib/route-fuzz.js | 2 +- site/i18n/de.js | 10 ++ site/i18n/es.js | 10 ++ site/i18n/fr.js | 10 ++ site/i18n/it.js | 10 ++ site/i18n/pt.js | 10 ++ src/agent/10-domains.js | 3 +- src/agent/20-commands.js | 3 + src/game/90-actions/70-dashboard-lists.js | 5 +- src/game/94-dashboard/35-unbuilt-pops.js | 13 ++ src/game/94-dashboard/40-connections.js | 2 +- src/game/94-dashboard/60-dashboard.js | 3 +- src/game/94-dashboard/90-noc-window.js | 4 +- src/i18n/en.js | 10 ++ tests/unbuilt-pops.test.js | 137 ++++++++++++++++++++++ 17 files changed, 227 insertions(+), 8 deletions(-) create mode 100644 src/game/94-dashboard/35-unbuilt-pops.js create mode 100644 tests/unbuilt-pops.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e1dc2b2..73bcf21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The NOC dashboard has a new tab listing every city where you have no POP yet, with its eyeballs, exchange and price. Sort it, filter by region, and jump to a city to build there. - Sweden gets Gothenburg, Malmö and Haparanda (#206). Gothenburg sits between Oslo and Copenhagen with its own exchange, Malmö faces Copenhagen across the Øresund, and Haparanda on the Finnish border is where the fibre crosses over land to Finland, with no exchange yet for you to found one. A Nordic fibre carrier sells transit along that route from Berlin to the border, and Swedish home networks reach the new cities. - The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. - Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f067aa0..de92159 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -39,7 +39,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers | | `91-save.js`, `92-audio.js` | Save, export and import; sound effects | | `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning | -| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints | +| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, cities with no POP yet, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints | | `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals | | `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, `draw()`, the world layer, cities, input and click delegation | | `99-loop.js` | `frame()` and `boot()` | diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index b5b5eb2..ca90eb5 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -56,7 +56,7 @@ const LEFT = ['nets', 'noc', 'deals', 'goals']; const PRESETS = ['freeze', 'oncall', 'bgp']; // How often a button is pressed against the others on screen: what changes the network often, looking around rarely. const BUILD = /^(buy\w*|pni\w*All|pni|peer|peerAll|unpeer|cache|cacheSite|rmCache|buildLink|buildPop|launchBB|accept|decline|dropBiz|takeLoan|repayLoan|lag[TPI]x?|setPref|setCarry|setStandby|setMetric|togglePrem|cleanPipe|sacrif|rs|foundIx|myIxUp|addRouter|rmRouter|upRouter|addSite|rmSite|siteSet|decomToggle|rmLink|upLink|addParallel|cancel\w*|upVxc|buyNni|rmNni|buildScrub|scrubUp|rmScrub|addGen|regen|addCh|rmCh|addPair|upSys|spares|layShip|crews|fixInc|seaPackage|subUpgrade|orderCable|orderDf|ownCab|opsHire|opsToggle|opsParam|opsCap|opsPop|opsTpl|opsNewPop|popStdSet|coreSet|teRecipe|dkOptOut|dkStay|utility\w*|listFiber|unlistFiber|leaseSwap|custGo|confGo|confSponsor|seatBuy|charter|cnPrem|applyCn|ad|ddosAuto|pz(Pop|RmPop|Link|AddPar|Tier|RmLink|RtAdd|RtRm|RtModel|Route|Via|Div)|setRoute|route|via|metricSet)$/; -const UIACT = /^(tab|dashTab|leftTab|\w*Sort|\w*Filter|pniGrp|trace\w*|focusCity|findGo|selLink|dashLink|logAll|tailTog|listMore|netFocus|netFilter|meetGo|phoneTab|dashClose|connF|connCity|connNet|connFor|custF|custCity|opsOpen|decomOpen|linkCheck)$/; +const UIACT = /^(tab|dashTab|leftTab|\w*Sort|\w*Filter|pniGrp|trace\w*|focusCity|findGo|selLink|dashLink|logAll|tailTog|listMore|netFocus|netFilter|meetGo|phoneTab|dashClose|connF|connCity|connNet|connFor|custF|custCity|popGo|popsReg|opsOpen|decomOpen|linkCheck)$/; const DW = { launchBB: 4, accept: 4, buyTransit: 3, pni: 3, buyIx: 3, setPref: 4, cache: 2, peerAll: 2, setCarry: 2, takeLoan: 2 }; const weight = (b) => (BUILD.test(b.act) ? 8 : UIACT.test(b.act) ? 0.3 : 1); diff --git a/site/i18n/de.js b/site/i18n/de.js index 159a8d4..8858e6f 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -4148,6 +4148,16 @@ "tutorial.your_customers_want_the_whole":"Deine Kunden wollen das ganze Internet. Öffne den Tab Transit und kauf einen Port bei einem Carrier.", "tutorial.your_router_is_live_press_launch":"Dein Router ist live. Drück auf „Breitband starten“, um den Leuten in deiner Stadt Internet zu verkaufen.", "ui.n_d_left":"noch {n} T.", +"unbuilt_pops.all_regions":"Alle Regionen", +"unbuilt_pops.cities_without_a_pop_n":"Städte ohne POP ({n})", +"unbuilt_pops.cost_then_mo":"{cost}, dann {mo}/Monat", +"unbuilt_pops.every_city_where_you_could_still":"Jede Stadt, in der du noch einen POP eröffnen kannst. Öffne eine, um zu sehen, was sie bietet, und dort zu bauen.", +"unbuilt_pops.n_more_city":{"one":"{n} weitere Stadt","other":"{n} weitere Städte"}, +"unbuilt_pops.needs_a_license_first":"Braucht zuerst eine Lizenz", +"unbuilt_pops.no_pop_yet":"Noch kein POP", +"unbuilt_pops.nothing_left_to_build_in_this":"In dieser Region gibt es nichts mehr zu bauen.", +"unbuilt_pops.region":"Region", +"unbuilt_pops.you_have_a_pop_in_every":"Du hast in jeder Stadt auf der Karte einen POP. Die Karte braucht wohl mehr Städte.", "utilities.apply_kit":"Redundanz-Kit anwenden", "utilities.cache_moves":"Zu verschiebende Cache-Boxen: {n} (je Anbieter ausgeglichen)", "utilities.cache_note":"Fordert an jedem bestehenden Standort einen Cache pro berechtigtem Anbieter an. Vorhandene Boxen bleiben; die Anbieter verlangen weiterhin genug Traffic.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6b51464..858e274 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -4146,6 +4146,16 @@ "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", +"unbuilt_pops.all_regions":"Todas las regiones", +"unbuilt_pops.cities_without_a_pop_n":"Ciudades sin POP ({n})", +"unbuilt_pops.cost_then_mo":"{cost}, luego {mo}/mes", +"unbuilt_pops.every_city_where_you_could_still":"Todas las ciudades donde aún puedes abrir un POP. Abre una para ver qué ofrece y construir allí.", +"unbuilt_pops.n_more_city":{"one":"{n} ciudad más","other":"{n} ciudades más"}, +"unbuilt_pops.needs_a_license_first":"Primero necesita una licencia", +"unbuilt_pops.no_pop_yet":"Sin POP aún", +"unbuilt_pops.nothing_left_to_build_in_this":"No queda nada por construir en esta región.", +"unbuilt_pops.region":"Región", +"unbuilt_pops.you_have_a_pop_in_every":"Tienes un POP en todas las ciudades del mapa. Al mapa le hacen falta más ciudades.", "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.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c530438..4b306c9 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -4146,6 +4146,16 @@ "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", +"unbuilt_pops.all_regions":"Toutes les régions", +"unbuilt_pops.cities_without_a_pop_n":"Villes sans POP ({n})", +"unbuilt_pops.cost_then_mo":"{cost}, puis {mo}/mois", +"unbuilt_pops.every_city_where_you_could_still":"Toutes les villes où tu peux encore ouvrir un POP. Ouvres-en une pour voir ce qu'elle offre et y construire.", +"unbuilt_pops.n_more_city":{"one":"{n} ville de plus","other":"{n} villes de plus"}, +"unbuilt_pops.needs_a_license_first":"Il faut d'abord une licence", +"unbuilt_pops.no_pop_yet":"Pas encore de POP", +"unbuilt_pops.nothing_left_to_build_in_this":"Plus rien à construire dans cette région.", +"unbuilt_pops.region":"Région", +"unbuilt_pops.you_have_a_pop_in_every":"Tu as un POP dans chaque ville de la carte. Il faudrait plus de villes.", "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.", diff --git a/site/i18n/it.js b/site/i18n/it.js index e37fafe..8c76f65 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -4146,6 +4146,16 @@ "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", +"unbuilt_pops.all_regions":"Tutte le regioni", +"unbuilt_pops.cities_without_a_pop_n":"Città senza POP ({n})", +"unbuilt_pops.cost_then_mo":"{cost}, poi {mo}/mese", +"unbuilt_pops.every_city_where_you_could_still":"Tutte le città dove puoi ancora aprire un POP. Aprine una per vedere cosa offre e costruire lì.", +"unbuilt_pops.n_more_city":{"one":"{n} altra città","other":"altre {n} città"}, +"unbuilt_pops.needs_a_license_first":"Serve prima una licenza", +"unbuilt_pops.no_pop_yet":"Ancora senza POP", +"unbuilt_pops.nothing_left_to_build_in_this":"In questa regione non resta niente da costruire.", +"unbuilt_pops.region":"Regione", +"unbuilt_pops.you_have_a_pop_in_every":"Hai un POP in ogni città della mappa. Alla mappa servono più città.", "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.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 06e7c30..29335c4 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -4146,6 +4146,16 @@ "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", +"unbuilt_pops.all_regions":"Todas as regiões", +"unbuilt_pops.cities_without_a_pop_n":"Cidades sem POP ({n})", +"unbuilt_pops.cost_then_mo":"{cost}, depois {mo}/mês", +"unbuilt_pops.every_city_where_you_could_still":"Todas as cidades onde você ainda pode abrir um POP. Abra uma para ver o que ela oferece e construir lá.", +"unbuilt_pops.n_more_city":{"one":"mais {n} cidade","other":"mais {n} cidades"}, +"unbuilt_pops.needs_a_license_first":"Precisa de uma licença primeiro", +"unbuilt_pops.no_pop_yet":"Ainda sem POP", +"unbuilt_pops.nothing_left_to_build_in_this":"Não há mais nada para construir nesta região.", +"unbuilt_pops.region":"Região", +"unbuilt_pops.you_have_a_pop_in_every":"Você tem um POP em todas as cidades do mapa. O mapa precisa de mais cidades.", "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.", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index 953c915..277e6ad 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -56,7 +56,8 @@ const API_DOMAINS={ leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, netFilter:{kind:'enum',values:['all','out']}, pniFilter:{kind:'enum',values:['all','t','worth','pni']}, - listPage:{kind:'enum',values:['conn','cust','nets','pni']}, + listPage:{kind:'enum',values:['conn','cust','nets','pni','pops']}, + popsSortKey:{kind:'enum',values:['eye','cost','name']}, custSortKey:{kind:'enum',values:['mood','mo','name','city']}, connFilter:{kind:'enum',values:['all','k']}, connSortKey:{kind:'enum',values:['k','city','name','use','mo']}, diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index a725106..15977c5 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -443,6 +443,9 @@ const API_VIEW={ custCity:{args:[['v','string']],doc:'Filter the customers list by city.'}, custSort:{args:[['k','custSortKey']],doc:'Flip the customers list sort.'}, custOpen:{args:[['sad','boolean',false]],doc:'Open the customers dashboard tab.'}, + popGo:{args:[['city','cityId']],doc:'Jump from the dashboard to a city with no POP yet.'}, + popsReg:{args:[['v','string']],doc:'Filter the list of cities with no POP by region.'}, + popsSort:{args:[['k','popsSortKey']],doc:'Flip the sort of the list of cities with no POP.'}, goConn:{args:[['city','cityId'],['k','connKind']],doc:'Open a city\'s connections tab.'}, goEgress:{args:[['city','cityId'],['k','egressKind']],doc:'Open a city\'s connections tab (l2 for the customer list).'}, connOpen:{args:[],doc:'Open the connections dashboard tab.'}, diff --git a/src/game/90-actions/70-dashboard-lists.js b/src/game/90-actions/70-dashboard-lists.js index 96ae70d..da73f96 100644 --- a/src/game/90-actions/70-dashboard-lists.js +++ b/src/game/90-actions/70-dashboard-lists.js @@ -1,10 +1,13 @@ 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'&&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();}, + listMore:({k})=>{if(k!=='conn'&&k!=='cust'&&k!=='nets'&&k!=='pni'&&k!=='pops')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();}, custOpen:({sad}={})=>{if(!S)return;UI.kf=sad?{f:'sad'}:{};listReset('cust');UI.dtab='cust';const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;}, + popGo:({city})=>{if(!isCity(city)||!cityOn(city))return;$('dash').hidden=true;ACT.focusCity({city});}, + popsReg:({v})=>{UI.popF=UI.popF||{};UI.popF.reg=own(REG,v)?v:'';listReset('pops');renderDash();}, + popsSort:({k})=>{if(!['eye','cost','name'].includes(k))return;listReset('pops');const sk=UI.popSort||'eye',d0=k==='eye'?-1:1;UI.popDir=sk===k?-(UI.popDir||d0):d0;UI.popSort=k;renderDash();}, goConn:({city,k})=>{if(!isCity(city)||!own(CONN_K,k))return;$('dash').hidden=true;ACT.goEgress({city,k});}, connF:({f,v})=>{const F=UI.cf=UI.cf||{};listReset('conn');if(f==='all'){UI.cf={};}else if(f==='k'){F.k=own(CONN_K,v)?v:'';}renderDash();}, connCity:({v})=>{UI.cf=UI.cf||{};listReset('conn');UI.cf.city=isCity(v)?v:'';renderDash();}, diff --git a/src/game/94-dashboard/35-unbuilt-pops.js b/src/game/94-dashboard/35-unbuilt-pops.js new file mode 100644 index 0000000..7a4b23e --- /dev/null +++ b/src/game/94-dashboard/35-unbuilt-pops.js @@ -0,0 +1,13 @@ +/* ---------- cities with no POP of yours yet ---------- */ +function popsSection(){const F=UI.popF||{},q=popStdQuote(),cost=c=>popCost(c)+(q?q.cost:0),mo=c=>popMo(c)+(q?q.mo:0); + const all=CITIES.filter(C=>cityOn(C.id)&&!S.pops[C.id]); + let h=`

${tr('unbuilt_pops.cities_without_a_pop_n',{n:all.length})}

`; + if(!all.length)return h+`

${tr('unbuilt_pops.you_have_a_pop_in_every')}

`; + h+=`

${tr('unbuilt_pops.every_city_where_you_could_still')}

`; + const sk=UI.popSort||'eye',dir=UI.popDir||-1,val=C=>sk==='name'?C.name.toLowerCase():sk==='cost'?cost(C.id):eyeP(C.id); + h+=`
`; + h+=`
${[['eye',tr('common.eyeballs')],['cost',tr('common.cost')],['name',tr('common.name')]].map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'popsSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; + const rows=all.filter(C=>!F.reg||C.reg===F.reg).sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||a.name.localeCompare(b.name);}); + if(!rows.length)return h+`

${tr('unbuilt_pops.nothing_left_to_build_in_this')}

`; + h+=rows.slice(0,listN('pops')).map(C=>{const ix=ixName(C.id);return `
${esc(C.name)} ${esc(REG[C.reg])}
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(C.id))})}${ix?` · ${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''} · ${tr('unbuilt_pops.cost_then_mo',{cost:fmt$(cost(C.id)),mo:fmt$(mo(C.id))})}
${C.cn&&!cnOk()?`
${tr('unbuilt_pops.needs_a_license_first')}
`:''}
${btn(tr('common.open'),'popGo',{city:C.id},'ghost sm')}
`;}).join(''); + return h+listMore('pops',rows.length,n=>trn('unbuilt_pops.n_more_city',n))+``;} diff --git a/src/game/94-dashboard/40-connections.js b/src/game/94-dashboard/40-connections.js index 9f4e440..568a32b 100644 --- a/src/game/94-dashboard/40-connections.js +++ b/src/game/94-dashboard/40-connections.js @@ -64,4 +64,4 @@ function netWhereIdx(){const B={t:{},p:{},ix:{},c:{}},add=(k,id,x)=>(B[k][id]||( function netWhere(n,where){const ch=(where||netWhereIdx())(n.id); if(!ch.length)return '';const MAX=6; return `
${ch.slice(0,MAX).map(([l,c,k])=>btn(`${esc(l)} ${esc(CITY[c].name)}`,'goConn',{city:c,k},'ghost sm')).join('')}${ch.length>MAX?btn(tr('dashboard.n_more',{n:ch.length-MAX}),'connFor',{net:n.id},'ghost sm'):''}
`;} -const DTABS=['overview','cust','conn','traffic','infra','lease']; +const DTABS=['overview','cust','conn','traffic','infra','pops','lease']; diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 4ea4fae..4a1e450 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -1,4 +1,4 @@ -function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),lease:tr('common.leased_lines')}; +function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),pops:tr('unbuilt_pops.no_pop_yet'),lease:tr('common.leased_lines')}; return ``;} function renderDash(){checkLayer(); const H=S.hist||[],rows=H.slice(-90),last30=H.slice(-30); @@ -29,6 +29,7 @@ function renderDash(){checkLayer(); if(DT==='infra')h+=`

${tr('common.busiest_links')}

${ls.length?ls.map(({l,u})=>`
${CITY[l.a].name} ⇄ ${CITY[l.b].name} ${capName(l)} · ${linkLat(l).toFixed(1)} ms
${pct(u)}${btn(tr('common.open'),'dashLink',{id:l.id},'ghost sm')}
`).join(''):'

'+tr('common.no_links_yet')+'

'}

${tr('common.router_load')}

${rs.map(({c,u})=>`
${CITY[c].name} ${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}
${pct(u)}
`).join('')}

${tr('common.your_as')}

${tr('common.as_number')}AS${S.asn}
${tr('common.prefixes')}${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6
${tr('common.bgp_sessions')}${R.sessions}
${tr('common.upstreams')}${new Set(S.transit.map(t=>t.net)).size}
${tr('common.reach')}${pct(R.reach)}
${tr('common.customers')}${tr('dashboard.n_businesses',{n:S.biz.length})}
`; + if(DT==='pops')h+=popsSection(); if(DT==='lease')h+=leaseTab(); if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);} } diff --git a/src/game/94-dashboard/90-noc-window.js b/src/game/94-dashboard/90-noc-window.js index 83d8189..db66bed 100644 --- a/src/game/94-dashboard/90-noc-window.js +++ b/src/game/94-dashboard/90-noc-window.js @@ -5,8 +5,8 @@ per network, opened once a window says hello, so other games' tabs never unpack them. With no window nothing is sent. */ const NOC_HB=3000,NOC_LOST=10000,NOC_GAP=1000; // What a click in the window does: changes only its own view, or runs in the game. Every button the dashboard draws is in one list. -const NOC_LOCAL=['chartToggle','connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore']; -const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagP','lagT','leaseSwap','netFocus','opsOpen','pni','pniAllOpen']; +const NOC_LOCAL=['chartToggle','connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore','popsReg','popsSort']; +const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagP','lagT','leaseSwap','netFocus','opsOpen','pni','pniAllOpen','popGo']; const NOC={win:false,id:null,ctl:null,st:null,stId:null,peer:false,until:0,dirty:false,sent:0,speed:1,hid:false,yoAt:0,gone:false}; {const id=RW_IN?null:new URLSearchParams(location.search).get('noc');if(slotOkId(id)){NOC.win=true;NOC.id=id;}} if(!RW_IN)try{if(typeof BroadcastChannel==='function'){NOC.ctl=new BroadcastChannel('sot-noc');NOC.ctl.onmessage=e=>{const m=e.data;if(!m||typeof m!=='object'||!slotOkId(m.id))return;if(NOC.win)nocWinMsg(m);else nocGameMsg(m);};}}catch(e){} diff --git a/src/i18n/en.js b/src/i18n/en.js index ad8a9de..00ecaf3 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -4147,6 +4147,16 @@ "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", +"unbuilt_pops.all_regions":"All regions", +"unbuilt_pops.cities_without_a_pop_n":"Cities without a POP ({n})", +"unbuilt_pops.cost_then_mo":"{cost}, then {mo}/mo", +"unbuilt_pops.every_city_where_you_could_still":"Every city where you could still open a POP. Open one to see what it offers and build there.", +"unbuilt_pops.n_more_city":{"one":"{n} more city","other":"{n} more cities"}, +"unbuilt_pops.needs_a_license_first":"Needs a license first", +"unbuilt_pops.no_pop_yet":"No POP yet", +"unbuilt_pops.nothing_left_to_build_in_this":"Nothing left to build in this region.", +"unbuilt_pops.region":"Region", +"unbuilt_pops.you_have_a_pop_in_every":"You have a POP in every city on the map. The map may need more cities.", "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.", diff --git a/tests/unbuilt-pops.test.js b/tests/unbuilt-pops.test.js new file mode 100644 index 0000000..04d47b4 --- /dev/null +++ b/tests/unbuilt-pops.test.js @@ -0,0 +1,137 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// The NOC dashboard's list of cities where the player has no POP yet. +function game(t) { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev("ACT.start({});closeModal();UI.speed=0;S.nextFail=S.nextEvent=1e9;compute();ACT.dash();ACT.dashTab({k:'pops'})"); + return h; +} +const json = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`)); +const shown = (ev) => json(ev, "[...document.querySelectorAll('#popsSec [data-act=\"popGo\"]')].map(b=>JSON.parse(b.dataset.args).city)"); +const open = (ev) => json(ev, 'CITIES.filter(C=>cityOn(C.id)&&!S.pops[C.id]).map(C=>C.id)'); +const more = (ev) => { while (ev("!!document.querySelector('#popsSec [data-act=\"listMore\"]')")) ev("ACT.listMore({k:'pops'})"); }; +const rowOf = (ev, c) => ev(`[...document.querySelectorAll('#popsSec .row')].find(r=>JSON.parse(r.querySelector('[data-act="popGo"]').dataset.args).city==='${c}').textContent`); + +test('it lists exactly the cities you could still open, biggest first', (t) => { + const { ev, errors } = game(t); + more(ev); + const c = shown(ev), want = open(ev); + assert.deepEqual([...c].sort(), [...want].sort()); + assert.ok(!c.includes(ev('S.home')), 'not where you already are'); + const hidden = json(ev, 'CITIES.filter(C=>!cityOn(C.id)).map(C=>C.id)'); + assert.ok(hidden.every((x) => !c.includes(x)), 'a city not on the map is not listed'); + const sizes = json(ev, `${JSON.stringify(c)}.map(eyeP)`); + assert.deepEqual(sizes, [...sizes].sort((a, b) => b - a)); + assert.match(ev("$('popsSec').textContent"), new RegExp(`Cities without a POP \\(${want.length}\\)`)); + assert.deepEqual(errors, []); +}); + +test('a row says what a player needs: eyeballs, exchange, and what the build would charge', (t) => { + const { ev, errors } = game(t); + more(ev); + const c = shown(ev).find((x) => ev(`!!ixName('${x}')`)); + const text = rowOf(ev, c); + for (const part of [`fmtG(eyeP('${c}'))`, `ixName('${c}')`, `fmt$(popCost('${c}'))`, `fmt$(popMo('${c}'))`, `CITY['${c}'].name`]) assert.ok(text.includes(ev(part)), part); + ev(`S.cash=1e9;ACT.buildPop({city:'${c}'})`); + assert.ok(ev(`!!S.pops['${c}']`)); + assert.ok(text.includes(ev(`fmt$(1e9-S.cash)`)), 'the listed price is what it costs'); + assert.deepEqual(errors, []); +}); + +test('the listed price includes your POP standard, like the build button', (t) => { + const { ev, errors } = game(t); + ev('popStdQuote=()=>({cost:1234567,mo:7654,rt:1,g:0});UI._dh=null;renderDash()'); + more(ev); + const c = shown(ev)[0], text = rowOf(ev, c); + assert.ok(text.includes(ev(`fmt$(popCost('${c}')+1234567)`))); + assert.ok(text.includes(ev(`fmt$(popMo('${c}')+7654)`))); + assert.deepEqual(errors, []); +}); + +test('building a POP takes the city off the list; none left says so', (t) => { + const { ev, errors } = game(t); + const c = shown(ev).find((x) => ev(`!CITY['${x}'].cn`)); // the biggest cities can be Chinese, and those need a license first + ev(`S.cash=1e9;ACT.buildPop({city:'${c}'});$('dash').hidden=false;UI.dtab='pops';renderDash()`); + assert.ok(!shown(ev).includes(c)); + ev('for(const C of CITIES)if(cityOn(C.id)&&!S.pops[C.id])S.pops[C.id]={day:0,routers:1};UI._dh=null;popsCheck=popsSection();'); + assert.match(ev('popsCheck'), /You have a POP in every city/); + assert.doesNotMatch(ev('popsCheck'), /popGo/); + assert.deepEqual(errors, []); +}); + +test('sorts flip, each starts the useful way round, and bad keys are ignored', (t) => { + const { ev, errors } = game(t); + const vals = (code) => { more(ev); return json(ev, `${JSON.stringify(shown(ev))}.map(c=>${code})`); }; + const asc = (a) => a.every((x, i) => !i || a[i - 1] <= x), desc = (a) => a.every((x, i) => !i || a[i - 1] >= x); + ev("ACT.popsSort({k:'eye'})"); + assert.ok(asc(vals('eyeP(c)')), 'clicking the default sort flips it'); + ev("ACT.popsSort({k:'eye'})"); + assert.ok(desc(vals('eyeP(c)'))); + ev("ACT.popsSort({k:'cost'})"); + assert.ok(asc(vals('popCost(c)')), 'cheapest first'); + ev("ACT.popsSort({k:'cost'})"); + assert.ok(desc(vals('popCost(c)'))); + ev("ACT.popsSort({k:'name'})"); + const names = vals('CITY[c].name.toLowerCase()'); + assert.deepEqual(names, [...names].sort()); + ev("ACT.popsSort({k:'eye'})"); + assert.ok(desc(vals('eyeP(c)')), 'coming back to eyeballs starts biggest first'); + ev("ACT.popsSort({k:'nope'})"); + assert.equal(ev('UI.popSort'), 'eye'); + assert.deepEqual(errors, []); +}); + +test('the region filter narrows the list, ignores nonsense, and an emptied region says so', (t) => { + const { ev, errors } = game(t); + ev("ACT.popsReg({v:'OC'})"); + more(ev); + const oc = shown(ev); + assert.ok(oc.length > 0); + assert.ok(ev(`${JSON.stringify(oc)}.every(c=>CITY[c].reg==='OC')`)); + assert.equal(oc.length, ev("CITIES.filter(C=>cityOn(C.id)&&!S.pops[C.id]&&C.reg==='OC').length")); + ev("for(const C of CITIES)if(C.reg==='OC'&&cityOn(C.id))S.pops[C.id]={day:0,routers:1};UI._dh=null;renderDash()"); + assert.equal(shown(ev).length, 0); + assert.match(ev("$('popsSec').textContent"), /Nothing left to build in this region/); + assert.ok(ev("!!document.querySelector('#popsSec [data-chg=\"popsReg\"]')"), 'the filter is still there to change'); + ev("ACT.popsReg({v:'constructor'})"); + assert.equal(ev('UI.popF.reg'), ''); + assert.ok(shown(ev).length > 0); + assert.deepEqual(errors, []); +}); + +test('the list pages like the other long lists, and a new sort or filter starts from the top', (t) => { + const { ev, errors } = game(t); + assert.equal(shown(ev).length, ev('LIST_PAGE')); + ev("ACT.listMore({k:'pops'})"); + assert.ok(shown(ev).length > ev('LIST_PAGE')); + ev("ACT.popsSort({k:'name'})"); + assert.equal(shown(ev).length, ev('LIST_PAGE')); + ev("ACT.listMore({k:'pops'});ACT.popsReg({v:'EU'})"); + assert.equal(ev("listN('pops')"), ev('LIST_PAGE')); + assert.deepEqual(errors, []); +}); + +test('Open closes the dashboard and selects the city, without building anything', (t) => { + const { ev, errors } = game(t); + const c = shown(ev)[0], cash = ev('S.cash'); + ev(`ACT.popGo({city:'${c}'})`); + assert.equal(ev("$('dash').hidden"), true); + assert.equal(ev('UI.sel.id'), c); + assert.equal(ev('S.cash'), cash); + assert.ok(ev(`!S.pops['${c}']`)); + for (const bad of ["'nope'", "'constructor'", '1']) { ev('UI.sel=null'); ev(`ACT.popGo({city:${bad}})`); assert.equal(ev('UI.sel'), null, bad); } + assert.deepEqual(errors, []); +}); + +test('a Chinese city says it needs a license until you have one', (t) => { + const { ev, errors } = game(t); + more(ev); + const c = ev('CITIES.find(C=>C.cn&&cityOn(C.id)&&!S.pops[C.id]).id'); + assert.match(rowOf(ev, c), /Needs a license first/); + ev("S.cnLic={state:'ok'};UI._dh=null;renderDash()"); + assert.doesNotMatch(rowOf(ev, c), /Needs a license first/); + assert.deepEqual(errors, []); +}); From b9860edc7761ea4670acd9670b67db82b5bf1e31 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 08:19:05 +0000 Subject: [PATCH 340/491] Dark fiber leases cost half as much again (#203) A leased pair was $400 + $1/km a month, so a single 400G wave on the same route cost two to three times the whole fiber. It is now $600 + $1.50/km (amplifiers as before): a lease pays off at a couple of 400G waves, as dark fiber does. Leases already signed keep their price (l.mo). Alien-wave rent follows, since it is priced against the fiber. The differential route fuzz now also compares link prices, so a deliberate price change compares this checkout with itself, as a change to the world already does. --- CHANGELOG.md | 1 + src/game/10-catalog/50-dark-fiber.js | 4 +++- tests/alien-wave-rent.test.js | 14 ++++++++++++++ tests/route-fuzz.test.js | 9 +++++---- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbfce26..0c94f3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ All notable changes to this project are documented here. The project follows - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in. - Clean traffic that a scrubbing center sends back to a customer under attack no longer shows as DDoS junk on your backbone links; a link now lists it as scrubbed clean traffic, so a small flood no longer looks like hundreds of gigabits of junk (#289). - Alien waves you rent out on your dark fiber are now priced against the fiber itself: a wave costs a share of what leasing and lighting that fiber would cost the buyer, and each wave sold between the same two cities goes a little cheaper than the last. A route sold out to its market now earns a few times its lease, not dozens, and contracts already signed keep their price (#203). +- Leasing a dark fiber pair now costs about half as much again ($600 plus $1.50 per km a month, amplifiers as before), so it pays off once you light a couple of 400G waves on it. Leases you already hold keep their price (#203). - Extra crews can now cut a fiber build on land to half its planned time at most, since permits and rights of way do not speed up; the button shows the day it would be done (#203). - A link ordered by typing both ends (the AI tools) can no longer end in a city the map does not show (#203). ## [2.9.1] — 2026-11-04 diff --git a/src/game/10-catalog/50-dark-fiber.js b/src/game/10-catalog/50-dark-fiber.js index ef602d1..b03c36a 100644 --- a/src/game/10-catalog/50-dark-fiber.js +++ b/src/game/10-catalog/50-dark-fiber.js @@ -16,7 +16,9 @@ const OPT={ tp16:{n:'Sienna WaveMagic 1.6T',g:1600,cost:70000,reach:4000,modes:[[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:2,lvl:4,sys:'roadm',blurb:tr('dark_fiber.big_shelf_big_reach_big_invoice')}, tp32:{n:'Sienna WaveMagic 3.2T',g:3200,cost:130000,reach:1500,modes:[[3200,1500],[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:4,lvl:8,sys:'roadm',blurb:tr('dark_fiber.twice_the_wavemagic_full_speed_only')}, }; -const dfLeaseMo=km=>Math.round(400+km*1.0); +// A leased fiber pair, per month. Dear enough that it pays off at a couple of 400G waves, as dark fiber does (#203); +// a lease already signed keeps its price (l.mo). +const dfLeaseMo=km=>Math.round(600+km*1.5); const dfBuildCost=km=>Math.round((25000+km*120)*hwMul('build')); const dfBuildDays=km=>leadDays(Math.round(120+km*0.25)),IRU_DAYS=30; const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY)); diff --git a/tests/alien-wave-rent.test.js b/tests/alien-wave-rent.test.js index 9bd353e..92b68e1 100644 --- a/tests/alien-wave-rent.test.js +++ b/tests/alien-wave-rent.test.js @@ -65,3 +65,17 @@ test('#203 a dark fiber, cable or wave cannot be ordered to a city the map does assert.equal(ev(`S.links.some(l=>l.b==='${off}'||l.a==='${off}')`), false); assert.deepEqual(errors, []); }); + +test('#203 a dark fiber lease costs more, and a lease already signed keeps its price', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;for(const c of ['fra','ams'])if(!S.pops[c])ACT.buildPop({city:c})"); + assert.equal(ev('dfLeaseMo(1000)'), 2100); + ev("UI.pending={a:'fra',b:'ams'};UI.dfSrc='lease';UI.dfSys='lite';ACT.orderDf()"); + const km = ev("S.links.find(l=>l.kind==='df').km"); + assert.equal(ev("S.links.find(l=>l.kind==='df').mo"), Math.round(600 + km * 1.5)); + // An old save's lease, signed at the old price, keeps it. + const old = Math.round(400 + km); + ev(`S.links.find(l=>l.kind==='df').mo=${old};S=migrate(JSON.parse(JSON.stringify(S)))`); + assert.equal(ev("S.links.find(l=>l.kind==='df').mo"), old); + assert.deepEqual(errors, []); +}); diff --git a/tests/route-fuzz.test.js b/tests/route-fuzz.test.js index 4ac9d80..ff2980e 100644 --- a/tests/route-fuzz.test.js +++ b/tests/route-fuzz.test.js @@ -16,10 +16,11 @@ function pages() { let base = head; try { const b = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-base.html`); fs.writeFileSync(b, page.assembleRef('origin/main')); base = b; } catch (e) {} let P = { base: openPage(base, 'base'), head: openPage(head, 'head') }; - // A change to the world itself (cities, networks, cables) cannot route like main: there is no same game to compare. - // Then the base is this checkout too, and the cache on/off check still runs; equivalence with main resumes once it lands. - const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])])])"); - if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world differs from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; } + // A change to the world itself (cities, networks, cables) or to what links cost cannot route like main: there is no + // same game to compare. Then the base is this checkout too, and the cache on/off check still runs; equivalence with + // main resumes once it lands. + const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)])])"); + if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world or its prices differ from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; } return P; } From 27c4977412f8e085a6251345383b0404083cc73e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 09:32:24 +0100 Subject: [PATCH 341/491] A sales desk: the engineer turned salesdroid, the shark, or the CEO From customer level 2, one person runs sales at a time, next to the NOC intern: - The engineer turned salesdroid ($9k/mo) books you into every network operators' meeting 30 days ahead at the usual ticket price, brings 40% more offers (half as many again while a meeting's glow lasts) but never the huge deals, and their customers leave less often at renewal (half as often for the nerdy ones: HFT, ISPs, universities, L2). Haggles badly. - The shark ($15k/mo) brings bigger sizes at 25% more, takes a month of each deal as commission, oversells half of them with a requirement the network does not meet yet, never brings technical customers, makes selective peering desks want 25% more traffic, wins most haggles, and their customers leave 50% more often. - The CEO (free) signs the biggest internet customer the network can take on the golf course every 50-80 days at 30% off, often with a promise nobody checked, signs about a third of the offers you decline anyway, and has opinions. He cannot be fired: a board meeting brings a VP of Sales a month later. Customers remember who signed them (by), which the renewals read. Every roll is a hash of the day or the deal, so games without a salesperson keep their random stream. The differential fuzz also leaves out buttons for actions main does not have yet. --- CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 2 +- scripts/lib/fuzz-page.js | 3 +- scripts/lib/route-fuzz.js | 5 +- site/i18n/de.js | 36 ++++++ site/i18n/es.js | 36 ++++++ site/i18n/fr.js | 36 ++++++ site/i18n/it.js | 36 ++++++ site/i18n/pt.js | 36 ++++++ src/agent/10-domains.js | 1 + src/agent/20-commands.js | 7 ++ src/agent/30-docs.js | 1 + src/agent/40-read.js | 2 +- src/game/60-features/38-sales-desk.js | 75 +++++++++++ src/game/70-rules/70-sold-out.js | 2 +- src/game/80-simulation/30-compute.js | 2 +- src/game/80-simulation/50-sanitize.js | 2 +- .../80-simulation/75-customer-lifecycle.js | 4 +- src/game/88-days/10-day-tick.js | 4 +- src/game/90-actions/50-customers.js | 8 +- src/game/90-actions/52-sales.js | 12 ++ src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/58-sales-panel.js | 17 +++ src/i18n/en.js | 36 ++++++ tests/sales-desk.test.js | 118 ++++++++++++++++++ 25 files changed, 470 insertions(+), 14 deletions(-) create mode 100644 src/game/60-features/38-sales-desk.js create mode 100644 src/game/90-actions/52-sales.js create mode 100644 src/game/93-ui/58-sales-panel.js create mode 100644 tests/sales-desk.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c94f3f..46ed97e 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 sales desk joins the NOC intern: from customer level 2 you can put one person in charge of sales, and each brings deals their own way. The engineer turned salesdroid books you into every network operators' meeting (you pay the ticket), brings more small and mid deals but never the huge ones, and only sells what your network can do, so their customers stay longer; they haggle badly. The shark lands bigger deals at a quarter more and takes a month of each as commission, but oversells promises your network does not keep yet, ignores technical customers and meetings, and makes peering desks want more traffic from you. Or the CEO runs sales himself, for free: a huge discounted deal on the golf course every couple of months, the odd offer you declined signed anyway, opinions, and no way to fire him short of asking the board for a VP of Sales. - Customers now sign contracts, and when one ends they renew, grow, haggle or leave, not always because of you (#178). Most renew at today's bandwidth price, which falls about 10% a year but rises when hardware is short; happy customers often take a bigger size, and some ask for a discount you can match, meet halfway or turn down in Deals. Others are acquired, go bust, build their own network, move away (they stay if you have a POP where they go), split their traffic with a second provider or end their project, and now and then one leaves for a stranger reason. Nothing changes during a customer's first contract, renewals in an old save are spread over the next year, your happiest long-time customers send you referrals, and the NOC dashboard shows customers won and lost each month and why. - Sweden gets Gothenburg, Malmö and Haparanda (#206). Gothenburg sits between Oslo and Copenhagen with its own exchange, Malmö faces Copenhagen across the Øresund, and Haparanda on the Finnish border is where the fibre crosses over land to Finland, with no exchange yet for you to found one. A Nordic fibre carrier sells transit along that route from Berlin to the border, and Swedish home networks reach the new cities. - The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1dbb155..a14bb92 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -31,7 +31,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, 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()`) | +| `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()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers) | | `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | | `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service | | `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) | diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 2070d32..9a2c532 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -177,5 +177,6 @@ if (keep) UI.rkR = R; return { a, b, c }; }; - window.__fz = { direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen }; + const acts = () => Object.keys(ACT); + window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen }; })(); diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index bbc1683..6053bdd 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -98,7 +98,10 @@ function playGame(pages, seed, opts = {}) { if (!div) compare('start'); // A screen's buttons on both pages; the same list or a divergence. - const screen = (w) => { const [a, b] = both('screen', w); same('buttons of ' + JSON.stringify(w), a, b); return a || []; }; + // Buttons for actions main's page does not have (a new feature's) are left out: the driver only presses what both have. + let baseActs = null; + const screen = (w) => { const [a, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts')); + const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)) : b0; same('buttons of ' + JSON.stringify(w), a, b); return a || []; }; const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); }; // Answer whatever window opened, a few levels deep, then close it. const modal = (bias) => { diff --git a/site/i18n/de.js b/site/i18n/de.js index 248b069..e8a6fd1 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3904,6 +3904,42 @@ "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.", +"sales.ask_vp":"Beim Vorstand einen VP Sales beantragen · {cost}", +"sales.at_desk":"{name} leitet den Vertrieb", +"sales.ceo_d":"Kostenlos, und überzeugt davon. Alle paar Monate unterschreibt er auf dem Golfplatz einen Riesendeal mit 30 % Rabatt, oft mit einem Versprechen, das niemand geprüft hat, und ab und zu ein Angebot, das du abgelehnt hast. Hat Meinungen. Kann nicht entlassen werden.", +"sales.ceo_golf":"Der CEO hat {name} auf dem Golfplatz unterschrieben: {bw} in {city} für {price}/Monat, 30 % unter Liste.", +"sales.ceo_n":"Der CEO, der besser verkauft als alle", +"sales.ceo_override":"Du hast {name} abgelehnt, aber der CEO hatte schon eingeschlagen. Jetzt sind sie Kunde.", +"sales.ceo_promised":"Er hat auch versprochen: {req}.", +"sales.ceo_s":"der CEO", +"sales.ceo_say_airport":"Gerade gelandet. Nichts unterschrieben, aber beim Lounge-WLAN hatte ich ein sehr gutes Gefühl.", +"sales.ceo_say_blockchain":"Haben wir mal überlegt, die Routingtabelle auf eine Blockchain zu legen?", +"sales.ceo_say_golf":"Die besten Deals passieren am neunten Loch. Das NOC sollte mehr Golf spielen.", +"sales.ceo_say_mbps":"Warum verkaufen wir Gigabit? Megabit klingt nach mehr.", +"sales.ceo_say_napkin":"Ich habe den nächsten Deal auf einer Serviette kalkuliert. Die Technik kann die Details klären.", +"sales.ceo_say_synergy":"Wir verkaufen keine Bandbreite, wir verkaufen Synergie. Schreibt das auf die Website.", +"sales.ceo_says":"Der CEO: „{say}“", +"sales.ceo_took_over":"{name} hat den Vertrieb persönlich übernommen. Er ist sicher, dass er besser verkauft als alle.", +"sales.commission":"{name} hat unterschrieben. Provision für den Hai: {cost}.", +"sales.desk":"Vertrieb", +"sales.eng_booked":"{name} hat dich für {conf} in {city} angemeldet ({cost}). Das Badge liegt schon bereit.", +"sales.eng_d":"War Netzwerkingenieur und hat jetzt ein Badge von jeder NOG. Meldet dich zu jeder an (das Ticket zahlst du), bringt viele kleine und mittlere Deals, aber nie die richtig großen, und verkauft nur, was das Netz kann, also bleiben die Kunden. Die Nerds lieben Dave. Verhandelt schlecht.", +"sales.eng_n":"Der Ingenieur, jetzt Salesdroide", +"sales.eng_s":"Dave", +"sales.fired":"{name} hat den Schreibtisch geräumt. Der Vertrieb ist frei.", +"sales.hire_sales":"Vertrieb einstellen", +"sales.hired":"{name} ist jetzt im Vertrieb. Rechne mit Deals in diesem Stil.", +"sales.intro":"Eine Person leitet den Vertrieb. Jede holt Deals auf ihre Art, und die Kunden, die sie abschließt, erinnern sich daran, wenn ihr Vertrag ausläuft.", +"sales.let_ceo":"Den CEO machen lassen", +"sales.locked":"Der Vertrieb öffnet ab Kundenstufe {lv}.", +"sales.one_at_a_time":"Immer nur eine Person: Lass sie gehen, um jemand anderen einzustellen.", +"sales.pitch":"Eine Person im Vertrieb holt Deals auf ihre eigene Art. Such sie aus.", +"sales.shark_d":"Holt die größten Deals zu einem Viertel mehr und kassiert einen Monat jedes Deals als Provision. Verkauft zu viel: Die Hälfte kommt mit einem Versprechen, das dein Netz noch nicht hält, und diese Kunden gehen früher. Ignoriert die Nerds: keine technischen Kunden, keine Meetings, und Peering-Desks wollen ein Viertel mehr Verkehr von dir. Gewinnt die meisten Verhandlungen.", +"sales.shark_n":"Der Hai", +"sales.shark_s":"Chad", +"sales.vp_arrived":"Der VP Sales hat angefangen, und der CEO ist zurück bei der Strategie. Der Vertrieb ist frei: Stell jemanden ein.", +"sales.vp_asked":"Der Vorstand hat zugestimmt, nach dem Mittagessen. Ein VP Sales fängt in {n} Tagen an; bis dahin verkauft der CEO weiter.", +"sales.vp_coming":"Ein VP Sales übernimmt in {n} Tagen.", "save.cash_in_the_bank":"{cash} auf der Bank", "save.import_failed_err":"Import fehlgeschlagen.
{err}", "save.load_name":"{name} laden?", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2bcc245..dc68dc0 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3902,6 +3902,42 @@ "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.", +"sales.ask_vp":"Pedir al consejo un VP de Ventas · {cost}", +"sales.at_desk":"{name} lleva las ventas", +"sales.ceo_d":"Gratis, y convencido. Cada par de meses firma un trato enorme en el campo de golf con un 30 % de descuento, a menudo con una promesa que nadie comprobó, y de vez en cuando firma una oferta que tú rechazaste. Tiene opiniones. No se le puede despedir.", +"sales.ceo_golf":"El CEO firmó a {name} en el campo de golf: {bw} en {city} por {price}/mes, un 30 % por debajo de tarifa.", +"sales.ceo_n":"El CEO, que vende mejor que nadie", +"sales.ceo_override":"Rechazaste a {name}, pero el CEO ya había dado la mano. Ahora son clientes.", +"sales.ceo_promised":"También prometió: {req}.", +"sales.ceo_s":"el CEO", +"sales.ceo_say_airport":"Acabo de aterrizar. No he firmado nada, pero el Wi-Fi de la sala VIP me dio muy buena espina.", +"sales.ceo_say_blockchain":"¿Hemos pensado en poner la tabla de rutas en una blockchain?", +"sales.ceo_say_golf":"Los mejores tratos se cierran en el hoyo nueve. El NOC debería jugar más al golf.", +"sales.ceo_say_mbps":"¿Por qué vendemos gigabits? Megabits suena a más.", +"sales.ceo_say_napkin":"He calculado el próximo trato en una servilleta. Ingeniería puede resolver los detalles.", +"sales.ceo_say_synergy":"No vendemos ancho de banda, vendemos sinergia. Ponedlo en la web.", +"sales.ceo_says":"El CEO: «{say}»", +"sales.ceo_took_over":"{name} se ha hecho cargo de las ventas en persona. Está seguro de que vende mejor que nadie.", +"sales.commission":"{name} firmó. Comisión para el tiburón: {cost}.", +"sales.desk":"Ventas", +"sales.eng_booked":"{name} te apuntó a {conf} en {city} ({cost}). Ya tiene la acreditación.", +"sales.eng_d":"Era ingeniero de redes y ahora tiene la acreditación de cada NOG. Te apunta a todas (la entrada la pagas tú), trae muchos tratos pequeños y medianos pero nunca los grandes de verdad, y solo vende lo que la red puede hacer, así que los clientes se quedan. Los nerds adoran a Dave. Negocia fatal.", +"sales.eng_n":"El ingeniero convertido en vendedroide", +"sales.eng_s":"Dave", +"sales.fired":"{name} ha vaciado su mesa. Ventas está libre.", +"sales.hire_sales":"Contratar ventas", +"sales.hired":"{name} se unió a ventas. Espera tratos a su estilo.", +"sales.intro":"Una persona lleva las ventas. Cada una trae tratos a su manera, y los clientes que firma lo recuerdan cuando les toca renovar.", +"sales.let_ceo":"Dejar que lo lleve el CEO", +"sales.locked":"Ventas se abre en el nivel de clientes {lv}.", +"sales.one_at_a_time":"Solo una a la vez: despídela para contratar a otra.", +"sales.pitch":"Una persona de ventas trae tratos a su manera. Elige quién.", +"sales.shark_d":"Consigue los tratos más grandes a un cuarto más, y se lleva un mes de cada trato de comisión. Vende de más: la mitad llega con una promesa que tu red aún no cumple, y esos clientes se van antes. Ignora a los nerds: nada de clientes técnicos ni de reuniones, y los equipos de peering te piden un cuarto más de tráfico. Gana casi todas las negociaciones.", +"sales.shark_n":"El tiburón", +"sales.shark_s":"Chad", +"sales.vp_arrived":"El VP de Ventas ya empezó, y el CEO ha vuelto a la estrategia. Ventas está libre: contrata a alguien.", +"sales.vp_asked":"El consejo aceptó, después de comer. Un VP de Ventas empieza en {n} días; hasta entonces el CEO sigue vendiendo.", +"sales.vp_coming":"Un VP de Ventas toma el relevo en {n} días.", "save.cash_in_the_bank":"{cash} en el banco", "save.import_failed_err":"Falló la importación.
{err}", "save.load_name":"¿Cargar {name}?", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index eefbefc..45c2445 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3902,6 +3902,42 @@ "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.", +"sales.ask_vp":"Demander un VP Ventes au conseil · {cost}", +"sales.at_desk":"{name} gère les ventes", +"sales.ceo_d":"Gratuit, et convaincu. Tous les deux mois, il signe un énorme contrat sur le terrain de golf à -30 %, souvent avec une promesse que personne n'a vérifiée, et de temps en temps une offre que vous aviez refusée. A des avis sur tout. Impossible à licencier.", +"sales.ceo_golf":"Le PDG a signé {name} sur le terrain de golf : {bw} à {city} pour {price}/mois, 30 % sous le tarif.", +"sales.ceo_n":"Le PDG, qui vend mieux que personne", +"sales.ceo_override":"Vous avez refusé {name}, mais le PDG avait déjà topé. C'est maintenant un client.", +"sales.ceo_promised":"Il a aussi promis : {req}.", +"sales.ceo_s":"le PDG", +"sales.ceo_say_airport":"Je viens d'atterrir. Rien signé, mais j'ai eu un très bon pressentiment avec le Wi-Fi du salon.", +"sales.ceo_say_blockchain":"Avons-nous pensé à mettre la table de routage sur une blockchain ?", +"sales.ceo_say_golf":"Les meilleurs contrats se signent au neuvième trou. Le NOC devrait jouer plus au golf.", +"sales.ceo_say_mbps":"Pourquoi vendre des gigabits ? Des mégabits, ça fait plus.", +"sales.ceo_say_napkin":"J'ai chiffré le prochain contrat sur une serviette. L'ingénierie réglera les détails.", +"sales.ceo_say_synergy":"Nous ne vendons pas de la bande passante, nous vendons de la synergie. Mettez ça sur le site.", +"sales.ceo_says":"Le PDG : « {say} »", +"sales.ceo_took_over":"{name} a pris les ventes en main personnellement. Il est sûr de vendre mieux que personne.", +"sales.commission":"{name} a signé. Commission du requin : {cost}.", +"sales.desk":"Service commercial", +"sales.eng_booked":"{name} vous a inscrit à {conf} à {city} ({cost}). Le badge est déjà prêt.", +"sales.eng_d":"Ancien ingénieur réseau, il a un badge de chaque NOG. Il vous inscrit à toutes (vous payez le billet), apporte beaucoup de petits et moyens contrats mais jamais les très gros, et ne vend que ce que le réseau sait faire : les clients restent. Les geeks adorent Dave. Il négocie mal.", +"sales.eng_n":"L'ingénieur devenu commercial-droïde", +"sales.eng_s":"Dave", +"sales.fired":"{name} a vidé son bureau. Le service commercial est libre.", +"sales.hire_sales":"Recruter un commercial", +"sales.hired":"{name} rejoint le service commercial. Attendez-vous à des contrats dans son style.", +"sales.intro":"Une seule personne gère les ventes. Chacune apporte des contrats à sa façon, et les clients qu'elle signe s'en souviennent à l'échéance.", +"sales.let_ceo":"Laisser le PDG s'en charger", +"sales.locked":"Le service commercial ouvre au niveau clients {lv}.", +"sales.one_at_a_time":"Une seule à la fois : laissez-la partir pour en recruter une autre.", +"sales.pitch":"Un commercial apporte des contrats à sa façon. Choisissez qui.", +"sales.shark_d":"Décroche les plus gros contrats un quart plus cher, et prend un mois de chaque contrat en commission. Survend : la moitié arrive avec une promesse que votre réseau ne tient pas encore, et ces clients partent plus tôt. Ignore les geeks : pas de clients techniques, pas de NOG, et les équipes peering vous demandent un quart de trafic en plus. Gagne la plupart des négociations.", +"sales.shark_n":"Le requin", +"sales.shark_s":"Chad", +"sales.vp_arrived":"Le VP Ventes a pris son poste, et le PDG est retourné à la stratégie. Le service commercial est libre : recrutez quelqu'un.", +"sales.vp_asked":"Le conseil a dit oui, après le déjeuner. Un VP Ventes arrive dans {n} jours ; d'ici là, le PDG continue de vendre.", +"sales.vp_coming":"Un VP Ventes prend le relais dans {n} jours.", "save.cash_in_the_bank":"{cash} en banque", "save.import_failed_err":"Échec de l’import.
{err}", "save.load_name":"Charger {name} ?", diff --git a/site/i18n/it.js b/site/i18n/it.js index e75fe8d..7ab959c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3902,6 +3902,42 @@ "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.", +"sales.ask_vp":"Chiedi al consiglio un VP vendite · {cost}", +"sales.at_desk":"{name} gestisce le vendite", +"sales.ceo_d":"Gratis, e convinto. Ogni paio di mesi firma un contratto enorme sul campo da golf con il 30% di sconto, spesso con una promessa che nessuno ha controllato, e ogni tanto firma un'offerta che avevi rifiutato. Ha opinioni. Non si può licenziare.", +"sales.ceo_golf":"Il CEO ha firmato {name} sul campo da golf: {bw} a {city} per {price}/mese, il 30% sotto listino.", +"sales.ceo_n":"Il CEO, che vende meglio di chiunque", +"sales.ceo_override":"Hai rifiutato {name}, ma il CEO aveva già stretto la mano. Ora sono clienti.", +"sales.ceo_promised":"Ha anche promesso: {req}.", +"sales.ceo_s":"il CEO", +"sales.ceo_say_airport":"Appena atterrato. Non ho firmato niente, ma il Wi-Fi della lounge mi ha dato ottime sensazioni.", +"sales.ceo_say_blockchain":"Abbiamo pensato di mettere la tabella di routing su una blockchain?", +"sales.ceo_say_golf":"I contratti migliori si chiudono alla nona buca. Il NOC dovrebbe giocare più a golf.", +"sales.ceo_say_mbps":"Perché vendiamo gigabit? I megabit sembrano di più.", +"sales.ceo_say_napkin":"Ho fatto il prezzo del prossimo contratto su un tovagliolo. L'ingegneria sistemerà i dettagli.", +"sales.ceo_say_synergy":"Non vendiamo banda, vendiamo sinergia. Mettetelo sul sito.", +"sales.ceo_says":"Il CEO: «{say}»", +"sales.ceo_took_over":"{name} ha preso in mano le vendite di persona. È sicuro di vendere meglio di chiunque.", +"sales.commission":"{name} ha firmato. Provvigione per lo squalo: {cost}.", +"sales.desk":"Ufficio vendite", +"sales.eng_booked":"{name} ti ha iscritto a {conf} a {city} ({cost}). Ha già il badge.", +"sales.eng_d":"Era un ingegnere di rete e ora ha il badge di ogni NOG. Ti iscrive a tutti (il biglietto lo paghi tu), porta tanti contratti piccoli e medi ma mai quelli davvero grandi, e vende solo ciò che la rete sa fare, così i clienti restano. I nerd adorano Dave. Tratta male.", +"sales.eng_n":"L'ingegnere diventato venditore-droide", +"sales.eng_s":"Dave", +"sales.fired":"{name} ha svuotato la scrivania. L'ufficio vendite è libero.", +"sales.hire_sales":"Assumi un venditore", +"sales.hired":"{name} è entrato nelle vendite. Aspettati contratti nel suo stile.", +"sales.intro":"Una persona alla volta gestisce le vendite. Ognuna porta contratti a modo suo, e i clienti che firma se ne ricordano alla scadenza.", +"sales.let_ceo":"Lascia fare al CEO", +"sales.locked":"L'ufficio vendite apre al livello clienti {lv}.", +"sales.one_at_a_time":"Uno alla volta: lascialo andare per assumerne un altro.", +"sales.pitch":"Un venditore porta contratti a modo suo. Scegli chi.", +"sales.shark_d":"Porta i contratti più grandi a un quarto in più, e si prende un mese di ogni contratto come provvigione. Vende troppo: metà arriva con una promessa che la tua rete non mantiene ancora, e quei clienti se ne vanno prima. Ignora i nerd: niente clienti tecnici, niente incontri, e i peering desk ti chiedono un quarto di traffico in più. Vince quasi tutte le trattative.", +"sales.shark_n":"Lo squalo", +"sales.shark_s":"Chad", +"sales.vp_arrived":"Il VP vendite ha iniziato, e il CEO è tornato alla strategia. L'ufficio vendite è libero: assumi qualcuno.", +"sales.vp_asked":"Il consiglio ha detto sì, dopo pranzo. Un VP vendite inizia tra {n} giorni; fino ad allora il CEO continua a vendere.", +"sales.vp_coming":"Un VP vendite subentra tra {n} giorni.", "save.cash_in_the_bank":"{cash} in cassa", "save.import_failed_err":"Importazione fallita.
{err}", "save.load_name":"Caricare {name}?", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 2145d01..bd87f12 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3902,6 +3902,42 @@ "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.", +"sales.ask_vp":"Pedir ao conselho um VP de Vendas · {cost}", +"sales.at_desk":"{name} cuida das vendas", +"sales.ceo_d":"De graça, e convicto. A cada dois meses fecha um contrato enorme no campo de golfe com 30% de desconto, muitas vezes com uma promessa que ninguém conferiu, e de vez em quando assina uma oferta que você recusou. Tem opiniões. Não pode ser demitido.", +"sales.ceo_golf":"O CEO fechou com {name} no campo de golfe: {bw} em {city} por {price}/mês, 30% abaixo da tabela.", +"sales.ceo_n":"O CEO, que vende melhor que ninguém", +"sales.ceo_override":"Você recusou {name}, mas o CEO já tinha apertado a mão. Agora são clientes.", +"sales.ceo_promised":"Ele também prometeu: {req}.", +"sales.ceo_s":"o CEO", +"sales.ceo_say_airport":"Acabei de pousar. Não assinei nada, mas tive um ótimo pressentimento com o Wi-Fi da sala VIP.", +"sales.ceo_say_blockchain":"Já pensamos em colocar a tabela de rotas numa blockchain?", +"sales.ceo_say_golf":"Os melhores negócios saem no nono buraco. O NOC devia jogar mais golfe.", +"sales.ceo_say_mbps":"Por que vendemos gigabits? Megabits parecem mais.", +"sales.ceo_say_napkin":"Fiz o preço do próximo contrato num guardanapo. A engenharia resolve os detalhes.", +"sales.ceo_say_synergy":"Não vendemos banda, vendemos sinergia. Coloquem isso no site.", +"sales.ceo_says":"O CEO: “{say}”", +"sales.ceo_took_over":"{name} assumiu as vendas pessoalmente. Tem certeza de que vende melhor que ninguém.", +"sales.commission":"{name} assinou. Comissão do tubarão: {cost}.", +"sales.desk":"Vendas", +"sales.eng_booked":"{name} inscreveu você no {conf} em {city} ({cost}). O crachá já está pronto.", +"sales.eng_d":"Era engenheiro de redes e agora tem o crachá de cada NOG. Inscreve você em todas (o ingresso é por sua conta), traz muitos negócios pequenos e médios, mas nunca os realmente grandes, e só vende o que a rede consegue entregar, então os clientes ficam. Os nerds adoram o Dave. Negocia mal.", +"sales.eng_n":"O engenheiro que virou vendedroide", +"sales.eng_s":"Dave", +"sales.fired":"{name} esvaziou a mesa. Vendas está livre.", +"sales.hire_sales":"Contratar vendas", +"sales.hired":"{name} entrou em vendas. Espere negócios no estilo dele.", +"sales.intro":"Uma pessoa por vez cuida das vendas. Cada uma traz negócios do seu jeito, e os clientes que ela fecha lembram disso quando o contrato vence.", +"sales.let_ceo":"Deixar o CEO cuidar", +"sales.locked":"Vendas abre no nível de clientes {lv}.", +"sales.one_at_a_time":"Uma por vez: dispense para contratar outra.", +"sales.pitch":"Uma pessoa de vendas traz negócios do jeito dela. Escolha quem.", +"sales.shark_d":"Fecha os maiores negócios por um quarto a mais, e leva um mês de cada contrato de comissão. Vende demais: metade chega com uma promessa que sua rede ainda não cumpre, e esses clientes saem mais cedo. Ignora os nerds: nada de clientes técnicos nem de encontros, e as equipes de peering pedem um quarto a mais de tráfego. Ganha quase todas as negociações.", +"sales.shark_n":"O tubarão", +"sales.shark_s":"Chad", +"sales.vp_arrived":"O VP de Vendas começou, e o CEO voltou para a estratégia. Vendas está livre: contrate alguém.", +"sales.vp_asked":"O conselho aprovou, depois do almoço. Um VP de Vendas começa em {n} dias; até lá o CEO continua vendendo.", +"sales.vp_coming":"Um VP de Vendas assume em {n} dias.", "save.cash_in_the_bank":"{cash} no banco", "save.import_failed_err":"Falha na importação.
{err}", "save.load_name":"Carregar {name}?", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index 953c915..09dd602 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -27,6 +27,7 @@ const API_DOMAINS={ metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, egress:{table:'PREF',kind:'key'}, routeMode:{table:'RT',kind:'key'}, + salesPersona:{table:'SALES',kind:'key'}, site:{kind:'enum',values:['a','b','ab']}, step:{kind:'enum',values:[1,-1]}, connKind:{kind:'enum',values:['t','p','ix','c','nni']}, diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index fd80aa6..cda7563 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -218,6 +218,12 @@ const API_CMD={ doc:'Sign a pending offer. Rejected without a POP in every city it needs, without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, decline:{args:[['id','entityId']], doc:'Throw an offer away.'}, + salesHire:{args:[['id','salesPersona']], + doc:'Put one salesperson at the sales desk: eng (engineer turned salesdroid: books every NOG at the usual ticket price, more small and mid deals, never the huge ones, customers stay longer), shark (bigger deals at higher prices plus a month of commission, oversells promises, no nerdy customers, peering desks want more traffic) or ceo (free, signs huge discounted deals on the golf course, sometimes signs what you declined, cannot be fired). One at a time; from customer level 2.'}, + salesFire:{args:[],confirm:'double', + doc:'Let the salesperson go (not the CEO: ask the board for a VP of Sales instead).'}, + salesVp:{args:[], + doc:'With the CEO running sales: pay for a board meeting that brings a VP of Sales, who frees the desk a month later.'}, renewMatch:{args:[['id','entityId']],watch:['biz.#id'], doc:'Answer a renewal haggle (a customer with hag): renew at the price they asked. Unanswered, this happens on its own when the term ends.'}, renewMeet:{args:[['id','entityId']],watch:['biz.#id'], @@ -466,6 +472,7 @@ const API_VIEW={ keys:{args:[],doc:'Open the list of keyboard shortcuts (the ? key).'}, routingOpen:{args:[],doc:'Open the Routing & DDoS window: backbone, Auto-TE and DDoS settings (the button at the top of the NOC tab).'}, opsOpen:{args:[],doc:'Open the Ops sheet: the NOC intern\'s mood, weekly shift report and standing orders.'}, + salesOpen:{args:[],doc:'Open the sales desk sheet: the three kinds of salesperson, who is at the desk and what they cost.'}, opsCity:{args:[['v','cityId',false]],doc:'Show one POP\'s standing-order exceptions in the Ops sheet.'}, utilities:{args:[['city','cityId',false]],doc:'Open the utilities sheet: route servers, the redundancy kit, caches and bulk peering, for one city or the whole network.'}, pniAllOpen:{args:[['net','pniAllNet']],doc:'Open the bulk PNI order sheet for one network (or every network with null).'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 50e5df8..1dffd47 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -34,6 +34,7 @@ const API_STATE_DOC={ nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates (te: the day the term ends, mk: the bandwidth market it was priced in, hag: an open renewal haggle {rate, until}).'}, offers:{type:'array',doc:'Pending customer offers, each expiring on a day (mk: the bandwidth market they were priced in; refN: the customer who referred them).'}, + sales:{type:'map',doc:'The sales desk: p (eng, shark, ceo or null), hired (day), vp (the day a VP of Sales takes over from the CEO), golf and say (the CEO\'s next golf deal and opinion). Offers and customers carry by: who brought or signed them.'}, cl:{type:'map',doc:'Customer lifecycle (#178): odd (the day of the last unusual departure) and mo, one entry a month of customers won, renewed, grown, haggling and lost by reason.'}, done:{type:'map',doc:'Goals landed, by goal id → day.'}, ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, diff --git a/src/agent/40-read.js b/src/agent/40-read.js index 38afbe1..8c43867 100644 --- a/src/agent/40-read.js +++ b/src/agent/40-read.js @@ -26,7 +26,7 @@ function apiJson(v){ carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders each recipe's script, because the source is a function and some read the live network. The recipes' relevance score is not exposed: judging which one fits is the agent's job. */ -const API_TABLES={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_TABLES={SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; const API_MADE={ BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), diff --git a/src/game/60-features/38-sales-desk.js b/src/game/60-features/38-sales-desk.js new file mode 100644 index 0000000..e1023b1 --- /dev/null +++ b/src/game/60-features/38-sales-desk.js @@ -0,0 +1,75 @@ +/* ---------- The sales desk: one salesperson, three kinds you meet in this industry ---------- + Next to the NOC intern, you can put one person in charge of sales. Each brings deals in their own way and leaves + their mark on the customers they sign (b.by), which the contracts (75-customer-lifecycle.js) remember at renewal. + - The engineer turned salesdroid goes to every network operators' meeting (you pay the ticket), brings plenty of + small and mid deals and never the huge ones, and only sells what the network can do: their customers stay longer, + the nerdy ones most of all. They haggle badly. + - The shark brings the biggest deals at a higher price and takes a commission, but oversells: many come with a + promise your network does not keep yet. Ignores the nerds: no technical customers, no meetings, and peering desks + want more traffic from you. Wins most haggles. + - The CEO runs sales himself, for free: now and then a huge deal signed on the golf course at a discount, with a + promise nobody checked, the odd declined offer signed anyway, and opinions. He cannot be fired; the board can + be asked for a VP of Sales instead. + Every roll is a hash of the day and the deal, so a game without a salesperson keeps its random stream. */ +const SALES={ + eng:{i:'🤓',n:N_('sales.eng_n'),s:N_('sales.eng_s'),d:N_('sales.eng_d'),mo:9000}, + shark:{i:'🦈',n:N_('sales.shark_n'),s:N_('sales.shark_s'),d:N_('sales.shark_d'),mo:15000}, + ceo:{i:'👔',n:N_('sales.ceo_n'),s:N_('sales.ceo_s'),d:N_('sales.ceo_d'),mo:0}, +}; +const SALES_LV=2,SALES_VP=50000,SALES_VP_DAYS=30; +// The ones the engineer never lands, and the nerds the shark never calls back. +const salesBig=t=>{const T=BIZ_T[t];return !!T&&(!!T.mega||(T.lv||1)>=4);}; +const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','dfpair']; +const SALES_SAY=[N_('sales.ceo_say_synergy'),N_('sales.ceo_say_golf'),N_('sales.ceo_say_blockchain'),N_('sales.ceo_say_napkin'),N_('sales.ceo_say_mbps'),N_('sales.ceo_say_airport')]; +const slP=()=>S&&S.sales&&own(SALES,S.sales.p)?S.sales.p:null; +const slName=(long)=>{const p=slP();return p?tr(long?SALES[p].n:SALES[p].s):'';}; +// The short name at the start of a sentence: Dave, Chad, The CEO. +const slCap=()=>{const t=slName();return t?t[0].toUpperCase()+t.slice(1):'';}; +const slR=q=>(hstr(((S&&S.asn)||0)+'|sales|'+q)%100000)/100000; +const salesMo=()=>{const p=slP();return p?SALES[p].mo:0;}; +const salesCanHire=()=>lvl()>=SALES_LV; +// How often offers come in: the engineer brings more, half as many again while a meeting's glow lasts. +function salesSpawn(){const p=slP();if(p==='eng')return 1.4*(S.conf&&S.conf.until>S.day?1.5:1);if(p==='shark')return 1.2;return 1;} +// What the salesperson does to the offers that just came in (from index n0): who brought them, which they drop, +// and how the shark dresses them up. +function salesShape(n0){const p=slP();if(!p)return;for(let i=S.offers.length-1;i>=n0;i--){const o=S.offers[i],T=BIZ_T[o.type];if(!T||o.ref)continue; + if(p==='eng'&&salesBig(o.type)){S.offers.splice(i,1);continue;} + if(p==='shark'&&SALES_NERDS.includes(o.type)){S.offers.splice(i,1);continue;} + o.by=p; + if(p==='shark'&&!T.event&&!T.cap){const up=(T.opts||[]).find(x=>x>o.bw);if(up&&!T.fiber)o.bw=up;o.rate=Math.round(o.rate*1.25); + if(slR('over|'+o.id)<0.5){const k=salesPromise(o);if(k)o.reqs=(o.reqs||[]).concat(k);}}}} +// A promise nobody checked: a requirement this deal can have, that the network does not meet today. +function salesPromise(o){const T=BIZ_T[o.type],pool=Object.keys(REQS).filter(k=>!(o.reqs||[]).includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,o)).sort(); + const no=pool.filter(k=>{try{return !REQS[k].ok(o);}catch(e){return false;}});return no.length?no[Math.floor(slR('promise|'+o.id)*no.length)]:null;} +// Their mark at renewal: how much likelier the customers they signed are to leave. +function salesLeaveMul(b){if(b.by==='eng')return SALES_NERDS.includes(b.type)?0.5:0.75;if(b.by==='shark')return 1.5;if(b.by==='ceo')return 1.25;return 1;} +// Haggles with whoever is at the desk now: how deep the discount they ask, and how often meeting halfway works. +const salesAsk=()=>slP()==='eng'?0.72:0.8; +const salesMeet=()=>({shark:0.9,eng:0.5,ceo:0.55})[slP()]||0.65; +// Peering desks notice who you send to meetings: with the shark, selective networks want a quarter more traffic. +const salesPeerMul=()=>slP()==='shark'?1.25:1; + +/* A day at the sales desk: the engineer books the next meeting (30 days ahead, the same day the invitation comes), + the CEO plays golf and has opinions, and a VP of Sales takes over from him when the board says so. */ +function salesDay(d){const L=S.sales;if(!L)return; + if(L.vp&&d>=L.vp){L.p=null;L.vp=null;toast(tr('sales.vp_arrived'),'good',[{l:tr('sales.desk'),act:'salesOpen',args:{}}]);return;} + const p=slP();if(!p)return; + if(p==='eng')for(const cf of upcomingConfs(30)){if(cf.cap||cf.day-d!==30||(S.confReg||{})[cf.key])continue; + if(S.cash>=CONF_COST){S.cash-=CONF_COST;(S.confReg=S.confReg||{})[cf.key]=true;toast(tr('sales.eng_booked',{name:esc(slCap()),conf:esc(cf.n),city:esc(CITY[cf.c].name),cost:fmt$(CONF_COST)}),'');}} + if(p==='ceo'){if(!(L.golf>=d))L.golf=d+50+Math.floor(slR('golf|'+d)*30);else if(d===L.golf){salesGolf(d);L.golf=d+50+Math.floor(slR('golf|'+d)*30);} + if(!(L.say>=d))L.say=d+20+Math.floor(slR('say|'+d)*15);else if(d===L.say){toast(tr('sales.ceo_says',{say:tr(SALES_SAY[Math.floor(slR('sayl|'+d)*SALES_SAY.length)])}),'');L.say=d+20+Math.floor(slR('say|'+d)*15);}}} +// The golf course: the biggest internet customer this network can take, in its biggest city, at 30% off, signed on the spot. +const SALES_GOLF=['metav','cgame','gpu','stream','isp','edu','host','dia']; +function salesGolf(d){const mine=Object.keys(S.pops).filter(c=>popUp(c)&&bizCity(c));if(!mine.length)return; + const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl());if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name); + const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40}; + const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b)); + toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');} +// Declining an offer the CEO likes: about one in three, he already shook hands on it. +function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||slR('veto|'+o.id)>=0.33)return false; + const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;} +// Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer. +function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null; + s.sales={p:own(SALES,L.p)?L.p:null,hired:n(L.hired)||0,vp:L.p==='ceo'?n(L.vp):null,golf:n(L.golf),say:n(L.say)}; + for(const x of [...s.biz,...s.offers])if(x.by!==undefined&&!own(SALES,x.by))delete x.by;} diff --git a/src/game/70-rules/70-sold-out.js b/src/game/70-rules/70-sold-out.js index 6ab07bc..2c0fb99 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)*(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)*salesPeerMul()*(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 d414a57..236f877 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -361,7 +361,7 @@ function computeMoney(R2){ C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0); C.caches=cachesMo(); 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.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)+salesMo(); 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)*(R2.bbF[c]??1),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)*(R2.tgtF[b.id]??1);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 c318652..ceee2b6 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -57,7 +57,7 @@ function sanitize(s){ const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;}; {const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz); // Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally. - for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s); + for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);salesFix(s); // Sponsorships and capacity conferences (#168): registrations are true or 'sp', the glow and the pending deals are checked. 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};} diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index 30e8625..ccc393e 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -79,10 +79,10 @@ function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],l if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;} if(d=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(0.8+0.12*clR(b,'ask'))); + if(open=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(salesAsk()+0.12*clR(b,'ask'))); if(ask>0&&ask=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}} clRenew(b,clFair(b));clNote('ren');out.ren++;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index f421ab8..ae9cd08 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -59,6 +59,8 @@ function dayPost(d){ if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;} // contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js) clDay(d); + // the sales desk: meetings booked, golf played (38-sales-desk.js) + salesDay(d); // own IX members join for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.lengthn.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg))); @@ -69,7 +71,7 @@ function dayPost(d){ // offers S.offers=S.offers.filter(o=>o.exp>d); brTick(); - if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)){const n0=S.offers.length;spawnOffer();mktPrice(n0);} + if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);} // 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(); diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index 87b7d94..aa6e6f4 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -12,9 +12,11 @@ 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);if(o.mk)customer.mk=o.mk;S.biz.push(clSign(customer)); + S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer)); + // The shark's commission: one month of what the deal pays, on signing. + if(o.by==='shark'){const c=Math.round(bizMo(customer));if(c>0){S.cash-=c;toast(tr('sales.commission',{name:esc(o.name),cost:fmt$(c)}),'');}} 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();}, + decline:({id})=>{if(salesOverride(S.offers.find(x=>x.id===id))){after();return;}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();}, }); /* The renewal haggle (#178, 75-customer-lifecycle.js): match their price, meet halfway (they take it about two times @@ -23,7 +25,7 @@ function clHagOf(id){const b=S.biz.find(x=>x.id===id);return b&&b.hag?b:null;} Object.assign(ACT,{ renewMatch:({id})=>{const b=clHagOf(id);if(!b)return;clRenew(b,b.hag.rate);clNote('ren');toast(tr('lifecycle.matched',{name:esc(b.name)}),'good');sfx('coin');after();}, renewMeet:({id})=>{const b=clHagOf(id);if(!b)return;const mid=Math.round((b.hag.rate+clFair(b))/2); - if(clR(b,'meet')<0.65){clRenew(b,mid);clNote('ren');toast(tr('lifecycle.meet_yes',{name:esc(b.name),price:fmt$(BIZ_T[b.type].fiber?b.rate:b.bw*b.rate)}),'good');sfx('coin');} + if(clR(b,'meet'){const b=clHagOf(id);if(!b)return;clGone(b,'cheap');toast(tr('lifecycle.let_go',{name:esc(b.name)}),'');after();}, }); diff --git a/src/game/90-actions/52-sales.js b/src/game/90-actions/52-sales.js new file mode 100644 index 0000000..68d36ee --- /dev/null +++ b/src/game/90-actions/52-sales.js @@ -0,0 +1,12 @@ +// The sales desk (38-sales-desk.js): hiring one salesperson, letting them go, and asking the board for a VP of Sales +// when the CEO has taken over. +Object.assign(ACT,{ + salesOpen:()=>{if(S)salesModal();}, + salesHire:({id})=>{if(!S||!own(SALES,id)||slP()||!salesCanHire()||!rule('clock'))return;const P=SALES[id];if(P.mo&&!spend(P.mo))return; + S.sales=Object.assign(S.sales||{},{p:id,hired:S.day,vp:null,golf:null,say:null});UI.confirm=null; + toast(id==='ceo'?tr('sales.ceo_took_over',{name:esc(slCap())}):tr('sales.hired',{name:esc(slCap())}),'good');sfx('coin');after();salesModal();}, + salesFire:()=>{const p=slP();if(!p||p==='ceo')return;if(UI.confirm!=='salesFire'){UI.confirm='salesFire';salesModal();return;}UI.confirm=null;const nm=slCap();S.sales.p=null; + toast(tr('sales.fired',{name:esc(nm)}),'');after();salesModal();}, + // The CEO cannot be fired. A board meeting (and its catering) can get you a VP of Sales, who takes over a month later. + salesVp:()=>{if(slP()!=='ceo'||S.sales.vp)return;if(!spend(SALES_VP))return;S.sales.vp=S.day+SALES_VP_DAYS;toast(tr('sales.vp_asked',{n:SALES_VP_DAYS}),'');after();salesModal();}, +}); diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 9408436..9ae66e3 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -42,7 +42,7 @@ function renderLeft(){checkLayer(); 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+=clDealsHtml()+confSection()+seatSection(); + h+=salesCard()+clDealsHtml()+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); diff --git a/src/game/93-ui/58-sales-panel.js b/src/game/93-ui/58-sales-panel.js new file mode 100644 index 0000000..9204186 --- /dev/null +++ b/src/game/93-ui/58-sales-panel.js @@ -0,0 +1,17 @@ +// The sales desk in Deals, and its sheet: the three kinds of salesperson, who is at the desk, and what they cost. +function salesCard(){if(!S||!rule('clock'))return '';const p=slP(),L=S.sales||{}; + return `
${p?`${SALES[p].i} ${esc(tr('sales.at_desk',{name:slCap()}))}`:`💼 ${tr('sales.desk')}`}
+
${p?(L.vp?tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)}):tr(SALES[p].d)):salesCanHire()?tr('sales.pitch'):tr('sales.locked',{lv:SALES_LV})}
+
${btn(p?tr('sales.desk'):tr('sales.hire_sales'),'salesOpen',{},p?'sm':'pink sm',!p&&!salesCanHire())}
`;} +function salesModal(){if(!S)return;const p=slP(),L=S.sales||{}; + let h=`
${tr('common.deals')}

${tr('sales.desk')}

`; + h+=`

${tr('sales.intro')}

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

${tr('ops.no_clock')}

`;else if(!salesCanHire()&&!p)h+=`

${tr('sales.locked',{lv:SALES_LV})}

`; + h+=Object.entries(SALES).map(([id,P])=>{const here=p===id; + const act=here?(id==='ceo'?(L.vp?`${tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)})}`:btn(tr('sales.ask_vp',{cost:fmt$(SALES_VP)}),'salesVp',{},'ghost sm',S.cash
${tr(P.n)}
+
${tr(P.d)}
${here&&id!=='ceo'?`
${tr('ops.salary',{price:fmt$(P.mo),d:dateStr(L.hired||0)})}
`:''}${act?`
${act}
`:''}
`;}).join(''); + if(p&&p!=='ceo')h+=`

${tr('sales.one_at_a_time')}

`; + openModal(h,'ops');} diff --git a/src/i18n/en.js b/src/i18n/en.js index cd6de57..eb68e4d 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3903,6 +3903,42 @@ "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.", +"sales.ask_vp":"Ask the board for a VP of Sales · {cost}", +"sales.at_desk":"{name} runs sales", +"sales.ceo_d":"Free, and sure of it. Every couple of months signs a huge deal on the golf course at 30% off, often with a promise nobody checked, and now and then signs an offer you declined. Has opinions. Cannot be fired.", +"sales.ceo_golf":"The CEO signed {name} on the golf course: {bw} in {city} for {price}/mo, 30% off list.", +"sales.ceo_n":"The CEO, who sells better than anyone", +"sales.ceo_override":"You declined {name}, but the CEO had already shaken hands on it. They are now a customer.", +"sales.ceo_promised":"He also promised: {req}.", +"sales.ceo_s":"the CEO", +"sales.ceo_say_airport":"Just landed. Signed nothing, but I had a very good feeling about the lounge Wi-Fi.", +"sales.ceo_say_blockchain":"Have we thought about putting the routing table on a blockchain?", +"sales.ceo_say_golf":"The best deals happen on the ninth hole. The NOC should play more golf.", +"sales.ceo_say_mbps":"Why do we sell gigabits? Megabits sound like more.", +"sales.ceo_say_napkin":"I priced the next deal on a napkin. Engineering can work out the details.", +"sales.ceo_say_synergy":"We don't sell bandwidth, we sell synergy. Put that on the website.", +"sales.ceo_says":"The CEO: “{say}”", +"sales.ceo_took_over":"{name} has taken over sales personally. He is sure he sells better than anyone.", +"sales.commission":"{name} signed. Commission for the shark: {cost}.", +"sales.desk":"Sales desk", +"sales.eng_booked":"{name} registered you for {conf} in {city} ({cost}). They already have the lanyard.", +"sales.eng_d":"Was a network engineer, now has a lanyard for every NOG. Books you into each one (you pay the ticket), brings plenty of small and mid deals but never the really big ones, and only sells what the network can do, so customers stay. The nerds love Dave. Haggles badly.", +"sales.eng_n":"The engineer turned salesdroid", +"sales.eng_s":"Dave", +"sales.fired":"{name} has cleared their desk. The sales desk is free.", +"sales.hire_sales":"Hire sales", +"sales.hired":"{name} joined sales. Expect deals in their style.", +"sales.intro":"One person runs sales at a time. Each brings deals in their own way, and the customers they sign remember it when their contract comes up.", +"sales.let_ceo":"Let the CEO run it", +"sales.locked":"The sales desk opens at customer level {lv}.", +"sales.one_at_a_time":"One at a time: let them go to hire someone else.", +"sales.pitch":"One salesperson brings in deals their own way. Pick who.", +"sales.shark_d":"Lands the biggest deals at a quarter more, and takes a month of each deal as commission. Oversells: half of them come with a promise your network does not keep yet, and those customers leave sooner. Ignores the nerds: no technical customers, no meetings, and peering desks want a quarter more traffic from you. Wins most haggles.", +"sales.shark_n":"The shark", +"sales.shark_s":"Chad", +"sales.vp_arrived":"The VP of Sales has started, and the CEO has gone back to strategy. The sales desk is free: hire someone.", +"sales.vp_asked":"The board agreed, after lunch. A VP of Sales starts in {n} days; until then the CEO keeps selling.", +"sales.vp_coming":"A VP of Sales takes over in {n} days.", "save.cash_in_the_bank":"{cash} in the bank", "save.import_failed_err":"Import failed.
{err}", "save.load_name":"Load {name}?", diff --git a/tests/sales-desk.test.js b/tests/sales-desk.test.js new file mode 100644 index 0000000..35de1a8 --- /dev/null +++ b/tests/sales-desk.test.js @@ -0,0 +1,118 @@ +// The sales desk: one salesperson at a time, three kinds (the engineer turned salesdroid, the shark, the CEO), each +// bringing deals their own way and leaving their mark on the customers they sign. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par','fra','nyc','ash'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=3;compute()"; +// Offers as the day brings them, shaped by whoever is at the desk. +const offers = (ev, n = 600) => JSON.parse(ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();mktPrice(0);salesShape(0);out.push(...S.offers.map(o=>({t:o.type,by:o.by||null,bw:o.bw,rate:o.rate,reqs:(o.reqs||[]).length})));}return JSON.stringify(out);})()`)); + +test('one salesperson at a time, from customer level 2, with a salary; the CEO is free and cannot be fired', () => { + const { ev, errors } = load(); + ev(start); + ev("S.lvl=1;ACT.salesHire({id:'eng'})"); + assert.equal(ev('slP()'), null, 'level 1: the desk is not open yet'); + ev("S.lvl=4;ACT.salesHire({id:'eng'})"); + assert.equal(ev('slP()'), 'eng'); + ev("ACT.salesHire({id:'shark'})"); + assert.equal(ev('slP()'), 'eng', 'one at a time'); + assert.equal(ev('salesMo()'), 9000, 'on the payroll'); + ev('compute()'); + assert.ok(ev('R.cost.extras') >= 9000); + ev('ACT.salesFire()'); ev('ACT.salesFire()'); + assert.equal(ev('slP()'), null, 'let go after a confirmation'); + ev("ACT.salesHire({id:'ceo'})"); + assert.equal(ev('slP()'), 'ceo'); + assert.equal(ev('salesMo()'), 0); + ev('ACT.salesFire()'); ev('ACT.salesFire()'); + assert.equal(ev('slP()'), 'ceo', 'nobody fires the CEO'); + const cash = ev('S.cash'); + ev('ACT.salesVp()'); + assert.equal(ev('S.cash'), cash - ev('SALES_VP'), 'a board meeting costs'); + ev('for(let i=0;i { + const { ev, errors } = load(); + ev(start); + ev("ACT.salesHire({id:'eng'})"); + const o = offers(ev); + assert.ok(o.length > 300); + assert.ok(o.every(x => !ev(`salesBig('${x.t}')`)), 'no mega AI, hyperscaler or AGI deals'); + assert.ok(o.every(x => x.by === 'eng'), 'every offer is theirs'); + assert.ok(ev('salesSpawn()') > 1, 'more offers come in'); + // A meeting 30 days out: they register you and you pay the ticket. + const r = JSON.parse(ev(`(()=>{const cf=upcomingConfs(400).find(c=>!c.cap);S.day=cf.day-30;const cash=S.cash;salesDay(S.day);const n=upcomingConfs(30).filter(c=>!c.cap&&c.day===cf.day).length;return JSON.stringify({reg:!!S.confReg[cf.key],paid:cash-S.cash,n});})()`)); + assert.equal(r.reg, true); + assert.equal(r.paid, r.n * ev('CONF_COST'), 'every meeting that day, each at the usual ticket price: not for free'); + assert.equal(ev("salesLeaveMul({by:'eng',type:'hft'})"), 0.5, 'the nerds love them'); + assert.ok(ev("salesLeaveMul({by:'eng',type:'dia'})") < 1); + assert.ok(ev('salesAsk()') < 0.8, 'and they haggle badly'); + assert.deepEqual(errors, []); +}); + +test('the shark: bigger deals at a quarter more, oversold promises, no nerds, a commission, tougher peering', () => { + const { ev, errors } = load(); + ev(start); + const plain = offers(ev); + ev("ACT.salesHire({id:'shark'})"); + const o = offers(ev); + assert.ok(o.every(x => !ev(`SALES_NERDS.includes('${x.t}')`)), 'no technical customers'); + const avg = (l, t) => { const x = l.filter(y => y.t === t); return x.reduce((a, y) => a + y.rate, 0) / Math.max(1, x.length); }; + assert.ok(avg(o, 'dia') > avg(plain, 'dia') * 1.15, `priced higher (${avg(o, 'dia')} vs ${avg(plain, 'dia')})`); + const oversold = o.filter(x => x.reqs > 0).length / o.length, before = plain.filter(x => x.reqs > 0).length / plain.length; + assert.ok(oversold > before + 0.15, `oversold: ${Math.round(oversold * 100)}% with promises, ${Math.round(before * 100)}% without the shark`); + assert.equal(ev('salesPeerMul()'), 1.25); + assert.equal(ev('salesMeet()'), 0.9, 'wins most haggles'); + assert.equal(ev("salesLeaveMul({by:'shark',type:'dia'})"), 1.5, 'and their customers leave sooner'); + // Signing one of theirs pays the commission. + ev("S.offers=[];for(let i=0;i<200&&!S.offers.some(o=>o.by==='shark'&&bHas(o)&&!BIZ_T[o.type].event&&!BIZ_T[o.type].fiber);i++){spawnOffer();salesShape(0);}"); + const r = JSON.parse(ev("(()=>{const o=S.offers.find(o=>o.by==='shark'&&bHas(o)&&!BIZ_T[o.type].event&&!BIZ_T[o.type].fiber);const cash=S.cash;ACT.accept({id:o.id});const b=S.biz.find(b=>b.id===o.id);return JSON.stringify({by:b&&b.by,paid:cash-S.cash,mo:b?bizMo(b):0});})()")); + assert.equal(r.by, 'shark', 'the customer remembers who signed it'); + assert.equal(r.paid, Math.round(r.mo), 'a month of the deal as commission'); + assert.deepEqual(errors, []); +}); + +test('the CEO: golf deals at 30% off, the odd declined offer signed anyway, opinions; all from hashes, not Math.random', () => { + const { ev, errors } = load(); + ev(start); + ev("ACT.salesHire({id:'ceo'})"); + ev('window.__r=0;window.__r0=Math.random;Math.random=()=>{__r++;return __r0();};'); + const n0 = ev('S.biz.length'); + ev('for(let i=1;i<=200;i++)salesDay(S.day+i)'); + ev('Math.random=__r0'); + assert.equal(ev('__r'), 0, 'no draws from the game\'s random stream'); + const golf = JSON.parse(ev(`JSON.stringify(S.biz.slice(${n0}).map(b=>({by:b.by,t:b.type,bw:b.bw,rate:b.rate,list:BIZ_T[b.type].rate})))`)); + assert.ok(golf.length >= 2 && golf.length <= 4, `a golf deal every 50–80 days (${golf.length} in 200 days)`); + for (const g of golf) { + assert.equal(g.by, 'ceo'); + assert.ok(g.rate <= Math.round(g.list * 0.7 * ev('mkt()')) + 1, '30% off list'); + } + assert.ok(ev("S.log.some(e=>/The CEO: /.test(e.t))"), 'and opinions'); + // Declining: about one in three, he already shook hands. + const r = JSON.parse(ev(`(()=>{let over=0,n=0;for(let i=0;i<300;i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>bHas(o)&&!BIZ_T[o.type].event);if(!o)continue;n++;const b0=S.biz.length;ACT.decline({id:o.id});if(S.biz.length>b0)over++;}return JSON.stringify({over,n});})()`)); + assert.ok(r.n > 50 && r.over / r.n > 0.2 && r.over / r.n < 0.45, `${r.over} of ${r.n} declines signed anyway`); + assert.deepEqual(errors, []); +}); + +test('the desk in Deals and its sheet, and saves that remember who is at the desk', () => { + const { ev, errors } = load(); + ev(start); + ev("UI.left='deals';renderLeft()"); + assert.match(ev("document.getElementById('left').innerHTML"), /data-act="salesOpen"/); + ev('ACT.salesOpen()'); + const m = ev("document.getElementById('modal').innerHTML"); + for (const id of ['eng', 'shark', 'ceo']) assert.match(m, new RegExp(`data-act="salesHire" data-args="\\{"id":"${id}"\\}"`)); + ev("ACT.salesHire({id:'shark'})"); + const s = JSON.parse(ev('JSON.stringify(packSave(S))')); + s.offers = [{ id: 'o1', city: 'ams', name: 'X', type: 'dia', bw: 1, rate: 600, reqs: [], exp: 99, by: 'pirate' }]; + const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})))`)); + assert.equal(out.sales.p, 'shark'); + assert.equal(out.offers[0].by, undefined, 'only real salespeople'); + s.sales = { p: 'intern', hired: 'yesterday' }; + assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})).sales)`)).p, null); + assert.deepEqual(errors, []); +}); From 939aaeea59e4eee2b210b7836790bc3016397f09 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 09:45:19 +0100 Subject: [PATCH 342/491] Sales and contract rolls hash what a deal is, not its clock-made id Offer and customer ids come from Date.now(), so the shark's oversell, the CEO's veto, his promises and every contract roll differed each time the same game was played, and the shark test could fail on CI (67% oversold against 54%, short of its 15-point margin). They now hash the deal or the customer (type, cities, name, size), and a test checks two ids give the same roll. --- src/game/60-features/38-sales-desk.js | 8 +++++--- src/game/80-simulation/75-customer-lifecycle.js | 8 +++++--- tests/customer-lifecycle.test.js | 14 +++++++++----- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/game/60-features/38-sales-desk.js b/src/game/60-features/38-sales-desk.js index e1023b1..2e5e00e 100644 --- a/src/game/60-features/38-sales-desk.js +++ b/src/game/60-features/38-sales-desk.js @@ -26,6 +26,8 @@ const slName=(long)=>{const p=slP();return p?tr(long?SALES[p].n:SALES[p].s):'';} // The short name at the start of a sentence: Dave, Chad, The CEO. const slCap=()=>{const t=slName();return t?t[0].toUpperCase()+t.slice(1):'';}; const slR=q=>(hstr(((S&&S.asn)||0)+'|sales|'+q)%100000)/100000; +// What a deal is, not its id: ids come from the clock, so a roll on them would differ every time the same game is played. +const slKey=o=>[o.type,o.city,o.city2||'',o.name,o.bw,o.exp].join('|'); const salesMo=()=>{const p=slP();return p?SALES[p].mo:0;}; const salesCanHire=()=>lvl()>=SALES_LV; // How often offers come in: the engineer brings more, half as many again while a meeting's glow lasts. @@ -37,10 +39,10 @@ function salesShape(n0){const p=slP();if(!p)return;for(let i=S.offers.length-1;i if(p==='shark'&&SALES_NERDS.includes(o.type)){S.offers.splice(i,1);continue;} o.by=p; if(p==='shark'&&!T.event&&!T.cap){const up=(T.opts||[]).find(x=>x>o.bw);if(up&&!T.fiber)o.bw=up;o.rate=Math.round(o.rate*1.25); - if(slR('over|'+o.id)<0.5){const k=salesPromise(o);if(k)o.reqs=(o.reqs||[]).concat(k);}}}} + if(slR('over|'+slKey(o))<0.5){const k=salesPromise(o);if(k)o.reqs=(o.reqs||[]).concat(k);}}}} // A promise nobody checked: a requirement this deal can have, that the network does not meet today. function salesPromise(o){const T=BIZ_T[o.type],pool=Object.keys(REQS).filter(k=>!(o.reqs||[]).includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,o)).sort(); - const no=pool.filter(k=>{try{return !REQS[k].ok(o);}catch(e){return false;}});return no.length?no[Math.floor(slR('promise|'+o.id)*no.length)]:null;} + const no=pool.filter(k=>{try{return !REQS[k].ok(o);}catch(e){return false;}});return no.length?no[Math.floor(slR('promise|'+slKey(o))*no.length)]:null;} // Their mark at renewal: how much likelier the customers they signed are to leave. function salesLeaveMul(b){if(b.by==='eng')return SALES_NERDS.includes(b.type)?0.5:0.75;if(b.by==='shark')return 1.5;if(b.by==='ceo')return 1.25;return 1;} // Haggles with whoever is at the desk now: how deep the discount they ask, and how often meeting halfway works. @@ -67,7 +69,7 @@ function salesGolf(d){const mine=Object.keys(S.pops).filter(c=>popUp(c)&&bizCity const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b)); toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');} // Declining an offer the CEO likes: about one in three, he already shook hands on it. -function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||slR('veto|'+o.id)>=0.33)return false; +function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||slR('veto|'+slKey(o))>=0.33)return false; const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;} // Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer. function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null; diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index ccc393e..ec09dd6 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -18,9 +18,11 @@ const CL_TERMS={ip:[12,24,36],whole:[24,36,48,60],iru:[120,180,240]}; const clKind=t=>{const T=BIZ_T[t];if(!T||T.event||T.cap)return null;if(t==='dfpair'||t==='pairs')return 'iru';return T.l2||T.fiber||t==='isp'||t==='gpu'?'whole':'ip';}; const clOn=b=>!!b&&!b.scripted&&!!clKind(b.type); // A stable roll in [0,1) for this customer, this term and this question. -const clR=(b,q)=>(hstr(((S&&S.asn)||0)+'|'+b.id+'|'+b.te+'|'+q)%100000)/100000; +// Who the customer is (names are unique), not its id: ids come from the clock and would differ every time a game is replayed. +const clKey=b=>[b.type,b.city,b.city2||'',b.name].join('|'); +const clR=(b,q)=>(hstr(((S&&S.asn)||0)+'|'+clKey(b)+'|'+b.te+'|'+q)%100000)/100000; const clPick=(a,b,q)=>a[Math.floor(clR(b,q)*a.length)]; -function clTerm(b,from){const m=clPick(CL_TERMS[clKind(b.type)],{id:b.id,te:from},'term');return from+Math.round(m*365/12);} +function clTerm(b,from){const m=clPick(CL_TERMS[clKind(b.type)],{type:b.type,city:b.city,city2:b.city2,name:b.name,te:from},'term');return from+Math.round(m*365/12);} // What this customer's contract would be priced at today: its price moved by the market since it was signed. // A renewal moves at most 25% down or 10% up at once, so an old save is not repriced in one go. const clFair=b=>rule('market')&&b.mk>0?Math.round(b.rate*clamp(mkt()/b.mk,0.75,1.1)):b.rate; @@ -102,7 +104,7 @@ const CL_REF=['dia','game','host','isp','stream','edu','scrub','provedor','gpu', function clReferral(d){if(d%45!==0||S.offers.length>=6)return; const b=S.biz.filter(x=>clOn(x)&&CL_REF.includes(x.type)&&x.mood>=90&&d-(x.since||0)>=365&&bizCity(x.city)&&lvl()>=(BIZ_T[x.type].lv||1)).sort((a,c)=>c.mood-a.mood||(a.since||0)-(c.since||0)||(a.ido.ref===b.id))return;const T=BIZ_T[b.type],list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));if(!list.length)return; - const name=clPick(list,{id:b.id,te:d},'refname');useName(name); + const name=clPick(list,{type:b.type,city:b.city,city2:b.city2,name:b.name,te:d},'refname');useName(name); S.offers.push({id:uid(),city:b.city,city2:null,name,type:b.type,bw:(T.opts||[1])[0],rate:Math.round((CITY[b.city].au?T.rate*AU_ARPU:T.rate)*mkt()),mk:mkt(),reqs:[],exp:d+40,ref:b.id,refN:b.name});} // New offers are priced at today's market (spawnOffer and friends price at 1; this moves them). function mktPrice(from){const m=mkt();for(let i=from;ia+e.ren+e.grew+Object.values(e.lost).reduce((x,y)=>x+y,0),0)") > 0, 'contracts did end'); assert.deepEqual(errors, []); }); @@ -57,7 +61,7 @@ test('happy customers renew or grow; an unhappy one leaves, and says it was the const { ev, errors } = load(); ev(start); const te = ev('S.day') + 10; - const stay = idFor(ev, 'leave', 0.5, te, true), grow = ev(`(()=>{for(let i=0;i<20000;i++){const id='g'+i;if(clR({id,te:${te}},'leave')>=0.5&&clR({id,te:${te}},'grow')<0.3)return id;}})()`); + const stay = idFor(ev, 'leave', 0.5, te, true), grow = ev(`(()=>{for(let i=0;i<20000;i++){const id='g'+i,b={type:'dia',city:'ams',name:id,te:${te}};if(clR(b,'leave')>=0.5&&clR(b,'grow')<0.3)return id;}})()`); const sad = idFor(ev, 'leave', 0.3, te); for (const [id, mood] of [[stay, 100], [grow, 100], [sad, 20]]) ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:2,rate:600,reqs:[],mood:${mood},since:S.day-400,te:${te},mk:1})`); ev(`clDay(${te})`); @@ -82,7 +86,7 @@ test('leaving that is not your fault: only reasons that fit the customer, and th assert.ok(!(r.moved || []).some(t => t === 'l2vpn' || t === 'dfpair'), 'circuits and fiber do not move away'); assert.ok(!(r.bust || []).includes('dfpair')); // The odd reasons: never twice within 60 days. - const gaps = JSON.parse(ev(`(()=>{S.day=5000;S.cl={odd:-1e9,mo:[]};const days=[];for(let d=0;d<400;d++){for(let i=0;i<6;i++){const b={id:'o'+d+'_'+i,city:'ams',city2:null,name:'O',type:'dia',bw:1,rate:100,reqs:[],mood:90,since:0,te:S.day,mk:1};S.biz=[b];const o=S.cl.odd;clDay(S.day);if(S.cl.odd!==o)days.push(S.day);}S.day++;}return JSON.stringify(days);})()`)); + const gaps = JSON.parse(ev(`(()=>{S.day=5000;S.cl={odd:-1e9,mo:[]};const days=[];for(let d=0;d<400;d++){for(let i=0;i<6;i++){const b={id:'o'+d+'_'+i,city:'ams',city2:null,name:'O'+d+'_'+i,type:'dia',bw:1,rate:100,reqs:[],mood:90,since:0,te:S.day,mk:1};S.biz=[b];const o=S.cl.odd;clDay(S.day);if(S.cl.odd!==o)days.push(S.day);}S.day++;}return JSON.stringify(days);})()`)); assert.ok(gaps.length >= 3, `odd reasons do come (${gaps.length} in 400 days)`); assert.ok(gaps.every((d, i) => !i || d - gaps[i - 1] >= 60), 'at most one every 60 days'); assert.deepEqual(errors, []); @@ -93,7 +97,7 @@ test('a haggle: 30 days ahead, in Deals; match, meet halfway, let go, or no answ ev(start); const te = ev('S.day') + 30; const id = idFor(ev, 'hag', 0.05, te); - ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'Haggle Co',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:${te},mk:1})`); + ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:${te},mk:1})`); ev(`clDay(S.day)`); const hag = JSON.parse(ev(`JSON.stringify(S.biz.find(b=>b.id==='${id}').hag)`)); assert.ok(hag && hag.rate < 600 && hag.rate >= 480 && hag.until === te, `asks 8–20% off until the term ends (${JSON.stringify(hag)})`); From c1d726c105571267db16206e15ba30f2d172fcdb Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 11:04:47 +0100 Subject: [PATCH 343/491] Relay test waits for the late page instead of a fixed 2.5 s On a busy CI runner the page took longer than that to load and answer, and the test failed although the server did proceed. --- tests/agent-relay.test.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/agent-relay.test.js b/tests/agent-relay.test.js index 2966901..21074f9 100644 --- a/tests/agent-relay.test.js +++ b/tests/agent-relay.test.js @@ -22,6 +22,8 @@ const PORT = 8799 + (process.pid % 500); // dodge a busy por const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-relay-')); const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +// Waits until ok() holds, up to ms: a busy CI runner can take seconds to load a page, so no fixed delay is enough. +const until = async (ok, ms = 20000) => { const t0 = Date.now(); while (!ok() && Date.now() - t0 < ms) await wait(50); return ok(); }; // The relay in-process, riding a real http.Server (the same createRelay the servers host): no child to leak, and // 'listening' means the first dial cannot race the bind. @@ -373,7 +375,7 @@ test('the MCP server answers the handshake at once and waits for the game page', assert.match(m.stderr(), /waiting for the game page/); a = page({ seed: 4 }); a.ev("ACT.start({});S.cash=444000;compute()"); - await wait(2500); + await until(() => /ready/.test(m.stderr())); assert.match(m.stderr(), /ready/, 'the server proceeded once the page answered'); assert.equal(await m.json('state', { path: 'cash' }), 444000, 'and drives the late page'); } finally { stop(a); await m.kill(); } From f9c85ab0c37306fb3c110f49b4a3f7fbcebda9b1 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 10:30:37 +0100 Subject: [PATCH 344/491] GPU benchmark: answer only its own page, and print what it sends as plain text Any site open in the same browser could POST results (printed to the terminal, escape sequences included, and written to --out), and DNS rebinding could read the save. The server now checks the Host header and the origin of a POST, caps the body at 2 MB, drops control characters, and no longer sends stack traces. The panel no longer shows tags. --- scripts/gpu-bench.js | 25 +++++++++++++++-- scripts/lib/gpu-bench-client.js | 2 +- tests/gpu-bench-server.test.js | 50 +++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 tests/gpu-bench-server.test.js diff --git a/scripts/gpu-bench.js b/scripts/gpu-bench.js index 52cfd8a..b2e45ff 100644 --- a/scripts/gpu-bench.js +++ b/scripts/gpu-bench.js @@ -29,14 +29,29 @@ const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); retur const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8'); const page = () => assemble().html.replace('', ``); +/* Only the page this server hands out may talk to it. Any other site open in the same browser could otherwise + POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host + header must name this server, and a POST must come from its own origin. */ +const HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', HOST.includes(':') ? `[${HOST}]` : HOST]); +if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4') HOSTS.add(l.address); +const hostOk = (h) => { const m = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(h || ''); return !!m && HOSTS.has(m[1].toLowerCase()) && (m[2] ? +m[2] : 80) === PORT; }; +const MAX_BODY = 2 * 1048576; +// What the page sends is printed and written as text: no terminal escape sequences or other control characters. +const plain = (s) => String(s ?? '').replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u2028\u2029]/g, ''); + http.createServer((req, res) => { const url = new URL(req.url, 'http://localhost'); try { + if (!hostOk(req.headers.host)) { res.writeHead(421); return res.end(); } if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); } if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); } if (url.pathname === '/__bench/results' && req.method === 'POST') { - let body = ''; req.on('data', (c) => { body += c; }); req.on('end', () => { - try { const r = JSON.parse(body); console.log('\n' + r.md + '\n'); if (OUT) { fs.writeFileSync(OUT, r.md + '\n\n```json\n' + JSON.stringify(r, null, 1) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results', e); } + if (req.headers.origin !== `http://${req.headers.host}`) { res.writeHead(403); return res.end(); } + let body = '', size = 0, over = false; + req.on('data', (c) => { size += c.length; if (size > MAX_BODY) { over = true; req.destroy(); return; } body += c; }); + req.on('end', () => { + if (over) return; + try { const r = JSON.parse(body), md = plain(r && r.md); console.log('\n' + md + '\n'); if (OUT) { fs.writeFileSync(OUT, md + '\n\n```json\n' + plain(JSON.stringify(r, null, 1)) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results:', e.message); } res.writeHead(204); res.end(); }); return; } @@ -46,7 +61,11 @@ http.createServer((req, res) => { if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); } res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); fs.createReadStream(file).pipe(res); - } catch (e) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); res.end(String(e && e.stack || e)); } + } catch (e) { + // A malformed address (decodeURIComponent) or a missing file: the details stay in this terminal. + console.error('bench server:', e && e.message || e); + res.writeHead(e instanceof URIError ? 400 : 500); res.end(); + } }).listen(PORT, HOST, () => { const s = JSON.parse(save).S; console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`); diff --git a/scripts/lib/gpu-bench-client.js b/scripts/lib/gpu-bench-client.js index 690fbb3..0d85b4b 100644 --- a/scripts/lib/gpu-bench-client.js +++ b/scripts/lib/gpu-bench-client.js @@ -130,7 +130,7 @@ mapGl(want0, false); await reset(); MD = table(res, env); st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).'); - box.querySelector('#bout').innerHTML = '
' + MD.replace(/&/g, '&').replace(/';
+    box.querySelector('#bout').innerHTML = '
' + MD.replace(/<\/?sub>/g, '').replace(/&/g, '&').replace(/';
     box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
     try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
   }
diff --git a/tests/gpu-bench-server.test.js b/tests/gpu-bench-server.test.js
new file mode 100644
index 0000000..4187738
--- /dev/null
+++ b/tests/gpu-bench-server.test.js
@@ -0,0 +1,50 @@
+// npm run bench:gpu serves the game on this machine: only its own page may talk to it (no other site in the
+// browser, no DNS rebinding), and what it prints or writes holds no terminal control characters.
+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 http = require('node:http');
+const { spawn } = require('node:child_process');
+
+const ROOT = path.join(__dirname, '..');
+
+function req(port, { method = 'GET', p = '/', host, headers = {}, body } = {}) {
+  return new Promise((resolve, reject) => {
+    const r = http.request({ host: '127.0.0.1', port, method, path: p, headers: { host: host || `localhost:${port}`, ...headers } }, (res) => {
+      let d = ''; res.on('data', (c) => { d += c; }); res.on('end', () => resolve({ status: res.statusCode, body: d }));
+    });
+    r.on('error', reject); if (body !== undefined) r.write(body); r.end();
+  });
+}
+
+test('the benchmark server answers only its own page', async (t) => {
+  const port = 20000 + Math.floor(Math.random() * 20000), out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'bench-')), 'out.md');
+  const srv = spawn(process.execPath, [path.join(ROOT, 'scripts', 'gpu-bench.js'), '--port', String(port), '--out', out], { stdio: ['ignore', 'pipe', 'pipe'] });
+  let log = ''; srv.stdout.on('data', (c) => { log += c; }); srv.stderr.on('data', (c) => { log += c; });
+  t.after(() => srv.kill());
+  for (let i = 0; i < 100 && !/Ctrl\+C/.test(log); i++) await new Promise((r) => setTimeout(r, 100));
+  assert.match(log, /Ctrl\+C/, 'the server started');
+
+  // DNS rebinding: a request for another host name gets nothing.
+  assert.equal((await req(port, { p: '/__bench/save.json', host: `evil.example:${port}` })).status, 421);
+  assert.equal((await req(port, { p: '/__bench/save.json' })).status, 200);
+
+  // A POST from another site, or with no origin at all, is refused and writes nothing.
+  const md = 'ok\u001b]52;c;Zm9v\u0007\u001b[2Jdone';
+  const post = (origin) => req(port, { method: 'POST', p: '/__bench/results', headers: { 'content-type': 'text/plain', ...(origin ? { origin } : {}) }, body: JSON.stringify({ md }) });
+  assert.equal((await post('https://evil.example')).status, 403);
+  assert.equal((await post(null)).status, 403);
+  assert.equal(fs.existsSync(out), false);
+
+  // Its own page may send results; control characters are dropped before printing and writing.
+  assert.equal((await post(`http://localhost:${port}`)).status, 204);
+  const written = fs.readFileSync(out, 'utf8');
+  assert.match(written, /^ok\]52;c;Zm9v\[2Jdone/);
+  assert.doesNotMatch(written + log, /[\u001b\u0007]/);
+
+  // A malformed address is a plain 400: no stack trace or paths in the answer.
+  const bad = await req(port, { p: '/%E0' });
+  assert.equal(bad.status, 400); assert.equal(bad.body, '');
+});

From 7f4fdf6043d0de58b6b6074e3df195c59ac14d9e Mon Sep 17 00:00:00 2001
From: Frederic Jung 
Date: Thu, 5 Nov 2026 10:31:19 +0100
Subject: [PATCH 345/491] WebGL map: join each line's segments, and draw a link
 being dragged out under the cities

A see-through line on the card was one round-ended quad per segment, so
where two met it was blended twice: the selected tube's halo showed a
darker blob at every point, and the cables a notch at every corner. Each
segment now knows its neighbours' directions and keeps only its side of
the corner's bisector, as the 2D canvas strokes a path once.

The link being dragged out was painted on the overlay, above the cities
and their labels; it now goes to the card, under them, as in 2D, and its
price label is a picture like the others.

Auto after Always 2D, when the browser will not give the context back,
gives the card up instead of waiting for it all session. Firefox reads
the card's name from RENDERER, without the extension it warns about.
---
 src/game/96-map/55-link-look.js        |   5 +-
 src/game/96-map/56-webgl.js            |   9 +-
 src/game/96-map/57-webgl-background.js |  17 ++--
 src/game/96-map/58-webgl-links.js      |  50 ++++++++---
 src/game/96-map/60-draw.js             |   8 +-
 tests/map-2d.test.js                   |   2 +-
 tests/webgl-coast.test.js              |   2 +-
 tests/webgl-context-restore.test.js    |  12 +++
 tests/webgl-frame-garbage.test.js      |   2 +-
 tests/webgl-line-joins.test.js         | 115 +++++++++++++++++++++++++
 tests/webgl-map.test.js                |  14 +--
 tests/webgl-sprites.test.js            |   2 +-
 tests/webgl-zoom-sprites.test.js       |   2 +-
 13 files changed, 201 insertions(+), 39 deletions(-)
 create mode 100644 tests/webgl-line-joins.test.js

diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js
index 8ca98b6..32c636c 100644
--- a/src/game/96-map/55-link-look.js
+++ b/src/game/96-map/55-link-look.js
@@ -1,7 +1,8 @@
 /* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in
    58-webgl-links.js), so they cannot drift apart. */
-// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable.
-const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5]];
+// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable,
+// 7 a link being dragged out.
+const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12]];
 // A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash.
 function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
   const 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);
diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js
index 7f4196d..0fe11a7 100644
--- a/src/game/96-map/56-webgl.js
+++ b/src/game/96-map/56-webgl.js
@@ -19,7 +19,9 @@ const glCan=()=>!GLX.dead&&typeof WebGL2RenderingContext!=='undefined';
 // Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not.
 // Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back.
 function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){}
-  if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}}
+  if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;
+    // A context the browser will not give back would leave the map waiting for it all session: give the card up instead.
+    try{GLX.lose.restoreContext();}catch(e){if(GLX.ctx&&GLX.ctx.isContextLost&&GLX.ctx.isContextLost()===false)GLX.lost=false;else glKill(e);}}
   GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;}
 function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;}
 // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame.
@@ -72,7 +74,8 @@ function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false;
     const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'});
     if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl;
     if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}}
-    try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){}
+    // Firefox names the card in RENDERER and warns that the extension is going away; other browsers need it.
+    try{const x=/Firefox\//.test(navigator.userAgent)?null:gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){}
     if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu);
     const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)};
     // The tubes' points for the packets: floats read with texelFetch, never filtered.
@@ -83,7 +86,7 @@ function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false;
     const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype;
     if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}}
     const V=s=>glVao(gl,s);
-    Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;}
+    Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4,4]),hv:V([4,4,4,4]),pv:V([4,4]),cb:V([4,4,4,4]),wv:V([4,4,4,4]),dv:V([4,4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;}
   catch(e){glKill(e);return false;}}
 // Colours as [r,g,b,a] from '#rrggbb', '#rgb' or 'rgba(r,g,b,a)', kept by string.
 const GLCOL=new Map();
diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js
index 5055126..c245aee 100644
--- a/src/game/96-map/57-webgl-background.js
+++ b/src/game/96-map/57-webgl-background.js
@@ -53,11 +53,12 @@ function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@'
   COAST.forEach((ring,ri)=>{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return;
     const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return;
     coastFan(P,fan);
-    // Round ends make the joins round, as lineJoin='round' does; both lines are opaque, so the overlaps do not show.
-    for(let i=0;i+1new Float32Array(a);
-  G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE,
+  G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE,
     hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};
   glMem(gl,'the land');return GLX.land[key]=G;}
 // Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map.
@@ -84,10 +85,11 @@ function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z));
 // written into the same array every frame (no garbage for the collector to pick up while you play).
 const WAVE_COL=glColor('rgba(255,255,255,.45)');
 function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0;
-  for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;
+  for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3,m0=m;
     // Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame).
     for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y;
-      for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}}
+      for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}
+    glJoin(A,m0,m,false);}
   gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);}
 // The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack.
 function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)return;
@@ -103,8 +105,9 @@ function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)retu
 function glCables(gl,ks,selC,ar){const key=[selC,ar];
   if(!GLX.ckey||key.some((v,i)=>v!==GLX.ckey[i])){const A=[];
     for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;
-      const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0;
-      for(let j=0;j+12;
+  for(let i=i0;ii0?i-1:closed?i1-1:-1,n=i+1=0){const q=p*LINE_STRIDE;A[o+12]=A[q+2]-A[q];A[o+13]=A[q+3]-A[q+1];}else A[o+12]=A[o+13]=0;
+    if(n>=0){const q=n*LINE_STRIDE;A[o+14]=A[q+2]-A[q];A[o+15]=A[q+3]-A[q+1];}else A[o+14]=A[o+15]=0;}}
 /* One instance per segment, a quad around it; the fragment keeps what lies within half the line width of the segment
-   (or of a dash of it, both with round ends), which also gives round joins and caps. */
-const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC;
+   (or of a dash of it, both with round ends), which also gives round joins and caps. Where two segments of a line
+   meet, their round ends overlap: each keeps only its side of the corner's bisector, so a see-through line (the
+   halo, the cables, the waves, the fiber's dots) is blended once there, as the 2D canvas strokes a path once. */
+const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC;layout(location=3) in vec4 aN;
 uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uBusy;uniform int uPass;
-out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol;flat out vec2 vDash;
+out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol,vK;flat out vec2 vDash,vEnd;
+// The corner's bisector between directions u and v, in the segment's own frame (t along it, n across), and whether there is one.
+vec3 cut(vec2 u,vec2 v,vec2 t,vec2 n){vec2 m=u+v;float l=length(m);if(length(u)<.5||length(v)<.5||l<1e-3)return vec3(0.);m/=l;return vec3(dot(t,m),dot(n,m),1.);}
 vec2 dashOf(int k){${LDASH.map((d,i)=>d.length?`if(k==${i})return vec2(${d[0]}.,${d[1]}.);`:'').join('')}return vec2(0.);}
 void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h;
   float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false;
@@ -29,10 +39,16 @@ void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCa
   vec2 d=b-a;float L=length(d);vec2 t=L>1e-4?d/L:vec2(1.,0.),n=vec2(-t.y,t.x);float m=hw+1./uDpr;
   float sx=(gl_VertexID&1)==0?-m:L+m,sy=(gl_VertexID&2)==0?-m:m;
   vLoc=vec2(sx,sy);vLen=L;vS0=aP.x*uCam.z;vHalf=hw;vCol=col;vDash=dash;vButt=uPass==${LP.plain}&&(fl&${LINE_ROUND})==0?1.:0.;
+  float lp=length(aN.xy),ln=length(aN.zw);vec3 c0=L>1e-4&&lp>1e-9?cut(aN.xy/lp,t,t,n):vec3(0.),c1=L>1e-4&&ln>1e-9?cut(t,aN.zw/ln,t,n):vec3(0.);
+  vK=vec4(c0.xy,c1.xy);vEnd=vec2(c0.z,c1.z);
   gl_Position=clip(a+t*sx+n*sy,uView,(uPass==${LP.plain}?.9998:aC.x)*2.-1.);}`;
-const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol;flat in vec2 vDash;uniform float uDpr;out vec4 o;
+const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol,vK;flat in vec2 vDash,vEnd;uniform float uDpr;out vec4 o;
 void main(){float x=vLoc.x,y=vLoc.y,d;
-  if(vButt>.5&&(x<0.||x>vLen))discard;
+  // A corner: the side of the bisector that belongs to the neighbour is the neighbour's to paint.
+  if(vEnd.x>.5&&x*vK.x+y*vK.y<0.)discard;
+  if(vEnd.y>.5&&(x-vLen)*vK.z+y*vK.w>0.)discard;
+  // Flat ends only where the line really ends; its corners are joined.
+  if(vButt>.5&&((vEnd.x<.5&&x<0.)||(vEnd.y<.5&&x>vLen)))discard;
   if(vDash.x<=0.){float c=clamp(x,0.,vLen);d=length(vec2(x-c,y));}
   else{float P=vDash.x+vDash.y,g=vS0+x,k=floor(g/P);d=1e9;
     for(int i=-1;i<=1;i++){float a0=(k+float(i))*P,lo=max(a0,vS0),hi=min(a0+vDash.x,vS0+vLen);if(lo<=hi){float c=clamp(g,lo,hi);d=min(d,length(vec2(g-c,y)));}}}
@@ -67,7 +83,8 @@ function glBuild(LG,GM,looks){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0;
   for(let gi=0;gix.id===selId))continue;const L=looks[gi],{pts,cum,len}=GM[gi],dep=glDepth(gi,N),col=glColor(L.col);
-    for(let j=0;j+1(x-CW/2)/z+cam.x,my=y=>(y-CH/2)/z+cam.y;
+  glSegAt(A,0,mx(ax),my(ay),mx(tx),my(ty),0,7,7,LINE_ROUND,1,DRAG_INK);
+  glSegAt(A,1,mx(ax),my(ay),mx(tx),my(ty),-now/30/z,4,7,LINE_ROUND,1,DRAG_PINK);
+  gl.bindBuffer(gl.ARRAY_BUFFER,GLX.dv.b);gl.bufferData(gl.ARRAY_BUFFER,A,gl.DYNAMIC_DRAW);
+  gl.disable(gl.DEPTH_TEST);glLines(gl,GLX.dv.v,2,[0]);gl.bindVertexArray(null);}
diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js
index 6709e30..3d8b80a 100644
--- a/src/game/96-map/60-draw.js
+++ b/src/game/96-map/60-draw.js
@@ -86,12 +86,14 @@ function drawFrame(now){
     if(UI.snap){const sv=UI.snap;tx=sv.sx;ty=sv.sy;}
     let [ax,ay]=toS(A.x,A.y,0);if(UI.snap){const B=CITY[UI.snap.id];const bxw=A.x+wrapDx(A.x,B.x);[tx,ty]=toS(bxw,B.y,0);}else{/* nearest copy of origin to cursor */for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k);if(Math.abs(px-tx)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));}}
diff --git a/tests/map-2d.test.js b/tests/map-2d.test.js
index 450ad59..51cab17 100644
--- a/tests/map-2d.test.js
+++ b/tests/map-2d.test.js
@@ -106,7 +106,7 @@ const GLSTUB = `window.__GLSTUB=(()=>{const calls=[];const gl=new Proxy({calls},
       return (...a)=>{calls.push(k);return {};};}});
     const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
     const fx=document.createElement('canvas').getContext('2d');
-    Object.assign(GLX,{want:true,dead:false,gl,c,f,fx,line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+    Object.assign(GLX,{want:true,dead:false,gl,c,f,fx,line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
     GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})();0`;
 
 function open() {
diff --git a/tests/webgl-coast.test.js b/tests/webgl-coast.test.js
index f0ba261..0438e6b 100644
--- a/tests/webgl-coast.test.js
+++ b/tests/webgl-coast.test.js
@@ -19,7 +19,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in
   return (...a)=>{calls.push([k,...a]);return {};};}});
   const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
   const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
-  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
 
 test('a simplified coastline never strays more than the tolerance from the full one', () => {
   const { ev, errors } = open();
diff --git a/tests/webgl-context-restore.test.js b/tests/webgl-context-restore.test.js
index ea46ea2..bb3a2c3 100644
--- a/tests/webgl-context-restore.test.js
+++ b/tests/webgl-context-restore.test.js
@@ -161,3 +161,15 @@ test('opening Settings never makes a context, and still says when the card canno
   assert.equal(note(), true, 'no WebGL2 in this browser: Settings says so');
   assert.deepEqual(errors, []);
 });
+
+test('Auto after Always 2D, when the browser will not give the context back, gives the card up instead of waiting all session', () => {
+  const { ev, errors } = open();
+  assert.equal(JSON.parse(frame(ev)).gl, true);
+  ev(`ACT.mapSet({v:'2d'});`);
+  assert.equal(ev('GLX.sleep&&GLX.lost'), true, 'Always 2D let the context go');
+  ev(`GLX.lose.restoreContext=()=>{throw new Error('not now');};ACT.mapSet({v:'auto'});`);
+  const f = JSON.parse(frame(ev));
+  assert.deepEqual([f.gl, f.dead, f.lost], [false, true, true], 'given up for 2D, with a reason');
+  assert.match(ev('diagMap()'), /map: 2D \(not now\)/, 'Diagnostic info says why, not "waiting for it back"');
+  assert.deepEqual(errors, []);
+});
diff --git a/tests/webgl-frame-garbage.test.js b/tests/webgl-frame-garbage.test.js
index a672b14..9c68e4f 100644
--- a/tests/webgl-frame-garbage.test.js
+++ b/tests/webgl-frame-garbage.test.js
@@ -19,7 +19,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in
   return (...a)=>{calls.push([k,...a]);return {};};}});
   const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
   const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
-  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
   GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
 
 // Counts the keys joined during one frame (Array#join with '|', as the picture keys are), but the ships' (a handful).
diff --git a/tests/webgl-line-joins.test.js b/tests/webgl-line-joins.test.js
new file mode 100644
index 0000000..47b54d7
--- /dev/null
+++ b/tests/webgl-line-joins.test.js
@@ -0,0 +1,115 @@
+// Lines on the card are one instance per segment. Where two segments of a line meet, each keeps only its side of the
+// corner (glJoin() tells it which way its neighbours run), so a see-through line is blended once there, as the 2D
+// canvas strokes a path once: the selected tube's halo, the cables, the waves, the fiber's dots. Also: the link being
+// dragged out is drawn on the card, under the cities as in 2D, not on the overlay above them.
+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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+
+function open() {
+  const h = load({ seed: 777 });
+  h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
+  return h;
+}
+
+const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
+  return (...a)=>{calls.push([k,...a]);return {};};}});
+  const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
+  const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+  GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
+
+// For records A of segments: which neighbour directions are wrong. A segment whose start is where the previous one
+// ended must point back along it; one that starts a line (or ends one) must say it has no neighbour there.
+const CHECK = `const joins=(A,n,lines)=>{const S=LINE_STRIDE,bad=[];let joined=0;
+  for(let i=0;iMath.abs(a-b)<=1e-3*Math.max(1,Math.abs(b));if(!near(A[o+12],pv[0])||!near(A[o+13],pv[1])||!near(A[o+14],nx[0])||!near(A[o+15],nx[1]))bad.push(i);if(!first)joined++;}
+  return {bad:bad.slice(0,5),joined,n};};`;
+
+test('the tubes and the selected one’s halo are joined segment to segment, and only within a tube', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  const r = JSON.parse(ev(`(()=>{${CHECK}const ML=mapLinks(S.day),{SEG}=glBuild(ML.LG,ML.GM,ML.looks),starts=new Set();let si=0;
+    for(const gm of ML.GM){starts.add(si);si+=gm.pts.length-1;}
+    const gi=ML.GM.findIndex(gm=>gm.pts.length>4),H=glHalo(ML.LG,ML.GM,ML.looks,ML.LG[gi][0].id);
+    return JSON.stringify({tubes:joins(SEG,si,starts),halo:joins(H,H.length/LINE_STRIDE,new Set([0]))});})()`));
+  assert.deepEqual(r.tubes.bad, [], 'every tube segment knows its neighbours, and no tube runs into the next');
+  assert.ok(r.tubes.joined > r.tubes.n / 2, `most segments have a neighbour before them (${r.tubes.joined} of ${r.tubes.n})`);
+  assert.deepEqual(r.halo.bad, []);
+  assert.ok(r.halo.joined >= 3, 'the halo is one joined line');
+  assert.deepEqual(errors, []);
+});
+
+test('coastlines close on themselves; cables and waves are joined along each line', () => {
+  const { ev, errors } = open();
+  ev(STUB);
+  // A closed ring: the first segment's neighbour before it is the last one.
+  const ring = JSON.parse(ev(`(()=>{const A=[];const P=[[0,0],[10,0],[10,10],[0,10],[0,0]];for(let i=0;i+1{GLX.land={};const gl=GLX.gl;gl.calls.length=0;glLandGeo(gl,false,0);
+    const sent=gl.calls.filter(c=>c[0]==='bufferData'&&c[2]&&c[2].length%LINE_STRIDE===0&&c[2].length>LINE_STRIDE*10).map(c=>c[2]);
+    const A=sent[0];let open=0;for(let i=0;i 1000, 'the coastlines went to the card');
+  assert.equal(land.open, 0, 'every coastline is a closed ring');
+  const r = JSON.parse(ev(`(()=>{${CHECK}const gl=GLX.gl;GLX.ckey=null;glCables(gl,[0],null,false);
+    const F=gl.calls.filter(c=>c[0]==='bufferData').pop()[2],cs=new Set();let ci=0;for(const cp of CABLE_PAIRS){cs.add(ci);ci+=cp.pts.length-1;}const cab=joins(F,F.length/LINE_STRIDE,cs);
+    glWaves(gl,1234,[0]);const starts=new Set();for(let i=0;i 100, `cables have corners (${r.cab.joined})`);
+  assert.deepEqual(r.wav.bad, [], 'each wave is one line of eight segments');
+  assert.deepEqual(errors, []);
+});
+
+test('the line shader takes the neighbours and splits each corner along its bisector', () => {
+  const { ev } = open();
+  const vs = ev('GL_LINE_VS'), fs_ = ev('GL_LINE_FS');
+  assert.match(vs, /layout\(location=3\) in vec4 aN/);
+  assert.match(fs_, /vEnd\.x>\.5&&x\*vK\.x\+y\*vK\.y<0\./);
+  assert.match(fs_, /vEnd\.y>\.5&&\(x-vLen\)\*vK\.z\+y\*vK\.w>0\./);
+  // The rule itself: at a corner, every point is painted by exactly one of the two segments that meet there.
+  const r = JSON.parse(ev(`(()=>{const norm=v=>{const l=Math.hypot(v[0],v[1]);return [v[0]/l,v[1]/l];},dot=(a,b)=>a[0]*b[0]+a[1]*b[1];
+    let both=0,none=0,n=0;
+    for(const deg of [5,30,60,90,135,170]){const r=deg*Math.PI/180,J=[0,0],tA=[1,0],tB=[Math.cos(r),Math.sin(r)],m=norm([tA[0]+tB[0],tA[1]+tB[1]]);
+      for(let x=-12;x<=12;x+=0.37)for(let y=-12;y<=12;y+=0.41){const P=[x,y];
+        // In capsule A (ending at J) or B (starting at J), half-width 6.
+        const inA=Math.hypot(x>0?x:x<-20?x+20:0,y)<=6,
+          pb=dot(P,tB),qb=Math.max(0,Math.min(20,pb)),inB=Math.hypot(x-qb*tB[0],y-qb*tB[1])<=6;
+        if(!inA&&!inB)continue;n++;const ownA=inA&&dot(P,m)<=0,ownB=inB&&dot(P,m)>=0;if(ownA&&ownB&&dot(P,m)!==0)both++;if(!ownA&&!ownB)none++;}}
+    return JSON.stringify({n,both,none});})()`));
+  assert.ok(r.n > 1000);
+  assert.equal(r.both, 0, 'no point is painted twice');
+  assert.equal(r.none, 0, 'no point of the joined line is left out');
+});
+
+test('the link being dragged out goes to the card, under the cities, and its price label is a picture', () => {
+  const { ev, errors } = open();
+  ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`);
+  ev(STUB);
+  ev(`(()=>{const fx=GLX.fx;fx.__st=0;fx.stroke=function(){fx.__st++;};})()`);
+  ev(`UI.drag=null;draw(1000);`);
+  const base = ev('GLX.fx.__st');
+  ev(`(()=>{const h=CITY[S.home],[x,y]=toS(h.x,h.y,0);UI.drag={mode:'link',from:S.home,cx:x+120,cy:y+40};UI.snap=null;GLX.gl.calls.length=0;GLX.fx.__st=0;draw(1000);})()`);
+  assert.equal(ev('GLX.fx.__st'), base, 'nothing more is stroked on the overlay above the cities');
+  const r = JSON.parse(ev(`(()=>{const c=GLX.gl.calls,i=c.findIndex(x=>x[0]==='bufferData'&&x[2]===GLX.da),
+    d=c.findIndex((x,j)=>j>i&&x[0]==='drawArraysInstanced'&&x[4]===2),A=GLX.da,S=LINE_STRIDE;
+    return JSON.stringify({sent:i>=0,drawn:d>i,dash:[A[6],A[S+6]],w:[A[5],A[S+5]],off:[A[4],A[S+4]],z:cam.z,dash7:LDASH[7]});})()`));
+  assert.ok(r.sent && r.drawn, 'the two dotted lines go to the card in one draw');
+  assert.deepEqual(r.dash, [7, 7]); assert.deepEqual(r.dash7, [2, 12]);
+  assert.deepEqual(r.w, [7, 4], 'the dark line under the pink one, as in 2D');
+  assert.equal(r.off[0], 0); assert.ok(Math.abs(r.off[1] - (-1000 / 30 / r.z)) < 1e-3, 'the pink dots run along the line as in 2D');
+  // Snapped to a city, the price shows on a pill picture with the cities' pictures, not on the overlay.
+  const label = ev(`(()=>{const h=S.home,b=CITIES.find(c=>c.id!==h&&!isSub(h,c.id)).id,[x,y]=toS(CITY[b].x,CITY[b].y,0);UI.snap={id:b,sx:x,sy:y};GLX.fx.__st=0;draw(1016);
+    return [...SPRS.keys()].some(k=>k.startsWith('pill|')&&k.includes(' km'));})()`);
+  assert.equal(label, true);
+  assert.equal(ev('GLX.fx.__st'), base);
+  assert.deepEqual(errors, []);
+});
diff --git a/tests/webgl-map.test.js b/tests/webgl-map.test.js
index 7d41a6e..c61544b 100644
--- a/tests/webgl-map.test.js
+++ b/tests/webgl-map.test.js
@@ -21,7 +21,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in
   return (...a)=>{calls.push([k,...a]);return {};};}});
   const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
   const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
-  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
 
 test('without WebGL2 the map stays 2D, and asking for WebGL changes nothing', () => {
   const { ev, errors } = open();
@@ -41,14 +41,14 @@ test('the instance data says what the 2D map draws: points, colours, dashes, pac
     const sel=LG[3][0].id,looks=LG.map(g=>linkLook(g,S.day)),{SEG,PK,PT}=glBuild(LG,GM,looks),H=glHalo(LG,GM,looks,sel);let si=0,ki=0,pi=0,hi=0,bad=[];const deps=[];
     for(let gi=0;gix.id===sel);
       for(let j=0;j1e-3*Math.max(1,Math.abs(SEG[o+x])))bad.push('halo '+gi);hi++;}
         if(j===0)deps.push(SEG[o+8]);si++;}
       const n=!L.cut&&L.load>0.01?clamp(Math.round(2+L.u*10),2,12):0;for(let i=0;i!i||dd>0&&d<1),sel:hi>0&&hi===GLX.nHalo,moving:looks.filter(L=>!L.cut&&L.load>0.01).length});})()`));
   assert.deepEqual(r.bad, []);
   assert.equal(r.si, r.segs, 'one instance per segment');
@@ -74,7 +74,7 @@ test('with WebGL the lines go to the card, the rest to the overlay, and the map
   assert.ok(draws.includes(ev('GLX.nSeg')) && draws.includes(ev('GLX.nPk')), 'every segment and every packet in instanced draws');
   // Nothing changed: the next frame reuses the buffers. A cut link changes routing, and the tubes are rebuilt.
   // The tubes' own buffers (segments, packets, points) are what must not be sent again on an ordinary frame; the waves and clouds move every frame by design.
-  const uploads = () => ev(`GLX.gl.calls.filter(c=>c[0]==='bufferData'&&c[2]&&c[2].length===GLX.nSeg*12).length`);
+  const uploads = () => ev(`GLX.gl.calls.filter(c=>c[0]==='bufferData'&&c[2]&&c[2].length===GLX.nSeg*LINE_STRIDE).length`);
   const u0 = uploads(); ev('draw(1016)'); assert.equal(uploads(), u0, 'a frame alone uploads no tube data');
   const id = ev(`(()=>{const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));l.cut=S.day+5;compute();draw(1032);return l.id;})()`);
   assert.ok(uploads() > u0, 'a cut rebuilds the tubes');
@@ -298,10 +298,10 @@ test('selecting a tube sends its halo to the card, not the network again', () =>
     sent();const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));UI.sel={type:'link',id:l.id};draw(1016);const on=sent(),halo=GLX.nHalo;
     UI.sel=null;draw(1032);const off=sent();
     return JSON.stringify({nSeg,on,off,halo,haloDraw:GLX.nHalo});})()`));
-  const tubes = r.nSeg * 12;
+  const tubes = r.nSeg * ev('LINE_STRIDE');
   assert.ok(r.halo > 0, 'the halo has the selected tube’s segments');
   assert.ok(!r.on.b.includes(tubes) && r.on.t === 0, 'selecting sends no tube, packet or point again');
-  assert.ok(r.on.b.includes(r.halo * 12), 'only the halo goes up');
+  assert.ok(r.on.b.includes(r.halo * ev('LINE_STRIDE')), 'only the halo goes up');
   assert.ok(!r.off.b.includes(tubes) && r.off.t === 0, 'nor does unselecting');
   assert.equal(r.haloDraw, 0, 'and the halo is gone');
   assert.deepEqual(errors, []);
diff --git a/tests/webgl-sprites.test.js b/tests/webgl-sprites.test.js
index 95d4874..b8122d6 100644
--- a/tests/webgl-sprites.test.js
+++ b/tests/webgl-sprites.test.js
@@ -19,7 +19,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in
   return (...a)=>{calls.push([k,...a]);return {};};}});
   const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
   const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
-  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
   GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;
   // Counts the canvases the page makes from here on.
   const ce=document.createElement.bind(document);window.__canvases=0;document.createElement=function(t){if(String(t).toLowerCase()==='canvas')__canvases++;return ce.apply(document,arguments);};
diff --git a/tests/webgl-zoom-sprites.test.js b/tests/webgl-zoom-sprites.test.js
index ae35c7f..59be188 100644
--- a/tests/webgl-zoom-sprites.test.js
+++ b/tests/webgl-zoom-sprites.test.js
@@ -21,7 +21,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in
   return (...a)=>{calls.push([k,...a]);return {};};}});
   const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
   const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
-  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
+  Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
   GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
 
 // One POP's city pictures painted during frames from zoom z0 to z1 (the clock moving 16 ms a frame), by scale.

From aef744af50d2eb2365f1121684bf87b258a9bb4e Mon Sep 17 00:00:00 2001
From: Frederic Jung 
Date: Thu, 5 Nov 2026 10:31:19 +0100
Subject: [PATCH 346/491] Show a cable's name and a repair button from a save
 as text

The city panel put the name of your own subsea cable and an incident's
repair label into its HTML as they came from the save. Both are escaped
now, and sanitize() keeps a cable's name to a string of 60 characters.
---
 CHANGELOG.md                          |  1 +
 src/game/80-simulation/50-sanitize.js |  2 +-
 src/game/93-ui/50-city-panel.js       |  4 ++--
 tests/save-text.test.js               | 31 +++++++++++++++++++++++++++
 4 files changed, 35 insertions(+), 3 deletions(-)
 create mode 100644 tests/save-text.test.js

diff --git a/CHANGELOG.md b/CHANGELOG.md
index f3367bf..222fb27 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,7 @@ All notable changes to this project are documented here. The project follows
 - Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the map also draws far fewer shapes each frame. (#281)
 - In Firefox on a computer, the 2D map is up to three times as fast when zoomed in: its land picture now stays on the graphics card instead of being sent to it again on every frame. Firefox on Android keeps the old way, which avoids its drawing glitches. (#281)
 - Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report. (#281)
+- A save file can no longer put formatting or links into the game: the name of your own subsea cable and the repair button on a POP that is down always show as plain text, and a cable name from a save is cut to 60 characters.
 
 ## [2.9.1] — 2026-11-04
 
diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js
index ceee2b6..244437d 100644
--- a/src/game/80-simulation/50-sanitize.js
+++ b/src/game/80-simulation/50-sanitize.js
@@ -21,7 +21,7 @@ function sanitize(s){
   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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}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)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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;});
+  s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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);
   /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its
      links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */
diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js
index 4452395..17993d9 100644
--- a/src/game/93-ui/50-city-panel.js
+++ b/src/game/93-ui/50-city-panel.js
@@ -22,7 +22,7 @@ function cityPanel(c){
   h+=`
`; if(C.cn&&UI.tab==='cust')h+=chinaSection(c); const sf=sfOf(R,c),dem=R.cityDem[c]||0; - if(down){const i=S.inc.filter(x=>x.ref===c&&POPDOWN.includes(x.type)).sort((a,b)=>b.until-a.until)[0];h+=`

${tr('city_panel.this_pop_is_down')}

${i?esc(i.msg):''} ${tr('city_panel.customers_here_get_nothing_until_it')}

${i&&i.cost?btn(`${i.fix} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red'):''}
`;} + if(down){const i=S.inc.filter(x=>x.ref===c&&POPDOWN.includes(x.type)).sort((a,b)=>b.until-a.until)[0];h+=`

${tr('city_panel.this_pop_is_down')}

${i?esc(i.msg):''} ${tr('city_panel.customers_here_get_nothing_until_it')}

${i&&i.cost?btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red'):''}
`;} 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')}

`; @@ -104,7 +104,7 @@ function cityPanel(c){ h+=`

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

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

${tr('common.no_links_yet')}

`; for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l); - h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:l.cname}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} h+=`
`; if(Object.keys(S.pops).length>1)h+=`

${tr('common.decommission')}

${tr('city_panel.shut_this_pop_down_its_links')}

${btn(tr('city_panel.decommission_city',{city:C.name}),'decomOpen',{city:c},'ghost sm')}${btn(tr('city_panel.decommission_several_pops'),'decomOpen',{},'ghost sm')}
`; } diff --git a/tests/save-text.test.js b/tests/save-text.test.js new file mode 100644 index 0000000..f8d4d41 --- /dev/null +++ b/tests/save-text.test.js @@ -0,0 +1,31 @@ +// Text that comes from a save (an imported file, or this device's storage) is shown as text, never as HTML: the +// name of your own subsea cable, the repair button of a POP that is down. sanitize() also keeps a cable's name short. +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 SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + +function open() { + const h = load({ seed: 777 }); + h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); + return h; +} + +test('text from a save is shown as text: a cable’s name and a repair button', () => { + const { ev, errors } = open(); + const r = JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S)),b0=s.links[0],own=(id,cname)=>({...b0,id,kind:'df',own:true,sub:true,ch:[],sys:'roadm',seaDesign:'standard',cable:null,trench:'own:'+id,ready:0,mo:100,cname}); + const l=own('zzl1','Cable'+'x'.repeat(200)),t=own('zzl2',12345);s.links.push(l,t); + const c=Object.keys(s.pops)[0];s.pops[c].down=s.day+5;s.inc.push({id:'zz',type:'crash',ref:c,until:s.day+5,cost:1000,msg:'boom',fix:'fix'}); + S=migrate(s);compute();UI.tab='links';const L=S.links.find(x=>x.id===l.id),T=t&&S.links.find(x=>x.id===t.id); + const h1=cityPanel(L.a)+cityPanel(L.b),h2=cityPanel(c); + return JSON.stringify({len:L.cname.length,num:T.cname,raw1://.test(h1),esc1:/<b id=/.test(h1),raw2://.test(h2),esc2:/<i id=/.test(h2)});})()`)); + assert.equal(r.len, 60, 'a cable name from a save is cut to 60 characters'); + assert.equal(r.num, '12345', 'and is always text'); + assert.equal(r.raw1, false); assert.equal(r.raw2, false); + assert.equal(r.esc1, true, 'the cable\u2019s name shows, escaped'); + assert.equal(r.esc2, true, 'the repair button shows its text escaped'); + assert.deepEqual(errors, []); +}); From 02d3709944b417db644450366ad692630830cafd Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 11:22:53 +0100 Subject: [PATCH 347/491] GPU benchmark server test: listen on 127.0.0.1, where it connects On the CI runners localhost resolves to ::1 first, so the server listened there while the test connected to 127.0.0.1. --- tests/gpu-bench-server.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/gpu-bench-server.test.js b/tests/gpu-bench-server.test.js index 4187738..7767842 100644 --- a/tests/gpu-bench-server.test.js +++ b/tests/gpu-bench-server.test.js @@ -21,7 +21,7 @@ function req(port, { method = 'GET', p = '/', host, headers = {}, body } = {}) { test('the benchmark server answers only its own page', async (t) => { const port = 20000 + Math.floor(Math.random() * 20000), out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'bench-')), 'out.md'); - const srv = spawn(process.execPath, [path.join(ROOT, 'scripts', 'gpu-bench.js'), '--port', String(port), '--out', out], { stdio: ['ignore', 'pipe', 'pipe'] }); + const srv = spawn(process.execPath, [path.join(ROOT, 'scripts', 'gpu-bench.js'), '--port', String(port), '--host', '127.0.0.1', '--out', out], { stdio: ['ignore', 'pipe', 'pipe'] }); let log = ''; srv.stdout.on('data', (c) => { log += c; }); srv.stderr.on('data', (c) => { log += c; }); t.after(() => srv.kill()); for (let i = 0; i < 100 && !/Ctrl\+C/.test(log); i++) await new Promise((r) => setTimeout(r, 100)); From 151b7786edb2023c72263d0227a282ed75d1494b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 11:38:26 +0100 Subject: [PATCH 348/491] Tests wait for state instead of sleeping, on free ports The relay, parity and benchmark server tests slept fixed times before asserting, which a busy CI runner overran. They now wait for what they need (the relay reports what it holds), take a port from the OS, and use fresh HTTP connections. npm test -- --stress N hunts flakes. --- .claude/skills/write-tests/SKILL.md | 14 ++++ scripts/agent/relay.js | 2 + scripts/test.js | 28 +++++++- tests/agent-relay.test.js | 105 +++++++++++++++------------- tests/gpu-bench-server.test.js | 8 ++- tests/mcp-parity.test.js | 9 +-- tests/net.js | 33 +++++++++ tests/noc-window.test.js | 4 +- tests/save-size.test.js | 4 +- tests/save-slots.test.js | 4 +- 10 files changed, 152 insertions(+), 59 deletions(-) create mode 100644 tests/net.js diff --git a/.claude/skills/write-tests/SKILL.md b/.claude/skills/write-tests/SKILL.md index 42937b9..bfdc934 100644 --- a/.claude/skills/write-tests/SKILL.md +++ b/.claude/skills/write-tests/SKILL.md @@ -54,3 +54,17 @@ pull requests collide. Run one file with `npm test -- tests/route-servers.test.j - **UI:** render with `renderAll()` and query `dom.window.document`; check phone layouts by setting `window.innerWidth = 390` before rendering. - Run `npm test`; the whole suite must pass, not just the new test. + +## Servers, sockets and anything async + +CI runs four parts at once, each with its files in parallel, so a test can wait seconds for things that take +milliseconds on your machine. Never sleep a fixed time and then assert: wait for the state with `tests/net.js`. + +- `until(() => condition)` resolves true as soon as it holds (false after 20 s); assert on its result. +- `freePort()` asks the OS for a free port; never a fixed or random one. +- `kill(child)` stops a spawned server and resolves once it is gone. +- Listen and connect on `127.0.0.1`, not `localhost` (it can resolve to `::1` only on a CI runner). +- For HTTP to a test server, pass `agent: false`: a kept-alive socket can be reset by the server's idle timer. +- A fixed wait is fine only to prove that something does *not* happen. + +Hunt a suspected flake before pushing: `npm test -- --stress 8 tests/x.test.js` runs 8 copies at once, busier than CI. diff --git a/scripts/agent/relay.js b/scripts/agent/relay.js index a99e1da..a596f9a 100644 --- a/scripts/agent/relay.js +++ b/scripts/agent/relay.js @@ -106,6 +106,8 @@ function createRelay({ server } = {}) { return { wss, path: AGENT_PATH, + // What the relay holds right now, so tests wait for a state instead of sleeping. + status: () => ({ page: !!(page && page.readyState === 1), tools: [...tools].filter((t) => t.readyState === 1).length, calls: pending.size }), close() { for (const c of [page, ...tools]) { try { c.close(4002, 'relay shutdown'); } catch {} } try { wss.close(); } catch {} }, }; } diff --git a/scripts/test.js b/scripts/test.js index 2eb92f4..e847053 100644 --- a/scripts/test.js +++ b/scripts/test.js @@ -8,13 +8,15 @@ // npm test -- --shard 2/4 one of four parts of about equal time (CI runs the four at once) // npm test -- --shard 2/4 --list which files that part holds, without running them // TEST_JOBS=1 npm test one file at a time, as it used to be +// npm test -- --stress 8 tests/x.test.js hunt a flaky test: 8 copies of these files at once, on a machine kept +// busier than CI ever is, and how many runs failed (and why) // // Parts are balanced by tests/durations.json, each file's typical seconds (refresh: npm run test:timings). // A file missing from it counts as a typical one, so a stale list only makes the parts a little uneven. const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); -const { spawnSync } = require('node:child_process'); +const { spawn, spawnSync } = require('node:child_process'); const root = path.join(__dirname, '..'); const dir = path.join(root, 'tests'); @@ -22,6 +24,13 @@ const args = process.argv.slice(2); const list = args.includes('--list'); if (list) args.splice(args.indexOf('--list'), 1); +let stress = 0; +const ti = args.indexOf('--stress'); +if (ti >= 0) { + stress = parseInt(args[ti + 1], 10); + if (!(stress >= 1)) { console.error('--stress wants a count, like --stress 8'); process.exit(2); } + args.splice(ti, 2); +} let shard = null; const si = args.indexOf('--shard'); if (si >= 0) { @@ -58,5 +67,22 @@ if (shard && files.length) { } const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism()); +// Stress: N runs of the same files at once, each its own node --test, so they fight for the CPU the way the four +// CI parts and their own parallel files do (and worse). A test that only passes on a quiet machine fails here. +if (stress) { + if (!args.some((a) => a.endsWith('.test.js'))) { console.error('--stress wants the test files to run, like tests/agent-relay.test.js'); process.exit(2); } + const runs = Array.from({ length: stress }, (_, i) => new Promise((res) => { + const c = spawn(process.execPath, ['--test', '--test-reporter=dot', ...args], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }); + let out = ''; c.stdout.on('data', (d) => { out += d; }); c.stderr.on('data', (d) => { out += d; }); + c.on('close', (code) => res({ i: i + 1, code, out })); + })); + Promise.all(runs).then((rs) => { + const bad = rs.filter((r) => r.code !== 0); + for (const r of bad) console.log(`\n--- run ${r.i} failed ---\n${r.out.slice(-4000)}`); + console.log(`\n# stress: ${rs.length - bad.length} of ${rs.length} runs passed, ${stress} at once on ${os.availableParallelism()} cores`); + process.exit(bad.length ? 1 : 0); + }); + return; +} const r = spawnSync(process.execPath, ['--test', `--test-concurrency=${jobs}`, ...args, ...files], { stdio: 'inherit', cwd: root }); process.exit(r.status ?? 1); diff --git a/tests/agent-relay.test.js b/tests/agent-relay.test.js index 21074f9..d24148e 100644 --- a/tests/agent-relay.test.js +++ b/tests/agent-relay.test.js @@ -18,19 +18,19 @@ const ROOT = path.join(__dirname, '..'); const { createRelay } = require('../scripts/agent/relay'); const { createRelaySession } = require('../scripts/lib/relay-client'); const SERVER = path.join(ROOT, 'scripts', 'mcp.js'); -const PORT = 8799 + (process.pid % 500); // dodge a busy port across suites +const { wait, until, freePort, kill } = require('./net'); +let PORT; // a free one from the OS, before the first test +test.before(async () => { PORT = await freePort(); }); const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-relay-')); -const wait = (ms) => new Promise((r) => setTimeout(r, ms)); -// Waits until ok() holds, up to ms: a busy CI runner can take seconds to load a page, so no fixed delay is enough. -const until = async (ok, ms = 20000) => { const t0 = Date.now(); while (!ok() && Date.now() - t0 < ms) await wait(50); return ok(); }; // The relay in-process, riding a real http.Server (the same createRelay the servers host): no child to leak, and // 'listening' means the first dial cannot race the bind. +let CUR = null; // the relay started last function startRelay(port = PORT) { const srv = http.createServer((req, res) => { res.writeHead(404); res.end(); }); const relay = createRelay({ server: srv }); - return { + return CUR = { relay, srv, listening: () => new Promise((res, rej) => { srv.once('error', rej); srv.listen(port, '127.0.0.1', res); }), close: () => new Promise((r) => { relay.close(); srv.close(() => r()); }), @@ -46,6 +46,12 @@ function page(opts = {}) { return a; } const dial = (a, port = PORT) => a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='127.0.0.1:'+${port};apiAgentSync()`); +// Waits until the relay holds this page and the page knows how many tools are there (the clock follows that count). +async function joined(a) { + assert.ok(await until(() => { const s = CUR.relay.status(); return s.page && a.ev('API_RELAY.tools') === s.tools; }), 'the page joined the relay'); +} +// Waits until the page has heard the relay's tool count: its clock runs or holds by it. +const heard = async (a, n) => assert.ok(await until(() => a.ev('API_RELAY.tools') === n), `the page sees ${n} tool(s)`); // Kill the page's dial and retry timer before a test ends, or its backoff keeps the process alive. const stop = (...ps) => { for (const a of ps) if (a) a.ev("window.__AGENT_RELAY_TEST__=false;apiAgentSet('on',false)"); }; @@ -74,7 +80,8 @@ function toolClient(port = PORT, headers) { close: () => { try { ws.close(); } catch {} }, }; } -async function tool() { const t = toolClient(); await t.open(); t.auth('tool'); await wait(150); return t; } +// A tool that has been let in: the relay's first presence message comes right after the role is granted. +async function tool(port = PORT) { const t = toolClient(port); await t.open(); t.auth('tool'); assert.ok(await until(() => t.events.length > 0), 'the relay let the tool in'); return t; } async function withRelay(fn) { const r = startRelay(); @@ -104,7 +111,7 @@ function mcp(argv, onErr) { child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n'); return r; }, call: async (name, args) => (await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result, json: async (name, args) => JSON.parse((await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result.content[0].text), - kill: async () => { child.kill('SIGTERM'); await wait(200); child.kill('SIGKILL'); }, + kill: () => kill(child), }; } @@ -128,8 +135,8 @@ test('a live page answers tool calls through the relay, from a fixed list of too const a = page(); try { a.ev("ACT.start({});S.cash=500000;compute()"); - await wait(600); - assert.ok(t.events.some((e) => e.page === true), 'the tools see the page join'); + assert.ok(await until(() => t.events.some((e) => e.page === true)), 'the tools see the page join'); + await joined(a); const q = await t.call('act', { action: 'buildPop', args: { city: 'ams' }, dryRun: true }); assert.equal(q.value.outcome, 'quote'); assert.equal(q.value.quote.setup, 20000); @@ -156,7 +163,7 @@ test('in the player\'s tab the player owns the game, their windows, their settin const a = page({ ms: 0 }); try { a.ev("ACT.start({});S.cash=1e7;S.nextFail=S.day+40;S.nextEvent=S.day+50;compute()"); - await wait(500); + await joined(a); // The dice stay hidden, whole or by path, and the schema says so. const st = (await t.call('state')).value; for (const k of ['rng', 'nextFail', 'nextEvent']) assert.ok(!(k in st), `${k} is held back`); @@ -211,7 +218,7 @@ test('the agent\'s clock moves only with advance; a running clock only with time const a = page({ ms: 0 }); try { a.ev("ACT.start({});S.cash=1e7;compute()"); - await wait(500); + await joined(a); assert.equal(a.ev('UI.speed'), 0, 'a tool is connected, but the agent\'s clock stands still'); a.ev('last=performance.now();for(let i=1;i<=20;i++)frame(last+i*250)'); assert.equal(a.ev('S.day'), 0, 'the loop runs no days'); @@ -247,20 +254,19 @@ test('the page client reconnects after the relay restarts, and stops when the pl const a = page(); try { a.ev("ACT.start({});S.cash=500000;compute()"); - await wait(500); - assert.ok(t.events.some((e) => e.page === true)); + assert.ok(await until(() => t.events.some((e) => e.page === true))); await r.close(); - await wait(300); + assert.ok(await until(() => a.ev('!API_RELAY.ws||API_RELAY.ws.readyState!==1')), 'the page saw the relay go'); a.ev("apiAgentSet('on',false)"); const r2 = startRelay(); await r2.listening(); try { - await wait(1200); // past the first backoff retry + await wait(1200); // past the first backoff retry: it must not dial assert.equal(a.ev('API_RELAY.on'), false, 'the client is off'); + assert.equal(r2.relay.status().page, false, 'and never dialled'); a.ev("apiAgentSet('on',true)"); - await wait(1200); + await joined(a); const t2 = await tool(); - await wait(300); assert.ok(t2.events.some((e) => e.page === true), 'the page reconnected after the relay came back'); assert.equal((await t2.call('state', { path: 'cash' })).value, 500000, 'and answers calls again'); t2.close(); @@ -272,21 +278,21 @@ test('a paced clock holds while no tool is connected, and runs when one arrives' const a = page({ seed: 5 }); try { a.ev("ACT.start({});S.nextFail=S.day+99;S.nextEvent=S.day+99;compute()"); - await wait(500); + await joined(a); assert.equal(a.ev('UI.speed'), 0, 'no tool connected: the clock holds'); assert.equal(a.ev('UI.clockLocked'), true, 'agent mode stays on'); a.ev('last=performance.now();frame(last);frame(last+250);frame(last+500)'); assert.equal(a.ev('S.day'), 0, 'no day ran'); const t = await tool(); - await wait(300); + await heard(a, 1); assert.ok(a.ev('UI.speed') > 0, 'a tool connecting runs it'); t.close(); - await wait(400); + await heard(a, 0); assert.equal(a.ev('UI.speed'), 0, 'the tool leaving holds it again'); a.ev('S.uiSpeed=4;gameResume()'); assert.equal(a.ev('UI.speed'), 0, 'gameResume holds with no tool connected'); const t2 = await tool(); - await wait(300); + await heard(a, 1); assert.ok(a.ev('UI.speed') > 0, 'and a tool arriving runs it again'); // An unrelated preference change does not drop the connection or hold the clock. a.ev('window.__w0=API_RELAY.ws'); @@ -301,9 +307,11 @@ test('a paced clock holds while no tool is connected, and runs when one arrives' test('a second page replaces the first: one game per relay, the newest tab wins', () => withRelay(async () => { const a = page({ seed: 5 }); a.ev("ACT.start({});S.cash=111000;compute()"); + await joined(a); // in that order: two dials at once may land either way const b = page({ seed: 6 }); b.ev("ACT.start({});S.cash=222000;compute()"); - await wait(700); + assert.ok(await until(() => a.ev('API_RELAY.on') === false), 'the first page yields to the second'); + await joined(b); const t = await tool(); try { assert.equal((await t.call('state', { path: 'cash' })).value, 222000, 'the newest page answers'); @@ -313,7 +321,7 @@ test('a second page replaces the first: one game per relay, the newest tab wins' test('the MCP server drives the player\'s page in browser mode, over stdio', () => withRelay(async () => { const a = page({ seed: 9, ms: 0 }); a.ev("ACT.start({});S.cash=1000000;compute()"); - await wait(500); + await joined(a); const m = mcp(['--browser', '--relay-host', 'localhost', '--relay-port', String(PORT)]); try { const init = await m.init(); @@ -343,7 +351,7 @@ test('a game page older than the code stops the server rather than mislead', () a.ev("ACT.start({});compute()"); // A stale tab whose commands keep their names but change shape: only a deep compare of the sections catches it. a.ev('const __c=TUBES.call;TUBES.call=(t,x,c)=>{const v=__c(t,x,c);if(t==="schema"&&!x.section)v.commands.buildPop.args=[{name:"city",required:true}];return v;};'); - await wait(400); + await joined(a); const m = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '8000']); try { const init = await m.init(); @@ -368,10 +376,11 @@ test('the MCP server answers the handshake at once and waits for the game page', try { const t0 = Date.now(); await m.init(); - assert.ok(Date.now() - t0 < 3000, 'initialize does not wait for a browser tab'); + // Far below the page wait (20 s), with room for a slow start of the process on a busy runner. + assert.ok(Date.now() - t0 < 10000, 'initialize does not wait for a browser tab'); const early = await m.call('status'); assert.equal(early.isError, true, 'a tool before the page arrives is an error, not a hang'); - await wait(300); + await until(() => /waiting for the game page/.test(m.stderr())); assert.match(m.stderr(), /waiting for the game page/); a = page({ seed: 4 }); a.ev("ACT.start({});S.cash=444000;compute()"); @@ -381,19 +390,18 @@ test('the MCP server answers the handshake at once and waits for the game page', } finally { stop(a); await m.kill(); } })); -const free = () => new Promise((res, rej) => { const s = http.createServer(); s.on('error', rej); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)); }); }); test('dev.js binds loopback and parses --port; the page dials its own host', async () => { - const port = await free(); + const port = await freePort(); const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'dev.js'), '--port', String(port)], { stdio: ['ignore', 'ignore', 'pipe'] }); let serr = ''; child.stderr.on('data', (d) => { serr += d; }); let a = null; try { - await wait(700); - assert.match(serr, new RegExp(`agent relay on ws://127\\.0\\.0\\.1:${port}/agent`), 'dev.js binds loopback and honours --port'); - const t = toolClient(port); - await t.open(); t.auth('tool'); await wait(150); + const banner = new RegExp(`agent relay on ws://127\\.0\\.0\\.1:${port}/agent`); + await until(() => banner.test(serr)); // dev.js builds the page first: seconds on a busy runner + assert.match(serr, banner, 'dev.js binds loopback and honours --port'); + const t = await tool(port); assert.ok(t.events.some((e) => e.page === false), 'the relay answers on 127.0.0.1'); t.close(); a = load({ url: `http://127.0.0.1:${port}/`, agent: true, storage: { 'sot-agent': JSON.stringify({ on: true }) } }); @@ -403,7 +411,7 @@ test('dev.js binds loopback and parses --port; the page dials its own host', asy assert.equal(a.ev('apiRelayUrl()'), `ws://127.0.0.1:${port}/agent`, 'its own host and port, the relay path'); } finally { stop(a); - child.kill('SIGTERM'); await wait(150); child.kill('SIGKILL'); + await kill(child); } }); @@ -416,11 +424,11 @@ test('calls neither page nor relay can answer resolve as errors, not hangs', asy const a = page(); pages.push(a); a.ev('ACT.start({});S.cash=500000;compute()'); - await wait(400); + await joined(a); // The page dies with a call in flight; it is silenced first, so the call is provably pending when it closes. a.ev('API_RELAY.ws.onmessage=()=>{}'); const p = t.call('act', { action: 'buildPop', args: { city: 'ams' } }); - await wait(100); + assert.ok(await until(() => r.relay.status().calls === 1), 'the call reached the relay'); a.ev('API_RELAY.ws.close(1000)'); assert.match((await p).error || '', /disconnected before answering/i); stop(a); @@ -429,11 +437,11 @@ test('calls neither page nor relay can answer resolve as errors, not hangs', asy const b = page({ seed: 12 }); pages.push(b); b.ev('ACT.start({});S.cash=222000;compute()'); - await wait(400); + await joined(b); b.ev('API_RELAY.ws.onmessage=()=>{}'); const s = createRelaySession({ host: '127.0.0.1', port: PORT }); const p2 = s.call('state', { path: 'cash' }); - await wait(150); + assert.ok(await until(() => r.relay.status().calls === 1), 'the call reached the relay'); await r.close(); assert.match((await p2).refused || '', /connection closed/i); await s.close(); @@ -447,13 +455,13 @@ test('a page that hangs on a call answers within --call-ms, not minutes later', const a = page({ seed: 4 }); try { a.ev('ACT.start({});compute()'); - await wait(400); + await joined(a); a.ev('API_RELAY.ws.onmessage=()=>{}'); // connected, alive, and never answering const s = createRelaySession({ host: '127.0.0.1', port: PORT, callMs: 300 }); const t0 = Date.now(); const r = await s.call('state', { path: 'cash' }); assert.match(r.refused || '', /no answer from the game page in 0\.3 s/); - assert.ok(Date.now() - t0 < 2000, 'the configured timeout, not the default'); + assert.ok(Date.now() - t0 < 10000, 'the configured timeout, not the default (30 s)'); assert.equal(createRelaySession({}).config.callMs, 30000, 'the default is 30 s'); await s.close(); } finally { stop(a); } @@ -473,9 +481,8 @@ test('the relay refuses a cross-site Origin and takes a same-origin page or a to const same = toolClient(PORT, { Origin: `http://127.0.0.1:${PORT}` }); await same.open(); same.auth('page'); - await wait(150); const t = await tool(); - await wait(100); + await until(() => same.events.some((e) => e.tools === 1)); assert.ok(same.events.some((e) => e.tools === 1), 'the same-origin page connects and sees the tool'); t.close(); same.close(); })); @@ -486,16 +493,16 @@ function bannerOf(argv) { let serr = ''; return new Promise((res) => { const done = (v) => { clearTimeout(t); child.kill('SIGKILL'); res(v); }; - const t = setTimeout(() => done({ addr: null, serr }), 5000); + const t = setTimeout(() => done({ addr: null, serr }), 30000); // dev.js builds the page first child.stderr.on('data', (d) => { serr += d; const m = /agent relay on ws:\/\/(\S+)\/agent/.exec(serr); if (m) done({ addr: m[1], serr }); }); }); } test('dev.js: a bare --host binds loopback, never every interface; binding wider is the operator\'s choice, and said', async () => { - const p1 = await free(); + const p1 = await freePort(); const dev = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '--port', String(p1)]); assert.equal(dev.addr, `127.0.0.1:${p1}`, `the socket is bound to loopback (${dev.serr})`); - const p2 = await free(); + const p2 = await freePort(); const wide = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '0.0.0.0', '--port', String(p2)]); assert.equal(wide.addr, `0.0.0.0:${p2}`, 'the banner is the real socket, not the flag echoed back'); assert.match(wide.serr, /bound to 0\.0\.0\.0, so anything that can reach this address can drive/); @@ -504,7 +511,7 @@ test('dev.js: a bare --host binds loopback, never every interface; binding wider test('browser mode over HTTP: a client connects to the server, the server to the player\'s page', () => withRelay(async () => { const a = page({ seed: 11, ms: 0 }); a.ev("ACT.start({});S.cash=555000;compute()"); - await wait(400); + await joined(a); const child = spawn(process.execPath, [SERVER, '--browser', '--relay-port', String(PORT), '--http', '127.0.0.1:0'], { stdio: ['ignore', 'ignore', 'pipe'] }); let err = ''; try { @@ -514,11 +521,13 @@ test('browser mode over HTTP: a client connects to the server, the server to the }); const post = (body) => new Promise((res, rej) => { const data = JSON.stringify({ jsonrpc: '2.0', id: 1, ...body }); - const req = http.request({ host: '127.0.0.1', port, path: '/mcp', method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-06-18', 'content-length': Buffer.byteLength(data) } }, (r) => { + // A fresh connection each time (agent: false): a kept-alive one can be closed by the server's idle timer just + // as the next request goes out on it, which a slow runner hits now and then (ECONNRESET). + const req = http.request({ agent: false, host: '127.0.0.1', port, path: '/mcp', method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-06-18', 'content-length': Buffer.byteLength(data) } }, (r) => { let t = ''; r.setEncoding('utf8'); r.on('data', (d) => { t += d; }); r.on('end', () => { const line = t.split('\n').find((l) => l.startsWith('data: ')); res(JSON.parse(line ? line.slice(6) : t)); }); }); - req.on('error', rej); req.end(data); + req.on('error', (e) => rej(new Error(`${e.message}; the server said: ${err}`))); req.end(data); }); const init = await post({ method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }); assert.match(init.result.instructions, /player's own browser tab/); @@ -526,5 +535,5 @@ test('browser mode over HTTP: a client connects to the server, the server to the assert.equal(JSON.parse(r.result.content[0].text), 555000, 'the player\'s game, through HTTP and the relay'); const no = await post({ method: 'tools/call', params: { name: 'new_game', arguments: {} } }); assert.ok(no.error || (no.result && no.result.isError), 'no new_game in the player\'s tab'); - } finally { stop(a); child.kill('SIGTERM'); await wait(150); child.kill('SIGKILL'); } + } finally { stop(a); await kill(child); } })); diff --git a/tests/gpu-bench-server.test.js b/tests/gpu-bench-server.test.js index 7767842..eaaa6ff 100644 --- a/tests/gpu-bench-server.test.js +++ b/tests/gpu-bench-server.test.js @@ -8,6 +8,8 @@ const path = require('node:path'); const http = require('node:http'); const { spawn } = require('node:child_process'); +const { until, freePort, kill } = require('./net'); + const ROOT = path.join(__dirname, '..'); function req(port, { method = 'GET', p = '/', host, headers = {}, body } = {}) { @@ -20,11 +22,11 @@ function req(port, { method = 'GET', p = '/', host, headers = {}, body } = {}) { } test('the benchmark server answers only its own page', async (t) => { - const port = 20000 + Math.floor(Math.random() * 20000), out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'bench-')), 'out.md'); + const port = await freePort(), out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'bench-')), 'out.md'); const srv = spawn(process.execPath, [path.join(ROOT, 'scripts', 'gpu-bench.js'), '--port', String(port), '--host', '127.0.0.1', '--out', out], { stdio: ['ignore', 'pipe', 'pipe'] }); let log = ''; srv.stdout.on('data', (c) => { log += c; }); srv.stderr.on('data', (c) => { log += c; }); - t.after(() => srv.kill()); - for (let i = 0; i < 100 && !/Ctrl\+C/.test(log); i++) await new Promise((r) => setTimeout(r, 100)); + t.after(() => kill(srv)); + await until(() => /Ctrl\+C|Error/.test(log) || srv.exitCode !== null); assert.match(log, /Ctrl\+C/, 'the server started'); // DNS rebinding: a request for another host name gets nothing. diff --git a/tests/mcp-parity.test.js b/tests/mcp-parity.test.js index e47d135..7154b07 100644 --- a/tests/mcp-parity.test.js +++ b/tests/mcp-parity.test.js @@ -12,8 +12,9 @@ const { createRelay } = require('../scripts/agent/relay'); const { createSession, TOOLS } = require('../scripts/lib/mcp-game'); const { createBrowserSession } = require('../scripts/lib/mcp-browser'); -const PORT = 9399 + (process.pid % 400); -const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +const { freePort } = require('./net'); +let PORT; +test.before(async () => { PORT = await freePort(); }); const HEADLESS_JS = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'mcp-headless.js'), 'utf8'); const SCRIPT = [ @@ -66,8 +67,8 @@ test('the same scripted session gives the same outcomes headless and through the a.ev(HEADLESS_JS); a.ev("__mcpHeadless.newGame({city:'fra',name:'Scratch Networks',preset:'oncall'})"); a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='127.0.0.1:${PORT}';apiAgentSync()`); - await wait(400); - assert.deepEqual(await s.ready({ waitMs: 5000 }), { ok: true }, 'the tab serves this checkout\'s contract'); + // ready() waits for the page itself, generously: jsdom on a busy runner can take seconds to dial. + assert.deepEqual(await s.ready({ waitMs: 20000 }), { ok: true }, 'the tab serves this checkout\'s contract'); const there = await play(s); for (let i = 0; i < SCRIPT.length; i++) assert.deepEqual(there[i], here[i], `step ${i}: ${SCRIPT[i][0]} ${JSON.stringify(SCRIPT[i][1] || {})}`); assert.ok(here.some(([n, v]) => n === 'act' && v.outcome === 'decision'), 'the script meets a question'); diff --git a/tests/net.js b/tests/net.js new file mode 100644 index 0000000..5aca9a9 --- /dev/null +++ b/tests/net.js @@ -0,0 +1,33 @@ +// Helpers for tests that run servers and sockets. On a busy CI runner (four parts at once, each file in its own +// process) anything can take seconds, so a test waits for a state, never for a fixed time: a fixed sleep is either +// too short (a red build that means nothing) or longer than needed on every run. +const http = require('node:http'); + +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +// Resolves true as soon as ok() holds, false after ms. Assert on the result, so a timeout fails with your message. +async function until(ok, ms = 20000) { + const t0 = Date.now(); + while (!(await ok())) { if (Date.now() - t0 > ms) return false; await wait(10); } + return true; +} + +// A port nobody is using on 127.0.0.1, from the OS. A fixed or random one can be taken by another suite, or by +// the OS itself for an outgoing connection (the ephemeral range starts at 32768 on Linux). +const freePort = () => new Promise((res, rej) => { + const s = http.createServer(); + s.on('error', rej); + s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)); }); +}); + +// Stops a child process: asks first, then insists, and resolves once it has really gone (so its port is free). +function kill(child, ms = 2000) { + return new Promise((res) => { + if (!child || child.exitCode !== null || child.signalCode !== null) return res(); + const t = setTimeout(() => child.kill('SIGKILL'), ms); + child.once('exit', () => { clearTimeout(t); res(); }); + child.kill('SIGTERM'); + }); +} + +module.exports = { wait, until, freePort, kill }; diff --git a/tests/noc-window.test.js b/tests/noc-window.test.js index 3534bcd..0262b42 100644 --- a/tests/noc-window.test.js +++ b/tests/noc-window.test.js @@ -1,9 +1,11 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load, browser } = require('./harness'); +const { until } = require('./net'); // A game window and its NOC window in one fake browser: shared localStorage, broadcast channels and locks. -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); }; +// Waits for the page's async work (storage, channels) to land: up to 20 s, as a busy runner may need. +const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond); const wait = (ms = 30) => new Promise((r) => setTimeout(r, ms)); const START = "UI.pitched=true;ACT.pickStart({city:'fra'});ACT.start({});closeModal();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});ACT.buyIx({city:'fra',tier:0,signed:true});S.pni.push({id:'p1',city:'fra',net:'drz',tier:0,ready:0});compute();save(true)"; diff --git a/tests/save-size.test.js b/tests/save-size.test.js index 1607493..1d048ba 100644 --- a/tests/save-size.test.js +++ b/tests/save-size.test.js @@ -1,6 +1,7 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); +const { until } = require('./net'); // Make the browser's storage refuse the save: 'QuotaExceededError' (too big) or 'SecurityError' (not allowed). const refuse = name => `window.__err=${JSON.stringify(name)};{const P=Object.getPrototypeOf(localStorage),set=P.setItem; @@ -73,7 +74,8 @@ test('#176 an older, unpacked save still loads the same', () => { }); // Compressing runs in the background: wait for it, without depending on how long it takes. -const settle = async (ev, cond) => { for (let i = 0; i < 400 && !ev(cond); i++) await new Promise(r => setTimeout(r, 5)); assert.ok(ev(cond), cond); }; +// Waits for the page's async work (storage, channels) to land: up to 20 s, as a busy runner may need. +const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond); const huge = "for(let i=0;i<12000;i++){const slots=1+i%4;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,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()"; test('#176 small saves stay plain JSON, written at once', () => { diff --git a/tests/save-slots.test.js b/tests/save-slots.test.js index 74fbdcf..c656e38 100644 --- a/tests/save-slots.test.js +++ b/tests/save-slots.test.js @@ -1,10 +1,12 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load, browser, flush } = require('./harness'); +const { until } = require('./net'); // 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); }; +// Waits for the page's async work (storage, channels) to land: up to 20 s, as a busy runner may need. +const settle = async (ev, cond, what) => assert.ok(await until(() => 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"); From eb294e9b147bc09e92cbfcccc144a44fccfafe16 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 11:39:40 +0100 Subject: [PATCH 349/491] WebGL map, customer contracts and a sales desk (2.10.0) --- CHANGELOG.md | 37 ++++++++++++++++++++----------------- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 222fb27..aca88ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,23 +6,26 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- The NOC dashboard has a new tab listing every city where you have no POP yet, with its eyeballs, exchange and price. Sort it, filter by region, and jump to a city to build there. -- A sales desk joins the NOC intern: from customer level 2 you can put one person in charge of sales, and each brings deals their own way. The engineer turned salesdroid books you into every network operators' meeting (you pay the ticket), brings more small and mid deals but never the huge ones, and only sells what your network can do, so their customers stay longer; they haggle badly. The shark lands bigger deals at a quarter more and takes a month of each as commission, but oversells promises your network does not keep yet, ignores technical customers and meetings, and makes peering desks want more traffic from you. Or the CEO runs sales himself, for free: a huge discounted deal on the golf course every couple of months, the odd offer you declined signed anyway, opinions, and no way to fire him short of asking the board for a VP of Sales. -- Customers now sign contracts, and when one ends they renew, grow, haggle or leave, not always because of you (#178). Most renew at today's bandwidth price, which falls about 10% a year but rises when hardware is short; happy customers often take a bigger size, and some ask for a discount you can match, meet halfway or turn down in Deals. Others are acquired, go bust, build their own network, move away (they stay if you have a POP where they go), split their traffic with a second provider or end their project, and now and then one leaves for a stranger reason. Nothing changes during a customer's first contract, renewals in an old save are spread over the next year, your happiest long-time customers send you referrals, and the NOC dashboard shows customers won and lost each month and why. -- Sweden gets Gothenburg, Malmö and Haparanda (#206). Gothenburg sits between Oslo and Copenhagen with its own exchange, Malmö faces Copenhagen across the Øresund, and Haparanda on the Finnish border is where the fibre crosses over land to Finland, with no exchange yet for you to found one. A Nordic fibre carrier sells transit along that route from Berlin to the border, and Swedish home networks reach the new cities. -- The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. -- Bilbao joins the map, where the transatlantic cables really come ashore: Marea Carey, Grace Hopscotch and Sol Survivor now land there instead of Madrid. It has no exchange of its own, so traffic heads inland to Madrid, and Drizzle Electric, Tangerine Telecom and the big carriers sell transit there. A link you already run on the old Madrid landings keeps working as a plain subsea link, and the Mid-Atlantic Accent scenario now goes Azores, Bilbao, Madrid, and Marea Carey now leaves the American coast at Virginia Beach instead of crossing the northeast to New Jersey. Columbus III-and-a-half now comes ashore near Cádiz, where it really landed, on its way to Madrid. -- Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in. -- Clean traffic that a scrubbing center sends back to a customer under attack no longer shows as DDoS junk on your backbone links; a link now lists it as scrubbed clean traffic, so a small flood no longer looks like hundreds of gigabits of junk (#289). -- Alien waves you rent out on your dark fiber are now priced against the fiber itself: a wave costs a share of what leasing and lighting that fiber would cost the buyer, and each wave sold between the same two cities goes a little cheaper than the last. A route sold out to its market now earns a few times its lease, not dozens, and contracts already signed keep their price (#203). -- Leasing a dark fiber pair now costs about half as much again ($600 plus $1.50 per km a month, amplifiers as before), so it pays off once you light a couple of 400G waves on it. Leases you already hold keep their price (#203). -- Extra crews can now cut a fiber build on land to half its planned time at most, since permits and rights of way do not speed up; the button shows the day it would be done (#203). -- A link ordered by typing both ends (the AI tools) can no longer end in a city the map does not show (#203). -- The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same, and zoomed out the card draws the coastlines with fewer points where the extra detail was smaller than a pixel, which helps phones most. Settings › Map drawing › Always 2D keeps the old drawing and frees what the graphics card held, and browsers without WebGL2 or without a usable graphics card keep it on their own. If the graphics card stops for a moment (on a phone, switching apps can do that), the map is drawn in 2D until it is back, and stays in 2D for a game where it keeps failing. (#281) -- Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the map also draws far fewer shapes each frame. (#281) -- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in: its land picture now stays on the graphics card instead of being sent to it again on every frame. Firefox on Android keeps the old way, which avoids its drawing glitches. (#281) -- Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report. (#281) -- A save file can no longer put formatting or links into the game: the name of your own subsea cable and the repair button on a POP that is down always show as plain text, and a cable name from a save is cut to 60 characters. +## [2.10.0] — 2026-11-05 + +**The map now runs on your graphics card.** Panning, zooming and fast play stay smooth even on huge networks. If something looks wrong or your phone gets warm, switch back to the old map in **Settings › Map drawing › Always 2D**. Older browsers stay in 2D on their own, and Settings › Diagnostic info shows which one you have. + +**Customers sign contracts now.** When one ends they renew, grow, haggle or leave, and bandwidth gets cheaper every year. To bring in more deals, hire someone to run sales: an engineer who goes to every NOG, a shark who oversells, or the CEO, who thinks he sells best. + +**Also new:** a "No POP yet" tab on the dashboard, clearer puzzles on phones, Gothenburg, Malmö, Haparanda and Bilbao on the map, and tooltips on the NOC charts. + +- The map is now drawn by your graphics card, so panning, zooming and fast play stay smooth on big networks (#281). If it looks wrong or your device runs hot, go back to the old drawing in Settings › Map drawing › Always 2D. Browsers without WebGL2 stay in 2D on their own, and Settings › Diagnostic info shows which one you are on. +- Customers sign contracts, and when one ends they renew, grow, haggle or leave (#178). Bandwidth prices fall over the years and rise when hardware is short, and the dashboard shows who you won and lost each month. +- You can hire one person to run sales: an engineer, a shark or the CEO himself. Each brings different deals and leaves their mark on the customers they sign. +- The NOC dashboard has a "No POP yet" tab listing every city you could still expand to. +- Puzzles explain their goals in plain words, with a Show me button and marks on the map, and fit phones better. +- Sweden gets Gothenburg, Malmö and Haparanda (#206). +- Bilbao joins the map, where the transatlantic cables really land; Columbus III-and-a-half now lands near Cádiz. +- NOC charts have tooltips, and their legend can hide a series. +- Leasing dark fiber costs more, alien waves are priced against the fiber, and extra crews can only halve a land build (#203). +- Clean traffic sent back by a scrubbing center no longer shows as DDoS junk on your links (#289). +- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in. +- Fixes: a link ordered by the AI tools can no longer end in a city the map does not show, and names from a save file always show as plain text. ## [2.9.1] — 2026-11-04 diff --git a/package-lock.json b/package-lock.json index 409f309..262b33e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "2.9.1", + "version": "2.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "2.9.1", + "version": "2.10.0", "license": "MIT", "devDependencies": { "@modelcontextprotocol/node": "2.1.2", diff --git a/package.json b/package.json index 41b7083..a036e63 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "2.9.1", + "version": "2.10.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From f19b337d7b077c6c0f9bfe833d266e5bce33f6ac Mon Sep 17 00:00:00 2001 From: Wolfgang Nagele Date: Thu, 5 Nov 2026 10:07:37 -0500 Subject: [PATCH 350/491] Build container images for easy MCP use --- .dockerignore | 4 ++ .github/workflows/auto-release.yml | 7 +++ .github/workflows/docker.yml | 72 ++++++++++++++++++++++++++++++ docker/Dockerfile | 16 +++++++ docker/docker-entrypoint.sh | 42 +++++++++++++++++ docs/MCP.md | 33 ++++++++++++++ 6 files changed, 174 insertions(+) create mode 100644 .dockerignore create mode 100644 .github/workflows/docker.yml create mode 100644 docker/Dockerfile create mode 100644 docker/docker-entrypoint.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..dbdaf41 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +.git +.github +node_modules +_site diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 29bfba0..aa3bdfc 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -73,3 +73,10 @@ jobs: # Pre-releases are for testing and never go live. if: steps.v.outputs.skip == 'false' && steps.v.outputs.pre == 'false' run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}" + + - name: Publish the Docker image + # Same pattern as the deploy above: the image is built and pushed from the + # release tag by docker.yml. Pre-releases get one too: an image tag is + # pulled on purpose, so a test image costs nothing. + if: steps.v.outputs.skip == 'false' + run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}" diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..d62dc9a --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,72 @@ +name: Build and push Docker image + +# Every push to main publishes :latest and :. A release publishes : +# built from its tag: auto-release.yml dispatches this workflow alongside the Pages +# deploy, because releases created with the workflow token do not fire the +# "released" event. Hand-published releases fire it directly. +on: + push: + branches: [main] + release: + types: [released, prereleased] + workflow_dispatch: + inputs: + tag: + description: Existing release tag to build (e.g. v2.10.0); empty builds main + required: false + +permissions: + contents: read + packages: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || inputs.tag }} + + - name: Work out the image tags + id: tags + env: + TAG: ${{ github.event.release.tag_name || inputs.tag }} + run: | + set -euo pipefail + # The image is named after this repository (ghcr.io//, lowercased). + image=ghcr.io/${GITHUB_REPOSITORY,,} + if [ -n "$TAG" ]; then + want="v$(jq -r .version package.json)" + if [ "$TAG" != "$want" ]; then + echo "::error::Release tag $TAG does not match package.json version ($want)" + exit 1 + fi + echo "tags=$image:${TAG#v}" >> "$GITHUB_OUTPUT" + else + echo "tags=$image:latest,$image:$GITHUB_SHA" >> "$GITHUB_OUTPUT" + fi + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.tags.outputs.tags }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..1228b19 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,16 @@ +FROM node:26-slim + +COPY . /series-of-tubes +WORKDIR /series-of-tubes + +RUN npm install + +COPY docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh \ + && chown -R node:node /series-of-tubes + +USER node + +EXPOSE 8080 7777 + +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh new file mode 100644 index 0000000..1d5938d --- /dev/null +++ b/docker/docker-entrypoint.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -u +cd /series-of-tubes + +# MCP_MODE picks what runs: browser (default) serves the game page and relays the +# player's tab to the MCP server; headless runs a game of its own, no page needed. +mode=${MCP_MODE:-browser} +case "$mode" in + browser|headless) ;; + *) echo "[entrypoint] MCP_MODE must be browser or headless, not '$mode'" >&2; exit 1 ;; +esac + +# Everything after the image name is passed to the MCP server as well +# (node scripts/mcp.js --help lists the options). +extra=("$@") + +# A container needs 0.0.0.0 to be reachable at all; default --http unless given. +http=(--http 0.0.0.0:7777) +for a in "${extra[@]}"; do [ "$a" = --http ] && http=(); done + +pids=() +start() { "$@" & pids+=("$!"); } + +shutdown() { + trap '' TERM INT + kill -TERM "${pids[@]}" 2>/dev/null + wait "${pids[@]}" 2>/dev/null + exit 0 +} +trap shutdown TERM INT + +if [ "$mode" = browser ]; then + start npm run dev -- --host 0.0.0.0 --port 8080 + start npm run mcp -- --browser "${http[@]}" "${extra[@]}" +else + start npm run mcp -- "${http[@]}" "${extra[@]}" +fi + +status=0 +wait -n || status=$? +echo "[entrypoint] a process exited with status $status; stopping the container" >&2 +shutdown diff --git a/docs/MCP.md b/docs/MCP.md index 4398617..4c6b590 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -77,6 +77,39 @@ claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp - **Either session.** `--http` works headless and with `--browser` alike: then a client elsewhere drives the game in the player's tab, while the relay stays where `npm run dev` put it. +### In a container + +Every push to `main` and every release publishes a multi-arch (amd64/arm64) image at +`ghcr.io/fjaeckel/seriesoftubes`, built from the repo by the `docker.yml` workflow: `latest` and the commit SHA on +pushes, the release's version (pre-releases included) on releases. It packages the dev server and the MCP server; +`node scripts/mcp.js --help` options go after the image name, and `--http 0.0.0.0:7777` is the default (a container +bound to loopback would be unreachable; pass your own `--http` to override). + +`MCP_MODE=headless` runs just the MCP server with a game of its own; the default (`browser`) also serves the +development page so a browser tab can play it, as above. + +```sh +docker run -d -p 7777:7777 -e MCP_MODE=headless ghcr.io/fjaeckel/seriesoftubes +claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp + +# Options are passed to scripts/mcp.js; the token is its own env var. +docker run -d -p 7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret \ + ghcr.io/fjaeckel/seriesoftubes --clock realtime --pace 60000 + +# The browser session: open http://localhost:8080, then Settings → Agent API. +docker run -d -p 8080:8080 -p 7777:7777 ghcr.io/fjaeckel/seriesoftubes +``` + +`load_save` and `export_save` take JSON only unless the server runs with `--save-dir`; mount a volume for it: + +```sh +docker run -d -p 7777:7777 -e MCP_MODE=headless -v sot-saves:/saves \ + ghcr.io/fjaeckel/seriesoftubes --save-dir /saves +``` + +What "Over HTTP" says applies to the container too: the mapped port is reachable by anything that can reach the host, +so set a token before exposing one, and there is no TLS. + ## The clock Every session has one of two clocks, and `schema` (section `mode`) says which: From 8c96fa5bc1ffdbf791815196a6c615f286540e7d Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 17:10:22 +0100 Subject: [PATCH 351/491] Meet halfway between the bill and the ask; Fujairah back on its coast (#293, #295) Meeting halfway split the difference between the ask and today's market price, which after a fall in prices sat right next to the ask. It now splits the two prices the Deals row shows, and the button names it. Fujairah's display nudge moved it a degree south onto Muscat; it now sits on the UAE's east coast where its cables land. --- CHANGELOG.md | 3 +++ 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/20-world/50-cities.js | 2 +- src/game/80-simulation/75-customer-lifecycle.js | 5 ++++- src/game/90-actions/50-customers.js | 4 ++-- src/i18n/en.js | 2 +- tests/customer-lifecycle.test.js | 16 ++++++++++++++++ 11 files changed, 32 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aca88ae..6571cb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- "Meet halfway" on a renewal now offers the price halfway between what the customer pays and what they ask, and the button shows it before you press (#293). +- Fujairah sits on the UAE's east coast again, where its cables land, instead of on top of Muscat (#295). + ## [2.10.0] — 2026-11-05 **The map now runs on your graphics card.** Panning, zooming and fast play stay smooth even on huge networks. If something looks wrong or your phone gets warm, switch back to the old map in **Settings › Map drawing › Always 2D**. Older browsers stay in 2D on their own, and Settings › Diagnostic info shows which one you have. diff --git a/site/i18n/de.js b/site/i18n/de.js index 03e9246..4ea2cb0 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2627,7 +2627,7 @@ "lifecycle.market_below":"{p} unter deinem Start", "lifecycle.match":"Mitgehen", "lifecycle.matched":"{name} hat zum gewünschten Preis verlängert.", -"lifecycle.meet_halfway":"In der Mitte treffen", +"lifecycle.meet_halfway":"In der Mitte treffen: {price}", "lifecycle.meet_no":"{name} hat das Angebot der Konkurrenz genommen und ist weg.", "lifecycle.meet_yes":"{name} hat dein Angebot angenommen und für {price}/Monat verlängert.", "lifecycle.moved_stays":"{name} ist von {from} nach {to} gezogen, wo du einen POP hast, und bleibt also.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 3bf0442..c702e7e 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2625,7 +2625,7 @@ "lifecycle.market_below":"{p} por debajo de cuando empezaste", "lifecycle.match":"Igualar", "lifecycle.matched":"{name} renovó al precio que pidió.", -"lifecycle.meet_halfway":"Partir la diferencia", +"lifecycle.meet_halfway":"Partir la diferencia: {price}", "lifecycle.meet_no":"{name} aceptó la oferta de la competencia y se fue.", "lifecycle.meet_yes":"{name} aceptó tu oferta y renovó por {price}/mes.", "lifecycle.moved_stays":"{name} se mudó de {from} a {to}, donde tienes POP, así que se queda.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 776b0b9..2691495 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2625,7 +2625,7 @@ "lifecycle.market_below":"{p} en dessous de vos débuts", "lifecycle.match":"S'aligner", "lifecycle.matched":"{name} a renouvelé au prix demandé.", -"lifecycle.meet_halfway":"Couper la poire en deux", +"lifecycle.meet_halfway":"Couper la poire en deux : {price}", "lifecycle.meet_no":"{name} a pris l'offre du concurrent et est partie.", "lifecycle.meet_yes":"{name} a accepté votre offre et renouvelé à {price}/mois.", "lifecycle.moved_stays":"{name} a déménagé de {from} à {to}, où vous avez un POP : elle reste.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 7d9dc5b..b266267 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2625,7 +2625,7 @@ "lifecycle.market_below":"{p} sotto a quando hai iniziato", "lifecycle.match":"Accettare", "lifecycle.matched":"{name} ha rinnovato al prezzo richiesto.", -"lifecycle.meet_halfway":"Venirsi incontro", +"lifecycle.meet_halfway":"Venirsi incontro: {price}", "lifecycle.meet_no":"{name} ha preso l'offerta del concorrente e se n'è andata.", "lifecycle.meet_yes":"{name} ha accettato la tua offerta e rinnovato a {price}/mese.", "lifecycle.moved_stays":"{name} si è trasferita da {from} a {to}, dove hai un POP, quindi resta.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index ce8feae..04430bb 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2625,7 +2625,7 @@ "lifecycle.market_below":"{p} abaixo do começo", "lifecycle.match":"Igualar", "lifecycle.matched":"{name} renovou pelo preço que pediu.", -"lifecycle.meet_halfway":"Meio-termo", +"lifecycle.meet_halfway":"Meio-termo: {price}", "lifecycle.meet_no":"{name} aceitou a proposta do concorrente e foi embora.", "lifecycle.meet_yes":"{name} aceitou sua proposta e renovou por {price}/mês.", "lifecycle.moved_stays":"{name} mudou de {from} para {to}, onde você tem POP, então fica.", diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index ec41e1c..dc7eec9 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -453,7 +453,7 @@ const CITY_NUDGE={ dxb:[9,-7], fec:[-10.8,1.4], fln:[0.8,4.4], - fuj:[8,15], + fuj:[2,2], gdl:[-1.2,0.2], gyn:[-4,2.6], hel:[-.8,-.2], diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index ec09dd6..97a5d5d 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -109,13 +109,16 @@ function clReferral(d){if(d%45!==0||S.offers.length>=6)return; // New offers are priced at today's market (spawnOffer and friends price at 1; this moves them). function mktPrice(from){const m=mkt();for(let i=from;iMath.round((b.rate+b.hag.rate)/2); +const clBill=(b,rate)=>BIZ_T[b.type].fiber?rate:b.bw*rate; const clHags=()=>S?S.biz.reduce((a,b)=>a+(b.hag?1:0),0):0; // The renewals waiting for an answer, at the top of Deals. function clDealsHtml(){const hs=S.biz.filter(b=>b.hag).sort((a,b)=>a.hag.until-b.hag.until);if(!hs.length)return ''; return `

${tr('lifecycle.renewals')}

${tr('lifecycle.unanswered_matches')}

`+hs.map(b=>{const now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate,was=bizMo(b); return `
${esc(b.name)}
${esc(BIZ_T[b.type].l)} · ${esc(clWhere(b))} · ${tr('ui.n_d_left',{n:b.hag.until-S.day})}
${tr('lifecycle.wants_price',{was:fmt$(was),price:fmt$(now),p:pct(1-now/Math.max(1,was))})}
-
${btn(tr('lifecycle.match'),'renewMatch',{id:b.id},'green sm')}${btn(tr('lifecycle.meet_halfway'),'renewMeet',{id:b.id},'sm')}${btn(tr('lifecycle.let_them_go'),'renewLet',{id:b.id},'ghost sm')}
`;}).join('');} +
${btn(tr('lifecycle.match'),'renewMatch',{id:b.id},'green sm')}${btn(tr('lifecycle.meet_halfway',{price:fmt$(clBill(b,clMid(b)))}),'renewMeet',{id:b.id},'sm')}${btn(tr('lifecycle.let_them_go'),'renewLet',{id:b.id},'ghost sm')}
`;}).join('');} // The contract line on a customer row. const clTermTxt=b=>clOn(b)&&b.te?(b.hag?tr('lifecycle.renewal_haggle',{date:dateStr(b.te)}):tr('lifecycle.contract_until',{date:dateStr(b.te)})):''; diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index aa6e6f4..aa5e4c8 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -24,8 +24,8 @@ Object.assign(ACT,{ function clHagOf(id){const b=S.biz.find(x=>x.id===id);return b&&b.hag?b:null;} Object.assign(ACT,{ renewMatch:({id})=>{const b=clHagOf(id);if(!b)return;clRenew(b,b.hag.rate);clNote('ren');toast(tr('lifecycle.matched',{name:esc(b.name)}),'good');sfx('coin');after();}, - renewMeet:({id})=>{const b=clHagOf(id);if(!b)return;const mid=Math.round((b.hag.rate+clFair(b))/2); - if(clR(b,'meet'){const b=clHagOf(id);if(!b)return;const mid=clMid(b); + if(clR(b,'meet'){const b=clHagOf(id);if(!b)return;clGone(b,'cheap');toast(tr('lifecycle.let_go',{name:esc(b.name)}),'');after();}, }); diff --git a/src/i18n/en.js b/src/i18n/en.js index ff97ffe..c34f7df 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2626,7 +2626,7 @@ "lifecycle.market_below":"{p} below when you started", "lifecycle.match":"Match", "lifecycle.matched":"{name} renewed at the price they asked.", -"lifecycle.meet_halfway":"Meet halfway", +"lifecycle.meet_halfway":"Meet halfway: {price}", "lifecycle.meet_no":"{name} took the competitor's bid and left.", "lifecycle.meet_yes":"{name} took your offer and renewed at {price}/mo.", "lifecycle.moved_stays":"{name} moved from {from} to {to}, where you have a POP, so it stays.", diff --git a/tests/customer-lifecycle.test.js b/tests/customer-lifecycle.test.js index b824160..42c8cd7 100644 --- a/tests/customer-lifecycle.test.js +++ b/tests/customer-lifecycle.test.js @@ -120,6 +120,22 @@ test('a haggle: 30 days ahead, in Deals; match, meet halfway, let go, or no answ assert.deepEqual(errors, []); }); +test('meeting halfway lands between what the customer pays and what they ask, as the button says (#293)', () => { + const { ev, errors } = load(); + ev(start); + // The market has fallen a lot since they signed, so the old reference (today's fair price) sat right next to the ask. + // A name whose roll accepts the offer: the rolls are hashes of the deal, so the test picks one, never luck. + const id = ev(`(()=>{for(let i=0;i<200;i++){const b={id:'m'+i,city:'ams',city2:null,name:'m'+i,type:'dia',bw:5,rate:1000,reqs:[],mood:90,since:S.day-800,te:S.day+20,mk:2,hag:{rate:700,until:S.day+20}};if(clR(b,'meet') { const { ev, errors } = load(); ev(start); From d7fb2a96177ecbb9e6af464b5c613b21262b94df Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 17:18:37 +0100 Subject: [PATCH 352/491] Fujairah one step west, onto the coast it lands on The nudge to [2,2] put the city just off the UAE coastline, so the landmass test failed; [1,2] is on land, still on the east coast where its cables land and well away from Muscat. --- src/game/20-world/50-cities.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index dc7eec9..ac1f788 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -453,7 +453,7 @@ const CITY_NUDGE={ dxb:[9,-7], fec:[-10.8,1.4], fln:[0.8,4.4], - fuj:[2,2], + fuj:[1,2], gdl:[-1.2,0.2], gyn:[-4,2.6], hel:[-.8,-.2], From 107b0b825a226562bf9100e39efa5af2319642f8 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 17:14:40 +0100 Subject: [PATCH 353/491] Puzzles on phones: fixed overlays that never scroll A bar pinned at the top holds the puzzle's state (name, stars, money, undo, menu), the goal being worked on with Show me, and a chip per flow that opens its city. A city or a link opens a short card at the bottom, split into tabs (links, router, traffic; size, traffic, routing) that each fit on a 360 px phone, portrait or landscape. Architect runs get the same bar. Reset moves to the menu on phones. Desktop is unchanged. The old swipe-up sheet and its peek state are gone. --- CHANGELOG.md | 1 + src/agent/20-commands.js | 2 + src/game/90-actions/95-puzzles.js | 6 +- src/game/93-ui/20-phone.js | 5 +- src/game/95-modals/95-puzzles.js | 12 +-- src/game/95-modals/97-puzzles-phone.js | 95 +++++++++++++++++++++ src/styles/70-puzzles.css | 71 ++++++++++++---- tests/puzzle-sheet.test.js | 9 +- tests/puzzles-phone.test.js | 112 +++++++++++++++++++++++++ tests/puzzles.test.js | 18 ++-- 10 files changed, 292 insertions(+), 39 deletions(-) create mode 100644 src/game/95-modals/97-puzzles-phone.js create mode 100644 tests/puzzles-phone.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 6571cb5..65c8f06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - "Meet halfway" on a renewal now offers the price halfway between what the customer pays and what they ask, and the button shows it before you press (#293). - Fujairah sits on the UAE's east coast again, where its cables land, instead of on top of Muscat (#295). +- Puzzles on phones no longer scroll. A bar at the top shows the stars, the money and the one thing to do next, with a chip for every flow that turns green once it all arrives; tap a chip to jump to its city. A city or a link opens a short card at the bottom, split into tabs (links, router, traffic; size, traffic, routing), so every button is on screen at once. Architect runs get the same bar, and Reset is in the ☰ menu on phones. ## [2.10.0] — 2026-11-05 diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index d1dc62c..c243ed2 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -439,6 +439,8 @@ const API_VIEW={ bankClose:{args:[],doc:'Close the bank.'}, closePanel:{args:[],doc:'Close the selection panel.'}, tab:{args:[['t','string']],doc:'Switch the city panel\'s tab.'}, + pzCity:{args:[['c','cityId']],doc:'Puzzles on a phone: open a city\'s card from its flow chip.'}, + pzTab:{args:[['k','string'],['t','string']],doc:'Puzzles on a phone: switch the city (k:"city") or link (k:"link") card\'s tab.'}, leftTab:{args:[['t','leftTab']],doc:'Switch the left drawer and open it.'}, toggleLeft:{args:[],doc:'Open or close the left drawer.'}, netFocus:{args:[['id','netId']],doc:'Focus one network in the left drawer.'}, diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 3af3af5..881800c 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -14,6 +14,10 @@ Object.assign(ACT,{ pzRetry:()=>{if(!pzOn())return;if(S.ar){arBegin(arRun());return;}pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, pzLeave:()=>{if(pzOn())pzLeave();}, // The sheet's next-fix line: bring the city, or the link a cut hurts most, into view (the zoom stays). + // Phones split a puzzle's city and link cards into tabs (97-puzzles-phone.js); the tab shown is kept per kind of card. + pzTab:({k,t})=>{if(!pzOn()||!['city','link'].includes(k)||typeof t!=='string')return;UI.pzTab={...(UI.pzTab||{}),[k]:t};renderPanel();}, + // A flow chip on a phone: that city's card, with the city on screen. + pzCity:({c})=>{if(!pzOn()||!isCity(c)||!pzKind(c))return;ACT.pzLook({c});selectCity(c);renderTabbar();}, pzLook:({c,u})=>{if(!pzOn())return;let x,y;if(c&&isCity(c)){x=CITY[c].x;y=CITY[c].y;}else{const l=u&&S.links.find(q=>pzUnit(q)===u);if(!l)return;const A=CITY[l.a],B=CITY[l.b];x=A.x+wrapDx(A.x,B.x)/2;y=(A.y+B.y)/2;} const sh=isPhone()&&CW<=CH?($('pzBox').offsetHeight||0):0;cam.x=x;cam.y=y+sh/2/cam.z;wrapCam();haptic(8);}, 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();}, @@ -49,7 +53,7 @@ Object.assign(ACT,{ // 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;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();}, + pzReset:()=>{if(!pzOn())return;if(!$('modal').hidden)closeModal();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/93-ui/20-phone.js b/src/game/93-ui/20-phone.js index d428192..0daaa54 100644 --- a/src/game/93-ui/20-phone.js +++ b/src/game/93-ui/20-phone.js @@ -13,11 +13,10 @@ function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))retu function haptic(ms){if(UI.muted)return;try{navigator.vibrate&&navigator.vibrate(ms||12);}catch(e){}} // Bottom sheets: drag the handle up to expand, down to shrink or close; tap it to toggle. (function(){let g=null; - document.addEventListener('pointerdown',e=>{const h=e.target.closest('[data-grab]');if(!h||!isPhone()||e.target.closest('button,select,input'))return;const el=h.dataset.grab==='pz'?$('pzBox'):h.parentElement;g={el,y:e.clientY,dy:0,id:e.pointerId,full:el.classList.contains('full')};try{h.setPointerCapture(e.pointerId);}catch(_){}el.style.transition='none';}); + document.addEventListener('pointerdown',e=>{const h=e.target.closest('[data-grab]');if(!h||!isPhone()||e.target.closest('button,select,input'))return;const el=h.parentElement;g={el,y:e.clientY,dy:0,id:e.pointerId,full:el.classList.contains('full')};try{h.setPointerCapture(e.pointerId);}catch(_){}el.style.transition='none';}); document.addEventListener('pointermove',e=>{if(!g||e.pointerId!==g.id)return;g.dy=e.clientY-g.y;if(g.dy>0)g.el.style.transform=`translateY(${g.dy}px)`;}); const end=e=>{if(!g||e.pointerId!==g.id)return;const {el,dy,full}=g;g=null;el.style.transition='';el.style.transform=''; - if(Math.abs(dy)<6){el.classList.toggle(el.id==='pzBox'?'mini':'full');return;} - if(el.id==='pzBox'){el.classList.toggle('mini',dy>0);return;} + if(Math.abs(dy)<6){el.classList.toggle('full');return;} if(dy<-40){el.classList.add('full');return;} if(dy>40){if(full){el.classList.remove('full');return;}if(el.id==='panel')ACT.closePanel();else{UI.leftOpen=false;renderLeft();}}}; document.addEventListener('pointerup',end);document.addEventListener('pointercancel',end);})(); diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index b7e1ada..529e81a 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -35,12 +35,12 @@ function pzGoalRow(g,i){const ic=g.done?'⭐':g.cur?'👉':`${i+1}`; +(g.cur&&g.hint?`
${g.hint}${g.look?' '+btn(tr('puzzles.show_me'),'pzLook',g.look,'sm pzshow'):''}
`:'')+``;} // A delivered eyeball flow is a chip; anything still short, a circuit or a latency cap keeps its full row. const pzChip=x=>`👀 ${esc(CITY[x.f.a].name)} ${fmtG(x.f.g)} ✓`; -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;} +function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false;el.classList.toggle('ar',!!S.ar);UI._pzPhone=isPhone();if(S.ar){el.classList.toggle('dock',UI._pzPhone);(UI._pzPhone?arDock:arRender)(el);return;} const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); - // A phone held upright starts each puzzle with the sheet down to its status bar, so the map has the room (swipe it up for the rest). - const pk2=P.id+'|'+(P.key||'');if(UI._pzPeek!==pk2){UI._pzPeek=pk2;el.classList.toggle('mini',isPhone()&&CW<=CH);} + // A phone gets fixed overlays that never scroll (97-puzzles-phone.js). + el.classList.toggle('dock',UI._pzPhone);if(UI._pzPhone){pzDock(el,e);return;} const sp=fmt$(e.spend); - // The status bar stays at the top of the sheet, whatever scrolls: the puzzle, its stars, the money, undo and the menu. + // The status bar stays at the top of the card, whatever scrolls: the puzzle, its stars, the money, undo and the menu. 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')}
`; const gs=pzGoals(e),cur=gs.find(g=>g.cur);UI.pzMark=!UI.pzMk&&cur&&cur.mark||null; @@ -69,7 +69,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){if(S.ar)return arPanel(sel);const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; +function pzPanel(sel){if(S.ar)return arPanel(sel);if(isPhone())return pzPanelPhone(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')}`:'')+'
'; @@ -153,7 +153,7 @@ function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.lengt

${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);} - 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')}
`; + if(pzOn())h+=`
${isPhone()&&!S.ar?btn(tr('puzzles.reset'),'pzReset',{},'ghost',!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',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; h+=arMenuRows(); h+=pzWkRow(); // The packs' own total, right above them: it is what unlocks the next pack (#231). Runs and weeklies count their own. diff --git a/src/game/95-modals/97-puzzles-phone.js b/src/game/95-modals/97-puzzles-phone.js new file mode 100644 index 0000000..53a59f8 --- /dev/null +++ b/src/game/95-modals/97-puzzles-phone.js @@ -0,0 +1,95 @@ +/* ---------- puzzles on a phone: fixed overlays that never scroll ---------- + A bar pinned at the top says how the puzzle stands (its name, the three stars, the money, undo and the menu), the one + thing to do next and what each flow gets, as chips. A city or a link opens a card at the bottom whose content is + split into tabs, so each tab fits on the screen. Desktop keeps the side card (pzRender, pzPanel). */ +// A rate in a few characters, for the chips: 30G, 2.5G, 1.2T. +const pzG=g=>g>=1000?(g/1000).toFixed(g>=10000?0:1)+'T':g>=10||g===0?Math.round(g)+'G':g.toFixed(1)+'G'; +// One flow as a chip: what it is, how much of it arrives, a circuit's latency against its cap. Tapping it shows the city. +function pzFlowChip(x){const f=x.f,ok=x.full&&x.fast,part=x.g>0&&!ok; + const lat=f.ms?` · ${x.ms==null?'—':x.ms.toFixed(1)}/${f.ms} ms`:''; + return ``;} +// The rules of this puzzle as chips: the content's home, the cities to avoid, no subsea cables, the ring. +function pzRuleChips(e){const P=S.pz;let h=''; + if(P.src.length)h+=`🗄️ ${P.src.map(c=>esc(CITY[c].name)).join(', ')}`; + for(const t of e.tw)h+=t.k==='avoid'?`🚫 ${P.avoid.map(c=>esc(CITY[c].name)).join(', ')}`:`${t.ok?'✓':'✗'} ${pzTwistTxt(t)}`; + return h;} +function pzDock(el,e){const P=S.pz,d=pzDef(P.id),gs=pzGoals(e),cur=gs.find(g=>g.cur);UI.pzMark=!UI.pzMk&&cur&&cur.mark||null; + const stars=gs.map((g,i)=>`${g.done?'⭐':i+1}`).join(''); + const bud=P.budget?`${fmt$(e.spend)} / ${fmt$(P.budget)}`:`${tr('puzzles.free')}`; + let h=`
${esc(pzName(d||P))}${stars}${bud}` + +`${btn('☰','puzzleMenu',{},'ghost sm')}
`; + // The one thing to do: the goal being worked on, what is wrong and Show me; the monkey once the traffic arrives. + const act=UI.pzMk?btn('⏩ '+tr('puzzles.skip_the_monkey'),'pzMkSkip',{},'sm'):e.goal?btn('🐒 '+tr('puzzles.let_the_chaos_monkey_loose'),'pzMonkey',{},'ghost sm'):''; + if(cur)h+=`
👉
${cur.t}${cur.hint?` ${cur.hint}`:''}
${cur.look?btn(tr('puzzles.show_me'),'pzLook',cur.look,'sm pzshow'):''}${act}
`; + else h+=`
🛡
${tr('puzzles.survives_any_single_cut_under_load')}
${act}
`; + h+=`
${e.flows.map(pzFlowChip).join('')}${pzRuleChips(e)}
`; + if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +// The bar's height, for what must sit under it (toasts) or stop short of it (the card): it changes with its content and +// when a card opens, so it is watched rather than measured after each render. +try{new ResizeObserver(()=>{const H=$('pzBox').offsetHeight||0;document.documentElement.style.setProperty('--pzdock',H+'px');}).observe($('pzBox'));}catch(e){} +// An architect run on a phone: the same bar. The brief, its sites and rules as chips, and the review with its one button. +function arDock(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),T=e.tubes; + let h=`
🏗️ ${tr('architect.brief_n_of_m',{n:A.bi+1,m:n})}${fmt$(e.spend)} / ${fmt$(e.budget)} ${e.cheap?'⭐':'☆'}` + +`${btn('☰','puzzleMenu',{},'ghost sm')}
`; + h+=`
${run.briefs.map((x,i)=>``).join('')}

${esc(b.t)}

`; + let ch=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(''); + for(const r of e.rings)ch+=`💍 ${r.cs.map(nm).join(' · ')}`; + if(e.lat)ch+=`⏱ ${e.lat.ms==null?'—':e.lat.ms.toFixed(1)}/${e.lat.cap} ms`; + for(const c of S.pz.avoid)ch+=`🚫 ${nm(c)}`; + if(T.max!=null)ch+=`${tr('architect.tubes_this_brief')} ${T.u}/${T.max}`; + h+=`
${ch}
`; + const rev=sh?`🐒 ${tr('architect.cut_n_of_m',{n:sh.i+1,m:sh.units.length})}${sh.dark.length?' · '+sh.dark.map(nm).join(', '):''}`:f?`💥 ${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(', ')})}` + :e.passed?`✅ ${tr('architect.review_passed')}`:!e.ready?esc(e.why):A.gold.length?tr('architect.ready_send_the_backhoe'):tr('architect.ready_no_gold_yet'); + const main=sh?btn('⏩ '+tr('architect.skip'),'pzArSkip',{},'sm'):e.passed?btn(arLast()?tr('architect.finish_the_run')+' 🎉':tr('architect.next_brief')+' →','pzArNext',{},'pink sm'):btn('▶ '+tr('architect.send_the_backhoe'),'pzArGo',{},'pink sm',!e.ready); + h+=`
${rev}${A.gold.length&&!sh&&!f&&!e.passed?`
🚨 ${tr('architect.gold_must_survive',{list:A.gold.map(nm).join(', ')})}`:''}
${main}
`; + if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +// The tabs of a card; the one shown is kept per kind of card (city or link) while the puzzle runs. +const pzTabs=(kind,tabs,cur)=>``; +const pzTabOf=(kind,tabs,def)=>{const t=(UI.pzTab||{})[kind];return tabs.some(([k])=>k===t)?t:def;}; +// The card's head in two short lines: what it is (and whether it is yours) above the name, the facts beside the name. +const pzHead=(eb,name,facts)=>`
${eb}

${name}${facts?` ${facts}`:''}

`; +function pzPanelPhone(sel){ + 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=pzHead(`${PZ_ICON[k]} ${eb}${p?` · ${tr('common.your_pop')}`:''}`,esc(C.name),'')+'
'; + if(k==='avoid')return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

`; + const ev=pzEval(),fl=ev.flows.filter(x=>x.f.a===c||x.f.b===c); + const chips=fl.length||P.src.includes(c)?`
${P.src.includes(c)?`🗄️ ${tr('puzzles.the_content_origin_lives_here')}`:''}${fl.map(pzFlowChip).join('')}
`:''; + if(!p)return h+chips+(k==='off'?`

${tr('puzzles.no_traffic_starts_or_ends_here')}

`:'')+`
${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}

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

`; + const nb=[...new Set(S.links.filter(l=>l.a===c||l.b===c).map(l=>l.a===c?l.b:l.a))]; + const tabs=[['links',tr('common.links')],['router',tr('puzzles.router_model')]];if(fl.length)tabs.push(['traffic',tr('puzzles.carrying')]); + const t=pzTabOf('city',tabs,'links');h+=pzTabs('city',tabs,t); + if(t==='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)} · ${pzG(ld)}/${pzG(cp)}
${btn(tr('common.open'),'selLink',{id:ls[0].id},'ghost sm')}
`;} + 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('')}
`; + h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`;} + else if(t==='router'){const g=p.rgen||0,rt=p.routers||1,G=RG[g],cap=nodeCap(c),ld=R.nodeLoad[c]||0,u=cap?ld/cap:0,cur=pzRtCost(g,rt),dl=v=>(v>=0?'+':'−')+fmt$(Math.abs(v)); + h+=`
${rt>1?rt+' × ':''}${esc(G.n)} · ${tr('puzzles.u_of_m_used',{u:fmtPorts(portsUsed(c)),m:portsMax(c)})}${pzG(ld)}/${pzG(cap)}
`; + h+=`
${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'):''}
`; + // Every model at once, two to a row: what it can do, or why it does not fit; its price against the installed one. + h+=`
${PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i); + return ``;}).join('')}
`;} + else{if(P.src.includes(c))h+=`

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

`;h+=`
${fl.map(x=>pzFlowRow(x)).join('')}
`;} + return h+'
';} + const l=S.links.find(x=>x.id===sel.id);if(!l)return '';const pl=pairLinks(l.a,l.b); + let h=pzHead(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)})}`)+'
'; + const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0; + h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`; + const tabs=[['size',tr('puzzles.size')],['traffic',tr('puzzles.carrying')],['routing',tr('common.routing_metric')]],t=pzTabOf('link',tabs,'size');h+=pzTabs('link',tabs,t); + if(t==='size'){ + h+=`
${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+=`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} + else if(t==='traffic'){const rec=R.ef[edgeKey(l)],rows=[]; + if(rec){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;}); + for(const k in byc)if(byc[k]>0.01)rows.push([tr('puzzles.flow_eyeballs_in_city',{city:CITY[k].name}),byc[k]]);} + h+=rows.length?rows.map(([n,v])=>`
${esc(n)}${fmtG(v)}
`).join(''):`

—

`; + 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('');} + else h+=`
${metricSection(l)}${linkCheckControl(l)}
`; + return h+'
';} +// A phone turned or a window resized can switch between the two layouts: draw the puzzle again in the one that fits. +addEventListener('resize',()=>{if(!S||!pzOn())return;const ph=isPhone();if(ph===UI._pzPhone)return;UI._pzh=null;UI._ph=null;pzRender();renderPanel();}); diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index 39275c0..ace2ce8 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -47,27 +47,64 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .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 .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 .pztop{top:0;margin:0 -12px;padding:0 12px 2px} - /* Peek: only the status bar, so the map keeps the screen while you build; tap or swipe it up for the rest. */ - #pzBox.mini{max-height:none}#pzBox.mini>:not(.pztop){display:none} - #pzBox .pzh .eyebrow{display:none}#pzBox h3{font-size:17px} - #pzBox .pzgl{font-size:14.5px}#pzBox .pzgh{font-size:13.5px}#pzBox .pzgh .pzshow{min-height:32px} - body.pz:has(#pzBox.mini) #hint{bottom:calc(150px + env(safe-area-inset-bottom,0px)) !important} - 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} } +/* Phones (97-puzzles-phone.js): nothing scrolls. A bar pinned at the top holds the puzzle's state and the next thing to + do; a city or a link opens a card at the bottom, split into tabs that each fit. --pzdock is the bar's height. */ +@media (max-width:760px),(max-height:500px) and (pointer:coarse){ + body.pz #hud{display:none} + #pzBox.dock{top:calc(env(safe-area-inset-top,0px) + 6px);bottom:auto;left:max(6px,env(safe-area-inset-left,0px));right:max(6px,env(safe-area-inset-right,0px));width:auto;max-height:none;overflow:visible;border-radius:16px;border:3px solid var(--ink);box-shadow:3px 3px 0 var(--ink);padding:6px 8px 7px} + body.pz.sheet-open #pzBox.dock{display:block} + body.pz.sheet-open #pzBox.dock .pzd-goal,body.pz.sheet-open #pzBox.dock .pzd-chips{display:none} + .pzd-bar{display:flex;align-items:center;gap:6px;min-width:0} + .pzd-nm{flex:1 1 auto;min-width:0;font:800 15px/1.2 var(--display);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + .pzd-stars{display:flex;gap:2px;flex:none} + .pzd-st{display:inline-grid;place-items:center;width:22px;height:22px;border:2px solid var(--line);border-radius:50%;font:900 11px var(--body);color:var(--ink2);box-sizing:border-box} + .pzd-st.on{border:0;font-size:17px}.pzd-st.cur{border-color:var(--warn);background:#FFF4D6;color:var(--ink)} + .pzd-bud{flex:none;font-weight:900;font-size:12.5px;font-variant-numeric:tabular-nums;white-space:nowrap}.pzd-bud.bad{color:var(--bad)} + #pzBox.dock .pzd-bar .b.sm{min-width:36px;min-height:36px;padding:2px 8px;font-size:16px} + .pzd-goal{display:flex;align-items:center;gap:8px;margin-top:6px;padding:5px 8px;background:#FFF4D6;border:2px solid var(--warn);border-radius:12px} + .pzd-goal.done{background:#DFFBEA;border-color:var(--ok)}.pzd-goal.bad{background:#FFE6E9;border-color:var(--bad)} + #pzBox.dock .arsteps{margin:6px 0 4px}#pzBox.dock .arsteps i{height:6px}#pzBox.dock .arbrief{font-size:13px;margin:0 0 2px} + #pzBox.dock .arsites{display:contents}#pzBox.dock .arsite{font-size:12px;padding:2px 8px} + body.pz.sheet-open #pzBox.dock .arbrief,body.pz.sheet-open #pzBox.dock .arsteps{display:none} + .pzd-goal{flex-wrap:wrap}.pzd-gi{flex:none;font-size:16px}.pzd-gt{flex:1 1 170px;min-width:0;font-size:13px;line-height:1.3}.pzd-gt b{font-weight:800} + .pzd-ga{flex:none;display:flex;flex-direction:column;gap:4px}#pzBox.dock .pzd-ga{margin-left:auto}#pzBox.dock .pzd-ga .b{min-height:32px;padding:2px 10px;font-size:13px;white-space:nowrap} + .pzd-chips{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px} + .pzd-chip{font:800 12px/1.2 var(--body);color:var(--ink);background:#fff;border:2px solid var(--line);border-radius:999px;padding:3px 8px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis;cursor:pointer} + .pzd-chip b{font-weight:900;font-variant-numeric:tabular-nums}.pzd-chip .bad{color:var(--bad)} + .pzd-chip.ok{border-color:var(--ok);background:#DFFBEA}.pzd-chip.part{border-color:var(--warn);background:#FFF4D6}.pzd-chip.none{border-color:var(--bad);background:#FFE6E9} + .pzd-chip.rule{cursor:default;color:var(--ink2)} + /* The card: as tall as its tab, under the bar at most; tabs keep each part short enough to need no scrolling. */ + body.pz #panel{max-height:calc(100% - var(--pzdock,60px) - 18px - env(safe-area-inset-top,0px)) !important} + body.pz #panel>.grab{display:none} + body.pz #panel .pzd-ph{padding:10px 12px 6px;align-items:center}body.pz #panel .pzd-ph .grow{min-width:0} + body.pz #panel .pzd-ph h2{font-size:20px;line-height:1.15}body.pz #panel .pzd-ph h2 small{font:700 12px var(--body);color:var(--ink2);white-space:normal} + body.pz #panel .pzd-ph .eyebrow .mine{color:var(--me)} + .pzd-body{padding:0 14px calc(10px + env(safe-area-inset-bottom,0px))} + .pzd-tabs{display:flex;gap:4px;margin:6px 0 8px;border-bottom:2px solid var(--line)} + .pzd-tabs button{flex:1;font:800 13px var(--body);color:var(--ink2);background:none;border:0;border-bottom:3px solid transparent;margin-bottom:-2px;padding:6px 2px;min-height:36px} + .pzd-tabs button.on{color:var(--ink);border-bottom-color:var(--me)} + .pzd-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-bottom:1.5px dashed var(--line);font-size:13px}.pzd-row .grow{min-width:0}.pzd-row.on{background:#FFE3F0;border-radius:8px} + .pzd-to{flex-wrap:wrap}.pzd-foot{justify-content:flex-end} + .pzd-models{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:5px;margin-top:6px} + .pzd-model{display:flex;flex-direction:column;align-items:flex-start;gap:0;text-align:left;font:inherit;color:var(--ink);background:#fff;border:2px solid var(--ink);border-radius:10px;padding:3px 7px;min-width:0;cursor:pointer} + .pzd-mh{display:flex;gap:6px;width:100%;align-items:baseline}.pzd-mh b{flex:1 1 auto;min-width:0;font-size:12.5px;font-weight:900;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.pzd-mh span{flex:none;font-weight:900;font-size:12.5px} + .pzd-model small{font-size:11px;color:var(--ink2);line-height:1.25;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + .pzd-model.on{background:#FFE3F0;border-color:var(--me)}.pzd-model:disabled:not(.on){opacity:.45;border-color:var(--line)} + .pzd-rt{margin:6px 0 0}.pzd-rt .b{min-height:34px} + .pzd-tiers{display:grid;grid-template-columns:1fr 1fr;gap:6px}.pzd-tiers .b{margin:0;display:flex;flex-direction:column;align-items:center;gap:0;white-space:normal;line-height:1.15;padding:4px 6px}.pzd-tiers .b small{font-size:11px} + /* What a routing metric does, and the redundancy check's question, are on the desktop card; here the buttons speak. */ + .pzd-routing section{margin:0}.pzd-routing h3{font-size:15px;margin:4px 0}.pzd-routing .note,.pzd-routing .lead{display:none}.pzd-routing .btns{margin:4px 0 8px} + body.pz #hint{bottom:calc(env(safe-area-inset-bottom,0px) + 12px) !important} + body.pz #toasts{top:calc(env(safe-area-inset-top,0px) + var(--pzdock,60px) + 14px) !important;bottom:auto !important} +} @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: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} + #pzBox.dock{right:auto;width:min(380px,46%)} + body.pz #toasts{top:auto !important;bottom:12px !important;left:8px !important;transform:none !important;width:calc(46% - 16px) !important} + /* The bar sits on the left here, so the card on the right can have the whole height. */ + body.pz #panel{top:calc(env(safe-area-inset-top,0px) + 6px) !important;max-height:calc(100% - 6px - env(safe-area-inset-top,0px)) !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} diff --git a/tests/puzzle-sheet.test.js b/tests/puzzle-sheet.test.js index c47577a..2dc7e8d 100644 --- a/tests/puzzle-sheet.test.js +++ b/tests/puzzle-sheet.test.js @@ -54,17 +54,18 @@ test('delivered eyeballs are chips; Back to my network lives in the menu, not in assert.deepEqual(errors, []); }); -test('on a phone held upright the sheet starts as its status bar, and the bar opens it', () => { +test('a phone gets the fixed bar (tests/puzzles-phone.test.js), a desktop the whole card', () => { const { ev, dom, errors } = load(); ev("window.innerWidth=360;window.innerHeight=740;dispatchEvent(new Event('resize'))"); begin(ev); - assert.equal(box(dom).classList.contains('mini'), true, 'peek'); + assert.equal(box(dom).classList.contains('dock'), true, 'the bar'); ev('ACT.pzRetry()'); - assert.equal(box(dom).classList.contains('mini'), true, 'a fresh try of the same puzzle keeps the sheet as the player left it'); + assert.equal(box(dom).classList.contains('dock'), true, 'a fresh try keeps it'); const { ev: ev2, dom: dom2 } = load(); ev2("window.innerWidth=1280;window.innerHeight=800;dispatchEvent(new Event('resize'))"); begin(ev2); - assert.equal(box(dom2).classList.contains('mini'), false, 'a desktop shows the whole card'); + assert.equal(box(dom2).classList.contains('dock'), false, 'a desktop shows the whole card'); + assert.ok(box(dom2).querySelector('.pztop .pzgoals'), 'with its three goals'); assert.deepEqual(errors, []); }); diff --git a/tests/puzzles-phone.test.js b/tests/puzzles-phone.test.js new file mode 100644 index 0000000..f693271 --- /dev/null +++ b/tests/puzzles-phone.test.js @@ -0,0 +1,112 @@ +// Puzzles on a phone are fixed overlays that never scroll: a bar pinned at the top with the puzzle's state, the one +// thing to do and a chip per flow; a city or a link opens a card at the bottom split into tabs. Architect runs get the +// same bar. A desktop keeps the side card. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const phone = (ev, w = 360, h = 740) => ev(`innerWidth=${w};innerHeight=${h};dispatchEvent(new Event('resize'))`); +const q = (dom, s) => dom.window.document.querySelector(s); +const qa = (dom, s) => [...dom.window.document.querySelectorAll(s)]; + +test('the bar: name, three stars, the money, undo and the menu; the goal to work on; a chip per flow', () => { + const { ev, dom, errors } = load(); + phone(ev); + ev("pzBegin(pzDef('baltic'))"); + const box = q(dom, '#pzBox'); + assert.ok(box.classList.contains('dock')); + assert.equal(qa(dom, '#pzBox .pzd-bar .pzd-st').length, 3, 'three stars'); + assert.ok(q(dom, '#pzBox .pzd-bar [data-act="pzUndo"]') && q(dom, '#pzBox .pzd-bar [data-act="puzzleMenu"]')); + assert.match(q(dom, '#pzBox .pzd-bar .pzd-bud').textContent, /\$/, 'the money'); + assert.equal(qa(dom, '#pzBox .pzd-st.cur').length, 1, 'the goal being worked on is marked'); + assert.ok(q(dom, '#pzBox .pzd-goal [data-act="pzLook"]'), 'Show me'); + const flows = ev('S.pz.dem.length'); + assert.equal(qa(dom, '#pzBox .pzd-chips [data-act="pzCity"]').length, flows, 'one chip per flow'); + assert.ok(qa(dom, '#pzBox .pzd-chip.none').length > 0, 'nothing built: the chips say nothing arrives'); + assert.equal(q(dom, '#pzBox .pztop'), null, 'not the desktop card'); + assert.deepEqual(errors, []); +}); + +test('a chip opens its city’s card; the card’s tabs switch, and the choice is kept for the next city', () => { + const { ev, dom, errors } = load(); + phone(ev); + ev("pzBegin(pzDef('baltic'));ACT.pzPop({city:'fra'})"); + const c = ev("S.pz.dem[0].a"); + ev(`document.querySelector('#pzBox [data-act="pzCity"]').click()`); + assert.equal(ev("UI.sel&&UI.sel.id"), c, 'the chip picked its city'); + ev("selectCity('fra')"); + const tabs = qa(dom, '#panelBody .pzd-tabs button').map((b) => b.dataset.args); + assert.ok(tabs.length >= 2, 'tabs'); + assert.ok(q(dom, '#panelBody [data-act="pzLinkTo"]'), 'Links first: where to lease a wave'); + assert.equal(q(dom, '#panelBody .pzd-models'), null, 'the models wait in their own tab'); + ev(`document.querySelector('#panelBody .pzd-tabs button:nth-child(2)').click()`); + assert.equal(qa(dom, '#panelBody .pzd-model').length, ev('PZ_RG.length'), 'every router model, in a grid'); + assert.equal(q(dom, '#panelBody [data-act="pzLinkTo"]'), null); + ev("ACT.pzPop({city:'tll'});selectCity('tll')"); + assert.ok(q(dom, '#panelBody .pzd-models'), 'the next city opens on the same tab'); + ev("ACT.pzTab({k:'city',t:'nonsense'})"); + assert.ok(q(dom, '#panelBody [data-act="pzLinkTo"]'), 'an unknown tab falls back to Links'); + assert.deepEqual(errors, []); +}); + +test('a link’s card: sizes first, then what it carries, then its routing', () => { + const { ev, dom, errors } = load(); + phone(ev); + ev("pzBegin(pzDef('baltic'));ACT.pzPop({city:'fra'});ACT.pzLinkTo({a:'fra',b:'tll'});ACT.pzLink({tier:1});closeModal();selectLink(S.links[0].id)"); + assert.equal(qa(dom, '#panelBody .pzd-tiers [data-act="pzTier"]').length, ev('PZ_TIERS.length')); + assert.ok(q(dom, '#panelBody [data-act="pzRmLink"]')); + ev("ACT.pzTab({k:'link',t:'routing'})"); + assert.ok(q(dom, '#panelBody .pzd-routing [data-act="setMetric"]'), 'the metric buttons'); + assert.equal(q(dom, '#panelBody .pzd-tiers'), null); + ev("ACT.pzTab({k:'link',t:'traffic'})"); + assert.match(q(dom, '#panelBody').textContent, /Gbps/); + assert.deepEqual(errors, []); +}); + +test('nothing on a phone scrolls by design: the bar and the card’s body have no scroll of their own', () => { + const { ev, errors } = load(); + 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]).map(r=>({sel:r.selectorText||'',ov:r.style.getPropertyValue('overflow')+r.style.getPropertyValue('overflow-y'),mh:r.style.getPropertyValue('max-height')})))`)); + const dock = rules.find((r) => r.sel === '#pzBox.dock'); + assert.ok(dock && dock.ov === 'visible' && dock.mh === 'none', 'the bar is as tall as it needs, never a scroll box'); + assert.ok(!rules.some((r) => /pzd-/.test(r.sel) && /auto|scroll/.test(r.ov)), 'no part of the bar or the cards scrolls'); + assert.deepEqual(errors, []); +}); + +test('Reset moves to the menu on a phone; the desktop keeps its own', () => { + const { ev, dom, errors } = load(); + phone(ev); + ev("pzBegin(pzDef('baltic'));ACT.pzPop({city:'fra'});ACT.puzzleMenu()"); + assert.ok(q(dom, '#modalCard [data-act="pzReset"]'), 'in the menu'); + ev(`document.querySelector('#modalCard [data-act="pzReset"]').click()`); + assert.equal(ev('Object.keys(S.pops).length'), 0, 'it resets'); + assert.equal(q(dom, '#modal').hidden, true, 'and closes the menu'); + const d = load(); + d.ev("innerWidth=1280;innerHeight=800;dispatchEvent(new Event('resize'));pzBegin(pzDef('baltic'));ACT.puzzleMenu()"); + assert.equal(d.dom.window.document.querySelector('#modalCard [data-act="pzReset"]'), null, 'not in the desktop menu'); + assert.ok(d.dom.window.document.querySelector('#pzBox .pzfoot [data-act="pzReset"]'), 'it is on the card'); + assert.deepEqual(errors, []); +}); + +test('an architect run gets the same bar: its brief, the sites as chips and the review with its button', () => { + const { ev, dom, errors } = load(); + phone(ev); + ev('ACT.pzArStart({id:AR_RUNS[0].id});closeModal()'); + assert.ok(q(dom, '#pzBox').classList.contains('dock')); + assert.ok(q(dom, '#pzBox .pzd-bar [data-act="puzzleMenu"]')); + assert.ok(q(dom, '#pzBox .arbrief').textContent.length > 10, 'the brief'); + assert.ok(qa(dom, '#pzBox .arsite').length >= 2, 'the sites'); + assert.ok(q(dom, '#pzBox .pzd-goal [data-act="pzArGo"]'), 'the review and its button'); + assert.deepEqual(errors, []); +}); + +test('turning a tablet-sized window into a phone redraws the puzzle in the bar, and back', () => { + const { ev, dom, errors } = load(); + ev("innerWidth=1280;innerHeight=800;dispatchEvent(new Event('resize'));pzBegin(pzDef('baltic'))"); + assert.equal(q(dom, '#pzBox').classList.contains('dock'), false); + phone(ev); + assert.equal(q(dom, '#pzBox').classList.contains('dock'), true); + ev("innerWidth=1280;innerHeight=800;dispatchEvent(new Event('resize'))"); + assert.equal(q(dom, '#pzBox').classList.contains('dock'), false); + assert.deepEqual(errors, []); +}); diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index b815b3d..4d9ea67 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -392,24 +392,26 @@ test('puzzle HUD and panels fit a 360 px phone, portrait and landscape', () => { ev("pzBegin(pzDef('baltic'))"); assert.equal(ev("document.getElementById('tabbar').hidden"), true); assert.equal(ev("document.getElementById('pzBox').hidden"), false); + // The bar: each flow as a chip, the content's home as a rule. const box = ev("document.getElementById('pzBox').textContent"); - assert.match(box, /Eyeballs in Tallinn/); + assert.match(box, /👀 Tallinn/); assert.match(box, /Frankfurt ⇄ Tallinn circuit/); - assert.match(box, /Content lives in Frankfurt/); + assert.match(box, /🗄️ 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/); + assert.match(ev("document.getElementById('panelBody').textContent"), /Your POP[\s\S]*Links[\s\S]*Router model/); + ev("ACT.pzTab({k:'city',t:'router'})"); + assert.match(ev("document.getElementById('panelBody').textContent"), /1 of 8 used|of \d+ used/); 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. + // jsdom has no layout: the phone rules keep the bar from scrolling and its buttons big enough to tap. 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'); + .flatMap(m=>[...m.cssRules]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),ov:r.style.getPropertyValue('overflow')})))`)); + assert.ok(rules.some((r) => /^#pzBox\.dock$/.test(r.sel) && r.ov === 'visible'), 'the bar never scrolls'); + assert.ok(rules.some((r) => /#pzBox\.dock \.pzd-bar \.b\.sm/.test(r.sel) && parseFloat(r.mh) >= 36), 'touch targets'); assert.deepEqual(errors, []); }); From 908f2e0de9b4461d118caa08cf42e221e6810061 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 17:33:36 +0100 Subject: [PATCH 354/491] Puzzles on phones that never scroll, a fairer meet-halfway, Fujairah on its coast (2.10.1) --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65c8f06..d539784 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +## [2.10.1] — 2026-11-05 + - "Meet halfway" on a renewal now offers the price halfway between what the customer pays and what they ask, and the button shows it before you press (#293). - Fujairah sits on the UAE's east coast again, where its cables land, instead of on top of Muscat (#295). - Puzzles on phones no longer scroll. A bar at the top shows the stars, the money and the one thing to do next, with a chip for every flow that turns green once it all arrives; tap a chip to jump to its city. A city or a link opens a short card at the bottom, split into tabs (links, router, traffic; size, traffic, routing), so every button is on screen at once. Architect runs get the same bar, and Reset is in the ☰ menu on phones. diff --git a/package-lock.json b/package-lock.json index 262b33e..13274d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "2.10.0", + "version": "2.10.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "2.10.0", + "version": "2.10.1", "license": "MIT", "devDependencies": { "@modelcontextprotocol/node": "2.1.2", diff --git a/package.json b/package.json index a036e63..35e9aa0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "2.10.0", + "version": "2.10.1", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From 9c8cda44c1c7f39489c0e18ab5ea5701f6541d21 Mon Sep 17 00:00:00 2001 From: Wolfgang Nagele Date: Thu, 5 Nov 2026 10:07:37 -0500 Subject: [PATCH 355/491] Build container images for easy MCP use --- .dockerignore | 4 ++ .github/workflows/auto-release.yml | 7 +++ .github/workflows/docker.yml | 72 ++++++++++++++++++++++++++++++ docker/Dockerfile | 16 +++++++ docker/docker-entrypoint.sh | 42 +++++++++++++++++ docs/MCP.md | 33 ++++++++++++++ 6 files changed, 174 insertions(+) create mode 100644 .dockerignore create mode 100644 .github/workflows/docker.yml create mode 100644 docker/Dockerfile create mode 100644 docker/docker-entrypoint.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..dbdaf41 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +.git +.github +node_modules +_site diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 29bfba0..aa3bdfc 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -73,3 +73,10 @@ jobs: # Pre-releases are for testing and never go live. if: steps.v.outputs.skip == 'false' && steps.v.outputs.pre == 'false' run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}" + + - name: Publish the Docker image + # Same pattern as the deploy above: the image is built and pushed from the + # release tag by docker.yml. Pre-releases get one too: an image tag is + # pulled on purpose, so a test image costs nothing. + if: steps.v.outputs.skip == 'false' + run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}" diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..d62dc9a --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,72 @@ +name: Build and push Docker image + +# Every push to main publishes :latest and :. A release publishes : +# built from its tag: auto-release.yml dispatches this workflow alongside the Pages +# deploy, because releases created with the workflow token do not fire the +# "released" event. Hand-published releases fire it directly. +on: + push: + branches: [main] + release: + types: [released, prereleased] + workflow_dispatch: + inputs: + tag: + description: Existing release tag to build (e.g. v2.10.0); empty builds main + required: false + +permissions: + contents: read + packages: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || inputs.tag }} + + - name: Work out the image tags + id: tags + env: + TAG: ${{ github.event.release.tag_name || inputs.tag }} + run: | + set -euo pipefail + # The image is named after this repository (ghcr.io//, lowercased). + image=ghcr.io/${GITHUB_REPOSITORY,,} + if [ -n "$TAG" ]; then + want="v$(jq -r .version package.json)" + if [ "$TAG" != "$want" ]; then + echo "::error::Release tag $TAG does not match package.json version ($want)" + exit 1 + fi + echo "tags=$image:${TAG#v}" >> "$GITHUB_OUTPUT" + else + echo "tags=$image:latest,$image:$GITHUB_SHA" >> "$GITHUB_OUTPUT" + fi + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.tags.outputs.tags }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..1228b19 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,16 @@ +FROM node:26-slim + +COPY . /series-of-tubes +WORKDIR /series-of-tubes + +RUN npm install + +COPY docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh \ + && chown -R node:node /series-of-tubes + +USER node + +EXPOSE 8080 7777 + +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh new file mode 100644 index 0000000..1d5938d --- /dev/null +++ b/docker/docker-entrypoint.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -u +cd /series-of-tubes + +# MCP_MODE picks what runs: browser (default) serves the game page and relays the +# player's tab to the MCP server; headless runs a game of its own, no page needed. +mode=${MCP_MODE:-browser} +case "$mode" in + browser|headless) ;; + *) echo "[entrypoint] MCP_MODE must be browser or headless, not '$mode'" >&2; exit 1 ;; +esac + +# Everything after the image name is passed to the MCP server as well +# (node scripts/mcp.js --help lists the options). +extra=("$@") + +# A container needs 0.0.0.0 to be reachable at all; default --http unless given. +http=(--http 0.0.0.0:7777) +for a in "${extra[@]}"; do [ "$a" = --http ] && http=(); done + +pids=() +start() { "$@" & pids+=("$!"); } + +shutdown() { + trap '' TERM INT + kill -TERM "${pids[@]}" 2>/dev/null + wait "${pids[@]}" 2>/dev/null + exit 0 +} +trap shutdown TERM INT + +if [ "$mode" = browser ]; then + start npm run dev -- --host 0.0.0.0 --port 8080 + start npm run mcp -- --browser "${http[@]}" "${extra[@]}" +else + start npm run mcp -- "${http[@]}" "${extra[@]}" +fi + +status=0 +wait -n || status=$? +echo "[entrypoint] a process exited with status $status; stopping the container" >&2 +shutdown diff --git a/docs/MCP.md b/docs/MCP.md index 4398617..4c6b590 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -77,6 +77,39 @@ claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp - **Either session.** `--http` works headless and with `--browser` alike: then a client elsewhere drives the game in the player's tab, while the relay stays where `npm run dev` put it. +### In a container + +Every push to `main` and every release publishes a multi-arch (amd64/arm64) image at +`ghcr.io/fjaeckel/seriesoftubes`, built from the repo by the `docker.yml` workflow: `latest` and the commit SHA on +pushes, the release's version (pre-releases included) on releases. It packages the dev server and the MCP server; +`node scripts/mcp.js --help` options go after the image name, and `--http 0.0.0.0:7777` is the default (a container +bound to loopback would be unreachable; pass your own `--http` to override). + +`MCP_MODE=headless` runs just the MCP server with a game of its own; the default (`browser`) also serves the +development page so a browser tab can play it, as above. + +```sh +docker run -d -p 7777:7777 -e MCP_MODE=headless ghcr.io/fjaeckel/seriesoftubes +claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp + +# Options are passed to scripts/mcp.js; the token is its own env var. +docker run -d -p 7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret \ + ghcr.io/fjaeckel/seriesoftubes --clock realtime --pace 60000 + +# The browser session: open http://localhost:8080, then Settings → Agent API. +docker run -d -p 8080:8080 -p 7777:7777 ghcr.io/fjaeckel/seriesoftubes +``` + +`load_save` and `export_save` take JSON only unless the server runs with `--save-dir`; mount a volume for it: + +```sh +docker run -d -p 7777:7777 -e MCP_MODE=headless -v sot-saves:/saves \ + ghcr.io/fjaeckel/seriesoftubes --save-dir /saves +``` + +What "Over HTTP" says applies to the container too: the mapped port is reachable by anything that can reach the host, +so set a token before exposing one, and there is no TLS. + ## The clock Every session has one of two clocks, and `schema` (section `mode`) says which: From 98735eb76911e205529f8691795cdcc683e7b983 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 20:14:03 +0100 Subject: [PATCH 356/491] Container image: releases only, a token by default, lean layers; every action pinned The image is published to GHCR as the release's version when a release dispatches docker.yml, and never as latest or per commit. Pushes and pull requests that touch it build it and try headless (with and without a token) and browser mode, without publishing. The image: node:24-slim pinned by digest (the major CI tests on), npm ci from the lockfile in its own layer, only src, site, scripts and the harness copied in (an allow-list .dockerignore), root-owned and run as node, /saves ready for --save-dir. The entrypoint runs the servers with node directly and, with no SOT_MCP_TOKEN, makes a token for the run and prints it (MCP_NO_TOKEN=1 to opt out); the docs publish ports to 127.0.0.1 and explain --allow-host. Labels, SBOM and provenance on push. Every GitHub Action in every workflow is pinned to a commit SHA with its version, and Dependabot keeps the actions, the image's base and the npm tools current. tests/docker.test.js guards all of it. The ADR and the github-pages skill say the image is a tool: GHCR only, never Pages. --- .claude/skills/github-pages/SKILL.md | 3 + .dockerignore | 14 ++- .github/dependabot.yml | 39 ++++++ .github/workflows/auto-release.yml | 4 +- .github/workflows/ci.yml | 12 +- .github/workflows/claude.yml | 4 +- .github/workflows/docker.yml | 174 ++++++++++++++++++++------- .github/workflows/perf-comment.yml | 2 +- .github/workflows/perf.yml | 6 +- .github/workflows/release.yml | 10 +- .github/workflows/weekly-puzzle.yml | 4 +- docker/Dockerfile | 28 +++-- docker/docker-entrypoint.sh | 45 ++++--- docs/MCP.md | 51 +++++--- docs/adr/0001-github-pages-only.md | 3 + tests/docker.test.js | 78 ++++++++++++ 16 files changed, 367 insertions(+), 110 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 tests/docker.test.js diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index c0ed652..52010f0 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -35,6 +35,9 @@ one, redesign the feature. run on a developer's own machine against a checkout; nothing they serve is deployed, and the game never depends on them. Their code stays out of `_site/` (`src/agent/` is development-only, see `docs/adr/0004-dev-only-code.md`). +- **The container image is a tool too.** `docker/` packages those tools; `docker.yml` publishes it to GHCR for releases + (version tags only, no `latest`) and never to Pages. Someone may run its development server where they like; that is + not a host of the game, and the game never depends on it. ## How it deploys diff --git a/.dockerignore b/.dockerignore index dbdaf41..fbf5463 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,10 @@ -.git -.github -node_modules -_site +# The image takes only what docker/Dockerfile copies; everything else (git history, tests, docs, local saves, +# node_modules, _site) stays out of the build context. +* +!package.json +!package-lock.json +!src/ +!site/ +!scripts/ +!tests/harness.js +!docker/docker-entrypoint.sh diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..48e0a5e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,39 @@ +# Keeps what the workflows and the container image pin up to date: every GitHub Action is pinned to a commit SHA +# (Dependabot moves the SHA and its version comment together), the image's Node base to a digest, and the npm tools +# to the lockfile. Updates come as pull requests, one group per ecosystem, once a week. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + groups: + actions: + patterns: ["*"] + commit-message: + prefix: "CI" + + - package-ecosystem: docker + directory: /docker + schedule: + interval: weekly + day: monday + # The image runs the Node major CI tests on (ci.yml); a new major comes with CI, by hand. + ignore: + - dependency-name: node + update-types: ["version-update:semver-major"] + commit-message: + prefix: "Container" + + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + day: monday + groups: + tools: + patterns: ["*"] + update-types: [minor, patch] + commit-message: + prefix: "Tools" diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index aa3bdfc..4d41153 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -25,10 +25,10 @@ jobs: env: GH_TOKEN: ${{ github.token }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8bb0ed7..e135ebb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,8 +26,8 @@ jobs: matrix: part: [1, 2, 3, 4] steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -38,8 +38,8 @@ jobs: name: build runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -61,8 +61,8 @@ jobs: translations: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 8ff912c..12fba69 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -27,9 +27,9 @@ jobs: id-token: write actions: read steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 1 - - uses: anthropics/claude-code-action@v1 + - uses: anthropics/claude-code-action@c0949c50a78c1ec8ce2647db36629b870e715d0c # v1.0.268 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index d62dc9a..2deeef2 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,72 +1,164 @@ -name: Build and push Docker image +name: Container image -# Every push to main publishes :latest and :. A release publishes : -# built from its tag: auto-release.yml dispatches this workflow alongside the Pages -# deploy, because releases created with the workflow token do not fire the -# "released" event. Hand-published releases fire it directly. +# Publishes ghcr.io//: for releases, and nothing else: auto-release.yml dispatches this workflow +# with the new tag (pre-releases too). There is no :latest and no image per commit. Pushes and pull requests that change +# what goes into the image only build it and try both modes; they never publish. The image packages the MCP server and +# the development server; the game itself is hosted on GitHub Pages only (docs/adr/0001-github-pages-only.md). on: - push: - branches: [main] - release: - types: [released, prereleased] workflow_dispatch: inputs: tag: - description: Existing release tag to build (e.g. v2.10.0); empty builds main - required: false + description: Release tag to build and publish (e.g. v2.10.1) + required: true + push: + branches: [main] + paths: + - docker/** + - .dockerignore + - package.json + - package-lock.json + - scripts/** + - tests/harness.js + - .github/workflows/docker.yml + pull_request: + paths: + - docker/** + - .dockerignore + - package.json + - package-lock.json + - scripts/** + - tests/harness.js + - .github/workflows/docker.yml permissions: contents: read - packages: write + +concurrency: + group: docker-${{ github.event_name }}-${{ inputs.tag || github.ref }} + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} jobs: - build: + test: runs-on: ubuntu-latest + timeout-minutes: 20 steps: - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.event.release.tag_name || inputs.tag }} + ref: ${{ inputs.tag || '' }} + persist-credentials: false - - name: Work out the image tags - id: tags - env: - TAG: ${{ github.event.release.tag_name || inputs.tag }} + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build for this runner + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64 + load: true + push: false + tags: sot:test + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Try both modes run: | set -euo pipefail - # The image is named after this repository (ghcr.io//, lowercased). - image=ghcr.io/${GITHUB_REPOSITORY,,} - if [ -n "$TAG" ]; then - want="v$(jq -r .version package.json)" - if [ "$TAG" != "$want" ]; then - echo "::error::Release tag $TAG does not match package.json version ($want)" - exit 1 - fi - echo "tags=$image:${TAG#v}" >> "$GITHUB_OUTPUT" - else - echo "tags=$image:latest,$image:$GITHUB_SHA" >> "$GITHUB_OUTPUT" - fi + init='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"1"}}}' + mcp() { curl -sS -o /tmp/out -w '%{http_code}' -X POST http://127.0.0.1:7777/mcp \ + -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' "$@" -d "$init"; } + until_up() { for i in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; docker logs "$2"; exit 1; } - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 + # Headless, with a token: refused without it, answered with it. + docker run -d --name h -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:7777/ h + test "$(mcp)" = 401 + test "$(mcp -H 'authorization: Bearer ci-token')" = 200 + grep -q serverInfo /tmp/out + docker rm -f h - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + # No token given: the container makes one, says so, and wants it. + docker run -d --name t -p 127.0.0.1:7777:7777 -e MCP_MODE=headless sot:test + until_up http://127.0.0.1:7777/ t + test "$(mcp)" = 401 + tok=$(docker logs t 2>&1 | sed -n "s/.*this run's token is //p" | head -1) + test -n "$tok" + test "$(mcp -H "authorization: Bearer $tok")" = 200 + docker rm -f t - - name: Log in to GitHub Container Registry - uses: docker/login-action@v3 + # Browser mode: the development page and the MCP server. + docker run -d --name b -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:8080/ b + test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/)" = 200 + until_up http://127.0.0.1:7777/ b + test "$(mcp -H 'authorization: Bearer ci-token')" = 200 + docker rm -f b + + # The server runs as node, not root. + test "$(docker run --rm --entrypoint id sot:test -u)" != 0 + + publish: + if: github.event_name == 'workflow_dispatch' + needs: test + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: read + packages: write + steps: + - name: Check the tag + env: + TAG: ${{ inputs.tag }} + run: | + [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "::error::Not a release tag: $TAG"; exit 1; } + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag }} + persist-credentials: false + + - name: Work out the image name and version + id: meta + env: + TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + want="v$(jq -r .version package.json)" + if [ "$TAG" != "$want" ]; then echo "::error::Release tag $TAG does not match package.json ($want)"; exit 1; fi + # Named after this repository (ghcr.io//, lowercased), so forks publish their own. + echo "image=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT" + echo "version=${TAG#v}" >> "$GITHUB_OUTPUT" + echo "revision=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "created=$(git log -1 --format=%cI)" >> "$GITHUB_OUTPUT" + + - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Build and push - uses: docker/build-push-action@v6 + - name: Build and push the release's version + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . file: docker/Dockerfile platforms: linux/amd64,linux/arm64 push: true - tags: ${{ steps.tags.outputs.tags }} + tags: ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }} + labels: | + org.opencontainers.image.title=Series of Tubes MCP server + org.opencontainers.image.description=The Series of Tubes MCP server and development server, so an AI client can play the game. + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.documentation=${{ github.server_url }}/${{ github.repository }}/blob/${{ inputs.tag }}/docs/MCP.md + org.opencontainers.image.version=${{ steps.meta.outputs.version }} + org.opencontainers.image.revision=${{ steps.meta.outputs.revision }} + org.opencontainers.image.created=${{ steps.meta.outputs.created }} + org.opencontainers.image.licenses=MIT + provenance: mode=max + sbom: true cache-from: type=gha cache-to: type=gha,mode=max diff --git a/.github/workflows/perf-comment.yml b/.github/workflows/perf-comment.yml index 2f6c286..ca461da 100644 --- a/.github/workflows/perf-comment.yml +++ b/.github/workflows/perf-comment.yml @@ -17,7 +17,7 @@ jobs: if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-latest steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: perf run-id: ${{ github.event.workflow_run.id }} diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index 48c05e4..00ffce2 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -22,8 +22,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 40 steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -48,7 +48,7 @@ jobs: env: PR: ${{ github.event.pull_request.number }} run: echo "$PR" > pr-number.txt - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 if: github.event_name == 'pull_request' with: name: perf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c9e813f..b77850e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -42,10 +42,10 @@ jobs: ALLOW_OLDER: ${{ inputs.allow_older || false }} GH_TOKEN: ${{ github.token }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ env.TAG }} - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -100,7 +100,7 @@ jobs: 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 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: ./_site @@ -115,9 +115,7 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} steps: - id: deployment - uses: actions/deploy-pages@v5 - - # Tell IndexNow (Bing, Yandex, Seznam, …) about the new version, only after + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 # the site is live. indexnow: needs: deploy diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml index fdff934..6cfa3d5 100644 --- a/.github/workflows/weekly-puzzle.yml +++ b/.github/workflows/weekly-puzzle.yml @@ -38,10 +38,10 @@ jobs: GH_TOKEN: ${{ github.token }} KEY: ${{ inputs.key }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: main - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm diff --git a/docker/Dockerfile b/docker/Dockerfile index 1228b19..1ce5130 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,16 +1,28 @@ -FROM node:26-slim +# The MCP server and the development server in one image (docs/MCP.md, "In a container"). docker.yml builds it and +# publishes it to GHCR for releases only; nothing here is ever deployed to GitHub Pages (docs/adr/0001-github-pages-only.md). +# The base is pinned by digest and kept current by Dependabot (.github/dependabot.yml); CI tests on the same Node major. +FROM node:24-slim@sha256:01d566e8d94d8c619591d78652babfccd3c6992a3dffa9ed5ab39e11cf6c70e9 -COPY . /series-of-tubes WORKDIR /series-of-tubes -RUN npm install +# Dependencies first, exactly as locked, so a change to the code reuses this layer. Every dependency is a dev one (the +# game has none), and the servers need them all. No install scripts run. +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund --ignore-scripts && npm cache clean --force -COPY docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh -RUN chmod +x /usr/local/bin/docker-entrypoint.sh \ - && chown -R node:node /series-of-tubes +# Only what the servers read: the game's source and static files, the scripts, and the harness the MCP server plays +# through. Owned by root and read-only to the server, which runs as node. +COPY src ./src +COPY site ./site +COPY scripts ./scripts +COPY tests/harness.js ./tests/harness.js +COPY --chmod=0755 docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh + +# --save-dir /saves needs somewhere the server may write: a volume mounted here takes this ownership. +RUN mkdir /saves && chown node:node /saves +VOLUME /saves USER node - +ENV NPM_CONFIG_UPDATE_NOTIFIER=false EXPOSE 8080 7777 - ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh index 1d5938d..355af5a 100644 --- a/docker/docker-entrypoint.sh +++ b/docker/docker-entrypoint.sh @@ -1,42 +1,55 @@ #!/usr/bin/env bash -set -u +# Starts the container's servers (docker/Dockerfile, docs/MCP.md "In a container"). +# MCP_MODE=browser (default): the development server on :8080, with the relay a player's tab dials, and the MCP server +# on :7777 driving that tab. +# MCP_MODE=headless: only the MCP server, with a game of its own. +# Everything after the image name goes to scripts/mcp.js (node scripts/mcp.js --help lists the options). +set -uo pipefail cd /series-of-tubes -# MCP_MODE picks what runs: browser (default) serves the game page and relays the -# player's tab to the MCP server; headless runs a game of its own, no page needed. mode=${MCP_MODE:-browser} case "$mode" in browser|headless) ;; *) echo "[entrypoint] MCP_MODE must be browser or headless, not '$mode'" >&2; exit 1 ;; esac -# Everything after the image name is passed to the MCP server as well -# (node scripts/mcp.js --help lists the options). extra=("$@") +has() { local a; for a in "${extra[@]}"; do [ "$a" = "$1" ] && return 0; done; return 1; } -# A container needs 0.0.0.0 to be reachable at all; default --http unless given. +# A container must listen beyond loopback to be reachable at all; --http in the arguments overrides it. http=(--http 0.0.0.0:7777) -for a in "${extra[@]}"; do [ "$a" = --http ] && http=(); done +has --http && http=() + +# Listening beyond loopback, the MCP server would take orders from anyone who reaches the port (its Host check stops +# browsers, not other clients), so it gets a token. None given (SOT_MCP_TOKEN or --token-file): this run makes one and +# prints it. MCP_NO_TOKEN=1 turns that off, for a port published to 127.0.0.1 only. +if [ -z "${SOT_MCP_TOKEN:-}" ] && ! has --token-file && [ "${MCP_NO_TOKEN:-}" != 1 ]; then + SOT_MCP_TOKEN=$(node -e "process.stdout.write(require('node:crypto').randomBytes(24).toString('base64url'))") + export SOT_MCP_TOKEN + echo "[entrypoint] No SOT_MCP_TOKEN given: this run's token is $SOT_MCP_TOKEN" >&2 + echo "[entrypoint] claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header \"Authorization: Bearer $SOT_MCP_TOKEN\"" >&2 +fi pids=() start() { "$@" & pids+=("$!"); } - shutdown() { trap '' TERM INT - kill -TERM "${pids[@]}" 2>/dev/null - wait "${pids[@]}" 2>/dev/null - exit 0 + kill -TERM "${pids[@]}" 2>/dev/null || true + wait "${pids[@]}" 2>/dev/null || true + exit "${1:-0}" } trap shutdown TERM INT +# node directly, not npm run: one process less, and signals reach the server. if [ "$mode" = browser ]; then - start npm run dev -- --host 0.0.0.0 --port 8080 - start npm run mcp -- --browser "${http[@]}" "${extra[@]}" + start node scripts/dev.js --host 0.0.0.0 --port 8080 + start node scripts/mcp.js --browser "${http[@]}" "${extra[@]}" else - start npm run mcp -- "${http[@]}" "${extra[@]}" + start node scripts/mcp.js "${http[@]}" "${extra[@]}" fi +# One server stopping stops the container, with its status, so a restart policy can bring both back. status=0 wait -n || status=$? -echo "[entrypoint] a process exited with status $status; stopping the container" >&2 -shutdown +echo "[entrypoint] a server exited with status $status; stopping the container" >&2 +shutdown "$status" diff --git a/docs/MCP.md b/docs/MCP.md index 4c6b590..a93ef93 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -79,36 +79,49 @@ claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp ### In a container -Every push to `main` and every release publishes a multi-arch (amd64/arm64) image at -`ghcr.io/fjaeckel/seriesoftubes`, built from the repo by the `docker.yml` workflow: `latest` and the commit SHA on -pushes, the release's version (pre-releases included) on releases. It packages the dev server and the MCP server; -`node scripts/mcp.js --help` options go after the image name, and `--http 0.0.0.0:7777` is the default (a container -bound to loopback would be unreachable; pass your own `--http` to override). +Every release publishes a multi-arch (amd64/arm64) image at `ghcr.io/fjaeckel/seriesoftubes:` +(`docker.yml`, dispatched by the release; pre-releases too). There is no `latest` and no image per commit: pick a +version from the [releases](https://github.com/fjaeckel/seriesoftubes/releases). It holds the MCP server and the +development server, nothing else from the repository, and runs as `node`, not root. It is published to GHCR only; the +game itself is served from GitHub Pages and nowhere else. -`MCP_MODE=headless` runs just the MCP server with a game of its own; the default (`browser`) also serves the -development page so a browser tab can play it, as above. +- **`MCP_MODE=browser`** (the default) serves the development page on 8080, with the relay, and runs the MCP server on + 7777 driving that tab. **`MCP_MODE=headless`** runs only the MCP server, with a game of its own. +- **Options** go after the image name, to `scripts/mcp.js` (`node scripts/mcp.js --help`). The MCP server listens on + `0.0.0.0:7777` inside the container, since loopback there is unreachable; pass your own `--http` to change it. +- **A token, always.** The Host check stops browsers, not other clients, so a published port without a token is open to + anyone who reaches it. Give one with `-e SOT_MCP_TOKEN=…` (or `--token-file`); without one the container makes a + token for this run and prints it, with the `claude mcp add` line to use it. `MCP_NO_TOKEN=1` turns that off. +- **Publish the ports to loopback** (`-p 127.0.0.1:7777:7777`), as below. A bare `-p 7777:7777` listens on every + interface of the host, and Docker's rules go around ufw and firewalld. To reach it from elsewhere, keep the token, + add `--allow-host NAME` for the name or address clients use (requests naming the host's address are refused + otherwise, since that is not an address inside the container), and put TLS in front. +- **The relay has no token** (as with `npm run dev -- --host`): in browser mode, anyone who reaches port 8080 can drive + a game whose player turned agent mode on. Publish it to loopback too. ```sh -docker run -d -p 7777:7777 -e MCP_MODE=headless ghcr.io/fjaeckel/seriesoftubes -claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp +V=2.10.1 # a release -# Options are passed to scripts/mcp.js; the token is its own env var. -docker run -d -p 7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret \ - ghcr.io/fjaeckel/seriesoftubes --clock realtime --pace 60000 +# Headless, with your own token +docker run -d --name sot -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret \ + ghcr.io/fjaeckel/seriesoftubes:$V --clock realtime --pace 60000 +claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header "Authorization: Bearer secret" -# The browser session: open http://localhost:8080, then Settings → Agent API. -docker run -d -p 8080:8080 -p 7777:7777 ghcr.io/fjaeckel/seriesoftubes +# The browser session: open http://localhost:8080, then Settings → Agent API. The token is in `docker logs sot`. +docker run -d --name sot -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 ghcr.io/fjaeckel/seriesoftubes:$V ``` -`load_save` and `export_save` take JSON only unless the server runs with `--save-dir`; mount a volume for it: +`load_save` and `export_save` take JSON only unless the server runs with `--save-dir`; the image has `/saves` for it, +owned by the server's user, so mount a volume there: ```sh -docker run -d -p 7777:7777 -e MCP_MODE=headless -v sot-saves:/saves \ - ghcr.io/fjaeckel/seriesoftubes --save-dir /saves +docker run -d -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret -v sot-saves:/saves \ + ghcr.io/fjaeckel/seriesoftubes:$V --save-dir /saves ``` -What "Over HTTP" says applies to the container too: the mapped port is reachable by anything that can reach the host, -so set a token before exposing one, and there is no TLS. +The image's Node base is pinned by digest, its dependencies by the lockfile, and every workflow action by commit; +Dependabot (`.github/dependabot.yml`) keeps them current. Pull requests that touch the image build it and try both modes +without publishing. ## The clock diff --git a/docs/adr/0001-github-pages-only.md b/docs/adr/0001-github-pages-only.md index 039db57..d435457 100644 --- a/docs/adr/0001-github-pages-only.md +++ b/docs/adr/0001-github-pages-only.md @@ -41,6 +41,9 @@ Anything that needs data at runtime fetches it from the same origin as a static what is cached for offline play, versioned by the release. - **Deploys only come from releases.** `release.yml` is the only workflow with `pages: write`. Pushes to `main` never deploy. +- **Tools are not hosting.** `npm run dev`, the MCP server and the container image that packages them + (`docker/`, published to GHCR for releases) are tools. What someone serves with them is theirs; seriesoftub.es is + the game, and nothing is ever deployed anywhere but GitHub Pages. - **Tests guard it.** `tests/pages.test.js` checks that a build is plain static files that GitHub Pages can serve as they are: no server or host configuration files, every local reference resolving inside `_site/`, nothing over the size limits, `CNAME` and `404.html` in place, and the deploy going diff --git a/tests/docker.test.js b/tests/docker.test.js new file mode 100644 index 0000000..b541998 --- /dev/null +++ b/tests/docker.test.js @@ -0,0 +1,78 @@ +// The container image and the workflows that build things: what is published, how, and that every third-party piece is +// pinned. The image goes to GHCR for releases only (no :latest, no image per commit), never to Pages; it runs as node, +// from a base pinned by digest, with only what the servers read; its MCP server gets a token unless told otherwise; every +// GitHub Action is pinned to a commit; Dependabot keeps all of it current. docs/MCP.md, "In a container". +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const ROOT = path.join(__dirname, '..'); +const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8'); +// Without comments: what a file says about itself is not what it does. +const code = (p) => read(p).split('\n').map((l) => l.replace(/(^|\s)#.*$/, '')).join('\n'); +const WF = path.join(ROOT, '.github', 'workflows'); + +test('every GitHub Action in every workflow is pinned to a commit, with its version beside it', () => { + const loose = []; + for (const f of fs.readdirSync(WF).filter((f) => /\.ya?ml$/.test(f))) + for (const [i, line] of read(`.github/workflows/${f}`).split('\n').entries()) { + const m = /^\s*(?:-\s*)?uses:\s*(\S+)(.*)$/.exec(line); + if (!m || m[1].startsWith('./')) continue; + if (!/^[\w.-]+\/[\w./-]+@[0-9a-f]{40}$/.test(m[1]) || !/#\s*v\d+(\.\d+)*/.test(m[2])) loose.push(`${f}:${i + 1} ${m[1]}`); + } + assert.deepEqual(loose, []); +}); + +test('Dependabot keeps the actions, the image’s base and the npm tools current', () => { + const d = read('.github/dependabot.yml'); + for (const [eco, dir] of [['github-actions', '/'], ['docker', '/docker'], ['npm', '/']]) + assert.match(d, new RegExp(`package-ecosystem: ${eco}\\s+directory: ${dir.replace('/', '\\/')}\\n`), eco); +}); + +test('the image is published for releases only, as their version, never as latest', () => { + const w = code('.github/workflows/docker.yml'); + assert.doesNotMatch(w, /:latest\b|\blatest\b.*tags|tags:.*latest/, 'no latest'); + assert.doesNotMatch(w, /\$GITHUB_SHA|github\.sha\b.*tags/, 'no image per commit'); + assert.doesNotMatch(w, /^\s+release:/m, 'releases dispatch it; the release event does not'); + // Only the publish job may push or hold packages: write, and it runs only when a release dispatches it. + const pub = w.slice(w.indexOf('\n publish:')); + const tst = w.slice(w.indexOf('\n test:'), w.indexOf('\n publish:')); + assert.match(pub, /if: github\.event_name == 'workflow_dispatch'/); + assert.match(pub, /needs: test/, 'only an image that passed the smoke test'); + assert.match(pub, /push: true/); + assert.match(pub, /tags: \$\{\{ steps\.meta\.outputs\.image \}\}:\$\{\{ steps\.meta\.outputs\.version \}\}\n/, 'one tag: the version'); + assert.match(pub, /does not match package\.json/, 'the tag must be the release in package.json'); + assert.doesNotMatch(tst, /push: true|packages: write/, 'the test job never publishes'); + assert.match(w, /^permissions:\n {2}contents: read\n/m, 'read-only unless publishing'); + assert.doesNotMatch(w, /pages: write|deploy-pages/, 'never to Pages'); + // auto-release.yml is what dispatches it, with the new tag. + assert.match(read('.github/workflows/auto-release.yml'), /gh workflow run docker\.yml [^\n]*-f tag=/); +}); + +test('the image: pinned base, locked dependencies, only what the servers need, not root', () => { + const d = code('docker/Dockerfile'); + assert.match(d, /^FROM node:\d+-slim@sha256:[0-9a-f]{64}$/m, 'the base is pinned by digest'); + const nodeMajor = /FROM node:(\d+)/.exec(d)[1]; + for (const m of read('.github/workflows/ci.yml').matchAll(/node-version: (\d+)/g)) assert.equal(m[1], nodeMajor, 'the Node major CI tests on'); + assert.match(d, /npm ci\b/); assert.doesNotMatch(d, /npm install\b/); + assert.ok(d.indexOf('COPY package.json package-lock.json') < d.indexOf('npm ci') && d.indexOf('npm ci') < d.indexOf('COPY src'), 'dependencies are their own layer'); + assert.doesNotMatch(d, /^COPY \. /m, 'not the whole repository'); + assert.doesNotMatch(d, /chown -R/, 'no second copy of every file just to change its owner'); + assert.match(d, /^USER node$/m); + const ig = read('.dockerignore').split('\n').filter((l) => l && !l.startsWith('#')); + assert.equal(ig[0], '*', 'the build context is an allow-list'); + for (const m of d.matchAll(/^COPY (?:--\S+ )*(\S+)/gm)) if (m[1] !== 'package.json') assert.ok(ig.includes('!' + m[1]) || ig.includes('!' + m[1] + '/'), `${m[1]} is let into the context`); +}); + +test('the entrypoint: both modes, a token unless told otherwise, and the servers run directly', () => { + const e = code('docker/docker-entrypoint.sh'); + assert.match(e, /browser\|headless/); + assert.match(e, /SOT_MCP_TOKEN=\$\(node -e/, 'makes a token when none is given'); + assert.match(e, /MCP_NO_TOKEN/, 'and can be told not to'); + assert.match(e, /start node scripts\/dev\.js --host 0\.0\.0\.0 --port 8080/); + assert.match(e, /start node scripts\/mcp\.js --browser/); + assert.doesNotMatch(e, /npm run/); + // Every file the image's servers load at start is in the image. + for (const f of ['scripts/mcp.js', 'scripts/dev.js', 'tests/harness.js', 'scripts/lib/page.js']) assert.ok(fs.existsSync(path.join(ROOT, f)), f); +}); From 8ebd1fd425ace4a514ddcc87a190e2481929e8a1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 19:15:05 +0000 Subject: [PATCH 357/491] Tools: Bump jsdom from 24.1.3 to 30.1.3 Bumps [jsdom](https://github.com/jsdom/jsdom) from 24.1.3 to 30.1.3. - [Release notes](https://github.com/jsdom/jsdom/releases) - [Commits](https://github.com/jsdom/jsdom/compare/v24.1.3...v30.1.3) --- updated-dependencies: - dependency-name: jsdom dependency-version: 30.1.3 dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- package-lock.json | 777 +++++++++++++++------------------------------- package.json | 2 +- 2 files changed, 243 insertions(+), 536 deletions(-) diff --git a/package-lock.json b/package-lock.json index 13274d4..9210ed1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "devDependencies": { "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", - "jsdom": "24.1.3", + "jsdom": "30.1.3", "playwright-core": "1.56.0", "ws": "8.22.0" }, @@ -20,23 +20,55 @@ } }, "node_modules/@asamuzakjp/css-color": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", - "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "version": "7.1.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.9.tgz", + "integrity": "sha512-vZ6JQVq8Ivgz6b/IBlAf90wZviXdluY13cQOPO+nJHbmXwGrPl2GcpqUY7a55/8ZVdfONXpCFMpRijOBCHNlcQ==", "dev": true, "license": "MIT", "dependencies": { - "@csstools/css-calc": "^2.1.3", - "@csstools/css-color-parser": "^3.0.9", - "@csstools/css-parser-algorithms": "^3.0.4", - "@csstools/css-tokenizer": "^3.0.3", - "lru-cache": "^10.4.3" + "@csstools/css-calc": "^3.4.3", + "@csstools/css-color-parser": "^4.2.6", + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "10.0.5", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.5.tgz", + "integrity": "sha512-EgmJ7oEaGQECTn3H3wmnQpEy4hKY66VvM7VQndwPIQob3p877BgbyOUE3EX0LgXQCciF2H8KMdR+RznqjMNOLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bidi-js": "^1.1.0", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" } }, "node_modules/@csstools/color-helpers": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", - "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", "dev": true, "funding": [ { @@ -50,13 +82,13 @@ ], "license": "MIT-0", "engines": { - "node": ">=18" + "node": ">=20.19.0" } }, "node_modules/@csstools/css-calc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", - "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", "dev": true, "funding": [ { @@ -70,17 +102,17 @@ ], "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20.19.0" }, "peerDependencies": { - "@csstools/css-parser-algorithms": "^3.0.5", - "@csstools/css-tokenizer": "^3.0.4" + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" } }, "node_modules/@csstools/css-color-parser": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", - "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.7.tgz", + "integrity": "sha512-zgm9yjQz5iJB4VL8RyVwd71TWB8Q89FSxt/NzXoWqPSkEBOVtn9L6vAPtSc9hpKfB0Awo/AL2VKFHjYetBLFHQ==", "dev": true, "funding": [ { @@ -94,21 +126,21 @@ ], "license": "MIT", "dependencies": { - "@csstools/color-helpers": "^5.1.0", - "@csstools/css-calc": "^2.1.4" + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" }, "engines": { - "node": ">=18" + "node": ">=20.19.0" }, "peerDependencies": { - "@csstools/css-parser-algorithms": "^3.0.5", - "@csstools/css-tokenizer": "^3.0.4" + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" } }, "node_modules/@csstools/css-parser-algorithms": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", - "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", "dev": true, "funding": [ { @@ -122,16 +154,41 @@ ], "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20.19.0" }, "peerDependencies": { - "@csstools/css-tokenizer": "^3.0.4" + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.16.tgz", + "integrity": "sha512-LsDbJPP/B8cPasUJyTA5S99F7C4G93ngW8hUluXz8CFeOaaRnBPtBiIlvgcPYU0HmHNz8CXg+1vwFrIB4F6Dgw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } } }, "node_modules/@csstools/css-tokenizer": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", - "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", "dev": true, "funding": [ { @@ -145,7 +202,25 @@ ], "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20.19.0" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } } }, "node_modules/@hono/node-server": { @@ -205,101 +280,42 @@ "node": ">=20" } }, - "node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", "dev": true, "license": "MIT", "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" + "require-from-string": "^2.0.2" } }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", "dev": true, "license": "MIT", "dependencies": { - "delayed-stream": "~1.0.0" + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" }, "engines": { - "node": ">= 0.8" + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" } }, - "node_modules/cssstyle": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", - "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@asamuzakjp/css-color": "^3.2.0", - "rrweb-cssom": "^0.8.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/cssstyle/node_modules/rrweb-cssom": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", - "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", - "dev": true, - "license": "MIT" - }, "node_modules/data-urls": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", - "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", "dev": true, "license": "MIT", "dependencies": { - "whatwg-mimetype": "^4.0.0", - "whatwg-url": "^14.0.0" + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" }, "engines": { - "node": ">=18" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "node": "^22.14.0 || >=24.0.0" } }, "node_modules/decimal.js": { @@ -309,214 +325,19 @@ "dev": true, "license": "MIT" }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/entities": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", - "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=0.12" + "node": ">=20.19.0" }, "funding": { "url": "https://github.com/fb55/entities?sponsor=1" } }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", - "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/form-data": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", - "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.4", - "mime-types": "^2.1.35" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/hono": { "version": "4.13.16", "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.16.tgz", @@ -528,57 +349,16 @@ } }, "node_modules/html-encoding-sniffer": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", - "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", "dev": true, "license": "MIT", "dependencies": { - "whatwg-encoding": "^3.1.1" + "@exodus/bytes": "^1.15.1" }, "engines": { - "node": ">=18" - } - }, - "node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" + "node": "^22.13.0 || >=24.0.0" } }, "node_modules/is-potential-custom-element-name": { @@ -589,39 +369,38 @@ "license": "MIT" }, "node_modules/jsdom": { - "version": "24.1.3", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-24.1.3.tgz", - "integrity": "sha512-MyL55p3Ut3cXbeBEG7Hcv0mVM8pp8PBNWxRqchZnSfAiES1v1mRnMeFfaHWIPULpwsYfvO+ZmMZz5tGCnjzDUQ==", + "version": "30.1.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz", + "integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==", "dev": true, "license": "MIT", "dependencies": { - "cssstyle": "^4.0.1", - "data-urls": "^5.0.0", - "decimal.js": "^10.4.3", - "form-data": "^4.0.0", - "html-encoding-sniffer": "^4.0.0", - "http-proxy-agent": "^7.0.2", - "https-proxy-agent": "^7.0.5", + "@asamuzakjp/css-color": "^7.1.3", + "@asamuzakjp/dom-selector": "^10.0.3", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.15", + "@exodus/bytes": "^1.16.0", + "css-tree": "^3.2.1", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.12", - "parse5": "^7.1.2", - "rrweb-cssom": "^0.7.1", + "lru-cache": "^11.5.3", + "parse5": "^8.0.1", "saxes": "^6.0.0", - "symbol-tree": "^3.2.4", - "tough-cookie": "^4.1.4", - "w3c-xmlserializer": "^5.0.0", - "webidl-conversions": "^7.0.0", - "whatwg-encoding": "^3.1.1", - "whatwg-mimetype": "^4.0.0", - "whatwg-url": "^14.0.0", - "ws": "^8.18.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.1", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.2.0", "xml-name-validator": "^5.0.0" }, "engines": { - "node": ">=18" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "peerDependencies": { - "canvas": "^2.11.2" + "canvas": "^3.2.3" }, "peerDependenciesMeta": { "canvas": { @@ -630,67 +409,30 @@ } }, "node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", "dev": true, - "license": "ISC" - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "dev": true, - "license": "MIT", + "license": "BlueOak-1.0.0", "engines": { - "node": ">= 0.4" + "node": "20 || >=22" } }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/nwsapi": { - "version": "2.2.28", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", - "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", - "dev": true, - "license": "MIT" + "license": "CC0-1.0" }, "node_modules/parse5": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", - "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.0.tgz", + "integrity": "sha512-sq3qBFpee5jeocbFbO48VHlGr8sT7mbXS0vxlKN6sottBtJzrOG3998sr0llSZcQAGgfpdmEYAIZE0P9z0dE8w==", "dev": true, "license": "MIT", "dependencies": { - "entities": "^6.0.0" + "entities": "^9.0.0" }, "funding": { "url": "https://github.com/inikulin/parse5?sponsor=1" @@ -709,19 +451,6 @@ "node": ">=18" } }, - "node_modules/psl": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", - "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "punycode": "^2.3.1" - }, - "funding": { - "url": "https://github.com/sponsors/lupomontero" - } - }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -732,33 +461,15 @@ "node": ">=6" } }, - "node_modules/querystringify": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", - "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", "dev": true, - "license": "MIT" - }, - "node_modules/requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/rrweb-cssom": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", - "integrity": "sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==", - "dev": true, - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } }, "node_modules/saxes": { "version": "6.0.0", @@ -773,122 +484,118 @@ "node": ">=v12.22.7" } }, - "node_modules/symbol-tree": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tldts": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", + "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.20", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz", + "integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==", "dev": true, "license": "MIT" }, "node_modules/tough-cookie": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", - "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" + "tldts": "^7.0.5" }, "engines": { - "node": ">=6" + "node": ">=16" } }, "node_modules/tr46": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", - "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", "dev": true, "license": "MIT", "dependencies": { "punycode": "^2.3.1" }, "engines": { - "node": ">=18" + "node": "^22.14.0 || >=24.0.0" } }, - "node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "node_modules/undici": { + "version": "8.12.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", + "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", "dev": true, "license": "MIT", "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/url-parse": { - "version": "1.5.10", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", - "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "querystringify": "^2.1.1", - "requires-port": "^1.0.0" + "node": ">=22.19.0" } }, "node_modules/w3c-xmlserializer": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", - "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", "dev": true, "license": "MIT", "dependencies": { "xml-name-validator": "^5.0.0" }, "engines": { - "node": ">=18" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=12" - } - }, - "node_modules/whatwg-encoding": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", - "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", - "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", - "dev": true, - "license": "MIT", - "dependencies": { - "iconv-lite": "0.6.3" - }, - "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/whatwg-mimetype": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", - "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", "dev": true, "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/whatwg-url": { - "version": "14.2.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", - "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", "dev": true, "license": "MIT", "dependencies": { - "tr46": "^5.1.0", - "webidl-conversions": "^7.0.0" + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" }, "engines": { - "node": ">=18" + "node": "^22.14.0 || >=24.0.0" } }, "node_modules/ws": { diff --git a/package.json b/package.json index 35e9aa0..cf12d46 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "devDependencies": { "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", - "jsdom": "24.1.3", + "jsdom": "30.1.3", "playwright-core": "1.56.0", "ws": "8.22.0" } From 8d3db207be73638b3d2eaa2b03bbe201e50ef8d7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 19:15:08 +0000 Subject: [PATCH 358/491] CI: Bump the actions group with 2 updates Bumps the actions group with 2 updates: [actions/download-artifact](https://github.com/actions/download-artifact) and [actions/upload-artifact](https://github.com/actions/upload-artifact). Updates `actions/download-artifact` from 4.3.0 to 8.0.2 - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/d3f86a106a0bac45b974a628896c90dbdf5c8093...9000827ccba6bdab643e8b6fd33ac0654aef8333) Updates `actions/upload-artifact` from 4.6.2 to 7.0.2 - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/ea165f8d65b6e75b540449e92b4886f43607fa02...cf430e030ddbb5b0abf93d22962f4752f3646cd9) --- updated-dependencies: - dependency-name: actions/download-artifact dependency-version: 8.0.2 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/upload-artifact dependency-version: 7.0.2 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions ... Signed-off-by: dependabot[bot] --- .github/workflows/perf-comment.yml | 2 +- .github/workflows/perf.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/perf-comment.yml b/.github/workflows/perf-comment.yml index ca461da..9508742 100644 --- a/.github/workflows/perf-comment.yml +++ b/.github/workflows/perf-comment.yml @@ -17,7 +17,7 @@ jobs: if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-latest steps: - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: perf run-id: ${{ github.event.workflow_run.id }} diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index 00ffce2..f2657ab 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -48,7 +48,7 @@ jobs: env: PR: ${{ github.event.pull_request.number }} run: echo "$PR" > pr-number.txt - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: github.event_name == 'pull_request' with: name: perf From 131e2f7b9c5cc8078882b255e0472db2aa695a57 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 20:15:44 +0100 Subject: [PATCH 359/491] Container smoke test: container names Docker accepts A name must be at least two characters; the build itself passed. --- .github/workflows/docker.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 2deeef2..9bcb23a 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -70,29 +70,29 @@ jobs: until_up() { for i in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; docker logs "$2"; exit 1; } # Headless, with a token: refused without it, answered with it. - docker run -d --name h -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=ci-token sot:test - until_up http://127.0.0.1:7777/ h + docker run -d --name sot-h -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:7777/ sot-h test "$(mcp)" = 401 test "$(mcp -H 'authorization: Bearer ci-token')" = 200 grep -q serverInfo /tmp/out - docker rm -f h + docker rm -f sot-h # No token given: the container makes one, says so, and wants it. - docker run -d --name t -p 127.0.0.1:7777:7777 -e MCP_MODE=headless sot:test - until_up http://127.0.0.1:7777/ t + docker run -d --name sot-t -p 127.0.0.1:7777:7777 -e MCP_MODE=headless sot:test + until_up http://127.0.0.1:7777/ sot-t test "$(mcp)" = 401 - tok=$(docker logs t 2>&1 | sed -n "s/.*this run's token is //p" | head -1) + tok=$(docker logs sot-t 2>&1 | sed -n "s/.*this run's token is //p" | head -1) test -n "$tok" test "$(mcp -H "authorization: Bearer $tok")" = 200 - docker rm -f t + docker rm -f sot-t # Browser mode: the development page and the MCP server. - docker run -d --name b -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 -e SOT_MCP_TOKEN=ci-token sot:test - until_up http://127.0.0.1:8080/ b + docker run -d --name sot-b -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:8080/ sot-b test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/)" = 200 - until_up http://127.0.0.1:7777/ b + until_up http://127.0.0.1:7777/ sot-b test "$(mcp -H 'authorization: Bearer ci-token')" = 200 - docker rm -f b + docker rm -f sot-b # The server runs as node, not root. test "$(docker run --rm --entrypoint id sot:test -u)" != 0 From 478e767c83282a91e885ba0689acdcd3d87eeab1 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 20:25:23 +0100 Subject: [PATCH 360/491] Latency test: no padding is zero however the DOM spells it jsdom 30 reports an unset padding as '0', not '0px', which failed the check for the yellow bars in the jsdom update (#302). --- tests/latency.test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/latency.test.js b/tests/latency.test.js index 5a4714e..9e7bb58 100644 --- a/tests/latency.test.js +++ b/tests/latency.test.js @@ -57,8 +57,9 @@ test('the slow-city warning box does not restyle the yellow progress bars', () = const { ev, errors } = load(); // .bar.warn is the yellow bar; the latency box once used a plain .warn class and padded every yellow bar const st = JSON.parse(ev(`(()=>{const b=document.createElement('div');b.className='bar warn';const w=document.createElement('div');w.className='latwarn';document.body.append(b,w); - const a=getComputedStyle(b),c=getComputedStyle(w);return JSON.stringify({bar:a.paddingTop+a.paddingLeft,box:c.paddingTop});})()`)); - assert.ok(!st.bar || st.bar === '0px0px', `yellow bars have no padding (${st.bar})`); + const a=getComputedStyle(b),c=getComputedStyle(w);return JSON.stringify({bar:[a.paddingTop,a.paddingLeft],box:c.paddingTop});})()`)); + // No padding reads as '', '0px' or (jsdom 30) '0', depending on the DOM: any of them is zero. + assert.ok(st.bar.every((v) => !v || parseFloat(v) === 0), `yellow bars have no padding (${st.bar})`); assert.equal(st.box, '8px', 'the warning box keeps its own'); assert.deepEqual(errors, []); }); From 1a6c63e920a8c6486c3fb3171ec1736a71ddd25f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 20:35:55 +0100 Subject: [PATCH 361/491] Tools: playwright-core 1.64.1, ws 8.22.1 (#301) Dependabot's group update, applied on top of the jsdom update (#302), whose lockfile it conflicted with. --- package-lock.json | 18 +++++++++--------- package.json | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9210ed1..23919c8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,8 +12,8 @@ "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", "jsdom": "30.1.3", - "playwright-core": "1.56.0", - "ws": "8.22.0" + "playwright-core": "1.64.1", + "ws": "8.22.1" }, "engines": { "node": ">=20" @@ -439,16 +439,16 @@ } }, "node_modules/playwright-core": { - "version": "1.56.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.0.tgz", - "integrity": "sha512-1SXl7pMfemAMSDn5rkPeZljxOCYAmQnYLBTExuh6E8USHXGSX3dx6lYZN/xPpTz1vimXmPA9CDnILvmJaB8aSQ==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "dev": true, "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" }, "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/punycode": { @@ -599,9 +599,9 @@ } }, "node_modules/ws": { - "version": "8.22.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", - "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "version": "8.22.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", + "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index cf12d46..80fbae3 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", "jsdom": "30.1.3", - "playwright-core": "1.56.0", - "ws": "8.22.0" + "playwright-core": "1.64.1", + "ws": "8.22.1" } } From e7729d0a1ef6d95d7d35b4d84e231e18ea4e3678 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 21:04:21 +0100 Subject: [PATCH 362/491] Harden workflows and dev scripts against code-scanning findings - auto-release: pass step outputs to run scripts through env, not ${{ }} interpolation - perf-comment: download the PR's perf artifact to RUNNER_TEMP, outside the workspace - dev server: log errors to the terminal instead of sending stack traces in the response - i18n-add/i18n-check: escape every regex metacharacter when building patterns from labels --- .github/workflows/auto-release.yml | 18 +++++++++++++----- .github/workflows/perf-comment.yml | 3 +++ scripts/dev.js | 4 +++- scripts/i18n-add.js | 2 +- scripts/i18n-check.js | 2 +- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 4d41153..ae6a513 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -63,20 +63,28 @@ jobs: - name: Publish the release if: steps.v.outputs.skip == 'false' + env: + TAG: ${{ steps.v.outputs.tag }} + VER: ${{ steps.v.outputs.ver }} + PRE: ${{ steps.v.outputs.pre }} run: | set -euo pipefail - pre=(); [ "${{ steps.v.outputs.pre }}" = "true" ] && pre=(--prerelease) - gh release create "${{ steps.v.outputs.tag }}" --repo "$GITHUB_REPOSITORY" \ - --target "$GITHUB_SHA" --title "${{ steps.v.outputs.ver }}" --notes-file notes.md "${pre[@]}" + pre=(); [ "$PRE" = "true" ] && pre=(--prerelease) + gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \ + --target "$GITHUB_SHA" --title "$VER" --notes-file notes.md "${pre[@]}" - name: Deploy it # Pre-releases are for testing and never go live. if: steps.v.outputs.skip == 'false' && steps.v.outputs.pre == 'false' - run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}" + env: + TAG: ${{ steps.v.outputs.tag }} + run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" - name: Publish the Docker image # Same pattern as the deploy above: the image is built and pushed from the # release tag by docker.yml. Pre-releases get one too: an image tag is # pulled on purpose, so a test image costs nothing. if: steps.v.outputs.skip == 'false' - run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}" + env: + TAG: ${{ steps.v.outputs.tag }} + run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" diff --git a/.github/workflows/perf-comment.yml b/.github/workflows/perf-comment.yml index 9508742..a214fff 100644 --- a/.github/workflows/perf-comment.yml +++ b/.github/workflows/perf-comment.yml @@ -20,6 +20,8 @@ jobs: - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: perf + # Outside the workspace: the files come from a PR's run and are only ever read as text. + path: ${{ runner.temp }}/perf run-id: ${{ github.event.workflow_run.id }} github-token: ${{ secrets.GITHUB_TOKEN }} - name: Post or update the comment @@ -28,6 +30,7 @@ jobs: REPO: ${{ github.repository }} HEAD_SHA: ${{ github.event.workflow_run.head_sha }} run: | + cd "$RUNNER_TEMP/perf" pr=$(tr -cd '0-9' < pr-number.txt) [ -n "$pr" ] || { echo "no PR number"; exit 0; } # Trust the number only if that PR's head is the commit that was benchmarked. diff --git a/scripts/dev.js b/scripts/dev.js index 79b10b7..2a5ffda 100644 --- a/scripts/dev.js +++ b/scripts/dev.js @@ -53,8 +53,10 @@ const server = http.createServer((req, res) => { res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); fs.createReadStream(file).pipe(res); } catch (e) { + // The stack goes to the terminal running the server, never into the response. + console.error(e); res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); - res.end(String(e && e.stack || e)); + res.end('Could not build the page: see the terminal running npm run dev.'); } }); const relay = createRelay({ server }); diff --git a/scripts/i18n-add.js b/scripts/i18n-add.js index 27468e5..027b3db 100644 --- a/scripts/i18n-add.js +++ b/scripts/i18n-add.js @@ -36,7 +36,7 @@ if (args[0] === '--rename') { for (const f of listFiles(src)) { if (f === 'i18n/en.js') continue; const p = path.join(src, f), t = fs.readFileSync(p, 'utf8'); - const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/\./g, '\\.')}\1`, 'g'), (m, q) => { n++; return q + to + q; }); + const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\1`, 'g'), (m, q) => { n++; return q + to + q; }); if (u !== t) fs.writeFileSync(p, u); } console.log(`renamed ${from} → ${to} in every dictionary and ${n} place(s) in src/`); diff --git a/scripts/i18n-check.js b/scripts/i18n-check.js index fd21bb2..eacf61a 100644 --- a/scripts/i18n-check.js +++ b/scripts/i18n-check.js @@ -103,7 +103,7 @@ function registration(lang, html) { const sw = fs.readFileSync(path.join(SITE, 'sw.js'), 'utf8'); const out = []; const m = html.match(/SOT_LANGS=\{([^}]*)\}/); - if (!m || !new RegExp(String.raw`(^|[,{\s])${lang}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in src/index.html)'); + if (!m || !new RegExp(String.raw`(^|[,{\s])${lang.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in src/index.html)'); if (!sw.includes(`/i18n/${lang}.js`)) out.push('not cached for offline play (CORE in site/sw.js)'); if (!D.tidy(lang)) out.push('not sorted one entry per line: run npm run i18n:fix'); return out; From dd6e4f4f8a999e08fb932015e7dbbff19de8f9d0 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 21:24:26 +0100 Subject: [PATCH 363/491] Fix CodeQL code-scanning alerts - Values pasted into eval'd or inline-script code go through lit() (scripts/lib/js-literal.js), which escapes <, >, /, U+2028 and U+2029 after JSON.stringify - build test and i18n-check read script tags with a DOM parser or a plain search, not HTML regexes - mcp.js parses the Authorization header without a backtracking regex --- scripts/dev.js | 3 ++- scripts/gpu-bench.js | 3 ++- scripts/i18n-check.js | 13 ++++++++++++- scripts/lib/js-literal.js | 5 +++++ scripts/lib/scenario-bot.js | 5 +++-- scripts/lib/scenario-ref.js | 3 ++- scripts/mcp.js | 5 +++-- scripts/perf-bench.js | 3 ++- scripts/weekly-architect.js | 17 +++++++++-------- scripts/weekly-puzzle.js | 17 +++++++++-------- scripts/weekly-scenario.js | 11 ++++++----- tests/agent-relay.test.js | 3 ++- tests/agent-settings.test.js | 3 ++- tests/any-home-city.test.js | 3 ++- tests/automation.test.js | 5 +++-- tests/backbone-core.test.js | 3 ++- tests/badges-variants.test.js | 7 ++++--- tests/bilbao-landing.test.js | 3 ++- tests/build.test.js | 9 +++++---- tests/cache-ports.test.js | 3 ++- tests/call-the-bank.test.js | 7 ++++--- tests/chaos-monkey.test.js | 3 ++- tests/compute-idempotent.test.js | 3 ++- tests/customer-lifecycle.test.js | 9 +++++---- tests/ddos-floods.test.js | 3 ++- tests/ddos-model.test.js | 11 ++++++----- tests/ddos-scrub-clean.test.js | 7 ++++--- tests/diagnostic-info.test.js | 5 +++-- tests/find-city.test.js | 3 ++- tests/gameplay-rules.test.js | 5 +++-- tests/gangnam.test.js | 3 ++- tests/gpu-bench.test.js | 5 +++-- tests/i18n.test.js | 5 +++-- tests/intern-optics.test.js | 7 ++++--- tests/intern-ports.test.js | 3 ++- tests/issues.test.js | 11 ++++++----- tests/latency-offers.test.js | 3 ++- tests/levels.test.js | 3 ++- tests/link-preconditions.test.js | 7 ++++--- tests/load-time.test.js | 3 ++- tests/map-2d-sprite-budget.test.js | 3 ++- tests/map-2d.test.js | 17 +++++++++-------- tests/mcp-parity.test.js | 3 ++- tests/modes.test.js | 9 +++++---- tests/noc-window.test.js | 7 ++++--- tests/own-asn.test.js | 3 ++- tests/peering-desk.test.js | 3 ++- tests/persist.test.js | 7 ++++--- tests/pop-standard.test.js | 3 ++- tests/puzzles.test.js | 7 ++++--- tests/regions.test.js | 15 ++++++++------- tests/release-story.test.js | 3 ++- tests/route-cache.test.js | 3 ++- tests/route-fuzz.test.js | 3 ++- tests/route-server-peers.test.js | 3 ++- tests/route-skip.test.js | 7 ++++--- tests/route-worker.test.js | 3 ++- tests/routing-reference.test.js | 3 ++- tests/rules-locked.test.js | 9 +++++---- tests/rules.test.js | 7 ++++--- tests/sales-desk.test.js | 5 +++-- tests/sales-trial.test.js | 15 ++++++++------- tests/save-size.test.js | 3 ++- tests/save-slots.test.js | 15 ++++++++------- tests/save-text.test.js | 3 ++- tests/scenarios-playtest.test.js | 3 ++- tests/sea-routing.test.js | 7 ++++--- tests/services.test.js | 3 ++- tests/specialist.test.js | 5 +++-- tests/speed.test.js | 5 +++-- tests/standing-orders.test.js | 5 +++-- tests/tier1-cone.test.js | 3 ++- tests/traceroute-modes.test.js | 3 ++- tests/unbuilt-pops.test.js | 7 ++++--- tests/utilities-caches.test.js | 3 ++- tests/utilities.test.js | 5 +++-- tests/webgl-coast.test.js | 3 ++- tests/webgl-context-restore.test.js | 3 ++- tests/webgl-frame-garbage.test.js | 3 ++- tests/webgl-line-joins.test.js | 3 ++- tests/webgl-map.test.js | 9 +++++---- tests/webgl-out-of-memory.test.js | 7 ++++--- tests/webgl-sprites.test.js | 3 ++- tests/webgl-zoom-sprites.test.js | 3 ++- tests/weekly-architect.test.js | 9 +++++---- tests/weekly-puzzle.test.js | 23 ++++++++++++----------- tests/weekly-scenario.test.js | 17 +++++++++-------- tests/where-things-happen.test.js | 3 ++- tests/world-layer-firefox.test.js | 5 +++-- 89 files changed, 316 insertions(+), 213 deletions(-) create mode 100644 scripts/lib/js-literal.js diff --git a/scripts/dev.js b/scripts/dev.js index 2a5ffda..2f4fab5 100644 --- a/scripts/dev.js +++ b/scripts/dev.js @@ -12,6 +12,7 @@ const http = require('node:http'); const path = require('node:path'); const { assemble, ROOT } = require('./lib/page'); const { createRelay } = require('./agent/relay'); +const { lit } = require('./lib/js-literal'); // --host/--port; a bare --host binds loopback (never undefined, which would listen on every interface). const argOf = (k) => { const i = process.argv.indexOf(k); return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--') ? process.argv[i + 1] : null; }; @@ -27,7 +28,7 @@ const clients = new Set(); function page() { const { html, map } = assemble({ dev: true }); // Errors report a line of the assembled page; the console also says which file under src/ that is. - const hint = ``; + const hint = ``; return html.replace('', `${hint}${RELOAD}`); } diff --git a/scripts/gpu-bench.js b/scripts/gpu-bench.js index b2e45ff..59ed482 100644 --- a/scripts/gpu-bench.js +++ b/scripts/gpu-bench.js @@ -15,6 +15,7 @@ const os = require('node:os'); const http = require('node:http'); const path = require('node:path'); const { assemble, ROOT } = require('./lib/page'); +const { lit } = require('./lib/js-literal'); const args = process.argv.slice(2); const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; }; @@ -27,7 +28,7 @@ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; ch // An exported save is {app, version, S}; a plain one is S itself. const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); return JSON.stringify({ S: d && d.S && d.S.pops ? d.S : d }); })(); const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8'); -const page = () => assemble().html.replace('', ``); +const page = () => assemble().html.replace('', ``); /* Only the page this server hands out may talk to it. Any other site open in the same browser could otherwise POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host diff --git a/scripts/i18n-check.js b/scripts/i18n-check.js index eacf61a..7db2676 100644 --- a/scripts/i18n-check.js +++ b/scripts/i18n-check.js @@ -20,10 +20,21 @@ const SITE = path.join(__dirname, '..', 'site'); const page = () => require('./lib/page').assemble({ dev: true }).html; const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/; +// The bodies of the page's bare ', i += 8); + if (end < 0) break; + out.push(html.slice(i, end)); i = end; + } + return out; +} + // The labels the game uses, with problems in how they are used. function sourceLabels(html) { const labels = new Set(), problems = []; - const scripts = [...html.matchAll(/'; +const MP = process.argv.includes('--mp') ? require('./lib/mp').createMp({ dir: path.join(ROOT, 'mp-data'), createPerHour: 1000, joinPerHour: 1000, log: (s) => console.error(s) }) : null; const clients = new Set(); function page() { const { html, map } = assemble({ dev: true }); // Errors report a line of the assembled page; the console also says which file under src/ that is. const hint = ``; - return html.replace('', `${hint}${RELOAD}`); + return (MP ? html.replace("/*__MP_API__*/''", () => "'/api/mp'") : html).replace('', `${hint}${RELOAD}`); } const server = http.createServer((req, res) => { const url = new URL(req.url, 'http://localhost'); + if (MP && MP.handle(req, res)) return; if (url.pathname === '/__dev') { res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' }); res.write(': hi\n\n'); @@ -69,6 +73,7 @@ server.listen(PORT, HOST, () => { console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`); console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`); console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser'); + if (MP) console.error(`[series-of-tubes] multiplayer on: API at http://${at}/api/mp, sessions in ${path.relative(ROOT, MP.dir) || MP.dir}/`); }); const shutdown = () => { relay.close(); process.exit(0); }; process.on('SIGINT', shutdown); diff --git a/scripts/lib/mp.js b/scripts/lib/mp.js new file mode 100644 index 0000000..051c1cc --- /dev/null +++ b/scripts/lib/mp.js @@ -0,0 +1,448 @@ +// The multiplayer API (docs/MULTIPLAYER.md): sessions players share by a short code, each player's save kept on the +// server, and a small public card per player for the session's leaderboard and feed. Plain node:http, no dependencies. +// scripts/mp-server.js runs it on its own (optionally serving the built site too); npm run dev -- --mp mounts it in the +// dev server. It is never part of the page or of site/: the page only talks to it when the build stamped MP_API. +// +// Storage: one JSON file per session (DIR/.json: settings, players, cards, feed) and one file per player's save +// (DIR/..save), kept apart so a card push never rewrites a dozen saves. Writes go to a temporary file and are +// renamed into place, one session at a time, in order. A session code is checked against CODE_RE before it ever becomes +// part of a file name, and so is a player id. +const fs = require('node:fs'); +const path = require('node:path'); +const net = require('node:net'); +const crypto = require('node:crypto'); + +// Crockford's base32 (no I, L, O or U): codes read aloud or typed from a phone do not get mixed up. +const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; +const CODE_RE = /^[0-9A-HJKMNP-TV-Z]{6}$/; +const PID_RE = /^[a-z0-9]{8}$/; +const TOKEN_RE = /^[0-9a-f]{64}$/; +const PRESETS = ['soft', 'freeze', 'oncall', 'bgp']; +const PPOL = ['open', 'selective', 'closed']; +const TIERS = ['t1', 't2', 't3']; +const ASN_LO = 200000, ASN_HI = 214999; +const COLORS = ['#ff4f9a', '#3a86ff', '#ffbe0b', '#2ec4b6', '#8338ec', '#fb5607', '#06d6a0', '#e63946', '#118ab2', '#8ac926', '#b5179e', '#6c757d']; +const MAX_SAVE = 4 * 1024 * 1024; // characters of save text ('gz:'+base64 or JSON) +const LIMIT = { small: 16 * 1024, save: MAX_SAVE + 64 * 1024 }; +const SAVE_MS = 120000; // a save's body must arrive within this, or the upload is cut (it holds one of few places) +const FEED_MAX = 100, CHAT_MAX = 200; +const DAY = 86400000; + +// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code itself, or null. I, L and O are read as 1, 1 and 0, as Crockford meant. +function normCode(s) { + if (typeof s !== 'string' || s.length > 20) return null; + const c = s.toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0'); + return CODE_RE.test(c) ? c : null; +} +const showCode = (c) => c.slice(0, 3) + '-' + c.slice(3); +const randCode = () => { const b = crypto.randomBytes(6); let s = ''; for (const x of b) s += ALPHA[x & 31]; return s; }; +const randPid = () => crypto.randomBytes(4).toString('hex'); +const sha = (t) => crypto.createHash('sha256').update(t).digest(); + +// Text from players: no control or bidi-override characters, none of <>&"'` (the page escapes everything anyway), one +// space between words, at most max characters (whole characters, never half an emoji). +function cleanText(v, max) { + if (typeof v !== 'string') return ''; + const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩<>&"'`]/g, '').replace(/\s+/g, ' ').trim(); + return Array.from(s).slice(0, max).join('').trim(); +} +const cleanChat = (v) => { + if (typeof v !== 'string') return ''; + const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim(); + return Array.from(s).slice(0, CHAT_MAX).join('').trim(); +}; +const num = (v, lo, hi, d = 0) => { v = +v; if (!Number.isFinite(v)) return d; return Math.min(hi, Math.max(lo, v)); }; +const int = (v, lo, hi, d = 0) => Math.round(num(v, lo, hi, d)); +// Only the first few times max entries are even looked at: a card padded with copies costs no more than an honest one. +const ids = (v, re, max) => { + if (!Array.isArray(v)) return []; + const out = new Set(); + for (const x of v.slice(0, max * 4)) { if (typeof x === 'string' && re.test(x)) out.add(x); if (out.size >= max) break; } + return [...out]; +}; +const CITY_RE = /^[a-z0-9]{2,8}$/, IX_RE = /^[a-z0-9~_-]{1,16}$/, NET_RE = /^[a-z0-9]{1,12}$/; + +/* A player's public card: only these fields, numbers clamped, ids only in their shape (the page checks them against its + catalogs again: this is other players' data there). Name and AS number come from the server, never from the card. */ +function cleanCard(c) { + if (!c || typeof c !== 'object' || Array.isArray(c)) return null; + const links = []; + if (Array.isArray(c.links)) for (const l of c.links.slice(0, 1200)) { + if (!Array.isArray(l) || typeof l[0] !== 'string' || typeof l[1] !== 'string' || !CITY_RE.test(l[0]) || !CITY_RE.test(l[1]) || l[0] === l[1]) continue; + links.push([l[0], l[1], num(l[2], 0, 1e7)]); + if (links.length >= 300) break; + } + return { + day: int(c.day, 0, 1e7), tier: TIERS.includes(c.tier) ? c.tier : 't3', t1: c.t1 === true, lvl: int(c.lvl, 0, 99), + pops: ids(c.pops, CITY_RE, 500), links, ix: ids(c.ix, IX_RE, 500), transit: ids(c.transit, NET_RE, 64), + ppol: PPOL.includes(c.ppol) ? c.ppol : 'open', reach: num(c.reach, 0, 1), peak: num(c.peak, 0, 1e9), served: num(c.served, 0, 1e9), + cust: int(c.cust, 0, 1e7), rev: num(c.rev, -1e13, 1e13), cashB: int(c.cashB, -1, 20), score: num(c.score, 0, 1e15), + }; +} + +/* Small in-memory rate limits: at most n events per window for one key (an address, a player). Keys are kept in the + order they were last seen, so the ones nobody used for a whole window go from the front, a few at a time, and above + cap keys the oldest go too: memory stays bounded and no call ever walks the whole map. */ +function limiter(n, ms, cap = 20000) { + const m = new Map(); + const live = (k, now) => { const a = m.get(k); return a ? a.filter((t) => now - t < ms) : []; }; + return { + // Counts one more, unless the key is already at its limit. + ok(k, now) { + const a = live(k, now), ok = a.length < n; + if (ok) a.push(now); + m.delete(k); m.set(k, a); + for (const [x, v] of m) { if (m.size > cap || !v.length || now - v[v.length - 1] >= ms) m.delete(x); else break; } + return ok; + }, + full: (k, now) => live(k, now).length >= n, + size: () => m.size, + }; +} + +/* The address a limit counts against. One IPv6 customer (a phone, a home, a server) usually holds a whole /64, so an + IPv6 address counts as its /64; an IPv4 address mapped into IPv6 counts as itself. null: not an address. */ +function addrKey(a) { + a = String(a || '').trim(); + if (a.startsWith('[')) a = a.slice(1, a.indexOf(']') >>> 0); + const z = a.indexOf('%'); if (z >= 0) a = a.slice(0, z); + const m4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(a); if (m4) a = m4[1]; + const v = net.isIP(a); + if (v === 4) return a; + if (v !== 6) return null; + const [h, t] = a.toLowerCase().split('::'), head = h ? h.split(':') : [], tail = t ? t.split(':') : []; + // The groups :: stands for (a dotted IPv4 at the end is two of them). + const n = head.length + tail.length + (tail.length && tail[tail.length - 1].includes('.') ? 1 : 0); + const g = t === undefined ? head : [...head, ...Array(8 - n).fill('0'), ...tail]; + return g.slice(0, 4).map((x) => parseInt(x, 16).toString(16)).join(':') + '::/64'; +} + +class HttpError extends Error { constructor(status, msg, extra) { super(msg); this.status = status; this.extra = extra; } } +const fail = (status, msg, extra) => { throw new HttpError(status, msg, extra); }; + +// The request body as JSON, refusing it as soon as it is longer than max bytes (never buffered beyond that). A body that +// has not arrived within ms is cut off: it would hold its place (and its memory) for as long as the sender likes. +function readJson(req, max, ms = 30000) { + return new Promise((resolve, reject) => { + const ct = String(req.headers['content-type'] || ''); + if (!/^application\/json\b/i.test(ct)) { req.resume(); return reject(new HttpError(415, 'send JSON (content-type: application/json)')); } + const len = +req.headers['content-length']; + if (len > max) { req.resume(); return reject(new HttpError(413, 'too large')); } + let parts = [], n = 0, done = false; + const stop = (e) => { if (done) return; done = true; clearTimeout(tm); parts = null; reject(e); }; + const tm = setTimeout(() => { stop(new HttpError(408, 'too slow')); req.destroy(); }, ms); + req.on('data', (b) => { + if (done) return; + n += b.length; + if (n > max) { stop(new HttpError(413, 'too large')); req.resume(); return; } + parts.push(b); + }); + req.on('end', () => { + if (done) return; done = true; clearTimeout(tm); + let j; + try { const t = Buffer.concat(parts).toString('utf8'); parts = null; j = JSON.parse(t); } catch (e) { return reject(new HttpError(400, 'bad JSON')); } + if (!j || typeof j !== 'object' || Array.isArray(j)) return reject(new HttpError(400, 'expected a JSON object')); + resolve(j); + }); + req.on('error', () => stop(new HttpError(400, 'request failed'))); + req.on('close', () => { if (!req.complete) stop(new HttpError(400, 'request failed')); }); + }); +} + +function send(res, status, body) { + if (res.headersSent) { try { res.end(); } catch (e) { /* gone */ } return; } + const txt = JSON.stringify(body); + res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(txt) }); + res.end(txt); +} + +/* createMp({dir, base, maxSessions, maxPlayers, pruneDays, trustProxy, verbose, log, now, ...limits}): the API. + handle(req, res) answers anything under base (default /api/mp) and returns true, or returns false for everything else. */ +function createMp(o = {}) { + const dir = path.resolve(o.dir || 'mp-data'); + const base = (o.base || '/api/mp').replace(/\/+$/, ''); + const maxSessions = o.maxSessions || 1000, maxPlayers = o.maxPlayers || 12, pruneDays = o.pruneDays || 60; + const now = o.now || Date.now, log = o.log || ((s) => console.log(s)); + fs.mkdirSync(dir, { recursive: true }); + const file = (code) => path.join(dir, code + '.json'); + const saveFile = (code, pid) => path.join(dir, `${code}.${pid}.save`); + const cache = new Map(), chains = new Map(), soon = new Map(); + let codes = new Set(), tmpN = 0; + const HOUR = 3600000, MIN = 60000; + const createRate = limiter(o.createPerHour || 10, HOUR), joinRate = limiter(o.joinPerHour || 60, HOUR); + // However many addresses ask, the server fills up slowly: a full server takes days, not minutes. + const createAll = limiter(o.sessionsPerHour || 100, HOUR); + const chatRate = limiter(6, 30000), chatGap = limiter(1, 1000); + // Wrong codes, counted per address: guessing codes runs out long before it finds one. + const missRate = limiter(o.missesPerHour || 120, HOUR); + // A player's pushes. The game sends a save at most every 15 seconds and a card with it, so these never touch it; they + // stop one player from keeping the disk busy rewriting their session. + const saveRate = limiter(o.savesPerMinute || 20, MIN), cardRate = limiter(o.cardsPerMinute || 60, MIN); + // Saves being uploaded: one per player, a few per address, a few more on the whole server. Each can hold megabytes. + const up = new Set(), upAddr = new Map(), maxUploads = o.maxUploads || 16, maxUploadsAddr = o.maxUploadsPerAddress || 4; + + // Atomic: write a temporary file next to it, then rename over the old one. + const writeAtomic = async (f, txt) => { + const tmp = `${f}.${process.pid}.${++tmpN}.tmp`; + await fs.promises.writeFile(tmp, txt); + await fs.promises.rename(tmp, f); + }; + // One session's writes happen one after another, in the order they were asked for. + const queue = (code, job) => { + const p = (chains.get(code) || Promise.resolve()).then(job, job); + const q = p.catch((e) => { log(`[mp] writing ${code} failed: ${e.message}`); }); + chains.set(code, q); + q.then(() => { if (chains.get(code) === q) chains.delete(code); }); + return p; + }; + // A session that is gone (its last player left) is never written again, whatever was still on its way. + const persist = (s) => { + const tm = soon.get(s.code); if (tm) { clearTimeout(tm); soon.delete(s.code); } + s.touched = now(); + if (s.dead) return Promise.resolve(); + return queue(s.code, () => s.dead ? null : writeAtomic(file(s.code), JSON.stringify(s))); + }; + // Cards change often and matter little: their session is written a moment later, once for all of that moment's. + const persistSoon = (s) => { + s.touched = now(); + if (s.dead || soon.has(s.code)) return; + const tm = setTimeout(() => { soon.delete(s.code); persist(s); }, o.persistMs ?? 2000); + if (tm.unref) tm.unref(); + soon.set(s.code, tm); + }; + + function scan() { codes = new Set(); for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.json$/.exec(f); if (m && CODE_RE.test(m[1])) codes.add(m[1]); } } + // Sessions nobody touched for pruneDays go, with their saves; so do leftovers of interrupted writes. + function prune() { + const cut = now() - pruneDays * DAY; let n = 0; + for (const f of fs.readdirSync(dir)) { + const p = path.join(dir, f); + let st; try { st = fs.statSync(p); } catch (e) { continue; } + if (!st.isFile()) continue; + if (f.endsWith('.tmp') && st.mtimeMs < now() - 3600000) { fs.rmSync(p, { force: true }); continue; } + const m = /^([0-9A-Z]{6})\.json$/.exec(f); + const live = m && cache.get(m[1]); + if (m && CODE_RE.test(m[1]) && st.mtimeMs < cut && !(live && live.touched >= cut)) { drop(m[1]); n++; } + } + for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.[a-z0-9]{8}\.save$/.exec(f); if (m && !fs.existsSync(file(m[1]))) fs.rmSync(path.join(dir, f), { force: true }); } + scan(); + return n; + } + function drop(code) { + const s = cache.get(code); if (s) s.dead = true; + const tm = soon.get(code); if (tm) { clearTimeout(tm); soon.delete(code); } + for (const f of fs.readdirSync(dir)) if (f === code + '.json' || (f.startsWith(code + '.') && f.endsWith('.save'))) fs.rmSync(path.join(dir, f), { force: true }); + cache.delete(code); codes.delete(code); + } + function load(code) { + if (!CODE_RE.test(code)) return null; + if (cache.has(code)) return cache.get(code); + if (!codes.has(code)) return null; + let s = null; + try { s = JSON.parse(fs.readFileSync(file(code), 'utf8')); } catch (e) { return null; } + if (!s || s.code !== code || !Array.isArray(s.players)) return null; + // A hand-edited or damaged file: players without an id or a token hash cannot be anyone. + s.players = s.players.filter((p) => p && typeof p === 'object' && PID_RE.test(p.pid) && typeof p.th === 'string'); + for (const p of s.players) if (!p.hit || typeof p.hit !== 'object') p.hit = { t1: !!(p.card && p.card.t1), t2: !!(p.card && (p.card.t1 || p.card.tier !== 't3')) }; + if (!Array.isArray(s.feed)) s.feed = []; + cache.set(code, s); + return s; + } + prune(); + + // The client's address, as the limits count it (see addrKey); behind your own proxy, the one it added last. + const ipOf = (req) => { + if (o.trustProxy) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map((v) => v.trim()).filter(Boolean); const k = x.length && addrKey(x[x.length - 1]); if (k) return k; } + return addrKey(req.socket.remoteAddress) || '?'; + }; + // The player this request's token belongs to, or null. Compares hashes of the same length, in constant time, even for + // a player who is not there. + function player(req, s) { + const m = /^Bearer ([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(String(req.headers.authorization || '')); + if (!m) return null; + const p = s.players.find((x) => x.pid === m[1]); + const want = p && /^[0-9a-f]{64}$/.test(p.th) ? Buffer.from(p.th, 'hex') : Buffer.alloc(32), got = sha(m[2]); + return crypto.timingSafeEqual(want, got) && p ? p : null; + } + const authed = (p) => { if (!p) fail(401, 'unauthorized'); p.seen = now(); return p; }; + // Still there after waiting for a body or a write: the player may have left meanwhile, or the session gone with them. + const still = (s, p) => !s.dead && cache.get(s.code) === s && (!p || s.players.includes(p)); + const event = (s, k, p, extra) => { s.feed.push({ k, pid: p.pid, name: p.name, at: now(), ...extra }); if (s.feed.length > FEED_MAX) s.feed.splice(0, s.feed.length - FEED_MAX); }; + const roster = (s) => ({ + code: s.code, title: s.title, preset: s.preset, seed: s.seed, created: s.created, + players: s.players.map((p) => ({ pid: p.pid, name: p.name, asn: p.asn, color: p.color, card: p.card, seen: p.seen, joined: p.joined })), + feed: s.feed, + }); + // A card can tell the feed something, once per player: reaching Tier 2, and Tier 1 (the first one in the session gets + // the headline). A network that drops out and comes back is not news again. + function applyCard(s, p, c) { + const hit = p.hit || (p.hit = {}); + if (c.t1 && !hit.t1) { hit.t1 = hit.t2 = true; if (!s.first) { s.first = p.pid; event(s, 't1first', p); } else event(s, 't1', p); } + else if (c.tier === 't2' && !hit.t2) { hit.t2 = true; event(s, 't2', p); } + p.card = c; + } + function newPlayer(s, body, ip) { + const net = body.net && typeof body.net === 'object' ? body.net : {}; + const name = cleanText(net.name, 32); + if (!name) fail(400, 'name your network'); + const home = typeof net.home === 'string' && CITY_RE.test(net.home) ? net.home : null; + if (!home) fail(400, 'pick a home city'); + let pid; do pid = randPid(); while (s.players.some((p) => p.pid === pid)); + const token = crypto.randomBytes(32).toString('hex'); + const avoid = new Set((Array.isArray(body.avoid) ? body.avoid.slice(0, 64) : []).filter((a) => Number.isInteger(a))); + for (const p of s.players) avoid.add(p.asn); + let asn; do asn = ASN_LO + crypto.randomInt(ASN_HI - ASN_LO + 1); while (avoid.has(asn)); + const color = COLORS.find((c) => !s.players.some((p) => p.color === c)) || COLORS[s.players.length % COLORS.length]; + const p = { pid, name, home, asn, color, th: sha(token).toString('hex'), joined: now(), seen: now(), card: null, sv: null, hit: {} }; + s.players.push(p); + event(s, 'join', p); + return { code: s.code, pid, token, seed: s.seed, asn, preset: s.preset, color, title: s.title }; + } + // The save as stored: its text alone (the number and time are in the session). Files from before that were wrapped. + const readSave = async (code, pid) => { + const t = await fs.promises.readFile(saveFile(code, pid), 'utf8'); + if (t.startsWith('{"seq":')) { try { const j = JSON.parse(t); if (typeof j.data === 'string') return j.data; } catch (e) { /* a save after all */ } } + return t; + }; + // A save upload holds a place until it is done: one per player, a few per address and on the whole server. + function upTake(key, ip) { + if (up.has(key)) fail(429, 'a save of yours is still on its way'); + if (up.size >= maxUploads || (upAddr.get(ip) || 0) >= maxUploadsAddr) fail(503, 'busy: try again in a moment', { busy: true }); + up.add(key); upAddr.set(ip, (upAddr.get(ip) || 0) + 1); + return () => { up.delete(key); const n = (upAddr.get(ip) || 1) - 1; if (n > 0) upAddr.set(ip, n); else upAddr.delete(ip); }; + } + + async function route(req, res, url) { + const rest = url.pathname.slice(base.length); + const t = now(), ip = ipOf(req), M = req.method; + if (rest === '/sessions') { + if (M !== 'POST') fail(405, 'method not allowed'); + const body = await readJson(req, LIMIT.small); + if (codes.size >= maxSessions) fail(503, 'the server is full: no new sessions for now'); + if (!createRate.ok(ip, t)) fail(429, 'too many new sessions from here: try again later'); + if (!createAll.ok('*', t)) fail(503, 'the server is full: no new sessions for now'); + const preset = PRESETS.includes(body.preset) ? body.preset : null; + if (!preset) fail(400, 'unknown rules preset'); + let code; do code = randCode(); while (codes.has(code)); + const s = { v: 1, code, title: cleanText(body.title, 40), preset, seed: crypto.randomBytes(4).readInt32LE(0), created: t, touched: t, first: null, players: [], feed: [] }; + const out = newPlayer(s, body, ip); + codes.add(code); cache.set(code, s); + await persist(s); + return send(res, 201, out); + } + const m = /^\/sessions\/([^/]{1,32})(\/[a-z]+)?$/.exec(rest); + if (!m) fail(404, 'not found'); + const sub = m[2] || ''; + let raw = ''; try { raw = decodeURIComponent(m[1]); } catch (e) { /* not a code */ } + const code = normCode(raw), s = code && load(code); + // A player of this very session, with their token, is never held up by somebody else's wrong codes from the same + // address. Everyone else is: a wrong code and a wrong token get the same answer then, so it says nothing either. + const me = s ? player(req, s) : null; + if (!me && missRate.full(ip, t)) fail(429, 'too many wrong codes from here: try again later'); + if (sub === '/join' && M === 'POST' && !joinRate.ok(ip, t)) fail(429, 'too many joins from here: try again later'); + if (!s) { missRate.ok(ip, t); fail(404, 'no such session'); } + if (sub === '/join') { + if (M !== 'POST') fail(405, 'method not allowed'); + const body = await readJson(req, LIMIT.small); + if (!still(s)) fail(404, 'no such session'); + if (s.players.length >= maxPlayers) fail(409, 'this session is full', { full: true }); + const out = newPlayer(s, body, ip); + await persist(s); + return send(res, 200, out); + } + if (sub === '') { + if (M !== 'GET') fail(405, 'method not allowed'); + authed(me); + return send(res, 200, roster(s)); + } + if (sub === '/card') { + if (M !== 'PUT') fail(405, 'method not allowed'); + const p = authed(me); + if (!cardRate.ok(code + '.' + p.pid, t)) fail(429, 'too many cards: slow down'); + const body = await readJson(req, LIMIT.small); + if (!still(s, p)) fail(401, 'unauthorized'); + const c = cleanCard(body.card); + if (!c) fail(400, 'bad card'); + applyCard(s, p, c); + persistSoon(s); + return send(res, 200, roster(s)); + } + if (sub === '/save') { + if (M === 'GET') { + const p = authed(me); + if (!p.sv) fail(404, 'no save yet'); + let data; try { data = await readSave(code, p.pid); } catch (e) { fail(404, 'no save yet'); } + return send(res, 200, { seq: p.sv.seq, at: p.sv.at, data }); + } + if (M !== 'PUT') fail(405, 'method not allowed'); + const p = authed(me), key = code + '.' + p.pid; + const free = upTake(key, ip); + try { + if (!saveRate.ok(key, t)) fail(429, 'too many saves: slow down'); + const body = await readJson(req, LIMIT.save, o.saveMs || SAVE_MS); + if (!still(s, p)) fail(401, 'unauthorized'); + const seq = body.seq, data = body.data; + if (!Number.isSafeInteger(seq) || seq < 1) fail(400, 'seq must be a positive integer'); + if (typeof data !== 'string' || !data.length) fail(400, 'no save data'); + if (data.length > MAX_SAVE) fail(413, 'save too large'); + if (!(data.startsWith('gz:') || data.startsWith('{'))) fail(400, 'not a save'); + const card = body.card === undefined ? undefined : cleanCard(body.card); + if (card === null) fail(400, 'bad card'); + const old = p.sv; + // Another device of the same player saved a newer game: never overwrite it unless the player says so. + if (old && seq <= old.seq && body.force !== true) fail(409, 'a newer save is on the server', { seq: old.seq, at: old.at }); + const at = num(body.at, 0, 1e15, t), sq = old && seq <= old.seq ? old.seq + 1 : seq; + // The session says it has this save only once the save is on disk. + await queue(code, () => writeAtomic(saveFile(code, p.pid), data)); + if (!still(s, p)) fail(401, 'unauthorized'); + p.sv = { seq: sq, at, size: data.length }; + if (card) applyCard(s, p, card); + await persist(s); + return send(res, 200, { ok: true, seq: sq, at, roster: roster(s) }); + } finally { free(); } + } + if (sub === '/feed') { + if (M !== 'POST') fail(405, 'method not allowed'); + const p = authed(me), body = await readJson(req, LIMIT.small); + if (!still(s, p)) fail(401, 'unauthorized'); + const text = cleanChat(body.text); + if (!text) fail(400, 'say something'); + if (!chatGap.ok(code + p.pid, t) || !chatRate.ok(code + p.pid, t)) fail(429, 'slow down a little'); + event(s, 'chat', p, { text }); + await persist(s); + return send(res, 200, roster(s)); + } + if (sub === '/me') { + if (M !== 'DELETE') fail(405, 'method not allowed'); + const p = authed(me); + s.players = s.players.filter((x) => x !== p); + await queue(code, () => fs.promises.rm(saveFile(code, p.pid), { force: true })); + if (!s.players.length) { s.dead = true; await queue(code, async () => drop(code)); return send(res, 200, { ok: true }); } + event(s, 'leave', p); + await persist(s); + return send(res, 200, { ok: true }); + } + fail(404, 'not found'); + } + + function handle(req, res) { + let url; + try { url = new URL(req.url, 'http://x'); } catch (e) { return false; } + if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return false; + const t0 = Date.now(); + res.on('finish', () => { if (o.verbose) log(`${new Date().toISOString()} ${ipOf(req)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - t0}ms`); }); + route(req, res, url).catch((e) => { + // A body nobody read (refused before it was needed) is drained, so the client still gets its answer. + if (!req.complete && !req.destroyed) req.resume(); + if (e instanceof HttpError) return send(res, e.status, { error: e.message, ...(e.extra || {}) }); + log(`[mp] ${req.method} ${url.pathname}: ${e && e.stack || e}`); + send(res, 500, { error: 'server error' }); + }); + return true; + } + // Everything written before the process goes, sessions waiting for their moment too. + const flush = () => { for (const code of [...soon.keys()]) { const s = cache.get(code); if (s) persist(s); else { clearTimeout(soon.get(code)); soon.delete(code); } } return Promise.all([...chains.values()]); }; + return { handle, prune, flush, dir, base, sessions: () => codes.size, uploads: () => up.size }; +} + +module.exports = { createMp, cleanCard, cleanText, normCode, showCode, addrKey, limiter, CODE_RE, PRESETS, MAX_SAVE }; diff --git a/scripts/mp-server.js b/scripts/mp-server.js new file mode 100644 index 0000000..64c86f4 --- /dev/null +++ b/scripts/mp-server.js @@ -0,0 +1,117 @@ +#!/usr/bin/env node +// The multiplayer server for a self-hosted Series of Tubes (docs/MULTIPLAYER.md). The public game at seriesoftub.es +// is GitHub Pages only and has no multiplayer: this is for your own copy, built with MP_API=/api/mp npm run build. +// Plain node:http, no dependencies. It answers the API under /api/mp and, with --site, serves the built game too, so +// one process can sit behind a reverse proxy. +const fs = require('node:fs'); +const http = require('node:http'); +const path = require('node:path'); +const { createMp } = require('./lib/mp'); + +const HELP = `Series of Tubes multiplayer server + + node scripts/mp-server.js [options] (npm run mp -- [options]) + + --port N port to listen on (default 8090, or $PORT) + --host H address to bind (default 127.0.0.1: put a reverse proxy in front) + --data DIR where sessions and saves are kept (default ./mp-data, created if missing) + --site DIR also serve the built game from DIR (e.g. _site from MP_API=/api/mp npm run build) + --base PATH the API's path (default /api/mp; the page's MP_API must match) + --prune-days N sessions nobody touched for N days are deleted at startup and daily (default 60) + --max-sessions N at most N sessions on this server (default 1000) + --max-players N at most N players per session (default 12, at most 12) + --create-per-hour N new sessions one address may start per hour (default 10; an IPv6 address counts as its /64) + --sessions-per-hour N new sessions on the whole server per hour (default 100) + --trust-proxy take the client's address from X-Forwarded-For (only behind your own reverse proxy) + --verbose log one line per API request (never tokens) + --help this text + +Storage: DIR/.json per session and DIR/..save per player's save. Back up DIR. +API (JSON; every call but create and join needs Authorization: Bearer .): + POST /api/mp/sessions {net:{name,home},preset,title?} start a session + POST /api/mp/sessions/:code/join {net:{name,home}} join one + GET /api/mp/sessions/:code roster, cards and feed + PUT /api/mp/sessions/:code/card {card} your public card + PUT /api/mp/sessions/:code/save {seq,at,data,card?,force?} your save (409 when the server has a newer one) + GET /api/mp/sessions/:code/save your save + POST /api/mp/sessions/:code/feed {text} a chat line + DELETE /api/mp/sessions/:code/me leave +`; + +const argv = process.argv.slice(2); +if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(0); } +const die = (m) => { console.error(`error: ${m}`); process.exit(2); }; +const KNOWN = new Set(['--port', '--host', '--data', '--site', '--base', '--prune-days', '--max-sessions', '--max-players', '--create-per-hour', '--sessions-per-hour', '--trust-proxy', '--verbose', '--help', '-h']); +for (const a of argv) if (a.startsWith('-') && !KNOWN.has(a)) die(`unknown option ${a} (see --help)`); +const opt = (k) => { const i = argv.indexOf(k); if (i < 0) return null; const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) die(`${k} needs a value`); return v; }; +const pos = (k, d, max = 1e9) => { const v = opt(k); if (v === null) return d; const n = +v; if (!Number.isInteger(n) || n < 1 || n > max) die(`${k} wants a whole number from 1 to ${max}`); return n; }; + +const PORT = pos('--port', +process.env.PORT || 8090, 65535); +const HOST = opt('--host') || '127.0.0.1'; +const DATA = path.resolve(opt('--data') || 'mp-data'); +const SITE = opt('--site') ? path.resolve(opt('--site')) : null; +const BASE = opt('--base') || '/api/mp'; +// A path, never "//host/..." (which a browser reads as another host). +if (!/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(BASE)) die('--base must be a path like /api/mp'); +if (SITE && !fs.statSync(SITE, { throwIfNoEntry: false })?.isDirectory()) die(`--site ${SITE} is not a directory`); +if (SITE && !fs.existsSync(path.join(SITE, 'index.html'))) die(`--site ${SITE} has no index.html (run npm run build first)`); + +const mp = createMp({ + dir: DATA, base: BASE, pruneDays: pos('--prune-days', 60), maxSessions: pos('--max-sessions', 1000), + maxPlayers: pos('--max-players', 12, 12), createPerHour: pos('--create-per-hour', 10), sessionsPerHour: pos('--sessions-per-hour', 100), + trustProxy: argv.includes('--trust-proxy'), verbose: argv.includes('--verbose'), +}); + +const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', + '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml', + '.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.jpg': 'image/jpeg', '.webp': 'image/webp' }; +// The page, the service worker and the files that change between releases are always checked; the rest may be cached. +const FRESH = /(^|\/)(index\.html|404\.html|sw\.js|version\.json)$|\/weekly\//; + +// What is at p, or null: a path the file system cannot even look at (too long, a loop of links...) is not there either. +const stat = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false }) || null; } catch (e) { return null; } }; +const isFile = (p) => { const st = stat(p); return !!(st && st.isFile()); }; + +// The built site, like GitHub Pages serves it: / is index.html, a missing file is 404.html, nothing outside SITE. +function serveSite(req, res) { + if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }); return res.end(); } + let rel; + try { rel = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch (e) { rel = null; } + let file = null; + if (rel !== null && !rel.includes('\0')) { + if (rel.endsWith('/')) rel += 'index.html'; + const p = path.resolve(SITE, '.' + path.posix.normalize('/' + rel)); + if (p.startsWith(SITE + path.sep)) { const st = stat(p); if (st && st.isFile()) file = p; else if (st && st.isDirectory() && isFile(path.join(p, 'index.html'))) file = path.join(p, 'index.html'); } + } + const status = file ? 200 : 404; + if (!file) file = path.join(SITE, '404.html'); + if (!isFile(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); return res.end('Not found'); } + const r = path.relative(SITE, file).split(path.sep).join('/'); + res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': FRESH.test('/' + r) ? 'no-cache' : 'public, max-age=3600', 'x-content-type-options': 'nosniff' }); + if (req.method === 'HEAD') return res.end(); + fs.createReadStream(file).on('error', () => res.destroy()).pipe(res); +} + +const server = http.createServer((req, res) => { + try { + if (mp.handle(req, res)) return; + if (SITE) return serveSite(req, res); + res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' }); + res.end('{"error":"not found"}'); + } catch (e) { + // One line, never a stack: whatever went wrong, a request should not be able to fill the log. + console.error(`[mp] ${req.method} ${String(req.url).slice(0, 200)}: ${e && e.message}`); + if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' }); + res.end('{"error":"server error"}'); + } +}); +server.on('clientError', (e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch (_) { /* gone */ } }); +server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); }); +server.listen(PORT, HOST, () => { + const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`; + console.log(`Series of Tubes multiplayer: http://${at}${BASE} (data in ${DATA}, ${mp.sessions()} sessions${SITE ? `, serving ${SITE}` : ''})`); +}); +setInterval(() => { try { mp.prune(); } catch (e) { console.error(`[mp] pruning failed: ${e.message}`); } }, 86400000).unref(); +const shutdown = () => { server.close(); mp.flush().finally(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref(); }; +process.on('SIGINT', shutdown); +process.on('SIGTERM', shutdown); diff --git a/site/i18n/de.js b/site/i18n/de.js index 4e82c6e..94cc2cd 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3085,6 +3085,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"Das Original: Folge einem Paket vom WLAN bis zur Unterseeglasfaser.", "modals.lay_your_own_subsea_cable":"Eigenes Seekabel verlegen…", "modals.your_own_subsea_cable_level_n":"Eigenes Seekabel Level {n} oder Tier 1", +"mp.code":"Session-Code", +"mp.copy_link":"Link kopieren", +"mp.door_d":"Eine Welt, die Netze deiner Freunde neben deinem: Code teilen und um Tier 1 wetteifern.", +"mp.err_code":"Ein Session-Code hat sechs Buchstaben und Ziffern, etwa K7Q-2XD.", +"mp.err_full":"Diese Session ist voll: Alle Plätze darin sind vergeben.", +"mp.err_no_session":"Mit diesem Code gibt es keine Session.", +"mp.err_offline":"Der Multiplayer-Server ist gerade nicht erreichbar. Versuch es gleich noch mal.", +"mp.err_refused":"Das hat der Server nicht angenommen. Versuch einen anderen Netznamen.", +"mp.err_server_full":"Der Server nimmt gerade keine neuen Sessions an.", +"mp.err_slow":"Zu viele Versuche von hier. Warte kurz und versuch es noch mal.", +"mp.feed":"Feed", +"mp.feed_empty":"Noch nichts. Sag hallo!", +"mp.feed_join":"{name} ist der Session beigetreten.", +"mp.feed_leave":"{name} hat die Session verlassen.", +"mp.feed_t1":"{name} ist jetzt auch Tier 1.", +"mp.feed_t1first":"{name} ist das erste Tier 1 in dieser Session!", +"mp.feed_t2":"{name} ist jetzt Tier 2.", +"mp.intro":"Alle bauen ihr eigenes Netz in derselben Welt, ab demselben Tag 0, mit denselben Regeln. Rangliste und Feed zeigen, wer vorne liegt.", +"mp.join":"Beitreten", +"mp.join_a_session":"Einer Session beitreten", +"mp.join_note":"Welt und Regeln kommen von dem, der die Session gestartet hat, und deine AS-Nummer bekommst du von der Session.", +"mp.joined":"Du bist Session {code} beigetreten. Öffne die Session, um zu sehen, wer vorne liegt.", +"mp.keep_mine":"Diesen behalten", +"mp.leaderboard":"Rangliste", +"mp.leave":"Session verlassen", +"mp.leave_d":"{name} bleibt auf diesem Gerät als eigenes Spiel. Die Session vergisst es, und sein Spielstand auf dem Server wird gelöscht.", +"mp.leave_q":"Session {code} verlassen?", +"mp.left":"Du hast die Session verlassen. {name} spielt hier allein weiter.", +"mp.link_bad":"Dieser Multiplayer-Link hat nicht funktioniert: Er ist alt, oder dieses Netz hat nie in der Session gespeichert.", +"mp.link_copied":"Link kopiert. Öffne ihn auf deinem anderen Gerät.", +"mp.load_newer":"Neueren Spielstand laden", +"mp.loaded_newer":"Den neueren Spielstand von {name} aus der Session geladen ({date}).", +"mp.loading":"Frage den Server…", +"mp.move_device":"Auf ein anderes Gerät umziehen", +"mp.move_note":"Öffne diesen Link auf deinem anderen Handy oder Computer, um dort mit diesem Netz weiterzumachen. Es zählt, welches Gerät zuletzt speichert.", +"mp.move_warn":"Wer diesen Link hat, kann als du spielen. Behalte ihn für dich.", +"mp.moved_on_elsewhere":"Die Session ist woanders weitergelaufen. Dein Netz wurde seitdem auf einem anderen Gerät gespielt. Lade jenen Spielstand, oder behalte deinen hier und überschreib den auf dem Server.", +"mp.multiplayer":"Multiplayer", +"mp.n_customers":{"one":"{n} Kunde","other":"{n} Kunden"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"hat noch keinen Tag beendet", +"mp.no_newer":"Die Session hat keinen neueren Spielstand von {name}. Dieser bleibt und geht beim nächsten Speichern an den Server.", +"mp.not_in_session":"Dieses Netz ist nicht mehr in seiner Session. Es spielt hier allein weiter.", +"mp.play_with_friends":"Mit Freunden spielen", +"mp.save_unreadable":"Der Spielstand dieses Netzes in der Session war nicht lesbar. Es geht mit dem hier weiter.", +"mp.say":"Sag was", +"mp.send":"Senden", +"mp.server_away":"Der Multiplayer-Server ist weg. Dein Netz spielt hier weiter und holt auf, sobald er zurück ist.", +"mp.session":"Multiplayer-Session", +"mp.session_code":"Session {code}", +"mp.session_live":"Session {code} läuft. Teil den Code: Wer beitritt, baut in derselben Welt.", +"mp.session_title":"Name der Session (optional)", +"mp.share_line":"Komm in meine Series-of-Tubes-Session {code}: {url}", +"mp.share_note":"Freunde treten vom Startbildschirm aus bei: Multiplayer, dann dieser Code.", +"mp.slow_down":"Mach mal langsam: eine Zeile pro Sekunde.", +"mp.start_a_session":"Session starten", +"mp.talking":"Spreche mit dem Server…", +"mp.welcome_device":"{name} ist auf dieses Gerät umgezogen. Willkommen zurück in Session {code}.", +"mp.you":"du", "networks.a_mobile_network_named_after_the":"Ein Mobilfunknetz, benannt nach dem Klang anstoßender Gläser. Prost auf jeden 5G-Mast.", "networks.a_spanish_carrier_starring_in_every":"Ein spanischer Carrier mit Hauptrolle in jedem lateinamerikanischen Markt, zumindest bis er den nächsten verkauft.", "networks.a_tiny_telco_in_a_country":"Eine winzige Telco in einem Land, in dem die Kabel der Welt an Land gehen. Die Preise passen dazu.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2b78345..cf40d69 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"Lo de verdad: sigue un paquete del Wi-Fi a la fibra submarina.", "modals.lay_your_own_subsea_cable":"Tender tu propio cable submarino…", "modals.your_own_subsea_cable_level_n":"Tu propio cable submarino nivel {n} o Tier 1", +"mp.code":"Código de la sesión", +"mp.copy_link":"Copiar el enlace", +"mp.door_d":"Un mundo, las redes de tus amigos junto a la tuya: comparte un código y compite por llegar a Tier 1.", +"mp.err_code":"Un código de sesión tiene seis letras y cifras, como K7Q-2XD.", +"mp.err_full":"Esa sesión está llena: no queda ningún hueco libre.", +"mp.err_no_session":"No hay ninguna sesión con ese código.", +"mp.err_offline":"Ahora mismo no se puede contactar con el servidor multijugador. Inténtalo de nuevo en un momento.", +"mp.err_refused":"El servidor no lo aceptó. Prueba con otro nombre de red.", +"mp.err_server_full":"El servidor no acepta sesiones nuevas ahora mismo.", +"mp.err_slow":"Demasiados intentos desde aquí. Espera un poco y vuelve a intentarlo.", +"mp.feed":"Actividad", +"mp.feed_empty":"Nada todavía. ¡Saluda!", +"mp.feed_join":"{name} se unió a la sesión.", +"mp.feed_leave":"{name} dejó la sesión.", +"mp.feed_t1":"{name} también es Tier 1.", +"mp.feed_t1first":"¡{name} es el primer Tier 1 de esta sesión!", +"mp.feed_t2":"{name} llegó a Tier 2.", +"mp.intro":"Cada uno construye su propia red en el mismo mundo, desde el mismo día 0 y con las mismas reglas. La clasificación y la actividad muestran quién va delante.", +"mp.join":"Unirse", +"mp.join_a_session":"Unirse a una sesión", +"mp.join_note":"El mundo y las reglas los pone quien empezó la sesión, y la sesión te da tu número de AS.", +"mp.joined":"Te uniste a la sesión {code}. Abre la sesión para ver quién va delante.", +"mp.keep_mine":"Quedarme con esta", +"mp.leaderboard":"Clasificación", +"mp.leave":"Dejar la sesión", +"mp.leave_d":"{name} se queda en este dispositivo como una partida propia. La sesión se olvida de ella y su partida guardada en el servidor se borra.", +"mp.leave_q":"¿Dejar la sesión {code}?", +"mp.left":"Dejaste la sesión. {name} sigue jugando aquí por su cuenta.", +"mp.link_bad":"Ese enlace multijugador no funcionó: es antiguo, o esa red nunca guardó en la sesión.", +"mp.link_copied":"Enlace copiado. Ábrelo en tu otro dispositivo.", +"mp.load_newer":"Cargar la más reciente", +"mp.loaded_newer":"Se cargó desde la sesión la partida más reciente de {name} ({date}).", +"mp.loading":"Preguntando al servidor…", +"mp.move_device":"Pasar a otro dispositivo", +"mp.move_note":"Abre este enlace en tu otro móvil u ordenador para seguir allí con esta red. Gana el dispositivo que guarde el último.", +"mp.move_warn":"Cualquiera con este enlace puede jugar como tú. Guárdalo para ti.", +"mp.moved_on_elsewhere":"Esta sesión siguió en otro sitio. Desde entonces tu red se jugó en otro dispositivo. Carga esa partida, o quédate con esta y sobrescríbela.", +"mp.multiplayer":"Multijugador", +"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"aún no ha terminado ningún día", +"mp.no_newer":"La sesión no tiene una partida más reciente de {name}. Se queda esta, que irá al servidor con el próximo guardado.", +"mp.not_in_session":"Esta red ya no está en su sesión. Sigue jugando aquí por su cuenta.", +"mp.play_with_friends":"Jugar con amigos", +"mp.save_unreadable":"No se pudo leer la partida de esta red en la sesión. Se sigue con la de aquí.", +"mp.say":"Di algo", +"mp.send":"Enviar", +"mp.server_away":"El servidor multijugador no está. Tu red sigue jugando aquí y se pone al día cuando vuelva.", +"mp.session":"Sesión multijugador", +"mp.session_code":"Sesión {code}", +"mp.session_live":"La sesión {code} está en marcha. Comparte el código: quien se una construye en el mismo mundo.", +"mp.session_title":"Nombre de la sesión (opcional)", +"mp.share_line":"Únete a mi sesión de Series of Tubes {code}: {url}", +"mp.share_note":"Tus amigos se unen desde la pantalla de inicio: Multijugador y luego este código.", +"mp.slow_down":"Más despacio: una línea por segundo.", +"mp.start_a_session":"Empezar una sesión", +"mp.talking":"Hablando con el servidor…", +"mp.welcome_device":"{name} se pasó a este dispositivo. Bienvenido de nuevo a la sesión {code}.", +"mp.you":"tú", "networks.a_mobile_network_named_after_the":"Una red móvil con el nombre del sonido de un brindis. Salud por cada torre 5G.", "networks.a_spanish_carrier_starring_in_every":"Un operador español protagonista en todos los mercados latinoamericanos, al menos hasta que vende el siguiente.", "networks.a_tiny_telco_in_a_country":"Una telco diminuta en un país donde llegan a tierra los cables del mundo. Precios a juego.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index d239d01..f1c7c81 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"La version réelle : suis un paquet du Wi-Fi à la fibre sous-marine.", "modals.lay_your_own_subsea_cable":"Pose ton propre câble sous-marin…", "modals.your_own_subsea_cable_level_n":"Ton propre câble sous-marin niveau {n} ou Tier 1", +"mp.code":"Code de la session", +"mp.copy_link":"Copier le lien", +"mp.door_d":"Un seul monde, les réseaux de tes amis à côté du tien : partage un code et fonce vers le Tier 1.", +"mp.err_code":"Un code de session a six lettres et chiffres, comme K7Q-2XD.", +"mp.err_full":"Cette session est pleine : toutes les places sont prises.", +"mp.err_no_session":"Aucune session n'a ce code.", +"mp.err_offline":"Le serveur multijoueur est injoignable pour l'instant. Réessaie dans un moment.", +"mp.err_refused":"Le serveur n'a pas accepté. Essaie un autre nom de réseau.", +"mp.err_server_full":"Le serveur n'accepte pas de nouvelles sessions pour l'instant.", +"mp.err_slow":"Trop d'essais depuis ici. Attends un peu et réessaie.", +"mp.feed":"Fil", +"mp.feed_empty":"Rien pour l'instant. Dis bonjour !", +"mp.feed_join":"{name} a rejoint la session.", +"mp.feed_leave":"{name} a quitté la session.", +"mp.feed_t1":"{name} est Tier 1 aussi.", +"mp.feed_t1first":"{name} est le premier Tier 1 de cette session !", +"mp.feed_t2":"{name} est passé Tier 2.", +"mp.intro":"Chacun construit son propre réseau dans le même monde, depuis le même jour 0, avec les mêmes règles. Le classement et le fil montrent qui mène.", +"mp.join":"Rejoindre", +"mp.join_a_session":"Rejoindre une session", +"mp.join_note":"Le monde et les règles viennent de qui a lancé la session, et la session te donne ton numéro d'AS.", +"mp.joined":"Tu as rejoint la session {code}. Ouvre la session pour voir qui mène.", +"mp.keep_mine":"Garder celle-ci", +"mp.leaderboard":"Classement", +"mp.leave":"Quitter la session", +"mp.leave_d":"{name} reste sur cet appareil comme une partie à part entière. La session l'oublie, et sa sauvegarde sur le serveur est supprimée.", +"mp.leave_q":"Quitter la session {code} ?", +"mp.left":"Tu as quitté la session. {name} continue ici en solo.", +"mp.link_bad":"Ce lien multijoueur n'a pas marché : il est trop vieux, ou ce réseau n'a jamais sauvegardé dans la session.", +"mp.link_copied":"Lien copié. Ouvre-le sur ton autre appareil.", +"mp.load_newer":"Charger la plus récente", +"mp.loaded_newer":"Sauvegarde plus récente de {name} chargée depuis la session ({date}).", +"mp.loading":"Je demande au serveur…", +"mp.move_device":"Passer sur un autre appareil", +"mp.move_note":"Ouvre ce lien sur ton autre téléphone ou ordinateur pour continuer ce réseau là-bas. C'est l'appareil qui sauvegarde en dernier qui gagne.", +"mp.move_warn":"Quiconque a ce lien peut jouer à ta place. Garde-le pour toi.", +"mp.moved_on_elsewhere":"Cette session a avancé ailleurs. Ton réseau a été joué sur un autre appareil depuis. Charge cette sauvegarde, ou garde celle-ci et écrase l'autre.", +"mp.multiplayer":"Multijoueur", +"mp.n_customers":{"one":"{n} client","other":"{n} clients"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POP"}, +"mp.no_card":"n'a pas encore fini de journée", +"mp.no_newer":"La session n'a pas de sauvegarde plus récente de {name}. Celle-ci reste, et part au serveur à la prochaine sauvegarde.", +"mp.not_in_session":"Ce réseau n'est plus dans sa session. Il continue ici en solo.", +"mp.play_with_friends":"Jouer avec des amis", +"mp.save_unreadable":"La sauvegarde de ce réseau dans la session est illisible. On continue avec celle d'ici.", +"mp.say":"Dis quelque chose", +"mp.send":"Envoyer", +"mp.server_away":"Le serveur multijoueur est absent. Ton réseau continue ici et se met à jour à son retour.", +"mp.session":"Session multijoueur", +"mp.session_code":"Session {code}", +"mp.session_live":"La session {code} est lancée. Partage le code : qui la rejoint construit dans le même monde.", +"mp.session_title":"Nom de la session (facultatif)", +"mp.share_line":"Rejoins ma session Series of Tubes {code} : {url}", +"mp.share_note":"Tes amis rejoignent depuis l'écran d'accueil : Multijoueur, puis ce code.", +"mp.slow_down":"Doucement : une ligne par seconde.", +"mp.start_a_session":"Lancer une session", +"mp.talking":"Je parle au serveur…", +"mp.welcome_device":"{name} est passé sur cet appareil. Bon retour dans la session {code}.", +"mp.you":"toi", "networks.a_mobile_network_named_after_the":"Un réseau mobile qui porte le nom du bruit d’un toast. Tchin-tchin à chaque antenne 5G.", "networks.a_spanish_carrier_starring_in_every":"Un opérateur espagnol en vedette sur chaque marché d’Amérique latine, au moins jusqu’à ce qu’il revende le suivant.", "networks.a_tiny_telco_in_a_country":"Un tout petit opérateur dans un pays où les câbles du monde entier touchent terre. Tarifs à l’avenant.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 49e3639..1db1657 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"La versione vera: segui un pacchetto dal Wi-Fi alla fibra sottomarina.", "modals.lay_your_own_subsea_cable":"Posa il tuo cavo sottomarino…", "modals.your_own_subsea_cable_level_n":"Il tuo cavo sottomarino livello {n} o Tier 1", +"mp.code":"Codice della sessione", +"mp.copy_link":"Copia il link", +"mp.door_d":"Un solo mondo, le reti dei tuoi amici accanto alla tua: condividi un codice e corri verso il Tier 1.", +"mp.err_code":"Un codice di sessione ha sei lettere e cifre, tipo K7Q-2XD.", +"mp.err_full":"Quella sessione è piena: tutti i posti sono occupati.", +"mp.err_no_session":"Non c'è nessuna sessione con quel codice.", +"mp.err_offline":"Il server multigiocatore non è raggiungibile adesso. Riprova tra un attimo.", +"mp.err_refused":"Il server non l'ha accettato. Prova un altro nome per la rete.", +"mp.err_server_full":"Il server non accetta nuove sessioni in questo momento.", +"mp.err_slow":"Troppi tentativi da qui. Aspetta un po' e riprova.", +"mp.feed":"Bacheca", +"mp.feed_empty":"Ancora niente. Saluta!", +"mp.feed_join":"{name} è entrato nella sessione.", +"mp.feed_leave":"{name} ha lasciato la sessione.", +"mp.feed_t1":"Anche {name} è Tier 1.", +"mp.feed_t1first":"{name} è il primo Tier 1 di questa sessione!", +"mp.feed_t2":"{name} è arrivato a Tier 2.", +"mp.intro":"Ognuno costruisce la propria rete nello stesso mondo, dallo stesso giorno 0 e con le stesse regole. Classifica e bacheca mostrano chi è in testa.", +"mp.join":"Entra", +"mp.join_a_session":"Entra in una sessione", +"mp.join_note":"Il mondo e le regole li sceglie chi ha avviato la sessione, e il numero di AS te lo dà la sessione.", +"mp.joined":"Sei entrato nella sessione {code}. Apri la sessione per vedere chi è in testa.", +"mp.keep_mine":"Tieni questa", +"mp.leaderboard":"Classifica", +"mp.leave":"Lascia la sessione", +"mp.leave_d":"{name} resta su questo dispositivo come partita a sé. La sessione se ne dimentica e il suo salvataggio sul server viene cancellato.", +"mp.leave_q":"Lasciare la sessione {code}?", +"mp.left":"Hai lasciato la sessione. {name} continua qui per conto suo.", +"mp.link_bad":"Quel link multigiocatore non ha funzionato: è vecchio, oppure quella rete non ha mai salvato nella sessione.", +"mp.link_copied":"Link copiato. Aprilo sull'altro dispositivo.", +"mp.load_newer":"Carica quello più recente", +"mp.loaded_newer":"Caricato dalla sessione il salvataggio più recente di {name} ({date}).", +"mp.loading":"Chiedo al server…", +"mp.move_device":"Passa a un altro dispositivo", +"mp.move_note":"Apri questo link sull'altro telefono o computer per continuare lì con questa rete. Vince il dispositivo che salva per ultimo.", +"mp.move_warn":"Chiunque abbia questo link può giocare al posto tuo. Tienilo per te.", +"mp.moved_on_elsewhere":"Questa sessione è andata avanti altrove. Da allora la tua rete è stata giocata su un altro dispositivo. Carica quel salvataggio, oppure tieni questo e sovrascrivilo.", +"mp.multiplayer":"Multigiocatore", +"mp.n_customers":{"one":"{n} cliente","other":"{n} clienti"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POP"}, +"mp.no_card":"non ha ancora finito un giorno", +"mp.no_newer":"La sessione non ha un salvataggio più recente di {name}. Resta questo, che andrà al server al prossimo salvataggio.", +"mp.not_in_session":"Questa rete non è più nella sua sessione. Continua qui per conto suo.", +"mp.play_with_friends":"Gioca con gli amici", +"mp.save_unreadable":"Non si riesce a leggere il salvataggio di questa rete nella sessione. Si continua con quello qui.", +"mp.say":"Scrivi qualcosa", +"mp.send":"Invia", +"mp.server_away":"Il server multigiocatore non risponde. La tua rete continua a giocare qui e si rimette in pari quando torna.", +"mp.session":"Sessione multigiocatore", +"mp.session_code":"Sessione {code}", +"mp.session_live":"La sessione {code} è partita. Condividi il codice: chi entra costruisce nello stesso mondo.", +"mp.session_title":"Nome della sessione (facoltativo)", +"mp.share_line":"Entra nella mia sessione di Series of Tubes {code}: {url}", +"mp.share_note":"Gli amici entrano dalla schermata iniziale: Multigiocatore, poi questo codice.", +"mp.slow_down":"Piano: una riga al secondo.", +"mp.start_a_session":"Avvia una sessione", +"mp.talking":"Parlo con il server…", +"mp.welcome_device":"{name} è passata su questo dispositivo. Bentornato nella sessione {code}.", +"mp.you":"tu", "networks.a_mobile_network_named_after_the":"Una rete mobile che porta il nome del suono di un brindisi. Cin cin a ogni antenna 5G.", "networks.a_spanish_carrier_starring_in_every":"Un carrier spagnolo protagonista in ogni mercato latinoamericano, almeno finché non vende il prossimo.", "networks.a_tiny_telco_in_a_country":"Una piccola telco in un paese dove approdano i cavi di mezzo mondo. Prezzi in proporzione.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 9875919..311571c 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"A coisa de verdade: siga um pacote do Wi-Fi até a fibra submarina.", "modals.lay_your_own_subsea_cable":"Lançar seu próprio cabo submarino…", "modals.your_own_subsea_cable_level_n":"Seu próprio cabo submarino nível {n} ou Tier 1", +"mp.code":"Código da sessão", +"mp.copy_link":"Copiar o link", +"mp.door_d":"Um só mundo, as redes dos seus amigos ao lado da sua: compartilhe um código e corra para o Tier 1.", +"mp.err_code":"Um código de sessão tem seis letras e números, como K7Q-2XD.", +"mp.err_full":"Essa sessão está cheia: todas as vagas já estão ocupadas.", +"mp.err_no_session":"Não existe sessão com esse código.", +"mp.err_offline":"Não dá para falar com o servidor multijogador agora. Tente de novo daqui a pouco.", +"mp.err_refused":"O servidor não aceitou. Tente outro nome de rede.", +"mp.err_server_full":"O servidor não está aceitando sessões novas agora.", +"mp.err_slow":"Tentativas demais daqui. Espere um pouco e tente de novo.", +"mp.feed":"Mural", +"mp.feed_empty":"Nada ainda. Diga oi!", +"mp.feed_join":"{name} entrou na sessão.", +"mp.feed_leave":"{name} saiu da sessão.", +"mp.feed_t1":"{name} também é Tier 1.", +"mp.feed_t1first":"{name} é o primeiro Tier 1 desta sessão!", +"mp.feed_t2":"{name} chegou a Tier 2.", +"mp.intro":"Cada um constrói a própria rede no mesmo mundo, a partir do mesmo dia 0 e com as mesmas regras. O ranking e o mural mostram quem está na frente.", +"mp.join":"Entrar", +"mp.join_a_session":"Entrar numa sessão", +"mp.join_note":"O mundo e as regras vêm de quem começou a sessão, e a sessão te dá o seu número de AS.", +"mp.joined":"Você entrou na sessão {code}. Abra a sessão para ver quem está na frente.", +"mp.keep_mine":"Ficar com esta", +"mp.leaderboard":"Ranking", +"mp.leave":"Sair da sessão", +"mp.leave_d":"{name} fica neste dispositivo como um jogo próprio. A sessão se esquece dela, e o jogo salvo dela no servidor é apagado.", +"mp.leave_q":"Sair da sessão {code}?", +"mp.left":"Você saiu da sessão. {name} continua aqui por conta própria.", +"mp.link_bad":"Esse link multijogador não funcionou: é antigo, ou essa rede nunca salvou na sessão.", +"mp.link_copied":"Link copiado. Abra no seu outro dispositivo.", +"mp.load_newer":"Carregar o mais recente", +"mp.loaded_newer":"Carregado da sessão o jogo salvo mais recente de {name} ({date}).", +"mp.loading":"Perguntando ao servidor…", +"mp.move_device":"Passar para outro dispositivo", +"mp.move_note":"Abra este link no seu outro celular ou computador para continuar com esta rede lá. Vale o dispositivo que salvar por último.", +"mp.move_warn":"Qualquer um com este link pode jogar como você. Guarde só para você.", +"mp.moved_on_elsewhere":"Esta sessão seguiu em outro lugar. Desde então sua rede foi jogada em outro dispositivo. Carregue aquele jogo salvo, ou fique com este e sobrescreva o outro.", +"mp.multiplayer":"Multijogador", +"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"ainda não terminou nenhum dia", +"mp.no_newer":"A sessão não tem um jogo salvo mais recente de {name}. Este fica e vai para o servidor no próximo salvamento.", +"mp.not_in_session":"Esta rede não está mais na sua sessão. Ela continua jogando aqui por conta própria.", +"mp.play_with_friends":"Jogar com amigos", +"mp.save_unreadable":"Não deu para ler o jogo salvo desta rede na sessão. Seguimos com o daqui.", +"mp.say":"Diga algo", +"mp.send":"Enviar", +"mp.server_away":"O servidor multijogador sumiu. Sua rede continua jogando aqui e se atualiza quando ele voltar.", +"mp.session":"Sessão multijogador", +"mp.session_code":"Sessão {code}", +"mp.session_live":"A sessão {code} está no ar. Compartilhe o código: quem entrar constrói no mesmo mundo.", +"mp.session_title":"Nome da sessão (opcional)", +"mp.share_line":"Entre na minha sessão de Series of Tubes {code}: {url}", +"mp.share_note":"Os amigos entram pela tela inicial: Multijogador, depois este código.", +"mp.slow_down":"Calma: uma linha por segundo.", +"mp.start_a_session":"Começar uma sessão", +"mp.talking":"Falando com o servidor…", +"mp.welcome_device":"{name} passou para este dispositivo. Bem-vindo de volta à sessão {code}.", +"mp.you":"você", "networks.a_mobile_network_named_after_the":"Uma rede móvel com nome de brinde. Tim-tim para cada torre 5G.", "networks.a_spanish_carrier_starring_in_every":"Uma operadora espanhola estrelando em todo mercado latino-americano, pelo menos até vender o próximo.", "networks.a_tiny_telco_in_a_country":"Uma operadora minúscula num país onde os cabos do mundo chegam à terra. Os preços acompanham.", diff --git a/site/sw.js b/site/sw.js index 745bafa..4cf8fa4 100644 --- a/site/sw.js +++ b/site/sw.js @@ -15,6 +15,8 @@ self.addEventListener('activate', (e) => { self.addEventListener('fetch', (e) => { const req = e.request; if (req.method !== 'GET') return; + // Calls with a player's credentials, or that ask not to be cached (a self-hosted copy's multiplayer server), are never cached. + if (req.cache === 'no-store' || req.headers.has('authorization')) return; const url = new URL(req.url); // The update check must always ask the network. if (url.origin === location.origin && url.pathname === '/version.json') return; diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index f4b8ca3..9d4f554 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -600,6 +600,7 @@ const API_WHY={ time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save', slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game', browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', + mp:'multiplayer talks to a session server for the player: only the player starts, joins, chats in or leaves a session', }; const API_DENY={ speed:'time',phonePlay:'time',phoneSpeed:'time', @@ -607,5 +608,6 @@ const API_DENY={ exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', + mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp', install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', }; diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 30da327..fb43b45 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -62,6 +62,7 @@ const API_STATE_DOC={ core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, + mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, diff --git a/src/game/00-core/20-analytics.js b/src/game/00-core/20-analytics.js index b273f59..327918f 100644 --- a/src/game/00-core/20-analytics.js +++ b/src/game/00-core/20-analytics.js @@ -7,6 +7,9 @@ const RELEASE_NOTES=/*__RELEASE_NOTES__*/[]; // A big release's story, shown in full in "What's new" (paragraphs; **bold** allowed). Empty for most releases. const RELEASE_STORY=/*__RELEASE_STORY__*/[]; const IS_DEV=APP_VERSION.startsWith('__'); +// Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build. +// Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests. +const MP_API=/*__MP_API__*/''; // Only report from the real site; previews, localhost and the Claude viewer stay silent. const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'}; (function(){ diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 9b8e154..e6e4956 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -44,6 +44,8 @@ function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let 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);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal'; + // A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world. + if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;} // 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;}} @@ -55,4 +57,5 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci 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'?(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'); // A Normal game asks for its charter first; the tutorial starts once it is signed. - renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}} + renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();} + if(S.mp)mpStartTell();} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index c661e15..3559593 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:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),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:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; + done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null}; } diff --git a/src/game/60-features/89-multiplayer.js b/src/game/60-features/89-multiplayer.js new file mode 100644 index 0000000..50b0c13 --- /dev/null +++ b/src/game/60-features/89-multiplayer.js @@ -0,0 +1,180 @@ +/* ================= MULTIPLAYER (docs/MULTIPLAYER.md) ================= + Only in a self-hosted copy built with MP_API (scripts/mp-server.js on the same origin); with MP_API empty nothing here + runs. Players share a session by a six-character code: each builds their own network in the same world (one seed, + one rules preset), each network's save is also kept on the server (so it can move to another device), and a small + public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing + when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq}; the secret token is never in + S (saves get exported and shared): it lives in this browser's storage, sot-mp::. */ +const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i; +// Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive +// request (the page is going away) carries at most 64 KiB, so only a small save goes with it (MP_KEEP bytes of request, +// with room to spare), else the card alone. +const MP_GAP=15000,MP_POLL=5000,MP_KEEP=63000,MP_GZ=32768,MP_FEED=['join','leave','t2','t1','t1first','chat']; +/* cur: the push on its way ({cut, ac}); staleSeq: the server's number when it said it has a newer save; sig: what the + last push that landed looked like (mpSig); force: the player chose to keep this save; now: push at the next save. */ +const MP={roster:null,day:-1,last:-1e9,busy:false,cur:null,stale:false,staleSeq:0,gone:false,leaving:false,wait:0,fails:0,told:false,poll:null,sig:'',force:false,now:false}; +const mpIs=()=>!!(MP_API&&S&&S.mp&&!pzOn()); +const mpShow=c=>c.slice(0,3)+'-'+c.slice(3); +// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code, or null. I, L and O read as 1, 1 and 0 (Crockford's base32). +function mpNorm(s){if(typeof s!=='string'||s.length>20)return null;const c=s.toUpperCase().replace(/[\s-]/g,'').replace(/[IL]/g,'1').replace(/O/g,'0');return MP_CODE.test(c)?c:null;} +const mpPath=(m,p)=>'/sessions/'+m.code+(p||''); +const mpTokK=(c,p)=>'sot-mp:'+c+':'+p; +function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;const t=lsGet(mpTokK(m.code,m.pid));return typeof t==='string'&&MP_TOK.test(t)?t:null;} +function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}} +// The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses. +const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64); +function mpSanitize(s){const m=s.mp; + if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;} + s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall', + color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0)};} +// What the server said when a session started or someone joined: checked before it becomes S.mp. +function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null; + return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};} +/* One call to the session server. Same origin, never cached; a call that takes over 15 s gives up. Rejects with + {status, j} on an HTTP error, so callers can tell "no such session" from "server away". */ +function mpReq(method,p,body,o={}){ + if(!MP_API||typeof fetch!=='function')return Promise.reject(Object.assign(new Error('off'),{status:0})); + const h={};if(body!==undefined)h['content-type']='application/json'; + // o.tok: a token not stored yet (a #mp= link's, until the server takes it). + if(o.auth){const t=o.tok||mpTok(o.auth);if(!t)return Promise.reject(Object.assign(new Error('no token'),{status:401}));h.authorization='Bearer '+o.auth.pid+'.'+t;} + const ac=o.keep?null:o.ac||(typeof AbortController==='function'?new AbortController():null),tm=ac?setTimeout(()=>ac.abort(),15000):0; + let f;try{f=fetch(MP_API+p,{method,headers:h,body:body===undefined?undefined:typeof body==='string'?body:JSON.stringify(body),cache:'no-store',credentials:'same-origin',...(o.keep?{keepalive:true}:{}),...(ac?{signal:ac.signal}:{})});} + catch(e){clearTimeout(tm);return Promise.reject(Object.assign(e,{status:0}));} + return Promise.resolve(f).then(r=>Promise.resolve(r.json?r.json():null).catch(()=>null).then(j=>{clearTimeout(tm);if(!r.ok)throw Object.assign(new Error(j&&j.error||'HTTP '+r.status),{status:r.status,j});return j;}), + e=>{clearTimeout(tm);throw Object.assign(e||new Error('failed'),{status:e&&e.status||0});});} +/* The public card: what the leaderboard shows (and what peering between players will need later). */ +function mpCard(){let t1=false,tl='Tier 3';try{t1=isTier1();tl=tierLabel();}catch(e){} + const tier=tl==='Tier 1'?'t1':tl==='Tier 2'?'t2':'t3',pairs=new Map(); + for(const l of S.links){if(l.ready>S.day)continue;const k=l.ab[1]-a[1]).slice(0,300).map(([k,g])=>{const [a,b]=k.split('|');return [a,b,Math.round(g)];}); + const served=R.served||0; + return {day:S.day,name:S.name,asn:S.asn,tier,t1,lvl:S.lvl||1,pops:Object.keys(S.pops).slice(0,500),links,ix:Object.keys(S.ixp).slice(0,500),transit:[...new Set(S.transit.map(t=>t.net))].slice(0,64), + ppol:ppol(),reach:Math.round((R.reach||0)*1e4)/1e4,peak:Math.round((S.stats.peak||0)*10)/10,served:Math.round(served*10)/10,cust:S.biz.length,rev:Math.round(R.revMo||0), + cashB:S.cash<0?-1:Math.min(20,Math.floor(Math.log10(Math.max(1,S.cash)))),score:(t1?2e9:tier==='t2'?1e9:0)+Math.round(served)};} +/* Other players' data, as it comes back: the same whitelist the server keeps, and every id checked against our own + catalogs. Names and chat stay text: everything that shows them escapes them. */ +function mpCardOk(c){if(!c||typeof c!=='object'||Array.isArray(c))return null; + const n=(v,lo,hi)=>{v=+v;return Number.isFinite(v)?Math.min(hi,Math.max(lo,v)):0;},L=(v,ok,max)=>Array.isArray(v)?[...new Set(v.filter(ok))].slice(0,max):[]; + return {day:Math.round(n(c.day,0,1e7)),tier:['t1','t2','t3'].includes(c.tier)?c.tier:'t3',t1:c.t1===true,lvl:Math.round(n(c.lvl,0,99)),pops:L(c.pops,isCity,500), + links:(Array.isArray(c.links)?c.links:[]).filter(l=>Array.isArray(l)&&isCity(l[0])&&isCity(l[1])&&l[0]!==l[1]).slice(0,300).map(l=>[l[0],l[1],n(l[2],0,1e7)]), + ix:L(c.ix,isIx,500),transit:L(c.transit,isNet,64),ppol:PPOL.includes(c.ppol)?c.ppol:'open',reach:n(c.reach,0,1),peak:n(c.peak,0,1e9),served:n(c.served,0,1e9), + cust:Math.round(n(c.cust,0,1e7)),rev:n(c.rev,-1e13,1e13),cashB:Math.round(n(c.cashB,-1,20)),score:n(c.score,0,1e15)};} +function mpRosterOk(j){if(!j||typeof j!=='object'||Array.isArray(j)||!Array.isArray(j.players))return null; + const txt=(v,max)=>typeof v==='string'?v.slice(0,max):''; + const players=j.players.filter(p=>p&&typeof p==='object'&&MP_PID.test(p.pid)).slice(0,12).map(p=>({pid:p.pid,name:txt(p.name,32),asn:int(p.asn,0,4294967294,0), + color:typeof p.color==='string'&&MP_COL.test(p.color)?p.color:'#888888',card:mpCardOk(p.card),seen:num(p.seen,0),joined:num(p.joined,0)})); + const feed=(Array.isArray(j.feed)?j.feed:[]).filter(f=>f&&typeof f==='object'&&MP_FEED.includes(f.k)).slice(-100).map(f=>({k:f.k,pid:MP_PID.test(f.pid)?f.pid:'',name:txt(f.name,32),at:num(f.at,0),text:f.k==='chat'?txt(f.text,200):''})); + return {code:MP_CODE.test(j.code)?j.code:'',title:txt(j.title,40),preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',players,feed};} +// Tier 1 first, then Tier 2, then whoever serves the most traffic; players who never pushed a card last. +const mpTierN=c=>c?(c.t1?3:c.tier==='t2'?2:1):0; +function mpRank(ps){return ps.slice().sort((a,b)=>mpTierN(b.card)-mpTierN(a.card)||(b.card?b.card.served:0)-(a.card?a.card.served:0)||(b.card?b.card.peak:0)-(a.card?a.card.peak:0)||a.joined-b.joined);} +/* ---------- staying in step with the server ---------- */ +function mpOk(roster){MP.fails=0;MP.wait=0;if(MP.told)MP.told=false;const r=mpRosterOk(roster);if(r)MP.roster=r;if(MP_API)mpHud();mpPanelUpdate();} +/* The server is away: back off (30 s, 1, 2, 4 min, at most 5), say so once, and keep playing. Too many pushes at once + (429: another one still on its way, or too often; 503 busy: too many uploads on the server right now) is not "away": + wait a little, quietly. The session panel's own refresh (poll) runs every few seconds while it is open: it may say + the server is away, but never stretches the wait. */ +function mpFail(e,poll){const st=e&&e.status; + if((st===401||st===404)&&S&&S.mp){MP.gone=true;toast(tr('mp.not_in_session'),'bad',[{l:tr('mp.session'),act:'mpOpen',args:{}}]);return;} + if(st===429||st===503&&e.j&&e.j.busy===true){MP.wait=performance.now()+MP_GAP*2;return;} + if(!poll||!MP.fails){MP.fails++;MP.wait=performance.now()+Math.min(300000,MP_GAP*2**MP.fails);} + if(!MP.told){MP.told=true;toast(tr('mp.server_away'),'bad');}} +const mpHid=()=>MP.leaving||document.visibilityState==='hidden'; +// What a save looks like, in a few characters (FNV-1a and the length): a page hidden on the same game day pushes only +// when something changed since the last push. +function mpSig(t){let h=0x811c9dc5;for(let i=0;i>>0).toString(36)+'.'+t.length;} +// The request's size in bytes (UTF-8), which is what the keepalive limit counts. +function mpBytes(t){let n=t.length;for(let i=0;i127)n+=c>2047&&(c<0xd800||c>0xdfff)?2:1;}return n;} +/* Does this save go to the server too? 1: yes; 2: if it changed since the last push (the page is being hidden, or the + player asked, on the same game day); 0: no. A push goes on a new game day at most every MP_GAP; at once when the page + is hidden or closed, when the player chose to keep this save (MP.force) or asked for it (MP.now). Never mid-day or in + a puzzle: save() returns before then. */ +function mpDue(){if(!mpIs()||MP.stale||MP.gone||S.lost)return 0; + const hid=mpHid(),now=performance.now(); + // One push at a time, except when the page goes away: that one cuts the one on its way short (mpPush). + if(MP.busy&&!hid)return 0; + const ask=MP.now;MP.now=false; + if(MP.force&&(hid||now>=MP.wait))return 1; + if(S.day===MP.day)return hid||ask?2:0; + return hid||ask||(now-MP.last>=MP_GAP&&now>=MP.wait)?1:0;} +/* save()'s text for a network in a session, and its push when one is due. The number the server will keep it under is + picked before the text is made, so the save here and the one on the server carry the same: reopening this device + then knows the server has nothing newer. A push that fails leaves this one ahead, which the server accepts. */ +function mpSave(st){let d=mpDue();if(d===1)S.mp.seq=(S.mp.seq||0)+1;let txt=JSON.stringify(packSave(st)); + if(d===2){if(mpSig(txt)===MP.sig)d=0;else{S.mp.seq=(S.mp.seq||0)+1;txt=JSON.stringify(packSave(st));}} + if(d)mpPush(txt);return txt;} +/* Sends that save (it carries S.mp.seq), gzipped when big, with the card. When the page is being hidden or closed it + goes at once, as a keepalive request: the save when the request fits in one, else the card alone. */ +function mpPush(txt){if(!mpIs()||MP.stale||MP.gone||S.lost)return; + const m=S.mp,day=S.day,seq=m.seq||0,hid=mpHid(),force=MP.force,me={cut:false,ac:null};let card;try{card=mpCard();}catch(e){card=undefined;} + // A push still on its way while the page goes away with a newer save: that one is cut short, this one goes. + if(MP.cur){MP.cur.cut=true;try{if(MP.cur.ac)MP.cur.ac.abort();}catch(e){}} + MP.cur=me;MP.busy=true;MP.last=performance.now(); + const sig=mpSig(txt),body=data=>({seq,at:Date.now(),data,card,...(force?{force:true}:{})}); + // Only a save that went counts as this day's push; a card alone does not. + const done=j=>{if(me.cut)return;if(j&&j.seq!==undefined&&S&&S.mp===m){m.seq=Math.max(m.seq||0,int(j.seq,0,1e15,seq));MP.day=day;MP.sig=sig;if(force)MP.force=false;}mpOk(j&&(j.roster||j));}; + const bad=e=>{if(me.cut)return;if(e&&e.status===409&&S&&S.mp===m){MP.stale=true;MP.staleSeq=int(e.j&&e.j.seq,0,1e15,seq);mpStaleTell();}else mpFail(e);}; + const fin=()=>{if(MP.cur===me){MP.cur=null;MP.busy=false;}}; + const send=(p,b,keep)=>{if(me.cut)return;if(!keep&&typeof AbortController==='function')me.ac=new AbortController(); + mpReq('PUT',mpPath(m,p),b,{auth:m,keep,ac:me.ac}).then(done,bad).finally(fin);}; + if(hid){const b=txt.lengthsend('/save',body(data),false); + if(txt.length>=MP_GZ&&gzOk())gzip(txt).then(go,()=>go(txt));else go(txt);} +// The page is going away (pagehide comes before save()'s own handler, which then pushes as a keepalive request). +if(MP_API){addEventListener('pagehide',()=>{MP.leaving=true;});addEventListener('pageshow',()=>{MP.leaving=false;});} +function mpStaleTell(){toast(tr('mp.moved_on_elsewhere'),'bad',[{l:tr('mp.load_newer'),act:'mpNewer',args:{}},{l:tr('mp.keep_mine'),act:'mpKeep',args:{}}]);} +// Pushes this network's save now if it changed since the last push (before a link to another device is handed out). +function mpSyncNow(){if(!mpIs())return;MP.now=true;save(true);} +// The server's save text as a game state: unzipped, parsed, and only if it is this very network. +function mpUnpack(data){if(typeof data!=='string')return Promise.reject(new Error('no save')); + return (data.startsWith(GZ)?gunzip(data):Promise.resolve(data)).then(t=>JSON.parse(t));} +function mpSaveOk(s,m){if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links)||s.lost)return false; + if(!Object.keys(s.pops).every(isCity))return false;return !!(s.mp&&s.mp.code===m.code&&s.mp.pid===m.pid);} +/* Opening a network of a session: if another device played on and pushed a newer save, that one is loaded instead. + Nothing is pushed until the answer is in. */ +function mpResume(){if(!mpIs())return;const m=S.mp;mpReset({day:S.day,last:performance.now(),busy:true});mpHud(); + // A push of the page going away meanwhile is its own: only an answer to this question frees the next one. + const free=()=>{if(!MP.cur)MP.busy=false;}; + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{free();if(S&&S.mp===m&&j&&int(j.seq,0,1e15,0)>(m.seq||0))mpAdopt(j,m);else mpRefresh();}, + e=>{free();if(e&&e.status===404&&S&&S.mp===m)mpRefresh();else mpFail(e);});} +// A network of a session opened or started: nothing from another one carries over (a push still on its way is forgotten). +function mpReset(o){if(MP.cur)MP.cur.cut=true;Object.assign(MP,{roster:null,cur:null,busy:false,stale:false,staleSeq:0,gone:false,fails:0,wait:0,told:false,sig:'',force:false,now:false},o);} +function mpAdopt(j,m,n=0){if(!S||S.mp!==m)return; + // A day still routing in the worker finishes first. + if(RW.job){if(n<50)setTimeout(()=>mpAdopt(j,m,n+1),100);return;} + mpUnpack(j.data).then(s=>{if(!S||S.mp!==m||!mpSaveOk(s,m))throw new Error('not this network');delete s.sv;const nx=migrate(s);nx.mp.seq=int(j.seq,0,1e15,0); + S=nx;compute();UI.sel=null;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);Object.assign(MP,{stale:false,staleSeq:0,force:false,day:S.day,last:performance.now()}); + renderAll();save(true);toast(tr('mp.loaded_newer',{name:esc(S.name),date:dateStr(S.day)}),'good');mpRefresh();}) + .catch(e=>{console.error('[tubes] loading the session save failed',e);toast(tr('mp.save_unreadable'),'bad');});} +function mpRefresh(poll){if(!mpIs()||MP.gone)return Promise.resolve();const m=S.mp;return mpReq('GET',mpPath(m),undefined,{auth:m}).then(mpOk,e=>mpFail(e,poll));} +/* ---------- a link to the same network on another device ---------- + /#mp=..: the fragment never reaches a server. At boot (before the slots are picked) the save + is fetched into a new slot, or the one this browser already has for that network is opened (one open in another tab + too: slotBoot then offers to take it over), and the fragment is cleared. The link's token is stored only once the + server took it: a wrong or old link never replaces nor deletes the one this browser already has. */ +const mpLink=m=>{const t=mpTok(m);return t?location.origin+location.pathname+'#mp='+m.code+'.'+m.pid+'.'+t:'';}; +function mpBoot(go){const hash=String(location.hash||''),h=MP_API?/^#mp=([0-9A-Za-z-]{6,8})\.([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(hash):null; + if(!h){go();return;} + try{history.replaceState(null,'',location.pathname+location.search);}catch(e){} + const code=mpNorm(h[1]),m={code,pid:h[2]},tok=h[3],fin=b=>{UI.mpBoot=b;go();}; + if(!code){fin({bad:1});return;} + const had=mpTok(m),keep=()=>{if(had!==tok)mpTokSet(code,m.pid,tok);}; + // The server is away (or busy): the link may be fine, so it stays in the address bar for a reload to try again. + const no=e=>{console.error('[tubes] moving the network here failed',e);const st=e&&e.status,away=st===0||st===429||st>=500; + if(away)try{history.replaceState(null,'',location.pathname+location.search+hash);}catch(x){}fin(away?{away:1}:{bad:1});}; + const ex=slotIdx(true).find(e=>e.mp===code+'.'+m.pid&&!e.broken); + if(ex){const open=()=>{ssSet(SLOT_SS,ex.id);fin({code});}; + // Opening it fetches the server's save when that one is newer. A link with another token is asked about first. + if(had===tok)open();else mpReq('GET',mpPath(m),undefined,{auth:m,tok}).then(()=>{keep();open();},no);return;} + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m,tok}).then(j=>mpUnpack(j&&j.data).then(s=>{if(!mpSaveOk(s,m))throw new Error('not this network'); + delete s.sv;s.mp.seq=int(j.seq,0,1e15,0);const txt=JSON.stringify(s);return (txt.length>=GZ_MIN&&gzOk()?gzip(txt):Promise.resolve(txt)).then(data=>{ + const id=slotRid();localStorage.setItem(SLOT_K+id,data);keep(); + slotIdxPut(slotIdx(true).filter(x=>x.id!==id).concat([slotClean({id,...slotMeta(s,null),seq:1,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})]));ssSet(SLOT_SS,id);});})) + .then(()=>fin({code}),no);} +// Said once the game is on screen (or the title is). +function mpBootTell(){const b=UI.mpBoot;if(!b)return;UI.mpBoot=null; + if(b.bad)toast(tr('mp.link_bad'),'bad');else if(b.away)toast(tr('mp.err_offline'),'bad'); + else if(S&&S.mp&&S.mp.code===b.code)toast(tr('mp.welcome_device',{name:esc(S.name),code:mpShow(b.code)}),'goal');} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index fea6574..e6c94b3 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -110,7 +110,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); + specSanitize(s);mpSanitize(s); pieSanitize(s);pieIncFix(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;} diff --git a/src/game/90-actions/86-specialist.js b/src/game/90-actions/86-specialist.js index cd59ae5..089794d 100644 --- a/src/game/90-actions/86-specialist.js +++ b/src/game/90-actions/86-specialist.js @@ -8,5 +8,7 @@ Object.assign(ACT,{ 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;if($('modal').className==='charter')closeModal(); - toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}after();}, + toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();} + // A new multiplayer session's code to share waited for the charter (95-modals/48-multiplayer.js). + if(UI.mpLater)mpStartTell();after();}, }); diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 1f8ad34..412f0c2 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -23,13 +23,13 @@ Object.assign(ACT,{ 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;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;setSpeed(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');}, + 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;setSpeed(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');if(MP_API)mpResume();}, 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')}

`} - + `);}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 098512a..735a4da 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -43,7 +43,7 @@ function bbCost(c){return 15000+CITY[c].P*20;} /* A click that changes nothing routing reads (the log, offers, cash, names, settings…) keeps the routing it has: compute() gives the same R again for the same state (tests/compute-idempotent), so it is skipped. The key is the save without the fields routing never reads (tests/route-skip checks each one); any other change routes again. */ -const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd']); +const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd','mp']); function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);} function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;} function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();} diff --git a/src/game/90-actions/91-slots.js b/src/game/90-actions/91-slots.js index 86ca1d8..060ad56 100644 --- a/src/game/90-actions/91-slots.js +++ b/src/game/90-actions/91-slots.js @@ -31,4 +31,4 @@ function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;U // Back from the title (or a puzzle) into a loaded network. function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([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);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} - closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');} + closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');if(MP_API)mpResume();} diff --git a/src/game/90-actions/92-multiplayer.js b/src/game/90-actions/92-multiplayer.js new file mode 100644 index 0000000..5515551 --- /dev/null +++ b/src/game/90-actions/92-multiplayer.js @@ -0,0 +1,34 @@ +// Multiplayer (60-features/89-multiplayer.js, 95-modals/48-multiplayer.js). Every one does nothing unless the build +// stamped MP_API; the title-screen ones are in the click delegate's no-game list (96-map/95-clicks.js). +Object.assign(ACT,{ + mpDoor:()=>{if(!MP_API)return;const i=$('nmIn');UI.nm=((i&&i.value)||UI.nm||randomNetworkName()).slice(0,24);openModal(mpStartHtml()); + const n=$('mpName');if(n)n.addEventListener('input',e=>{UI.nm=e.target.value;}); + const c=$('mpCode');if(c)c.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpJoin({});}});}, + mpBack:()=>{const n=$('mpName');if(n)UI.nm=n.value.slice(0,24);showTitle();}, + mpStart:()=>{if(!MP_API||UI.mpBusy)return;const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra',preset=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',t=$('mpTitle'); + mpBusy(true);mpReq('POST','/sessions',{net:{name:nm,home},preset,title:(t&&t.value||'').slice(0,40),avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,false);},e=>{mpBusy(false);mpErr(e);});}, + mpJoin:()=>{if(!MP_API||UI.mpBusy)return;const i=$('mpCode'),code=mpNorm(i?i.value:'');if(!code){toast(tr('mp.err_code'),'bad');if(i)i.focus();return;} + const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra'; + mpBusy(true);mpReq('POST','/sessions/'+code+'/join',{net:{name:nm,home},avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,true);},e=>{mpBusy(false);mpErr(e);});}, + mpOpen:()=>{if(!mpIs())return;openModal(mpPanelHtml(),'mp');const s=$('mpSay');if(s)s.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpChat({});}}); + // About to move to another device: the server gets what this one has first, so the link opens it as it is now. + const d=document.querySelector('#mpPanel details.mpmove');if(d)d.addEventListener('toggle',()=>{if(d.open)mpSyncNow();});mpPoll();}, + mpShare:()=>{if(!mpIs())return;mpSend(tr('mp.share_line',{code:mpShow(S.mp.code),url:location.origin+location.pathname}));}, + // The link carries the secret: it goes to the clipboard, or is selected for copying by hand, never into a toast. + mpCopyLink:()=>{if(!mpIs())return;const l=mpLink(S.mp);if(!l)return;mpSyncNow();const sel=()=>{const i=$('mpLink');if(i){i.focus();i.select();}}; + try{navigator.clipboard.writeText(l).then(()=>toast(tr('mp.link_copied'),'good'),sel);}catch(e){sel();}}, + mpChat:()=>{if(!mpIs()||MP.gone)return;const i=$('mpSay'),t=(i?i.value:'').trim().slice(0,200);if(!t)return;const m=S.mp; + mpReq('POST',mpPath(m,'/feed'),{text:t},{auth:m}).then(j=>{if(i)i.value='';mpOk(j);},e=>{if(e&&e.status===429)toast(tr('mp.slow_down'),'bad');else mpFail(e);});}, + mpLeaveAsk:()=>{if(!mpIs())return;openModal(`

${tr('mp.leave_q',{code:mpShow(S.mp.code)})}

${tr('mp.leave_d',{name:esc(S.name)})}

${btn(tr('mp.leave'),'mpLeave',{},'red big')}${btn(tr('common.keep_playing'),'mpOpen',{},'ghost big')}
`);}, + // Leaving keeps the network, as a game of its own; the session forgets it (and a session that forgot it already too). + mpLeave:()=>{if(!mpIs())return;const m=S.mp,out=()=>{if(!S||S.mp!==m)return;S.mp=null;mpTokSet(m.code,m.pid,null);mpReset(); + closeModal();renderAll();save(true);toast(tr('mp.left',{name:esc(S.name)}),'good');}; + mpReq('DELETE',mpPath(m,'/me'),undefined,{auth:m}).then(out,e=>{if(e&&(e.status===401||e.status===404))out();else toast(tr('mp.server_away'),'bad');});}, + // Only a save at least as new as the one the server said it has (after a conflict), or newer than this one, is loaded: + // "Load the newer save" never takes the player back to an older one. + mpNewer:()=>{if(!mpIs())return;const m=S.mp,min=(m.seq||0)+(MP.stale?0:1); + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{if(!S||S.mp!==m)return;const sq=int(j&&j.seq,0,1e15,0);if(sq>=min){mpAdopt(j,m);return;} + m.seq=Math.max(m.seq||0,sq);MP.stale=false;toast(tr('mp.no_newer',{name:esc(S.name)}),'good');mpPanelUpdate();},mpFail);}, + // Overwrite the server's save with this one: with a number past the server's, at the next save (never half a day). + mpKeep:()=>{if(!mpIs())return;S.mp.seq=Math.max(S.mp.seq||0,MP.staleSeq||0);Object.assign(MP,{stale:false,force:true,wait:0});save(true);mpPanelUpdate();}, +}); diff --git a/src/game/91-save.js b/src/game/91-save.js index faea37c..a7a45d6 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -14,7 +14,8 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot; UI.lastSave=performance.now(); // Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do. if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return; - const txt=JSON.stringify(packSave(st)); + // A network in a multiplayer session: the server keeps a copy too (60-features/89-multiplayer.js). + const txt=MP_API&&st===S&&S.mp?mpSave(st):JSON.stringify(packSave(st)); let tier=null;if(st===S)try{tier=tierLabel();}catch(e){} const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)}; if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));} diff --git a/src/game/91-slots.js b/src/game/91-slots.js index c647112..8bcb1e1 100644 --- a/src/game/91-slots.js +++ b/src/game/91-slots.js @@ -22,8 +22,11 @@ function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null; 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, // A save marked damaged (bv: the game version that could not load it) is tried again by the next version: the fault is // usually in the game, and the save itself is fine once it is fixed. - ...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false})};} -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}); + ...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false}), + // A network in a multiplayer session: ., so a link from another device finds it again. + ...(typeof e.mp==='string'&&/^[0-9A-HJKMNP-TV-Z]{6}\.[a-z0-9]{8}$/.test(e.mp)?{mp:e.mp}:{})};} +// mp is always there (null outside a session), so a network that left its session loses its badge in the list. +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,mp:s.mp&&s.mp.code?s.mp.code+'.'+s.mp.pid:null}); function slotKeys(){const out=[];try{for(let i=0;i({...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;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}} + if(m){const c=slotClean({...x,...m});if(!c.mp)delete x.mp;Object.assign(x,c);}else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}} const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at); // ---------- one writer per slot ---------- // The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a @@ -88,7 +91,7 @@ function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false; if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;} if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq); - const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})); + const e=ent||{id};if(!ent)list.push(e);const c=slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false});if(!c.mp)delete e.mp;Object.assign(e,c); slotIdxPut(list);return true;} function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}} // ---------- opening, leaving, losing ---------- diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index f05d9f8..b3052f9 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -6,6 +6,7 @@ function renderHUD(){ // A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud). {const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();} $('muteBtn').style.opacity=UI.muted?.4:1; + if(MP_API)mpHud();// the session chip: also hidden again on the title screen and in a puzzle if(!S)return; if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;} {const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 54b3867..e71afef 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -22,7 +22,7 @@ function showTitle(){ ${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()} + ${doorsHtml()}${MP_API?mpDoorHtml():''} ${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;}); @@ -44,8 +44,10 @@ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot 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)}`; +// The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js). +const presetBtns=pr=>`
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

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

${presetWhat(pr)}

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

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

`;} diff --git a/src/game/95-modals/45-slots.js b/src/game/95-modals/45-slots.js index 047c54d..690d2e3 100644 --- a/src/game/95-modals/45-slots.js +++ b/src/game/95-modals/45-slots.js @@ -5,7 +5,7 @@ const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'? // 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;} function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete'); - const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier); + const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);if(MP_API&&e.mp)bits.push('🌐 '+mpShow(e.mp.slice(0,6))); return bits.filter(Boolean).join(' · ');} function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network')); const tag=busy?`${tr('slots.open_in_another_window')}`:top?`▶ ${tr('slots.continue')}`:''; diff --git a/src/game/95-modals/48-multiplayer.js b/src/game/95-modals/48-multiplayer.js new file mode 100644 index 0000000..77767c9 --- /dev/null +++ b/src/game/95-modals/48-multiplayer.js @@ -0,0 +1,73 @@ +/* Multiplayer on screen (89-multiplayer.js has the logic): the title screen's door, the start/join sheet, the session + panel (leaderboard, feed and chat, the code to share, the link to another device) and the HUD chip. Only ever drawn + when the build stamped MP_API. Everything another player wrote is escaped here. */ +const MP_FEED_L={join:N_('mp.feed_join'),leave:N_('mp.feed_leave'),t2:N_('mp.feed_t2'),t1:N_('mp.feed_t1'),t1first:N_('mp.feed_t1first')}; +const mpDoorHtml=()=>`
`; +function mpStartHtml(){const pr=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall'; + return `
🌐 ${tr('mp.multiplayer')}

${tr('mp.play_with_friends')}

+

${tr('mp.intro')}

+ + ${homePick()}

${homeWhat()}

+

${tr('mp.start_a_session')}

${presetBtns(pr)} + +
${btn(tr('mp.start_a_session'),'mpStart',{},'pink big mpgo')}
+

${tr('mp.join_a_session')}

+
${btn(tr('mp.join'),'mpJoin',{},'big mpgo')}
+

${tr('mp.join_note')}

+ +
${btn(tr('common.back'),'mpBack',{},'ghost')}
`;} +function mpBusy(on){UI.mpBusy=on;document.querySelectorAll('.mpgo').forEach(b=>{b.disabled=on;});const b=$('mpBusy');if(b)b.hidden=!on;} +function mpErr(e){const st=e&&e.status;sfx('err'); + toast(st===404?tr('mp.err_no_session'):st===409?tr('mp.err_full'):st===429?tr('mp.err_slow'):st===503?tr('mp.err_server_full'):st===400?tr('mp.err_refused'):tr('mp.err_offline'),'bad');} +const mpNameIn=()=>{const n=$('mpName'),v=String((n&&n.value)||UI.nm||randomNetworkName()).trim().slice(0,24)||randomNetworkName();UI.nm=v;return v;}; +// The server said yes: the token goes to this browser's storage, the rest into a new game. +function mpBegin(j,nm,home,joined){const m=mpJoinOk(j);if(!m){toast(tr('mp.err_offline'),'bad');return;} + mpTokSet(m.code,m.pid,m.token);delete m.token;beginGame(nm,home,{mode:'normal',preset:m.preset,mp:{...m,joined}});} +// Called by beginGame just before its first save, which then pushes the day-0 save and the card: this player is on the +// leaderboard at once, and a link to another device works from the start. +function mpStarted(m){mpReset({day:-1,last:-1e9});mpHud();UI.mpLater={joined:!!(m&&m.joined)};} +// The code to share, with its buttons. A new Normal game asks for its charter first, on top of everything: the code +// waits until it is signed (ACT.charter), or its buttons could not be pressed. +function mpStartTell(){const b=UI.mpLater;if(!b||!mpIs())return;if(!$('modal').hidden&&$('modal').className==='charter')return;UI.mpLater=null; + const code=mpShow(S.mp.code),acts=[{l:tr('common.share'),act:'mpShare',args:{}},{l:tr('mp.session'),act:'mpOpen',args:{}}]; + toast(b.joined?tr('mp.joined',{code}):tr('mp.session_live',{code}),'goal',acts);} +/* ---------- the session panel ---------- */ +function mpBoardHtml(){const r=MP.roster;if(MP.gone)return `

${tr('mp.not_in_session')}

`; + // Another device moved on: the toast with the choice is long gone, the choice stays here until it is made. + const st=MP.stale?`

${tr('mp.moved_on_elsewhere')}

${btn(tr('mp.load_newer'),'mpNewer',{},'pink')}${btn(tr('mp.keep_mine'),'mpKeep',{},'')}
`:''; + if(st)return st;if(!r)return `

${tr('mp.loading')}

`;const me=S&&S.mp&&S.mp.pid; + return mpRank(r.players).map((p,i)=>{const c=p.card,mine=p.pid===me; + const meta=c?[`AS${p.asn}`,c.t1?'Tier 1':c.tier==='t2'?'Tier 2':'Tier 3',trn('mp.n_pops',c.pops.length),fmtG(c.peak),trn('mp.n_customers',c.cust)].join(' · '):`AS${p.asn} · ${tr('mp.no_card')}`; + return `
${i+1}
${esc(p.name)}${mine?` ${tr('mp.you')}`:''}
${meta}
${p.seen?slotAgo(p.seen):''}
`;}).join('');} +function mpFeedHtml(){const r=MP.roster;if(!r)return '';const f=r.feed.slice(-30).reverse();if(!f.length)return `

${tr('mp.feed_empty')}

`; + const col=pid=>{const p=r.players.find(x=>x.pid===pid);return p?p.color:'#888888';}; + return f.map(x=>{const who=`${esc(x.name)}`,t=x.k==='chat'?`${who}: ${esc(x.text)}`:tr(MP_FEED_L[x.k],{name:who}); + return `
${t}${x.at?slotAgo(x.at):''}
`;}).join('');} +function mpPanelHtml(){const m=S.mp,code=mpShow(m.code),link=mpLink(m); + return `
🌐 ${tr('mp.session')} · ${esc(PRESETS[m.preset].n)}

${m.title?esc(m.title):tr('mp.session_code',{code})}

+
${tr('mp.code')}${code}
${btn(tr('common.share'),'mpShare',{},'pink')}
+

${tr('mp.share_note')}

+

${tr('mp.leaderboard')}

${mpBoardHtml()}
+

${tr('mp.feed')}

${btn(tr('mp.send'),'mpChat',{},'')}
${mpFeedHtml()}
+ ${link?`
${tr('mp.move_device')}

${tr('mp.move_note')}

${tr('mp.move_warn')}

${btn(tr('mp.copy_link'),'mpCopyLink',{},'')}
`:''} +
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${btn(tr('mp.leave'),'mpLeaveAsk',{},'ghost')}
`;} +// The roster moved on: only the leaderboard and the feed are redrawn, so a chat line being typed stays. +function mpPanelUpdate(){const b=$('mpBoard'),f=$('mpFeed');if(!b||$('modal').hidden)return;b.innerHTML=mpBoardHtml();if(f)f.innerHTML=mpFeedHtml();} +// While the panel is open, the roster every 5 s; it stops by itself once the panel is gone. +function mpPoll(){clearInterval(MP.poll);MP.poll=null;if(!mpIs())return;mpRefresh();if(!window.__TUBES_TEST__)MP.poll=setInterval(mpPollTick,MP_POLL);} +function mpPollTick(){if($('modal').hidden||!$('mpPanel')||!mpIs()){clearInterval(MP.poll);MP.poll=null;return;}mpRefresh(true);} +/* The HUD chip: the session code and where you stand. A phone's top bar has no room for it (the menu has the session): + there, and on a tablet whose top bar is still too full (fitHud's last step), where you stand is a badge on the menu + button instead. Made the first time a session network is on screen. */ +function mpHud(){let c=$('hMp');const on=mpIs(); + if(!c){if(!on)return;c=document.createElement('button');c.className='chip mpchip hide-sm';c.id='hMp';c.dataset.act='mpOpen'; + c.innerHTML='';const n=$('hNoc');n.parentNode.insertBefore(c,n.nextSibling); + const b=document.createElement('span');b.className='badge mpbadge num';b.id='hMpB';b.setAttribute('aria-hidden','true');const mb=document.querySelector('#hud .menubtn');if(mb)mb.appendChild(b);} + const b=$('hMpB');c.hidden=!on;if(b)b.hidden=!on;if(!on)return; + const r=MP.roster,i=r?mpRank(r.players).findIndex(p=>p.pid===S.mp.pid):-1,rk=i>=0?`#${i+1}/${r.players.length}`:'—'; + c.setAttribute('aria-label',tr('mp.session'));c.title=tr('mp.session');c.style.borderColor=S.mp.color; + $('hMpCode').textContent=mpShow(S.mp.code);$('hMpRank').textContent='🌐 '+rk;if(b)b.textContent=i>=0?`#${i+1}`:'🌐';} +// Share text: the phone's share sheet, or the clipboard. +function mpSend(t){const 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),'');}} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index c10b794..88644c8 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','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','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);}); +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','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','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','mpDoor','mpBack','mpStart','mpJoin'].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 41f70a8..5a61189 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -43,7 +43,7 @@ function boot(data){ if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();} else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv; let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} - if(okSave){slotIn(UI.slot,stamp);UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); + if(okSave){slotIn(UI.slot,stamp);if(MP_API)mpResume();UI.started=true;setSpeed([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);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);} if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});} @@ -51,8 +51,9 @@ function boot(data){ // A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted. else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot); else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}} - renderHUD();renderLeft(); + renderHUD();renderLeft();if(MP_API)mpBootTell(); window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}})); if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);} } -if(NOC.win)nocWinBoot();else if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})); +// A #mp= link (a multiplayer network moving to this device) is read first: it picks the slot slotBoot opens. +if(NOC.win)nocWinBoot();else if(!RW_IN)mpBoot(()=>slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}))); diff --git a/src/i18n/en.js b/src/i18n/en.js index 3a0dd38..ef47c7b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3084,6 +3084,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"The real thing: follow a packet from Wi-Fi to undersea fiber.", "modals.lay_your_own_subsea_cable":"Lay your own subsea cable…", "modals.your_own_subsea_cable_level_n":"Your own subsea cable level {n} or Tier 1", +"mp.code":"Session code", +"mp.copy_link":"Copy the link", +"mp.door_d":"One world, your friends' networks next to yours: share a code and race to Tier 1.", +"mp.err_code":"A session code has six letters and digits, like K7Q-2XD.", +"mp.err_full":"That session is full: every seat in it is taken.", +"mp.err_no_session":"There is no session with that code.", +"mp.err_offline":"The multiplayer server cannot be reached right now. Try again in a moment.", +"mp.err_refused":"The server did not take that. Try another network name.", +"mp.err_server_full":"The server is not taking new sessions right now.", +"mp.err_slow":"Too many tries from here. Wait a little and try again.", +"mp.feed":"Feed", +"mp.feed_empty":"Nothing yet. Say hello!", +"mp.feed_join":"{name} joined the session.", +"mp.feed_leave":"{name} left the session.", +"mp.feed_t1":"{name} is Tier 1 too.", +"mp.feed_t1first":"{name} is the first Tier 1 in this session!", +"mp.feed_t2":"{name} made Tier 2.", +"mp.intro":"Everyone builds their own network in the same world, from the same day 0, under the same rules. The leaderboard and the feed show who is ahead.", +"mp.join":"Join", +"mp.join_a_session":"Join a session", +"mp.join_note":"The world and the rules come from whoever started the session, and the session hands you your AS number.", +"mp.joined":"You joined session {code}. Open the session to see who is ahead.", +"mp.keep_mine":"Keep this one", +"mp.leaderboard":"Leaderboard", +"mp.leave":"Leave the session", +"mp.leave_d":"{name} stays on this device as a game of its own. The session forgets it, and its save on the server is deleted.", +"mp.leave_q":"Leave session {code}?", +"mp.left":"You left the session. {name} plays on here on its own.", +"mp.link_bad":"That multiplayer link did not work: it is old, or that network never saved to the session.", +"mp.link_copied":"Link copied. Open it on your other device.", +"mp.load_newer":"Load the newer save", +"mp.loaded_newer":"Loaded the newer save of {name} from the session ({date}).", +"mp.loading":"Asking the server…", +"mp.move_device":"Move to another device", +"mp.move_note":"Open this link on your other phone or computer to carry on with this network there. Whichever device saves last wins.", +"mp.move_warn":"Anyone with this link can play as you. Keep it to yourself.", +"mp.moved_on_elsewhere":"This session moved on elsewhere. Your network was played on another device since. Load that save, or keep this one and overwrite it.", +"mp.multiplayer":"Multiplayer", +"mp.n_customers":{"one":"{n} customer","other":"{n} customers"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"has not finished a day yet", +"mp.no_newer":"The session has no newer save of {name}. This one stays, and goes to the server with the next save.", +"mp.not_in_session":"This network is no longer in its session. It keeps playing here on its own.", +"mp.play_with_friends":"Play with friends", +"mp.save_unreadable":"The session's save of this network could not be read. Playing on with the one here.", +"mp.say":"Say something", +"mp.send":"Send", +"mp.server_away":"The multiplayer server is away. Your network keeps playing here and catches up when it is back.", +"mp.session":"Multiplayer session", +"mp.session_code":"Session {code}", +"mp.session_live":"Session {code} is live. Share the code: whoever joins builds in the same world.", +"mp.session_title":"Session name (optional)", +"mp.share_line":"Join my Series of Tubes session {code}: {url}", +"mp.share_note":"Friends join from the title screen: Multiplayer, then this code.", +"mp.slow_down":"Slow down a little: one line a second.", +"mp.start_a_session":"Start a session", +"mp.talking":"Talking to the server…", +"mp.welcome_device":"{name} moved to this device. Welcome back to session {code}.", +"mp.you":"you", "networks.a_mobile_network_named_after_the":"A mobile network named after the sound of a toast. Cheers to every 5G tower.", "networks.a_spanish_carrier_starring_in_every":"A Spanish carrier starring in every Latin American market, at least until it sells the next one.", "networks.a_tiny_telco_in_a_country":"A tiny telco in a country where the world’s cables come ashore. Prices to match.", diff --git a/src/styles/41-multiplayer.css b/src/styles/41-multiplayer.css new file mode 100644 index 0000000..ccd50e6 --- /dev/null +++ b/src/styles/41-multiplayer.css @@ -0,0 +1,36 @@ +/* Multiplayer (only in a copy built with MP_API): the title row, the start/join sheet, the session panel, the HUD chip. */ +.mpdoor-row{margin-top:8px}.mpdoor{width:100%;background:var(--soft)} +.mpbox{border:2px dashed var(--line);border-radius:14px;padding:4px 12px 10px;margin-top:12px} +.mpbox h3,.mp-panel h3{font-family:var(--display);font-size:18px;margin:10px 0 4px} +.mpjoin,.mpchat{display:flex;gap:8px;align-items:center} +.mpjoin input.t,.mpchat input.t{flex:1 1 auto;min-width:0;width:auto} +#mpCode{text-transform:uppercase;letter-spacing:.12em;font-size:18px} +.mpchat input.t{font-size:16px;padding:6px 10px} +.mpcode{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:14px;padding:8px 12px;background:var(--soft);margin-top:10px} +.mpcode small{display:block;font-size:10.5px;font-weight:900;letter-spacing:.09em;text-transform:uppercase;color:var(--ink2)} +.mpcode b{font-family:var(--display);font-size:28px;letter-spacing:.08em;line-height:1.1} +.mpboard,.mpfeed{display:flex;flex-direction:column;gap:4px} +.mpfeed{max-height:220px;overflow:auto;margin-top:6px} +.mprow{display:flex;align-items:center;gap:8px;border:2px solid var(--line);border-radius:12px;padding:6px 10px;min-width:0} +.mprow.me{border-color:var(--me);background:#FFF2F8} +.mprow .grow,.mpf .grow{min-width:0;overflow-wrap:anywhere} +.mprow b{font-family:var(--display);font-size:15px} +.mprk{font:900 15px var(--display);width:20px;text-align:center;flex:0 0 auto} +.mpdot{display:inline-block;width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);flex:0 0 auto} +.mpseen,.mpf small{color:var(--ink2);font-size:11px;white-space:nowrap;flex:0 0 auto} +.mpf{display:flex;align-items:baseline;gap:8px;font-size:13px;line-height:1.35} +.mpf .mpdot{width:9px;height:9px;border-width:1.5px} +.mpf.t1first{font-weight:800} +.mpmove{margin-top:12px}.mpmove summary{cursor:pointer;font-weight:800} +.mpmove input.t{font-size:12px;font-family:monospace;padding:6px 8px} +#hud .mpchip{border-width:3px} +/* No room for the chip on a phone (it is hide-sm), nor on a tablet whose top bar still wraps at fitHud's last step: + where you stand shows as a badge on the menu button, which also opens the session. */ +#hud .menubtn{position:relative} +.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--ink);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none} +#hud.fit3 .mpchip{display:none !important} +#hud.fit3 .mpbadge{display:block} +@media (max-width:760px){ + .mpcode b{font-size:24px} + .mpbadge{display:block} +} diff --git a/tests/harness.js b/tests/harness.js index a9f897a..2be9e95 100644 --- a/tests/harness.js +++ b/tests/harness.js @@ -14,8 +14,10 @@ const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html); // opts.file: a built or older page to load instead (the perf bench, the release build test). // opts.agent: the development page, with src/agent/. +// opts.mp: the page with multiplayer on, as MP_API=… npm run build stamps it; opts.fetch: the page's fetch, from the start. function load(opts = {}) { - const html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent); + let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent); + if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp)); const errors = []; const vc = new VirtualConsole(); vc.on('jsdomError', (e) => { @@ -38,6 +40,7 @@ function load(opts = {}) { // 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.fetch) window.fetch = opts.fetch; 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. // (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.) diff --git a/tests/mp-server.test.js b/tests/mp-server.test.js new file mode 100644 index 0000000..7fbe90b --- /dev/null +++ b/tests/mp-server.test.js @@ -0,0 +1,450 @@ +// The multiplayer server (scripts/mp-server.js, docs/MULTIPLAYER.md), run for real on a free port with its own data +// folder: sessions, joining, who may read and write what, saves that never overwrite a newer one, cards cleaned of +// junk, limits, leaving, data that survives a restart, and the built site served without escaping its folder. The +// tests of what happens while a request is still on its way run the API in this process (inproc), where a request can +// be held half-sent and the limits made small. +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 http = require('node:http'); +const { spawn, execFileSync } = require('node:child_process'); +const { until, freePort, kill } = require('./net'); +const { createMp, cleanCard, addrKey, limiter } = require('../scripts/lib/mp'); + +const root = path.join(__dirname, '..'); +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-')); +const children = new Set(); +test.after(async () => { for (const c of children) await kill(c); fs.rmSync(tmp, { recursive: true, force: true }); }); + +async function start(opts = {}) { + const port = await freePort(), data = opts.data || fs.mkdtempSync(path.join(tmp, 'data-')); + const args = ['scripts/mp-server.js', '--port', String(port), '--data', data, '--create-per-hour', '50', ...(opts.args || [])]; + const child = spawn(process.execPath, args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }); + children.add(child); + let out = ''; + child.stdout.on('data', (b) => { out += b; }); + child.stderr.on('data', (b) => { out += b; }); + assert.ok(await until(() => /multiplayer: http/.test(out) || child.exitCode !== null), 'the server starts'); + assert.equal(child.exitCode, null, out); + const url = `http://127.0.0.1:${port}`; + const api = async (method, p, body, auth, headers = {}) => { + const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body) }); + const t = await r.text(); + let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } + return { status: r.status, json: j, type: r.headers.get('content-type'), text: t }; + }; + return { child, port, url, data, api, out: () => out, stop: async () => { await kill(child); children.delete(child); } }; +} +// A raw request, so paths reach the server exactly as written (fetch would tidy up ".."). +const raw = (port, p) => new Promise((res, rej) => { + const r = http.request({ host: '127.0.0.1', port, path: p, method: 'GET' }, (x) => { let b = ''; x.on('data', (c) => { b += c; }); x.on('end', () => res({ status: x.statusCode, body: b, type: x.headers['content-type'] })); }); + r.on('error', rej); r.end(); +}); +const make = (api, name = 'Packet Pals', home = 'fra', extra = {}) => api('POST', '/sessions', { net: { name, home }, preset: 'oncall', ...extra }); +// The API in this process, with its own options (small limits), on a free port. +async function inproc(t, opts = {}) { + const dir = opts.dir || fs.mkdtempSync(path.join(tmp, 'data-')); + const mp = createMp({ dir, log: () => {}, ...opts }); + const server = http.createServer((req, res) => { if (!mp.handle(req, res)) { res.writeHead(404); res.end(); } }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + t.after(() => new Promise((r) => { server.closeAllConnections(); server.close(r); })); + const port = server.address().port, url = `http://127.0.0.1:${port}`; + const api = async (method, p, body, auth, headers = {}) => { + const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : JSON.stringify(body) }); + const t = await r.text(); + let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } + return { status: r.status, json: j }; + }; + return { mp, dir, port, api }; +} +// A request sent all but the last byte of its body: it stays on its way until release(). +function held(port, method, p, body, auth, headers = {}) { + const b = Buffer.from(JSON.stringify(body)); + let r; + const done = new Promise((res, rej) => { + r = http.request({ host: '127.0.0.1', port, path: '/api/mp' + p, method, headers: { 'content-type': 'application/json', 'content-length': b.length, ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers } }, + (x) => { let t = ''; x.on('data', (c) => { t += c; }); x.on('end', () => { let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } res({ status: x.statusCode, json: j }); }); }); + r.on('error', rej); + r.write(b.subarray(0, b.length - 1)); + }); + return { done, release: () => { r.end(b.subarray(b.length - 1)); return done; } }; +} +const joinAs = (api, code, name, headers) => api('POST', `/sessions/${code}/join`, { net: { name, home: 'ams' } }, null, headers); + +test('mp server: --help documents it; --base is a path on this server, never another host', () => { + const t = execFileSync(process.execPath, ['scripts/mp-server.js', '--help'], { cwd: root, encoding: 'utf8' }); + for (const k of ['--port', '--host', '--data', '--site', '--prune-days', '--trust-proxy', '--sessions-per-hour', 'Authorization: Bearer', '/api/mp/sessions/:code/save']) assert.ok(t.includes(k), k); + for (const b of ['//evil-host/mp', '//api', 'api/mp', '/api/mp/']) assert.throws(() => execFileSync(process.execPath, ['scripts/mp-server.js', '--base', b, '--port', '1'], { cwd: root, stdio: 'pipe' }), /--base must be a path/, b); +}); + +test('mp server: start, join, roster; names cleaned; codes typed any way', async () => { + const s = await start(); + const a = await make(s.api, ' & "Co" ', 'fra', { preset: 'bgp', title: 'Friday night', avoid: [200000, 200001] }); + assert.equal(a.status, 201); + assert.match(a.json.code, /^[0-9A-HJKMNP-TV-Z]{6}$/); + assert.match(a.json.pid, /^[a-z0-9]{8}$/); + assert.match(a.json.token, /^[0-9a-f]{64}$/); + assert.ok(Number.isInteger(a.json.seed) && a.json.seed >= -(2 ** 31) && a.json.seed < 2 ** 31); + assert.ok(a.json.asn >= 200000 && a.json.asn <= 214999); + assert.equal(a.json.preset, 'bgp'); + assert.equal(a.json.title, 'Friday bnight/b'); + // Joined by the code as a person types it: lower case, with a dash. + const typed = (a.json.code.slice(0, 3) + '-' + a.json.code.slice(3)).toLowerCase(); + const b = await s.api('POST', `/sessions/${typed}/join`, { net: { name: 'Bee', home: 'nyc' }, preset: 'soft' }); + assert.equal(b.status, 200); + assert.equal(b.json.code, a.json.code); + assert.equal(b.json.seed, a.json.seed, 'one world: the same seed'); + assert.equal(b.json.preset, 'bgp', 'and the creator\'s rules'); + assert.notEqual(b.json.asn, a.json.asn); + assert.notEqual(b.json.color, a.json.color); + const r = await s.api('GET', `/sessions/${a.json.code}`, undefined, a.json); + assert.equal(r.status, 200); + assert.equal(r.type, 'application/json; charset=utf-8'); + assert.deepEqual(r.json.players.map((p) => p.name), ['img src=x onerror=alert(1) Co', 'Bee']); + assert.ok(r.json.players.every((p) => !('th' in p) && !('token' in p) && !('sv' in p)), 'no secrets in the roster'); + assert.deepEqual(r.json.feed.map((f) => f.k), ['join', 'join']); + assert.ok(!JSON.stringify(r.json).includes(a.json.token)); + // Junk names and homes are refused. + for (const net of [{ name: ' ', home: 'fra' }, { name: '<>&', home: 'fra' }, { name: 'ok', home: '../x' }, { name: 'ok' }]) assert.equal((await s.api('POST', '/sessions', { net, preset: 'oncall' })).status, 400, JSON.stringify(net)); + assert.equal((await s.api('POST', '/sessions', { net: { name: 'x', home: 'fra' }, preset: 'sandbox' })).status, 400, 'only the Normal presets'); + assert.equal((await s.api('POST', '/sessions', { net: { name: 'x'.repeat(80), home: 'fra' }, preset: 'soft' })).json.pid.length, 8); + await s.stop(); +}); + +test('mp server: every call but start and join needs the player\'s token', async () => { + const s = await start(); + const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json; + const p = `/sessions/${a.code}`; + assert.equal((await s.api('GET', p)).status, 401); + assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: b.token })).status, 401, 'someone else\'s token'); + assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: '0'.repeat(64) })).status, 401); + assert.equal((await s.api('GET', p, undefined, { pid: 'zzzzzzzz', token: a.token })).status, 401); + assert.equal((await s.api('GET', p, undefined, null, { authorization: 'Bearer nonsense' })).status, 401); + assert.equal((await s.api('PUT', p + '/card', { card: {} })).status, 401); + assert.equal((await s.api('PUT', p + '/save', { seq: 1, at: 1, data: '{}' })).status, 401); + assert.equal((await s.api('GET', p + '/save')).status, 401); + assert.equal((await s.api('POST', p + '/feed', { text: 'hi' })).status, 401); + assert.equal((await s.api('DELETE', p + '/me')).status, 401); + assert.equal((await s.api('GET', p, undefined, a)).status, 200); + assert.equal((await s.api('GET', '/sessions/ZZZZZZ', undefined, a)).status, 404); + assert.equal((await s.api('DELETE', p, undefined, a)).status, 405); + assert.equal((await s.api('GET', '/nope')).status, 404); + await s.stop(); +}); + +test('mp server: a save never overwrites a newer one unless forced', async () => { + const s = await start(); + const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json; + const p = `/sessions/${a.code}/save`; + assert.equal((await s.api('GET', p, undefined, a)).status, 404, 'nothing saved yet'); + const s1 = await s.api('PUT', p, { seq: 1, at: 1000, data: '{"v":1,"day":3}' }, a); + assert.equal(s1.status, 200); + assert.equal(s1.json.seq, 1); + assert.equal(s1.json.roster.players.length, 2, 'the roster rides along'); + assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 1, at: 1000, data: '{"v":1,"day":3}' }); + assert.equal((await s.api('GET', p, undefined, b)).status, 404, 'only your own save'); + const stale = await s.api('PUT', p, { seq: 1, at: 2000, data: '{"v":1,"day":1}' }, a); + assert.equal(stale.status, 409); + assert.equal(stale.json.seq, 1); + assert.equal((await s.api('PUT', p, { seq: 0, at: 1, data: '{}' }, a)).status, 400); + assert.equal((await s.api('PUT', p, { seq: 1.5, at: 1, data: '{}' }, a)).status, 400); + assert.equal((await s.api('PUT', p, { seq: 9, at: 1, data: 'not a save' }, a)).status, 400); + const g = await s.api('PUT', p, { seq: 2, at: 3000, data: 'gz:H4sIAAAA' }, a); + assert.equal(g.json.seq, 2, 'compressed saves are kept as they are'); + const f = await s.api('PUT', p, { seq: 1, at: 4000, data: '{"v":1,"day":9}', force: true }, a); + assert.equal(f.status, 200); + assert.equal(f.json.seq, 3, 'forced: it becomes the newest'); + assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 3, at: 4000, data: '{"v":1,"day":9}' }); + await s.stop(); +}); + +test('mp server: cards keep only what the leaderboard needs, and tell the feed about Tier 1', async () => { + const s = await start(); + const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json; + const junk = { day: 1e12, name: 'Evil', asn: 1, tier: 't0', t1: 'yes', lvl: -5, pops: ['fra', 'fra', '', text: '', at: 1 }, { k: 'join', pid: 'eeeeeeee', name: 'x', at: 1 }, { k: 'evil', name: 'x', at: 1 }]; + f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me(), evil, { pid: '../../x', name: 'bad' }], feed) }]]; + ev('ACT.mpOpen({})'); + assert.ok(await until(() => ev("document.querySelectorAll('#mpBoard .mprow').length===2"))); + for (const id of ['mpBoard', 'mpFeed']) { + const el = doc.getElementById(id); + assert.equal(el.querySelector('img,script,i:not(.mpdot)'), null, `${id}: no markup from the server`); + } + assert.ok(doc.getElementById('mpBoard').textContent.includes(''), 'the name shows as text'); + assert.ok(doc.getElementById('mpFeed').textContent.includes(' /^background: ?#[0-9a-f]{6};?$/i.test(d.getAttribute('style'))), 'colours are colours'); + assert.match(doc.querySelector('#mpBoard .mprow').textContent, /Tier 1/, 'Tier 1 leads the board'); + assert.match(doc.querySelector('#mpBoard .mprow').textContent, /2 POPs/, 'with only real cities'); + assert.equal(ev('window.__xss'), undefined); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: the session panel and the chip on a phone; chat, leaving', async () => { + const f = fake([okStart, okSave]); + const { dom, ev, errors } = await started({ fetch: f, load: { gzip: false } }); + const doc = dom.window.document; + ev('window.innerWidth=360;window.innerHeight=740;renderAll()'); + assert.equal(ev('isPhone()'), true); + const chip = doc.getElementById('hMp'); + assert.ok(chip && !chip.hidden, 'the chip is there'); + assert.match(chip.textContent, /K7Q-2XD/); + // A phone's top bar has no room for it (cash and the date would be cut): hide-sm. Where you stand is a badge on the + // menu button instead, there and on a tablet whose top bar still wraps at fitHud's last step (no layout in jsdom). + assert.ok(chip.classList.contains('hide-sm'), 'not in a phone\'s top bar'); + const badge = doc.querySelector('#hud .menubtn #hMpB'); + assert.ok(badge && !badge.hidden, 'a badge on the menu button'); + const css = [...doc.querySelectorAll('style')].map((x) => x.textContent).join(''); + assert.match(css, /#hud\.fit3 \.mpchip\{display:none !important\}/, 'a tablet drops the chip before the top bar wraps'); + assert.match(css, /\.mpbadge\{display:block\}/); + ev('ACT.menu({})'); + assert.ok(doc.querySelector('#modalCard .mtile[data-act=mpOpen]'), 'the menu has the session'); + f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me({ day: 1, tier: 't2', t1: false, pops: ['fra'], links: [], ix: [], transit: [], ppol: 'open', reach: 0.5, peak: 3, served: 2, cust: 1, rev: 1, cashB: 5, score: 1 }), { ...me(null), pid: 'bbbbbbbb', name: 'Bee', color: '#ff4f9a' }], [{ k: 'join', pid: PID, name: 'Packet Pals', at: Date.now() }]) }], + [/feed$/, (c) => c.body.text === 'fast' ? { status: 429, json: { error: 'slow' } } : { status: 200, json: roster([me()], [{ k: 'chat', pid: PID, name: 'Packet Pals', text: c.body.text, at: Date.now() }]) }], + [/^DELETE .*\/me$/, { status: 200, json: { ok: true } }]]; + doc.querySelector('#modalCard .mtile[data-act=mpOpen]').click(); + assert.ok(await until(() => doc.querySelectorAll('#mpBoard .mprow').length === 2)); + const card = doc.getElementById('modalCard'); + assert.ok(card.querySelector('.btns.cta'), 'the main buttons stay in reach (sticky on a phone)'); + assert.equal(card.querySelector('.mpcode b').textContent, 'K7Q-2XD'); + assert.ok(card.querySelector('details.mpmove #mpLink'), 'the link to another device, folded away'); + assert.match(card.querySelector('#mpLink').value, /#mp=K7Q2XD\.abcd1234\.[0-9a-f]{64}$/); + assert.match(doc.querySelector('#mpBoard .mprow.me').textContent, /you/); + assert.match(doc.getElementById('mpBoard').textContent, /has not finished a day yet/); + assert.equal(ev("$('hMpRank').textContent"), '🌐 #1/2'); + assert.equal(badge.textContent, '#1'); + // Chat. + ev("document.getElementById('mpSay').value='hello there';ACT.mpChat({})"); + assert.ok(await until(() => /hello there/.test(doc.getElementById('mpFeed').textContent))); + assert.equal(doc.getElementById('mpSay').value, '', 'the line went'); + ev("$('toasts').innerHTML='';document.getElementById('mpSay').value='fast';ACT.mpChat({})"); + assert.ok(await until(() => /Slow down/.test(ev("$('toasts').textContent")))); + // Landscape on a phone: still a phone layout. + ev('window.innerWidth=740;window.innerHeight=360;renderAll()'); + assert.ok(doc.getElementById('mpPanel')); + // Leaving: the network stays, the session and the token go. + ev('ACT.mpLeaveAsk({})'); + assert.match(doc.getElementById('modalCard').textContent, /Leave session K7Q-2XD\?/); + ev('ACT.mpLeave({})'); + assert.ok(await until(() => ev('S.mp===null'))); + assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), null); + assert.equal(doc.getElementById('hMp').hidden, true); + assert.equal(badge.hidden, true); + assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp, null, 'saved without it'); + assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'and the list of networks forgets the session too'); + assert.doesNotMatch(ev('slotListHtml()'), /K7Q-2XD/); + ev('dayTick();save(true)'); + assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'for good'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: the server away: the game plays on, backs off, says so once', async () => { + const f = fake([okStart, okSave]); + const { dom, ev, errors } = await started({ fetch: f }); + f.routes = [[/./, new Error('offline')]]; + ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.fails===1'))); + assert.ok(ev('MP.wait>performance.now()'), 'it waits before the next try'); + assert.match(ev("$('toasts').textContent"), /server is away/); + ev('dayTick();MP.last-=16000;save(true)'); + assert.equal(f.saves().length, 2, 'not while it waits'); + ev("$('toasts').innerHTML='';MP.wait=0;dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.fails===2'))); + assert.equal(ev("$('toasts').textContent"), '', 'told once'); + // Too many at once (429, or the server's own 503 "busy") is not "away": a short wait, quietly, and the back-off stays + // where it was. Behind a proxy without --trust-proxy every player is one address, so this happens to honest players. + for (const r of [{ status: 429, json: { error: 'slow down' } }, { status: 503, json: { error: 'busy', busy: true } }]) { + f.routes = [[/save$/, r]]; + ev("MP.told=false;MP.wait=0;dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('!MP.busy&&MP.wait>performance.now()'))); + assert.equal(ev('MP.fails'), 2, String(r.status)); + assert.ok(ev('MP.wait-performance.now()') <= 30000); + assert.equal(ev("$('toasts').textContent"), '', 'nothing to tell'); + } + // A proxy's own 503 (the server behind it is down) is "away". + f.routes = [[/save$/, { status: 503, json: null }]]; + ev("MP.wait=0;dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.fails===3'))); + assert.match(ev("$('toasts').textContent"), /server is away/); + f.routes = [okSave]; + ev('MP.wait=0;dayTick();MP.last-=16000;save(true)'); + assert.ok(await until(() => ev('MP.fails===0&&!MP.told')), 'back: all forgotten'); + assert.ok(ev('S.day') >= 4, 'and the game went on all along'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: S.mp from a save is checked; saves without it load as before', () => { + const { ev, errors } = load({ mp: MPA, fetch: fake() }); + ev(`ACT.start({});if(UI.pendGame)ACT.pitchSkip();${quiet}`); + assert.equal(ev('S.mp'), null, 'a game outside a session'); + const fix = (m, mode = 'normal') => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.mode=${lit(mode)};s.mp=${lit(m)};return JSON.stringify(sanitize(s).mp);})()`)); + assert.deepEqual(fix({ code: CODE, pid: PID, asn: 999, seed: 1e12, preset: 'sandbox', color: 'javascript:x', title: 'x'.repeat(99), seq: -4, token: TOK, extra: 1 }), + { code: CODE, pid: PID, asn: 200000, seed: 2147483647, preset: 'oncall', color: '#ff4f9a', title: 'x'.repeat(40), seq: 0 }); + for (const bad of [null, 7, 'K7Q2XD', [], { code: '../../x', pid: PID }, { code: CODE, pid: 'ABC' }, { code: 'k7q2xd', pid: PID }]) assert.equal(fix(bad), null, JSON.stringify(bad)); + assert.equal(fix({ code: CODE, pid: PID }, 'sandbox'), null, 'only a Normal game can be in a session'); + // An old save: no mp at all. + ev('const s=JSON.parse(JSON.stringify(S));delete s.mp;S=migrate(s);compute();dayTick();save(true)'); + assert.equal(ev('S.mp'), null); + assert.equal(ev("'mp' in S"), true); + ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('S.mp'), null, 'and it round-trips'); + assert.equal(ev("slotClean({id:'abc',mp:'K7Q2XD.abcd1234'}).mp"), 'K7Q2XD.abcd1234'); + assert.equal(ev("slotClean({id:'abc',mp:'.x'}).mp"), undefined, 'the slot list checks it too'); + assert.deepEqual(errors, []); +}); + +test('multiplayer: two players against the real server: start, join, see each other', async (t) => { + const { createMp } = require('../scripts/lib/mp'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-e2e-')); + const mp = createMp({ dir, log: () => {} }); + const server = http.createServer((req, res) => { if (!mp.handle(req, res)) { res.writeHead(404); res.end(); } }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + t.after(() => { server.close(); fs.rmSync(dir, { recursive: true, force: true }); }); + const base = `http://127.0.0.1:${server.address().port}`; + // The page's fetch, on the real network (the page's own AbortSignal stays behind: it belongs to another realm). + const net = (u, o = {}) => { const { signal, ...rest } = o; return fetch(base + u, rest); }; + const a = await started({ fetch: net, name: 'Alpha Net' }); + const code = a.ev('S.mp.code'); + const b = load({ mp: MPA, fetch: net, seed: 777 }); + b.ev(`UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Beta Net';ACT.pickStart({city:'nyc'});document.getElementById('mpCode').value=${lit(code.toLowerCase())};ACT.mpJoin({})`); + assert.ok(await until(() => b.ev('!!(S&&S.mp)')), 'B joined'); + b.ev(quiet); + assert.equal(b.ev('S.mp.seed'), a.ev('S.mp.seed'), 'one world'); + assert.equal(b.ev('S.rules.preset'), 'bgp', 'one set of rules'); + assert.notEqual(b.ev('S.asn'), a.ev('S.asn')); + assert.equal(b.ev('S.home'), 'nyc'); + await until(() => b.ev('!MP.busy')); + a.ev('mpRefresh()'); + assert.ok(await until(() => a.ev('MP.roster&&MP.roster.players.length===2')), 'A sees B'); + assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.players.map(p=>p.name))')), ['Alpha Net', 'Beta bNet/b']); + assert.equal(a.ev("MP.roster.players[1].card&&MP.roster.players[1].card.pops.join()"), 'nyc', 'and B\'s card'); + assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.feed.map(f=>f.k))')), ['join', 'join']); + // A plays on a few days and pushes; B's panel shows it. + a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)"); + await until(() => a.ev('!MP.busy')); + assert.equal(a.ev('S.mp.seq'), 2); + b.ev('ACT.mpOpen({})'); + assert.ok(await until(() => /Alpha Net/.test(b.ev("document.getElementById('mpBoard').textContent")))); + b.ev("document.getElementById('mpSay').value='hi from B';ACT.mpChat({})"); + assert.ok(await until(() => /hi from B/.test(b.ev("document.getElementById('mpFeed').textContent")))); + // B moves to another device by its link. + const link = b.ev('mpLink(S.mp)'); + await until(() => b.ev('!MP.busy')); + const c = load({ mp: MPA, fetch: net, url: link }); + assert.ok(await until(() => c.ev('!!(S&&S.mp&&UI.started)')), 'B on the other device'); + assert.equal(c.ev('S.name'), 'Beta Net'); + assert.equal(c.ev('S.home'), 'nyc'); + for (const h of [a, b, c]) { assert.deepEqual(h.errors, []); h.dom.window.close(); } + await mp.flush(); +}); + +test('multiplayer: the save here and the one on the server carry the same number: reopening finds nothing newer', async () => { + const srv = store(), f = fake(srv.routes); + const a = await started({ fetch: f }); + const slot = (h) => JSON.parse(h.ev('localStorage.getItem(SLOT_K+UI.slot)')); + a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)"); + await until(() => a.ev('!MP.busy')); + assert.equal(srv.st.save.seq, 2); + assert.equal(JSON.parse(srv.st.save.data).mp.seq, 2, 'the server\'s copy says 2'); + assert.equal(slot(a).mp.seq, 2, 'and so does the one here: the number was picked before the save was written'); + // Closing the tab after a new day: the last save goes as a keepalive request, numbered the same here and there. + a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))"); + assert.equal(f.calls.at(-1).keepalive, true); + await until(() => a.ev('!MP.busy')); + assert.equal(srv.st.save.seq, 3); + assert.equal(slot(a).mp.seq, 3); + assert.equal(slot(a).day, srv.day()); + const storage = storageOf(a); + a.dom.window.close(); + // Reopened on the same device: nothing newer on the server, nothing loaded, nothing said. + const g = fake(srv.routes); + const b = load({ mp: MPA, fetch: g, storage }); + assert.ok(await until(() => g.calls.some((c) => /K7Q2XD$/.test(c.url))), 'asked, then took the roster'); + await flush(); + assert.doesNotMatch(b.ev("$('toasts').textContent"), /Loaded the newer save/); + // A push still on its way when the page goes away: the newer save goes anyway, and cuts the slower one short. + b.ev(quiet); + srv.st.hold = true; + b.ev('dayTick();MP.last-=16000;save(true)'); + const slow = g.calls.at(-1); + assert.equal(slow.keepalive, false); + assert.equal(b.ev('MP.busy'), true); + const k = g.calls.length; + b.ev('for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)'); + assert.equal(g.calls.length, k, 'one push at a time while the page is on screen'); + b.ev("window.dispatchEvent(new Event('pagehide'))"); + const last = g.calls.at(-1); + assert.equal(last.keepalive, true); + assert.equal(last.body.seq, slow.body.seq + 1); + assert.equal(JSON.parse(last.body.data).day, b.ev('S.day'), 'the days played meanwhile go too'); + assert.equal(slow.signal.aborted, true, 'the slower one was cut short'); + await until(() => b.ev('!MP.busy')); + assert.equal(srv.day(), b.ev('S.day')); + assert.equal(slot(b).mp.seq, srv.st.save.seq); + // Reopened once more: the server's copy is this one, so the days stay. + const day = b.ev('S.day'), again = storageOf(b); + b.dom.window.close(); + const c = load({ mp: MPA, fetch: fake(srv.routes), storage: again }); + await flush(10); + assert.equal(c.ev('S.day'), day); + assert.doesNotMatch(c.ev("$('toasts').textContent"), /Loaded the newer save|moved on elsewhere/); + for (const h of [b, c]) assert.deepEqual(h.errors, []); + assert.deepEqual(a.errors, []); + c.dom.window.close(); +}); + +test('multiplayer: the server briefly away when the network opens is no conflict later', async () => { + const srv = store(), a = await started({ fetch: fake(srv.routes) }); + a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)"); + await until(() => a.ev('!MP.busy')); + a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))"); + await until(() => a.ev('!MP.busy')); + const storage = storageOf(a); + a.dom.window.close(); + const g = fake([[/./, new Error('offline')]]); + const b = load({ mp: MPA, fetch: g, storage }); + assert.ok(await until(() => b.ev('MP.fails===1'))); + b.ev(quiet + "for(let i=0;i<10;i++)dayTick();MP.wait=0;MP.last-=16000"); + g.routes = srv.routes; + b.ev('save(true)'); + await until(() => b.ev('!MP.busy')); + assert.equal(b.ev('MP.stale'), false, 'one device, so no "moved on elsewhere"'); + assert.equal(srv.day(), b.ev('S.day')); + assert.deepEqual(b.errors, []); + b.dom.window.close(); +}); + +test('multiplayer: hiding the page sends what changed on the same game day, only then, in a request that fits', async () => { + const srv = store(), f = fake(srv.routes); + const { dom, ev, errors } = await started({ fetch: f }); + const n = () => f.saves().length, k = n(); + // A paused game: the player builds, and the day never moves. + ev("ACT.launchBB({city:'fra'})"); + assert.equal(n(), k, 'same day, page on screen: nothing yet'); + ev(hide()); + assert.equal(n(), k + 1, 'hidden: what changed goes'); + assert.equal(f.saves().at(-1).keepalive, true); + assert.ok(JSON.parse(f.saves().at(-1).body.data).pops.fra.bb, 'with the change'); + await until(() => ev('!MP.busy')); + ev(hide()); + assert.equal(n(), k + 1, 'hidden again, nothing changed: nothing sent'); + // Moving to another device: the link goes with what this one has now. + ev(hide(false) + "S.name='Packet Pals Two';ACT.mpOpen({});ACT.mpCopyLink({})"); + assert.equal(n(), k + 2); + assert.equal(JSON.parse(f.saves().at(-1).body.data).name, 'Packet Pals Two'); + await until(() => ev('!MP.busy')); + ev("S.name='Packet Pals Three';const d=document.querySelector('#mpPanel details.mpmove');d.open=true;d.dispatchEvent(new Event('toggle'))"); + assert.equal(n(), k + 3, 'opening "Move to another device" pushes too'); + await until(() => ev('!MP.busy')); + // A keepalive request may carry 64 KiB in all: the request is measured, in bytes, quotes escaped, card and all. + ev('closeModal();' + hide()); + const send = (t) => { ev(`dayTick();S.mp.seq++;mpPush(${lit(t)})`); const c = f.calls.at(-1); return c.url.replace(/.*\//, ''); }; + assert.equal(send('{"x":"' + 'a'.repeat(50000) + '"}'), 'save', '50 kB of plain text fits'); + await until(() => ev('!MP.busy')); + assert.equal(send('{"x":[' + Array(10000).fill('"ab"').join(',') + ']}'), 'card', '50 kB of text with quotes does not'); + await until(() => ev('!MP.busy')); + assert.equal(send('{"x":"' + 'é'.repeat(40000) + '"}'), 'card', '40 000 characters of two bytes do not'); + await until(() => ev('!MP.busy')); + for (const c of f.calls.filter((x) => x.keepalive)) assert.ok(Buffer.byteLength(c.raw) < 63000, `${c.url}: ${Buffer.byteLength(c.raw)} bytes`); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: "Load the newer save" never loads an older one; "Keep this one" waits for the day to end', async () => { + const srv = store(), f = fake(srv.routes); + const { dom, ev, errors } = await started({ fetch: f }); + const day0 = srv.st.save; + ev("ACT.launchBB({city:'fra'});for(let i=0;i<5;i++)dayTick();MP.last-=16000;save(true)"); + await until(() => ev('!MP.busy')); + // The server says it has a newer save (409, number 3) but holds an older one (number 1, day 0). + srv.st.save = day0; + f.routes = [[/^PUT .*\/save$/, { status: 409, json: { error: 'newer', seq: 3, at: 1 } }], ...srv.routes]; + ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.stale'))); + const day = ev('S.day'); + ev('ACT.mpNewer({})'); + assert.ok(await until(() => /no newer save/.test(ev("$('toasts').textContent")))); + assert.equal(ev('S.day'), day, 'not rolled back to day 0'); + assert.equal(ev('MP.stale'), false); + f.routes = srv.routes; + ev('dayTick();MP.last-=16000;save(true)'); + await until(() => ev('!MP.busy')); + assert.equal(srv.day(), ev('S.day'), 'and the next push puts this one on the server'); + // Another device pushed number 9 meanwhile; the player keeps theirs, clicking while the day is still routing. + srv.st.save = { ...srv.st.save, seq: 9 }; + ev('dayTick();MP.last-=16000;save(true)'); + assert.ok(await until(() => ev('MP.stale&&MP.staleSeq===9'))); + const k = f.saves().length; + ev('RW.job={};ACT.mpKeep({})'); + assert.equal(f.saves().length, k, 'never half a day'); + ev('RW.job=null;rwDayDone()'); + const kept = f.saves().at(-1); + assert.equal(f.saves().length, k + 1, 'the day\'s end pushes it'); + assert.equal(kept.body.force, true); + assert.equal(kept.body.seq, 10, 'past the server\'s number, so it keeps the one it was sent'); + await until(() => ev('!MP.busy')); + assert.equal(srv.st.save.seq, 10); + assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp.seq, 10); + assert.equal(ev('MP.force'), false); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: a #mp= link never replaces nor deletes the token this browser has; a busy network is not copied', async () => { + const srv = store(), b = browser(), tab1 = new Map(); + const real = (c) => c.method === 'POST' || c.headers.authorization === `Bearer ${PID}.${TOK}`; + const guarded = srv.routes.map(([re, h]) => [re, (c) => (real(c) ? (typeof h === 'function' ? h(c) : h) : { status: 401, json: { error: 'unauthorized' } })]); + const f1 = fake(guarded); + const t1 = await started({ fetch: f1, load: { browser: b, tab: tab1 } }); + t1.ev("ACT.launchBB({city:'fra'});for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)"); + await until(() => t1.ev('!MP.busy')); + const link = t1.ev('mpLink(S.mp)'), wrong = link.replace(/[0-9a-f]{64}$/, '0'.repeat(64)), tok = () => b.ls.get(`sot-mp:${CODE}:${PID}`); + const slots = () => JSON.parse(b.ls.get('sot-slots')).slots.length; + // A wrong link (a rival's, or one mistyped character) while the game is open in another tab. + const t2 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong }); + assert.ok(await until(() => /did not work/.test(t2.ev("$('toasts').textContent")))); + assert.equal(tok(), TOK, 'the real token stays'); + assert.equal(slots(), 1); + t1.ev('dayTick();MP.last-=16000;save(true)'); + assert.equal(f1.calls.at(-1).headers.authorization, `Bearer ${PID}.${TOK}`, 'and the open tab plays on in its session'); + await until(() => t1.ev('!MP.busy')); + assert.equal(t1.ev('MP.gone'), false); + // The right link, while the network is open in the other tab: no second copy, the choice to take it over. + const t3 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: link }); + assert.ok(await until(() => t3.ev("!!document.querySelector('#modal [data-act=slotTake]')")), 'offered to take it over'); + assert.equal(slots(), 1, 'not copied into a second slot'); + // The server away: the link may be fine, so it is not called bad, stays for a reload, and no token changes. + b.close(t1.dom.window); + const t4 = load({ mp: MPA, fetch: fake([[/./, new Error('offline')]]), browser: b, tab: new Map(), url: wrong }); + assert.ok(await until(() => /cannot be reached/.test(t4.ev("$('toasts').textContent")))); + assert.equal(t4.ev('location.hash'), new URL(wrong).hash, 'kept for a reload'); + assert.equal(tok(), TOK); + // A wrong link once the game's tab is closed: still told, still the real token. + const t5 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong }); + assert.ok(await until(() => /did not work/.test(t5.ev("$('toasts').textContent")))); + assert.equal(tok(), TOK); + assert.equal(t5.ev('location.hash'), '', 'a bad link is gone from the address bar'); + // A fresh browser, server away: nothing stored at all. + const b2 = browser(), t6 = load({ mp: MPA, fetch: fake([[/./, { status: 503, json: { error: 'busy' } }]]), browser: b2, tab: new Map(), url: link }); + assert.ok(await until(() => /cannot be reached/.test(t6.ev("$('toasts').textContent")))); + assert.equal(b2.ls.get(`sot-mp:${CODE}:${PID}`), undefined); + for (const h of [t1, t2, t3, t4, t5, t6]) assert.deepEqual(h.errors.filter((e) => !/moving the network here failed/.test(e)), []); + for (const h of [t1, t2, t3, t4, t5, t6]) h.dom.window.close(); +}); + +test('multiplayer: the session panel\'s refresh while the server is away says so once and never stretches the wait', async () => { + const f = fake([okStart, okSave, [/^GET /, { status: 200, json: roster([me()]) }]]); + const { dom, ev, errors } = await started({ fetch: f }); + ev('ACT.mpOpen({})'); + await flush(); + f.routes = [[/./, new Error('offline')]]; + ev("$('toasts').innerHTML=''"); + for (let i = 0; i < 6; i++) { ev('mpPollTick()'); await flush(); } + assert.equal(f.calls.filter((c) => c.method === 'GET').length >= 6, true, 'it still looks every few seconds'); + assert.equal(ev('MP.fails'), 1); + assert.ok(ev('MP.wait-performance.now()') <= 30000, 'the push back-off stays at its first step'); + assert.equal(ev("$('toasts').textContent.split('server is away').length-1"), 1, 'said once'); + f.routes = [okSave, [/^GET /, { status: 200, json: roster([me()]) }]]; + ev('mpPollTick()'); + assert.ok(await until(() => ev('MP.fails===0&&MP.wait===0')), 'back: all forgotten'); + const k = f.calls.length; + ev('closeModal();mpPollTick()'); + assert.equal(f.calls.length, k, 'a closed panel stops asking'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: with a charter to sign first, the session code and its Share button wait for it', async () => { + const f = fake([okStart, okSave]); + const { dom, ev, errors } = load({ mp: MPA, fetch: f }); + const doc = dom.window.document; + ev("window.__TUBES_CHARTER__=true;UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Packet Pals';ACT.presetSet({p:'bgp'});ACT.mpStart({})"); + assert.ok(await until(() => ev('!!(S&&S.mp)'))); + assert.equal(ev("$('modal').className"), 'charter', 'the charter comes first'); + assert.equal(doc.querySelector('#toasts [data-act=mpShare]'), null, 'no buttons under it that cannot be pressed'); + ev('ACT.charter({k:Object.keys(CHARTERS)[0]})'); + const share = doc.querySelector('#toasts [data-act=mpShare]'); + assert.ok(share, 'signed: the code to share'); + assert.match(doc.getElementById('toasts').textContent, /K7Q-2XD/); + share.click(); + assert.match(doc.getElementById('toasts').textContent, /Join my Series of Tubes session K7Q-2XD/, 'and its button works'); + assert.deepEqual(errors, []); + dom.window.close(); +}); From 2cd6b71198d3b11f863ff2772c4e923bf7c249c9 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:01:50 +0100 Subject: [PATCH 413/491] =?UTF-8?q?Dark=20mode:=20Light,=20Dark=20or=20Aut?= =?UTF-8?q?o=20under=20Settings=20=E2=80=BA=20Theme=20(#80)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A device preference (localStorage sot-theme, never in the save), applied by a small script in before the first paint, so there is no flash; Auto follows prefers-color-scheme live, and a choice reaches other tabs and the NOC window. Panels, HUD, drawers, toasts, modals, the phone tab bar, charts, puzzles, the architect and Pie Control take their colours from custom properties with night values (AA text contrast); light tints keep their old colour as the fallback, so the light look is unchanged. Both map renderers read a light and a dark palette (96-map/15-palette.js): sea, land, clouds, coastlines, labels and the tube outline. A theme switch repaints the cached layers once (the WebGL land buffers are rebuilt once); nothing changes per frame. The multiplayer leaderboard's own row and the menu rank badge follow the theme too. --- CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 6 +- 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/agent/20-commands.js | 2 +- src/game/60-features/30-conferences.js | 2 +- src/game/60-features/36-specialist.js | 6 +- src/game/60-features/37-cable-broker.js | 4 +- .../85-incidents/10-incidents-and-ddos.js | 2 +- src/game/85-incidents/40-chaos-monkey.js | 2 +- src/game/90-actions/10-interface.js | 1 + src/game/90-actions/95-puzzles.js | 2 +- src/game/93-ui/15-theme.js | 27 ++ src/game/93-ui/30-install.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/70-link-panels.js | 4 +- src/game/94-dashboard/60-dashboard.js | 2 +- src/game/94-dashboard/65-chart-legend.js | 5 +- src/game/96-map/15-palette.js | 11 + src/game/96-map/30-settings.js | 1 + src/game/96-map/50-link-geometry.js | 2 +- src/game/96-map/57-webgl-background.js | 33 +- src/game/96-map/58-webgl-links.js | 16 +- src/game/96-map/60-draw.js | 32 +- src/game/96-map/80-cities.js | 4 +- src/game/96-map/85-puzzle-cities.js | 2 +- src/game/96-map/89-pie-globe.js | 3 +- src/game/96-map/95-clicks.js | 2 +- src/i18n/en.js | 4 + src/index.html | 9 + src/styles/00-base.css | 8 +- src/styles/05-theme.css | 23 ++ src/styles/10-hud.css | 4 +- src/styles/20-drawers.css | 20 +- src/styles/30-toasts.css | 6 +- src/styles/36-ops.css | 6 +- src/styles/38-pie-globe.css | 2 +- src/styles/40-modal.css | 58 +-- src/styles/41-multiplayer.css | 4 +- src/styles/42-chart-tooltips.css | 4 +- src/styles/45-noc-window.css | 2 +- src/styles/60-phone.css | 18 +- src/styles/70-puzzles.css | 38 +- src/styles/71-architect.css | 16 +- tests/build.test.js | 2 +- tests/dark-mode.test.js | 380 ++++++++++++++++++ 49 files changed, 645 insertions(+), 155 deletions(-) create mode 100644 src/game/93-ui/15-theme.js create mode 100644 src/game/96-map/15-palette.js create mode 100644 src/styles/05-theme.css create mode 100644 tests/dark-mode.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a6901a9..e349380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. +- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 77b2a1e..aad1e5e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,13 +38,13 @@ hoisted across files, and top-level statements run in path order. Find code by n | `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` | | `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers | | `91-save.js`, `92-audio.js` | Save, export and import; sound effects | -| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning | +| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the theme (light, dark or Auto: `15-theme.js`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning | | `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, cities with no POP yet, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints | | `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals | -| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation | +| `96-map/` | The canvas: resize, the map's colours per theme (`15-palette.js`), land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation | | `99-loop.js` | `frame()` and `boot()` | -`src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone. +`src/styles/` holds the CSS the same way: base, the dark theme's colours (`05-theme.css`), HUD, drawers, toasts, modal, tablet, then phone. `src/agent/` is the agent facade (`window.TUBES`): the typed commands, reads and screens the MCP server plays through. It is assembled into the **development page** only (`npm run dev`, the MCP server, tests that ask for it); diff --git a/site/i18n/de.js b/site/i18n/de.js index 94cc2cd..405ba56 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -4540,12 +4540,15 @@ "settings.always_2d":"Immer 2D", "settings.an_early_heads_up_below_60":"Eine frühe Warnung unter 60 % Zufriedenheit, lange bevor sie wütend sind.", "settings.auto_draws_the_map_with_your":"Auto zeichnet die Karte mit deiner Grafikkarte, wenn der Browser es erlaubt, damit auch große Netze flüssig bleiben. Immer 2D läuft überall, ist auf großen Karten aber langsamer.", +"settings.auto_follows_your_device_s_light":"Auto folgt der Hell- oder Dunkel-Einstellung deines Geräts. Dunkel schont nachts die Augen und auf OLED-Bildschirmen den Akku.", "settings.auto_follows_your_device_s_reduce":"Auto folgt der Einstellung „Bewegung reduzieren“ deines Geräts. Aus friert die Karte ein: keine wandernden Pakete, kein Pulsieren, kein schwebender Text.", "settings.customers_and_alerts":"Kunden und Warnungen", +"settings.dark":"Dunkel", "settings.diagnostic_info":"Diagnoseinfos", "settings.display_and_sound":"Anzeige und Ton", "settings.for_bug_reports_shows_your_screen":"Für Fehlerberichte: zeigt in einer Ecke die Größe deines Bildschirms, wie die Karte gezeichnet wird (Grafikkarte oder 2D, und warum) und wie schnell.", "settings.let_an_ai_agent_drive_this_game":"Eine KI soll dieses Spiel spielen", +"settings.light":"Hell", "settings.map_drawing":"Kartendarstellung", "settings.n_min":"{n} Min.", "settings.n_sec":"{n} s", @@ -4559,6 +4562,7 @@ "settings.the_agent_moves_it":"Der Agent stellt sie", "settings.the_clock_while_an_agent_plays":"Die Uhr, während ein Agent spielt", "settings.the_game_stops_so_you_can":"Das Spiel hält an, damit du ihren Dienst reparieren kannst, bevor sie kündigen. Am nützlichsten bei hoher Geschwindigkeit.", +"settings.theme":"Design", "settings.this_browser_cannot_so_the_map":"Dieser Browser kann das nicht, also wird die Karte in 2D gezeichnet.", "settings.warn_when_a_customer_gets_unhappy":"Bei unzufriedenen Kunden warnen", "settings.while_agent_mode_is_on_the":"Solange der Agenten-Modus an ist, gehört die Uhr nicht dir. Mit Tempo läuft sie von selbst und lässt sich von Hand nicht anhalten, auch nicht durch ein offenes Fenster (deins eingeschlossen), und sie wartet, solange kein Agent verbunden ist. Oder der Agent stellt sie, und nichts passiert, bis er nach Tagen fragt. Die Seite verbindet sich mit dem lokalen Agenten-Relay (npm run dev bringt eins mit), damit Tools wie der MCP-Server dieses Spiel spielen können, während du zusiehst.", diff --git a/site/i18n/es.js b/site/i18n/es.js index cf40d69..427ba64 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Siempre 2D", "settings.an_early_heads_up_below_60":"Un aviso temprano por debajo del 60 % de felicidad, mucho antes de que estén furiosos.", "settings.auto_draws_the_map_with_your":"Auto dibuja el mapa con tu tarjeta gráfica cuando el navegador lo permite, y así las redes grandes siguen fluidas. Siempre 2D funciona en todas partes, pero va más lento en mapas grandes.", +"settings.auto_follows_your_device_s_light":"Auto sigue el ajuste claro u oscuro de tu dispositivo. El oscuro descansa la vista de noche y ahorra batería en pantallas OLED.", "settings.auto_follows_your_device_s_reduce":"Auto sigue el ajuste de reducir movimiento de tu dispositivo. Desactivado congela el mapa: sin paquetes en movimiento, pulsos ni texto flotante.", "settings.customers_and_alerts":"Clientes y alertas", +"settings.dark":"Oscuro", "settings.diagnostic_info":"Información de diagnóstico", "settings.display_and_sound":"Pantalla y sonido", "settings.for_bug_reports_shows_your_screen":"Para informar de fallos: muestra en una esquina el tamaño de tu pantalla, cómo se dibuja el mapa (tarjeta gráfica o 2D, y por qué) y a qué velocidad.", "settings.let_an_ai_agent_drive_this_game":"Deja que un agente de IA juegue", +"settings.light":"Claro", "settings.map_drawing":"Dibujo del mapa", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"Lo mueve el agente", "settings.the_clock_while_an_agent_plays":"El reloj mientras juega un agente", "settings.the_game_stops_so_you_can":"El juego se detiene para que arregles su servicio antes de que cancelen. Muy útil a alta velocidad.", +"settings.theme":"Tema", "settings.this_browser_cannot_so_the_map":"Este navegador no puede, así que el mapa se dibuja en 2D.", "settings.warn_when_a_customer_gets_unhappy":"Avisar cuando un cliente se descontenta", "settings.while_agent_mode_is_on_the":"Mientras el modo agente está activo, el reloj no es tuyo. Con un ritmo, corre solo y no se puede pausar a mano, ni siquiera con una ventana abierta (las tuyas incluidas), y espera mientras no haya ningún agente conectado. O lo mueve el agente, y no pasa nada hasta que pide días. La página se conecta al relay local de agentes (npm run dev trae uno), para que herramientas como el servidor MCP jueguen esta partida mientras miras.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f1c7c81..2a134ae 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Toujours en 2D", "settings.an_early_heads_up_below_60":"Une alerte précoce sous 60 % de satisfaction, bien avant qu’il soit furieux.", "settings.auto_draws_the_map_with_your":"Auto dessine la carte avec ta carte graphique quand le navigateur le permet, ce qui garde les grands réseaux fluides. Toujours en 2D marche partout mais rame sur les grandes cartes.", +"settings.auto_follows_your_device_s_light":"Auto suit le réglage clair ou sombre de ton appareil. Le sombre repose les yeux la nuit et économise la batterie sur les écrans OLED.", "settings.auto_follows_your_device_s_reduce":"Auto suit le réglage « réduire les animations » de ton appareil. Inactif fige la carte : plus de paquets en mouvement, de pulsations ni de texte flottant.", "settings.customers_and_alerts":"Clients et alertes", +"settings.dark":"Sombre", "settings.diagnostic_info":"Infos de diagnostic", "settings.display_and_sound":"Affichage et son", "settings.for_bug_reports_shows_your_screen":"Pour signaler un bug : affiche dans un coin la taille de ton écran, comment la carte est dessinée (carte graphique ou 2D, et pourquoi) et à quelle vitesse.", "settings.let_an_ai_agent_drive_this_game":"Laisser un agent IA jouer", +"settings.light":"Clair", "settings.map_drawing":"Dessin de la carte", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"L'agent l'avance", "settings.the_clock_while_an_agent_plays":"L'horloge pendant qu'un agent joue", "settings.the_game_stops_so_you_can":"Le jeu s’arrête pour que tu répares leur service avant qu’ils résilient. Surtout utile à grande vitesse.", +"settings.theme":"Thème", "settings.this_browser_cannot_so_the_map":"Ce navigateur ne peut pas, la carte est donc dessinée en 2D.", "settings.warn_when_a_customer_gets_unhappy":"Prévenir quand un client devient mécontent", "settings.while_agent_mode_is_on_the":"Tant que le mode agent est actif, l'horloge n'est plus à toi. Avec un rythme, elle tourne toute seule et ne peut pas être mise en pause à la main, pas même par une fenêtre ouverte (les tiennes comprises), et elle attend tant qu'aucun agent n'est connecté. Ou bien c'est l'agent qui l'avance, et rien ne se passe tant qu'il ne demande pas de jours. La page se connecte au relais local pour agents (npm run dev en lance un), pour que des outils comme le serveur MCP jouent cette partie pendant que tu regardes.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 1db1657..2d75e8e 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Sempre 2D", "settings.an_early_heads_up_below_60":"Un avviso in anticipo sotto il 60% di soddisfazione, molto prima che siano furiosi.", "settings.auto_draws_the_map_with_your":"Auto disegna la mappa con la tua scheda grafica quando il browser lo consente, così anche le reti grandi restano fluide. Sempre 2D funziona ovunque ma è più lento sulle mappe grandi.", +"settings.auto_follows_your_device_s_light":"Auto segue l’impostazione chiara o scura del tuo dispositivo. Lo scuro riposa gli occhi di notte e fa risparmiare batteria sugli schermi OLED.", "settings.auto_follows_your_device_s_reduce":"Auto segue l’impostazione “riduci movimento” del tuo dispositivo. Off congela la mappa: niente pacchetti in movimento, pulsazioni o testo fluttuante.", "settings.customers_and_alerts":"Clienti e avvisi", +"settings.dark":"Scuro", "settings.diagnostic_info":"Info di diagnostica", "settings.display_and_sound":"Schermo e audio", "settings.for_bug_reports_shows_your_screen":"Per segnalare bug: mostra in un angolo le dimensioni dello schermo, come viene disegnata la mappa (scheda grafica o 2D, e perché) e a che velocità.", "settings.let_an_ai_agent_drive_this_game":"Lascia giocare un agente IA", +"settings.light":"Chiaro", "settings.map_drawing":"Disegno della mappa", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"Lo muove l'agente", "settings.the_clock_while_an_agent_plays":"L'orologio mentre gioca un agente", "settings.the_game_stops_so_you_can":"Il gioco si ferma così puoi sistemare il servizio prima che disdicano. Utilissimo ad alta velocità.", +"settings.theme":"Tema", "settings.this_browser_cannot_so_the_map":"Questo browser non può, quindi la mappa è disegnata in 2D.", "settings.warn_when_a_customer_gets_unhappy":"Avvisa quando un cliente diventa scontento", "settings.while_agent_mode_is_on_the":"Finché la modalità agente è attiva, l'orologio non è tuo. Con un ritmo va da solo e non si può fermare a mano, nemmeno con una finestra aperta (comprese le tue), e aspetta finché non è collegato nessun agente. Oppure lo muove l'agente, e non succede nulla finché non chiede dei giorni. La pagina si collega al relay locale per agenti (npm run dev ne avvia uno), così strumenti come il server MCP possono giocare questa partita mentre guardi.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 311571c..f65faba 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Sempre 2D", "settings.an_early_heads_up_below_60":"Um aviso antecipado abaixo de 60% de satisfação, bem antes de ficarem furiosos.", "settings.auto_draws_the_map_with_your":"Auto desenha o mapa com sua placa de vídeo quando o navegador permite, o que mantém redes grandes fluidas. Sempre 2D funciona em qualquer lugar, mas é mais lento em mapas grandes.", +"settings.auto_follows_your_device_s_light":"Auto segue a configuração clara ou escura do seu aparelho. O escuro descansa os olhos à noite e economiza bateria em telas OLED.", "settings.auto_follows_your_device_s_reduce":"Auto segue a configuração de reduzir movimento do seu aparelho. Desligado congela o mapa: sem pacotes andando, pulsos ou texto flutuante.", "settings.customers_and_alerts":"Clientes e alertas", +"settings.dark":"Escuro", "settings.diagnostic_info":"Informações de diagnóstico", "settings.display_and_sound":"Tela e som", "settings.for_bug_reports_shows_your_screen":"Para reportar bugs: mostra em um canto o tamanho da sua tela, como o mapa é desenhado (placa de vídeo ou 2D, e por quê) e a que velocidade.", "settings.let_an_ai_agent_drive_this_game":"Deixa um agente de IA jogar", +"settings.light":"Claro", "settings.map_drawing":"Desenho do mapa", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"O agente move-o", "settings.the_clock_while_an_agent_plays":"O relógio enquanto um agente joga", "settings.the_game_stops_so_you_can":"O jogo para para você consertar o serviço antes que cancelem. Muito útil em alta velocidade.", +"settings.theme":"Tema", "settings.this_browser_cannot_so_the_map":"Este navegador não consegue, então o mapa é desenhado em 2D.", "settings.warn_when_a_customer_gets_unhappy":"Avisar quando um cliente ficar insatisfeito", "settings.while_agent_mode_is_on_the":"Enquanto o modo agente estiver ligado, o relógio não é teu. Com um ritmo, corre sozinho e não pode ser parado à mão, nem por uma janela aberta (as tuas incluídas), e espera enquanto nenhum agente estiver ligado. Ou é o agente que o move, e nada acontece até ele pedir dias. A página liga-se ao relay local de agentes (npm run dev traz um), para que ferramentas como o servidor MCP joguem este jogo enquanto vês.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 9d4f554..6d3f47b 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -607,7 +607,7 @@ const API_DENY={ start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', - animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', + animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',themeSet:'prefs',vpSet:'prefs', mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp', install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', }; diff --git a/src/game/60-features/30-conferences.js b/src/game/60-features/30-conferences.js index c3cc0eb..4eb5bea 100644 --- a/src/game/60-features/30-conferences.js +++ b/src/game/60-features/30-conferences.js @@ -19,7 +19,7 @@ function confTick(d){S.confReg=S.confReg||{}; toast(tr('conferences.conf_in_city_you_shook_a',{conf:esc(cf.n),city:esc(CITY[cf.c].name),n:CONF_DAYS,region:esc(REG[reg])})+(sp?' '+tr('conferences.your_logo_was_on_every_lanyard',{region:esc(REG[reg])}):'')+(cf.cap?' '+tr('conferences.carriers_took_your_card_expect_big'):'')+extra,'goal');sfx('coin');} capDealTick(d);} function confSection(){const up=upcomingConfs(75).slice(0,3),cb=S.conf&&S.conf.until>S.day?S.conf:null;if(!up.length&&!cb)return ''; - return `

${tr('common.conferences')}

${cb?`
${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}
${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}
`:''}${up.map(confRow).join('')}`;} + return `

${tr('common.conferences')}

${cb?`
${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}
${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}
`:''}${up.map(confRow).join('')}`;} function confRow(cf){const reg=S.confReg&&S.confReg[cf.key],open=cf.day>S.day,sp=confSp(cf),cost=confCost(cf),lk=cf.cap&&glassLvl()'+tr('conferences.sponsor')+'':reg?''+tr('common.registered')+'':open?'':''+tr('common.registration_closed')+''); const btns=!open||reg==='sp'?'':(reg?'':lk?btn(tr('sites_and_service.level_n',{n:CAP_LV}),'confGo',{key:cf.key},'sm',true):btn(tr('conferences.attend_cost',{cost:fmt$(cost)}),'confGo',{key:cf.key},'sm',S.cash!S.pops[c]).reduce((x,c)=>x+newPopCost(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})}
+ 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')}

`;} @@ -97,8 +97,8 @@ function charterAsk(){if(!charterDue()||!$('modal').hidden||window.__TUBES_TEST_ function charterCard(){if(S.scn||S.mode!=='normal')return ''; if(broker())return baronCard(); 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('')}
`;} + 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, the boutique checks its win and carriers call the broker. function specDay(d){if(broker())brokerDay(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); diff --git a/src/game/60-features/37-cable-broker.js b/src/game/60-features/37-cable-broker.js index b63ed87..b85582d 100644 --- a/src/game/60-features/37-cable-broker.js +++ b/src/game/60-features/37-cable-broker.js @@ -20,8 +20,8 @@ function glassChain(g){const by={};for(const l of S.links)if(ownGlassL(l)&&dfCap return Object.values(by).some(s=>s.size>=2);} const baronOk=()=>cableConts()>=BARON_CONT&&capSalesMo()>=BARON_MO; // On the goals tab, under the charter: how far Glass Baron is. -function baronCard(){if(S.baronWon)return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}
`; - return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}
`;} +function baronCard(){if(S.baronWon)return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}
`; + return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}
`;} function showBaronWin(){openModal(`

🌊 ${tr('broker.glass_baron')}

${tr('broker.win_text',{name:esc(S.name),asn:S.asn,days:S.day,n:BARON_CONT,mo:fmt$(capSalesMo())})}

${btn(tr('help.share_my_network'),'share',{},'pink')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost')}
`);} /* Carriers call the broker now and then (about three times a year, from day 60) with a capacity deal on a route the capacity conferences trade: the same deals at the same terms, without the trip. Picked by a hash of the day, so a diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js index db254dc..ae6107e 100644 --- a/src/game/85-incidents/10-incidents-and-ddos.js +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -120,7 +120,7 @@ function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pop function ddosPanel(){return S?ddosAll().filter(a=>S.pops[a.city]).map(ddosOne).join(''):'';} const ddCities=l=>{const u=[...new Set(l)];return u.slice(0,3).map(c=>CITY[c].name).join(', ')+(u.length>3?' +'+(u.length-3):'');}; function ddosOne(a){const V=DDOS_VEC[a.vec]||{n:'?',fs:false},m=ddosReport(a),row=(ok,t)=>`
${ok===true?'✓':ok===false?'~':'—'} ${t}
`; - let h=`
🚨 ${tr('ddos.card_title',{g:fmtG(a.gbps),vec:esc(V.n)})}
+ let h=`
🚨 ${tr('ddos.card_title',{g:fmtG(a.gbps),vec:esc(V.n)})}
${esc(ddosWho(a))} · ${tr('ui.n_d_left',{n:Math.max(1,a.until-S.day)})}${a.carpet?' · '+tr('ddos.carpet'):''}
`; if(!m)return h+'
'; const engIdle=hasScrub()&&!a.bh&&m.eng<1&&S.scrubMode==='ondemand'&&S.ddosAuto&&S.ddosAuto.scrub===false&&a.eng===undefined; diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 6798c37..513979b 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -50,4 +50,4 @@ function mkLeave(why){const M=S.monkey,d=S.day,ok=!why&&M.n>0&&M.hurt===0;M.on=0 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
`;} + 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/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 7a0715e..80ec9fc 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -23,6 +23,7 @@ const ACT={ leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=glassLvl()>=3?'roadm':'lite';openLinkModal(a,b);}, dashLink:({id})=>{$('dash').hidden=true;selectLink(id);focusLink(id);}, mapSet:({v})=>{if(!['auto','2d'].includes(v))return;mapGl(v==='auto');refreshSettings();}, + themeSet:({v})=>{if(!themePick(v))return;refreshSettings();}, animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();}, soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();}, langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();}, diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 881800c..560d802 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -62,6 +62,6 @@ Object.assign(ACT,{ // 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','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); +const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','themeSet','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/93-ui/15-theme.js b/src/game/93-ui/15-theme.js new file mode 100644 index 0000000..c081ce1 --- /dev/null +++ b/src/game/93-ui/15-theme.js @@ -0,0 +1,27 @@ +/* ---------- Light or dark (#80) ---------- + Settings › Theme: Auto follows the device's light or dark setting, or the player picks one. A choice per device + (localStorage sot-theme, like the animation and map settings), not part of the save. The page's reads it and + sets before the first paint, so a dark screen never flashes light; this keeps it in step when the + choice or the device's setting changes. The panels follow at once (CSS custom properties, 00-base.css); the map + keeps pictures painted in the old colours, so it paints them again, once (themeRepaint()). */ +const THEME_OPTS=['auto','light','dark'],THEME_BAR={light:'#57C4E5',dark:'#0E2A44'}; // the browser bar: --sea +const THEME={pref:'auto',dark:false,mq:null,on:null}; +function themeRead(){let v=null;try{v=localStorage.getItem('sot-theme');}catch(e){}return THEME_OPTS.includes(v)?v:'auto';} +const themeSys=()=>{try{return !!(THEME.mq&&THEME.mq.matches);}catch(e){return false;}}; +// The page's colours from the choice (and the device's setting, on Auto). A switch repaints the map's cached pictures. +function themeApply(repaint=true){const dark=THEME.pref==='dark'||(THEME.pref==='auto'&&themeSys()),was=THEME.dark,R0=document.documentElement; + THEME.dark=dark;R0.setAttribute('data-theme',dark?'dark':'light'); + for(const [n,v] of [['theme-color',THEME_BAR[dark?'dark':'light']],['color-scheme',dark?'dark':'light']]){const m=document.querySelector(`meta[name="${n}"]`);if(m)m.setAttribute('content',v);} + if(repaint&&was!==dark)themeRepaint();return dark;} +function themePick(v){if(!THEME_OPTS.includes(v))return false;THEME.pref=v;try{v==='auto'?localStorage.removeItem('sot-theme'):localStorage.setItem('sot-theme',v);}catch(e){}themeApply();return true;} +// Reads the choice and listens to the device's setting, which Auto follows as it changes (a phone at dusk). +function themeInit(){THEME.pref=themeRead();THEME.on=()=>{if(THEME.pref==='auto')themeApply();}; + try{THEME.mq=window.matchMedia?matchMedia('(prefers-color-scheme: dark)'):null;}catch(e){} + const q=THEME.mq;if(q){try{q.addEventListener?q.addEventListener('change',THEME.on):q.addListener(THEME.on);}catch(e){}} + THEME.dark=document.documentElement.getAttribute('data-theme')==='dark';return themeApply(false);} +/* What the map painted in the old colours: the land (the 2D picture, the card's coastlines), every sprite (labels, + cities), the Pie globe unless the player chose its day or night. All painted again on the next frame, not every frame. */ +function themeRepaint(){WL.key=null;FRAME.length=0;UI.drawnAt=0;spritesReset();glLandDrop(); + let g=null;try{g=localStorage.getItem('sot-globe');}catch(e){}if(!g){PG.night=THEME.dark;PG.g=null;PG.dirty=true;}} +// Picked in another tab: this one follows, and so does the NOC window on a second screen. +if(!RW_IN){themeInit();addEventListener('storage',e=>{if(e.key==='sot-theme'||e.key===null){THEME.pref=themeRead();themeApply();}});} diff --git a/src/game/93-ui/30-install.js b/src/game/93-ui/30-install.js index 73e0c71..17d0f33 100644 --- a/src/game/93-ui/30-install.js +++ b/src/game/93-ui/30-install.js @@ -8,7 +8,7 @@ function installRow(){if(isStandalone())return ''; return `
📲 ${tr('install.best_played_as_an_app')}
${tr('install.full_screen_works_offline_one_tap')}${isIOS()?' '+tr('install.install_it_before_you_start_a'):''}
${btn(tr('common.install'),'install',{},'pink sm')}
`;} /* Phones get a real pitch before a new game: an installed app is full screen, works offline, and on iPhone keeps its save away from Safari's clean-ups. Storage is separate on iOS, so installing first matters. */ -const SHARE_SVG=''; +const SHARE_SVG=''; const needPitch=()=>isPhone()&&!isStandalone(); function installSteps(){ if(isIOS())return `
  1. ${tr('install.tap_share_icon_in_the_browser',{icon:SHARE_SVG})}
  2. ${tr('install.tap_add_to_home_screen_you')}
  3. ${tr('install.open_series_of_tubes_from_your')}
`; diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index b3052f9..fe442ca 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(); }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+=salesCard()+clDealsHtml()+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')}
`;} + {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)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${bRisk(o)}${reqList(o)} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 628dc3a..43a2309 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -49,7 +49,7 @@ function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE; }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('link_panels.this_backhoe_wins'):t.loss>.01?tr('link_panels.connected_but_tight'):tr('link_panels.one_backhoe_is_not_enough'); - openModal(`

${tr('common.redundancy_check')}

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

${title}

${t.split?tr('link_panels.no_alternate_backbone_path_connects'):t.loss>.01?tr('link_panels.an_alternate_path_exists_but_current'):tr('link_panels.with_current_demand_and_routing_this')}

${tr('link_panels.additional_traffic_lost')}${fmtG(t.loss)}
${t.losses.length?`

${tr('common.service_affected')}

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

${tr('link_panels.full_links_during_the_test')}

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

${tr('link_panels.snapshot_only_one_selected_link')}

${btn(tr('common.close'),'closeModal',{},'ghost')}
`,'link-check');} + openModal(`

${tr('common.redundancy_check')}

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

${title}

${t.split?tr('link_panels.no_alternate_backbone_path_connects'):t.loss>.01?tr('link_panels.an_alternate_path_exists_but_current'):tr('link_panels.with_current_demand_and_routing_this')}

${tr('link_panels.additional_traffic_lost')}${fmtG(t.loss)}
${t.losses.length?`

${tr('common.service_affected')}

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

${tr('link_panels.full_links_during_the_test')}

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

${tr('link_panels.snapshot_only_one_selected_link')}

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

${tr('common.redundancy_check')}

${tr('link_panels.what_happens_if_this_link_fails')}

${btn(tr('common.check_redundancy'),'linkCheck',{id:l.id},'ghost sm',linkDown(l))}
`;} // At its own POP a carrier's port always takes that carrier's traffic (25-direct-egress.js). From POPs with no port of it, the // traffic goes to the nearest transit port, or across your network to this one. Only worth asking when something else could take it. @@ -169,7 +169,7 @@ function svgChart(rows,stackKeys,lines,fmtY,id){ for(let j=0;j<=3;j++){const v=ymax*j/3,yy=y(v);g+=`${fmtY(v)}`;} const base=rows.map(()=>0); for(const k of stackKeys){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`;for(let i=1;i=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=``;top.forEach((v,i)=>base[i]=v);} - for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;const last=rows[rows.length-1][ln.k]||0;g+=``;} + for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;const last=rows[rows.length-1][ln.k]||0;g+=``;} g+=`${dateStr(rows[0].d)}${dateStr(rows[rows.length-1].d)}`; return `${g}`;} // For a network you currently reach over transit: the cheapest way to move it to peering. diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 2703cd9..b1e662f 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -7,7 +7,7 @@ function renderDash(){checkLayer(); const tile=(l,v,sub)=>`
${l}
${v}
${sub?`
${sub}
`:''}
`; let h=`
AS${S.asn} · ${esc(S.name)} · ${tierLabel()}

${tr('common.noc_dashboard')}

`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=`
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}
-

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}
+

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')}

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; diff --git a/src/game/94-dashboard/65-chart-legend.js b/src/game/94-dashboard/65-chart-legend.js index 63cfdfa..c6bdc71 100644 --- a/src/game/94-dashboard/65-chart-legend.js +++ b/src/game/94-dashboard/65-chart-legend.js @@ -1,13 +1,14 @@ /* The NOC charts: legend entries switch a series on and off (the scale follows what is left), and hovering or touching a chart shows every visible series on that day. View state only: UI.chartOff is never saved. */ const CHARTS={ - traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'#1E2640':EGC[k][1]}, + traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'var(--text)':EGC[k][1]}, mix:{stack:['c','p','ix','t'],lines:[],fmt:v=>fmtG(v),name:k=>EGC[k][0],col:k=>EGC[k][1]}, // the Traffic tab's table money:{stack:[],lines:['rev','cost'],fmt:v=>fmt$(v),name:k=>k==='rev'?tr('common.revenue'):tr('common.costs'),col:k=>k==='rev'?'#16A866':'#FF4D5E'} }; const chartKeys=C=>[...C.stack,...C.lines]; +// The demand line's key is a dashed outline, in the line's own colour (dark ink by day, light text at night). function chartLegend(id,label){const C=CHARTS[id],off=(UI.chartOff&&UI.chartOff[id])||{}; - return `
${chartKeys(C).map(k=>``).join('')}
`;} + return `
${chartKeys(C).map(k=>``).join('')}
`;} Object.assign(ACT,{ chartToggle:({c,k})=>{const C=CHARTS[c];if(!C||!chartKeys(C).includes(k))return; const off=((UI.chartOff=UI.chartOff||{})[c]=UI.chartOff[c]||{});if(off[k])delete off[k];else off[k]=1; diff --git a/src/game/96-map/15-palette.js b/src/game/96-map/15-palette.js new file mode 100644 index 0000000..0e3fca2 --- /dev/null +++ b/src/game/96-map/15-palette.js @@ -0,0 +1,11 @@ +/* The map's colours by theme (#80): the cartoon day, and a night under the same stickers (cities and markers keep + theirs; a dark outline round a white sticker reads on either). Both renderers read them when they paint: the 2D map + in drawFrame()/paintWorld(), the card in glBegin()/glFrame() (glPal()). Labels: the pill, its text and its edge. + What is only an outline turns light at night, or it would vanish into the dark land and sea: the tubes' casing + (casing) and a puzzle's stepping-stone ring (via). */ +const MAP_PAL={ + light:{sea:'#62CBEA',sea2:'#43AED6',wave:'rgba(255,255,255,.45)',cloud:'rgba(255,255,255,.55)',shadow:'rgba(20,90,130,.35)',sand:'#F8E6A8',land:'#9BDA6C',hill:'#86CB5B',shine:'rgba(255,255,255,.18)',coast:'#1E2640', + pill:'#FFFFFF',pillInk:'#1E2640',pillEdge:'#1E2640',halo:'rgba(255,255,255,.85)',casing:'#1E2640',via:'rgba(30,38,64,.7)'}, + dark:{sea:'#173E5E',sea2:'#0B2440',wave:'rgba(160,210,255,.14)',cloud:'rgba(200,220,255,.1)',shadow:'rgba(0,0,0,.35)',sand:'#4E5440',land:'#2E5A3A',hill:'#284F31',shine:'rgba(255,255,255,.05)',coast:'#081020', + pill:'#1A2340',pillInk:'#E9EFFB',pillEdge:'#070B16',halo:'rgba(8,16,32,.85)',casing:'#A9B7D8',via:'rgba(233,239,251,.75)'}}; +const MPAL=()=>THEME.dark?MAP_PAL.dark:MAP_PAL.light; diff --git a/src/game/96-map/30-settings.js b/src/game/96-map/30-settings.js index fcc7dac..fdf4132 100644 --- a/src/game/96-map/30-settings.js +++ b/src/game/96-map/30-settings.js @@ -31,6 +31,7 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${tr('settings.display_and_sound')} + ${seg(tr('settings.theme'),'themeSet',THEME.pref,[['auto',tr('common.auto')],['light',tr('settings.light')],['dark',tr('settings.dark')]],tr('settings.auto_follows_your_device_s_light'))} ${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))} ${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glCan()?' '+tr('settings.this_browser_cannot_so_the_map'):''))} ${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])} diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index 288553c..b792d3b 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -43,7 +43,7 @@ function drawCables(ks){const G=glOn(),z=cam.z,selC=UI.drag&&UI.drag.mode==='lin 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(!G&&(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&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,'rgba(255,255,255,.85)',3,m[0],m[1]-8);} + if((hot||(z>=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,MPAL().halo,3,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/57-webgl-background.js b/src/game/96-map/57-webgl-background.js index c245aee..c2a97de 100644 --- a/src/game/96-map/57-webgl-background.js +++ b/src/game/96-map/57-webgl-background.js @@ -2,8 +2,10 @@ the 2D map paints them (drawFrame(), paintWorld()) and in the same colours. The land and the cables are geometry built once, so panning and zooming repaint nothing; only the waves and the clouds move. */ const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends -const SEA_TOP=glPm('#62CBEA'),SEA_BOT=glPm('#43AED6'),CLOUD_COL=glPm('rgba(255,255,255,.55)'); -const LAND_SHADOW=glPm('rgba(20,90,130,.35)'),LAND_GRASS=glPm('#9BDA6C'),HILL_COL=glPm('#86CB5B'),HILL_SHINE=glPm('rgba(255,255,255,.18)'); +// The theme's colours (MPAL(), 15-palette.js) as the card takes them, worked out again only when the theme changes. +const GLP={m:null}; +function glPal(){const m=MPAL();if(GLP.m!==m)Object.assign(GLP,{m,seaTop:glPm(m.sea),seaBot:glPm(m.sea2),cloud:glPm(m.cloud),shadow:glPm(m.shadow),grass:glPm(m.land), + hill:glPm(m.hill),shine:glPm(m.shine),wave:glColor(m.wave),sand:glColor(m.sand),edge:glColor(m.coast),casing:glColor(m.casing)});return GLP;} // The land's fill: a fan of triangles per coastline, counted in the stencil (how many times the coasts wind round each // pixel: glLandFill()), then one cover where the count is not zero. uOff shifts it in CSS px (the shadow). const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam; @@ -49,7 +51,7 @@ function coastLevel(z){const want=Math.floor(Math.log2(Math.max(z,1/64))),cur=GL function coastFan(P,out){let a=0;const n=P.length;for(let i=0;i{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return; const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return; coastFan(P,fan); @@ -57,10 +59,14 @@ function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@' const s0=sand.length/LINE_STRIDE;for(let i=0;i+1new Float32Array(a); - G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE, - hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length}; + // The buffers are kept with the land, so a theme change can let them go (the coastlines' colours are in them). + const bufs=[],V=(sz,div,a)=>{const x=glVao(gl,sz,div,new Float32Array(a));bufs.push(x);return x.v;}; + G={fan:V([2],0,fan),nFan:fan.length/2,sand:V([4,4,4,4],1,sand),edge:V([4,4,4,4],1,edge),nSeg:sand.length/LINE_STRIDE, + hills:V([4],1,hills),shine:V([4],1,shine),nHill:HILLS.length,bufs}; glMem(gl,'the land');return GLX.land[key]=G;} +// A theme change (themeRepaint()): every level of the land is built again, in the new colours, when next drawn. +function glLandDrop(){const gl=GLX.gl,L=GLX.land;GLX.land={};if(!gl||!L)return; + try{if(gl.isContextLost())return;for(const G of Object.values(L))for(const x of G.bufs||[]){gl.deleteVertexArray(x.v);gl.deleteBuffer(x.b);}}catch(e){}} // Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map. // The stencil counts the coasts' windings (+1 for a triangle facing one way, -1 the other: coastFan()), as the 2D // canvas's nonzero rule does; counting only odd or even made two overlapping coasts cancel out into sea. @@ -75,16 +81,15 @@ function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col); for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} // In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline. -function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z)); - glLandFill(gl,G,ks,5,7,LAND_SHADOW); +function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z)),P=glPal(); + glLandFill(gl,G,ks,5,7,P.shadow); glLines(gl,G.sand,G.nSeg,ks); - glLandFill(gl,G,ks,0,0,LAND_GRASS); - glEllipses(gl,G.hills,G.nHill,ks,HILL_COL);glEllipses(gl,G.shine,G.nHill,ks,HILL_SHINE); + glLandFill(gl,G,ks,0,0,P.grass); + glEllipses(gl,G.hills,G.nHill,ks,P.hill);glEllipses(gl,G.shine,G.nHill,ks,P.shine); glLines(gl,G.edge,G.nSeg,ks);} // The waves: each one two quadratic curves of four segments, swaying with the map's clock as in drawFrame(). They are // written into the same array every frame (no garbage for the collector to pick up while you play). -const WAVE_COL=glColor('rgba(255,255,255,.45)'); -function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0; +function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900,WAVE_COL=glPal().wave;let m=0; for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3,m0=m; // Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame). for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y; @@ -100,7 +105,7 @@ function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)retu const F=A.subarray(0,n),P=GLX.circ;gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cl.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW); gl.enable(gl.STENCIL_TEST);gl.stencilFunc(gl.ALWAYS,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE);gl.colorMask(false,false,false,false); gl.useProgram(P.p);gl.bindVertexArray(GLX.cl.v);gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,F.length/4); - gl.colorMask(true,true,true,true);gl.stencilFunc(gl.EQUAL,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);glFill(gl,CLOUD_COL);gl.disable(gl.STENCIL_TEST);} + gl.colorMask(true,true,true,true);gl.stencilFunc(gl.EQUAL,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);glFill(gl,glPal().cloud);gl.disable(gl.STENCIL_TEST);} // The cables, as drawCables() strokes them: rebuilt only when the highlighted city or the architect view changes. function glCables(gl,ks,selC,ar){const key=[selC,ar]; if(!GLX.ckey||key.some((v,i)=>v!==GLX.ckey[i])){const A=[]; @@ -119,7 +124,7 @@ function glBegin(now,ks){const gl=GLX.gl,c=GLX.c,f=GLX.f;glShow(true);GLS.frame= gl.viewport(0,0,c.width,c.height);gl.clearColor(0,0,0,0);gl.clearDepth(1);gl.clearStencil(0);gl.colorMask(true,true,true,true);gl.depthMask(true); gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT|gl.STENCIL_BUFFER_BIT); gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST);gl.disable(gl.STENCIL_TEST); - glFill(gl,SEA_TOP,SEA_BOT); + const P=glPal();glFill(gl,P.seaTop,P.seaBot); glLand(gl,ks); glWaves(gl,now,ks); glClouds(gl,now,ks); diff --git a/src/game/96-map/58-webgl-links.js b/src/game/96-map/58-webgl-links.js index 04ec434..93c37a4 100644 --- a/src/game/96-map/58-webgl-links.js +++ b/src/game/96-map/58-webgl-links.js @@ -24,7 +24,7 @@ function glJoin(A,i0,i1,closed){closed=closed&&i1-i0>2; meet, their round ends overlap: each keeps only its side of the corner's bisector, so a see-through line (the halo, the cables, the waves, the fiber's dots) is blended once there, as the 2D canvas strokes a path once. */ const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC;layout(location=3) in vec4 aN; -uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uBusy;uniform int uPass; +uniform vec2 uView;uniform vec3 uCam,uCas;uniform float uWMul,uDpr,uBusy;uniform int uPass; out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol,vK;flat out vec2 vDash,vEnd; // The corner's bisector between directions u and v, in the segment's own frame (t along it, n across), and whether there is one. vec3 cut(vec2 u,vec2 v,vec2 t,vec2 n){vec2 m=u+v;float l=length(m);if(length(u)<.5||length(v)<.5||l<1e-3)return vec3(0.);m/=l;return vec3(dot(t,m),dot(n,m),1.);} @@ -32,7 +32,7 @@ vec2 dashOf(int k){${LDASH.map((d,i)=>d.length?`if(k==${i})return vec2(${d[0]}., void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h; float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false; if(uPass==${LP.halo}){hw=(w+14.)*.5;col=vec4(1.,79./255.,154./255.,.35);dash=vec2(0.);skip=(fl&${LINE_SEL})==0;} - else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(30./255.,38./255.,64./255.,1.);} + else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(uCas,1.);} else if(uPass==${LP.dots}){hw=max(1.,w*.25)*.5;col=vec4(1.,1.,1.,.75);dash=dashOf(5);skip=(fl&${LINE_FIBER})==0||uBusy>.5;} else if(uPass==${LP.plain})col.a=aC.x; if(skip){gl_Position=vec4(2.,2.,2.,1.);return;} @@ -103,7 +103,9 @@ function glFrame(ML,ks,far,busy,now,sc){const gl=GLX.gl; if(net)glBuild(ML.LG,ML.GM,ML.looks); if(net||GLX.key[1]!==selId){glHalo(ML.LG,ML.GM,ML.looks,selId);GLX.key=[ML,selId];} gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.depthMask(true); - const L=GLX.line,K=GLX.pk,wm=sc*(far?0.5:1),lines=(pass,v=GLX.lv.v,n=GLX.nSeg)=>{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass); + // The casing is the theme's (glPal()), a uniform: the tubes' buffers keep only their own colours. + const L=GLX.line,K=GLX.pk,wm=sc*(far?0.5:1),cas=glPal().casing,lines=(pass,v=GLX.lv.v,n=GLX.nSeg)=>{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass); + gl.uniform3f(L.u.uCas,cas[0],cas[1],cas[2]); for(const k of ks){glSet(gl,L,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}; if(GLX.nSeg)for(const pass of [LP.casing,LP.colour,LP.dots])lines(pass); if(GLX.nPk){gl.useProgram(K.p);gl.bindVertexArray(GLX.pv.v);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.uniform1i(K.u.uPts,0); @@ -111,11 +113,11 @@ function glFrame(ML,ks,far,busy,now,sc){const gl=GLX.gl; // The selection's halo goes over earlier tubes but under its own line and later ones, as in 2D. if(GLX.nHalo){gl.depthFunc(gl.LESS);gl.depthMask(false);lines(LP.halo,GLX.hv.v,GLX.nHalo);gl.depthMask(true);} gl.bindVertexArray(null);} -// The link being dragged out (x,y in CSS px): the dark dotted line, then the pink one running along it, over the tubes -// and, since the pictures are drawn after it, under the cities, as in 2D. -const DRAG_INK=glColor('#1E2640'),DRAG_PINK=glColor('#FF4F9A'); +// The link being dragged out (x,y in CSS px): the dotted line in the tubes' casing colour, then the pink one running +// along it, over the tubes and, since the pictures are drawn after it, under the cities, as in 2D. +const DRAG_PINK=glColor('#FF4F9A'); function glDrag(ax,ay,tx,ty,now){const gl=GLX.gl,A=GLX.da||(GLX.da=new Float32Array(2*LINE_STRIDE)),z=cam.z,mx=x=>(x-CW/2)/z+cam.x,my=y=>(y-CH/2)/z+cam.y; - glSegAt(A,0,mx(ax),my(ay),mx(tx),my(ty),0,7,7,LINE_ROUND,1,DRAG_INK); + glSegAt(A,0,mx(ax),my(ay),mx(tx),my(ty),0,7,7,LINE_ROUND,1,glPal().casing); glSegAt(A,1,mx(ax),my(ay),mx(tx),my(ty),-now/30/z,4,7,LINE_ROUND,1,DRAG_PINK); gl.bindBuffer(gl.ARRAY_BUFFER,GLX.dv.b);gl.bufferData(gl.ARRAY_BUFFER,A,gl.DYNAMIC_DRAW); gl.disable(gl.DEPTH_TEST);glLines(gl,GLX.dv.v,2,[0]);gl.bindVertexArray(null);} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 4753041..721926a 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -16,21 +16,21 @@ function drawFrame(now){ // WebGL on: the sea, land, waves, clouds and cables are on the card (glBegin); the 2D canvas below them stays empty. // Off (2D chosen, no game, a puzzle, the card given up), its layers are hidden here, before anything can return early. if(G){try{glBegin(now,ks);}catch(e){throw glErr(e);}} - else{glShow(false);GLX.c0clean=false;const wl=worldLayer(z); + else{glShow(false);GLX.c0clean=false;const wl=worldLayer(z),mp=MPAL(); ctx.setTransform(DPR,0,0,DPR,0,0); // sea - const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,'#62CBEA');g.addColorStop(1,'#43AED6');ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH); + const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,mp.sea);g.addColorStop(1,mp.sea2);ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH); for(const k of ks){ ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2)); // waves: one path, one stroke - ctx.strokeStyle='rgba(255,255,255,.45)';ctx.lineWidth=2/z;ctx.lineCap='round';ctx.beginPath(); + ctx.strokeStyle=mp.wave;ctx.lineWidth=2/z;ctx.lineCap='round';ctx.beginPath(); const ph0=now/900;for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;ctx.moveTo(x-9+o,y);ctx.quadraticCurveTo(x-4.5+o,y-4,x+o,y);ctx.quadraticCurveTo(x+4.5+o,y+4,x+9+o,y);}ctx.stroke(); } for(const k of ks){if(wl)drawWorldLayer(wl,k,z,ks[0]);else{ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));paintWorld(ctx,z,false);}} for(const k of ks){ ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2)); // clouds - ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath(); + ctx.fillStyle=mp.cloud;ctx.beginPath(); for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100,y=c.y;ctx.moveTo(x+16*c.s,y);ctx.arc(x,y,16*c.s,0,7);ctx.moveTo(x+38*c.s,y-8*c.s);ctx.arc(x+18*c.s,y-8*c.s,20*c.s,0,7);ctx.moveTo(x+55*c.s,y);ctx.arc(x+40*c.s,y,15*c.s,0,7);}ctx.fill(); } } @@ -41,7 +41,7 @@ function drawFrame(now){ drawCables(ks); // links AR_PILLS.length=0; - const far=lodFar(),ML=mapLinks(day),LG=ML.LG,GM=ML.GM,PI=ML.PI,busy=linesOnScreen(GM,ks)>MAP_BUSY; + const far=lodFar(),ML=mapLinks(day),LG=ML.LG,GM=ML.GM,PI=ML.PI,busy=linesOnScreen(GM,ks)>MAP_BUSY,cas=MPAL().casing; // WebGL on: the card draws every line and packet now, and the rest (labels, markers, cities…) goes on the overlay. if(G)try{glFrame(ML,ks,far,busy,now,sc);}catch(e){throw glErr(e);} for(let gi=0;gi{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;ipolyAtXY(SX,SY,gm.cum,t); @@ -75,7 +75,7 @@ function drawFrame(now){ [mxx,my]=at(.5);} if(bld){if(far)stamp('bldfar',12,12,6,6,1,mxx,my,g=>{g.fillStyle='#FF8A3D';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,4,0,7);g.fill();g.stroke();});else drawCone(mxx,my,now);} else if(cut&&!vx){if(far)stamp('cutfar',14,14,7,7,1,mxx,my,g=>{g.fillStyle='#FF4D5E';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,5,0,7);g.fill();g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText('!',0,0.5);});else if(!arPz)drawBackhoe(mxx,my,now,l.sub);} - 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);pill(t,ctx.font,tw,17,8,'#fff','#1E2640','#1E2640',2,mxx,my-0.5,1.5);} + 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);const mp=MPAL();pill(t,ctx.font,tw,17,8,mp.pill,mp.pillInk,mp.pillEdge,2,mxx,my-0.5,1.5);} // 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]); } @@ -88,7 +88,7 @@ function drawFrame(now){ if(UI.snap){const B=CITY[UI.snap.id];const wx=A.x+wrapDx(A.x,B.x);for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k),[qx]=toS(wx,B.y,k);if(Math.abs(qx-CW/2)c)c=p[0];if(p[1]>d)d=p[1];}return [a,b,c,d];} function drawCone(x,y,now){stamp('cone',26,28,13,13,1,x,y-12+Math.sin(now/300)*1.5,()=>{ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();});} // Static land + cable map, rendered once per zoom bucket into an offscreen canvas. -function paintWorld(c,z,withCables){const LANDP=lodFar()?LANDP_FAR:LANDP_ALL; - for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle='rgba(20,90,130,.35)';for(const p of LANDP)c.fill(p);c.restore();} - c.strokeStyle='#F8E6A8';c.lineWidth=10/z;c.lineJoin='round';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} - c.fillStyle='#9BDA6C';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.fill(p);c.restore();} - c.fillStyle='#86CB5B';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x+r*1.4,y);c.ellipse(x,y,r*1.4,r*.8,0,0,Math.PI*2);}c.fill(); - c.fillStyle='rgba(255,255,255,.18)';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x-r*.3+r*.6,y-r*.25);c.ellipse(x-r*.3,y-r*.25,r*.6,r*.3,0,0,Math.PI*2);}c.fill(); - c.strokeStyle='#1E2640';c.lineWidth=2.5/z;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} +function paintWorld(c,z,withCables){const LANDP=lodFar()?LANDP_FAR:LANDP_ALL,mp=MPAL(); + for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle=mp.shadow;for(const p of LANDP)c.fill(p);c.restore();} + c.strokeStyle=mp.sand;c.lineWidth=10/z;c.lineJoin='round';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} + c.fillStyle=mp.land;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.fill(p);c.restore();} + c.fillStyle=mp.hill;c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x+r*1.4,y);c.ellipse(x,y,r*1.4,r*.8,0,0,Math.PI*2);}c.fill(); + c.fillStyle=mp.shine;c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x-r*.3+r*.6,y-r*.25);c.ellipse(x-r*.3,y-r*.25,r*.6,r*.3,0,0,Math.PI*2);}c.fill(); + c.strokeStyle=mp.coast;c.lineWidth=2.5/z;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} if(withCables)for(const off of [0,W,-W]){c.save();c.translate(off,0);for(const cp of CABLE_PAIRS){const C=CAB[cp.cid];c.globalAlpha=0.4;c.strokeStyle=cableCol(C);c.lineWidth=1.6/z;c.lineJoin='round';c.setLineDash(C.age==='old'?[6/z,5/z]:[]);c.beginPath();c.moveTo(cp.pts[0][0],cp.pts[0][1]);for(let i=1;icityFarStatic(C,p,down,sel,hov,ph)); if(CM.dish&&CM.dish.has(C.id))dishBadge(sx+(p?10:6),sy+(p?6:5),CM.dish.get(C.id),CM.dl&&CM.dl[C.id]); if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride; - pill(t,ctx.font,tw,16,8,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',1.6,sx,ly,1);} + const mp=MPAL();pill(t,ctx.font,tw,16,8,p?'#FF4F9A':mp.pill,p?'#FFFFFF':mp.pillInk,mp.pillEdge,1.6,sx,ly,1);} } function cityFarStatic(C,p,down,sel,hov,ph){ctx.strokeStyle='#1E2640'; if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-ph;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;ctx.strokeStyle='#1E2640';} @@ -141,7 +141,7 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){ // label if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){ ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=LBLW[C.id+(p?1:0)]||(LBLW[C.id+(p?1:0)]=ctx.measureText(t).width+14),ly=lyOverride==null?sy+16*sc+8:lyOverride; - pill(t,ctx.font,tw,19,9,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',2,sx,ly+0.5,0.5); + const mp=MPAL();pill(t,ctx.font,tw,19,9,p?'#FF4F9A':mp.pill,p?'#FFFFFF':mp.pillInk,mp.pillEdge,2,sx,ly+0.5,0.5); } } diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index a501622..e84d84a 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -7,7 +7,7 @@ function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); 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,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]); + 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})`:MPAL().via;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,v.dem); 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 diff --git a/src/game/96-map/89-pie-globe.js b/src/game/96-map/89-pie-globe.js index 89fe3ed..c6abf57 100644 --- a/src/game/96-map/89-pie-globe.js +++ b/src/game/96-map/89-pie-globe.js @@ -13,7 +13,8 @@ const PG_ST={ const PG={cv:null,ctx:null,get:null,raf:0,last:0,t:0,yaw:-20,tilt:18,vy:0,drag:null,night:null,anim:true,dirty:true, data:null,dAt:-1e9,sig:'',sm:[],dish:[],fl:[],hi:null,pads:[],lch:[],fly:[],on:null,g:null,frames:0,m:new Float64Array(9)}; let PG_LAND=null,PG_LAND_DIR=null,PG_TURN=1,PG_GRID=null,PG_LIGHT=null,PG_STAR=null; -const pgNightPref=()=>{if(PG.night===null){try{PG.night=localStorage.getItem('sot-globe')==='night';}catch(e){PG.night=false;}}return PG.night;}; +// Day or night as the player last chose it; until then, as the theme (#80). +const pgNightPref=()=>{if(PG.night===null){try{const g=localStorage.getItem('sot-globe');PG.night=g?g==='night':THEME.dark;}catch(e){PG.night=THEME.dark;}}return PG.night;}; // Unit vectors for the land rings (LANDS_LL), the graticule, city lights and stars: worked out once, on first open. function pgUnit(lo,la,a,i){const b=la*PG_D,c=Math.cos(b),o=lo*PG_D;a[i]=c*Math.cos(o);a[i+1]=c*Math.sin(o);a[i+2]=Math.sin(b);} // One land ring, clipped to the near side (as map libraries clip). The coast runs to where it meets the horizon; from there the diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index 88644c8..fc74819 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','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','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','mpDoor','mpBack','mpStart','mpJoin'].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','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','themeSet','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','mpDoor','mpBack','mpStart','mpJoin'].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 ef47c7b..0c4838e 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -4539,12 +4539,15 @@ "settings.always_2d":"Always 2D", "settings.an_early_heads_up_below_60":"An early heads-up below 60% happiness, long before they are furious.", "settings.auto_draws_the_map_with_your":"Auto draws the map with your graphics card when the browser allows it, which keeps big networks smooth. Always 2D works everywhere but is slower on big maps.", +"settings.auto_follows_your_device_s_light":"Auto follows your device’s light or dark setting. Dark is easier on the eyes at night and saves battery on OLED screens.", "settings.auto_follows_your_device_s_reduce":"Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.", "settings.customers_and_alerts":"Customers and alerts", +"settings.dark":"Dark", "settings.diagnostic_info":"Diagnostic info", "settings.display_and_sound":"Display and sound", "settings.for_bug_reports_shows_your_screen":"For bug reports: shows in a corner your screen's size, how the map is drawn (graphics card or 2D, and why) and how fast.", "settings.let_an_ai_agent_drive_this_game":"Let an AI agent drive this game", +"settings.light":"Light", "settings.map_drawing":"Map drawing", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4558,6 +4561,7 @@ "settings.the_agent_moves_it":"The agent moves it", "settings.the_clock_while_an_agent_plays":"The clock while an agent plays", "settings.the_game_stops_so_you_can":"The game stops so you can fix their service before they cancel. Most useful at high speed.", +"settings.theme":"Theme", "settings.this_browser_cannot_so_the_map":"This browser cannot, so the map is drawn in 2D.", "settings.warn_when_a_customer_gets_unhappy":"Warn when a customer gets unhappy", "settings.while_agent_mode_is_on_the":"While agent mode is on, the clock is not yours. With a pace it runs by itself and cannot be paused by hand, not even by an open window (yours included), and it waits while no agent is connected. Or the agent moves it, and nothing happens until it asks for days. The page connects to the local agent relay (npm run dev hosts one), so tools like the MCP server can drive this game while you watch.", diff --git a/src/index.html b/src/index.html index 87083cb..2f730a1 100644 --- a/src/index.html +++ b/src/index.html @@ -85,6 +85,15 @@ "author": { "@type": "Person", "name": "Frederic Jung", "url": "https://github.com/fjaeckel" } } + diff --git a/src/styles/00-base.css b/src/styles/00-base.css index dc23fc4..c13c729 100644 --- a/src/styles/00-base.css +++ b/src/styles/00-base.css @@ -1,7 +1,9 @@ -/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). Single committed bright look. */ +/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). + Two looks, light and dark (05-theme.css): --ink is the stickers' dark outline (and text on bright fills) in both, + --text the text on the panels. */ :root{ --sea:#57C4E5; --sea2:#3AA6CF; --wave:#9BE2F2; --land:#9BDA6C; --land2:#7FC455; --sand:#F8E6A8; - --ink:#1E2640; --ink2:#55608A; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC; + --ink:#1E2640; --ink2:#55608A; --text:#1E2640; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC; --me:#FF4F9A; --sun:#FFD23F; --ok:#22C47A; --warn:#FFAA1F; --bad:#FF4D5E; --t1:#7B61FF; --t2:#2F8CFF; --cdn:#FF8A3D; --eye:#16A866; --display:'Baloo 2','Trebuchet MS',system-ui,sans-serif; @@ -14,7 +16,7 @@ body{margin:0} .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} .ver{font-size:11.5px;color:var(--ink2);margin-top:10px} .ver a{color:inherit} -body{background:var(--sea);color:var(--ink);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased} +body{background:var(--sea);color:var(--text);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased} #map{position:fixed;inset:0;width:100%;height:100%;touch-action:none;display:block;cursor:grab} #map.linking{cursor:crosshair} /* The WebGL tubes and the 2D overlay above them (58-webgl-links.js): pictures only, the map underneath takes the pointer. */ diff --git a/src/styles/05-theme.css b/src/styles/05-theme.css new file mode 100644 index 0000000..dce9763 --- /dev/null +++ b/src/styles/05-theme.css @@ -0,0 +1,23 @@ +/* Dark (#80): , set by the page's from Settings › Theme (93-ui/15-theme.js). The panels take + the night colours of the NOC window: dark paper, light text, the stickers' outlines darker still. Light tints (a goal + to work on, a toast, a pick) are written where they are used as var(--tint-…, light colour): only this look sets them. + Text on bright fills (yellow buttons, warning tags) stays dark ink in both looks. */ +:root[data-theme="dark"]{ + color-scheme:dark; + --sea:#0E2A44; --ink:#070B16; --ink2:#A9B7D8; --text:#E9EFFB; --paper:#1A2340; --soft:#232E50; --line:#364470; --eye:#2BC987; + --tint-y:#3B3418; --tint-g:#173B2C; --tint-r:#45212B; --tint-p:#43213D; --tint-b:#17324F; --tint-v:#2C2752; --tint-o:#42301A; + --tint-n:#252F4C; --tint-nl:var(--line); --tx-red:#FF8E9B; --tx-amber:#FFB65C; + scrollbar-color:#4A5B8E transparent; +} +/* The green of good news is lighter as text on dark paper; a tag keeps the deeper green under its white letters. */ +:root[data-theme="dark"] .tag.eye{background:#16A866} +/* A ghost button on dark paper: a shade lighter, so it still reads as a button. */ +:root[data-theme="dark"] .b.ghost,:root[data-theme="dark"] .x{background:var(--soft)} +/* The dropdowns' arrow is a picture: drawn again in the light text colour. */ +:root[data-theme="dark"] select.pick{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%23E9EFFB' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} +/* Badge variants: the frost and the fire, at night. */ +:root[data-theme="dark"] .bdg.on.v-freeze{background:linear-gradient(160deg,#15344C,#0F4562);box-shadow:0 2px 0 #5BC0EB,inset 0 0 0 2px var(--paper)} +:root[data-theme="dark"] .bdg.on.v-bgp{background:linear-gradient(160deg,#3E2A16,#55280F)} +:root[data-theme="dark"] .bdg.v-bgp .bv,:root[data-theme="dark"] .bdg.on.v-bgp .bv{color:#FF8A5C} +:root[data-theme="dark"] .bdg.v-freeze .bv{color:#7FD3F5} +:root[data-theme="dark"] .legend .lg:hover{background:rgba(233,239,251,.08)} diff --git a/src/styles/10-hud.css b/src/styles/10-hud.css index e00a535..2362dd3 100644 --- a/src/styles/10-hud.css +++ b/src/styles/10-hud.css @@ -16,7 +16,7 @@ #hNoc{position:relative}#hNoc .badge{position:absolute;top:-8px;right:-8px;background:var(--me);color:#fff;border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 6px;line-height:16px} .speed{flex-direction:row;align-items:center;gap:4px;padding:4px 6px} .speed button{border:2.5px solid var(--ink);background:var(--paper);border-radius:9px;min-width:34px;height:32px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13px} -.speed button.on{background:var(--sun)} +.speed button.on{background:var(--sun);color:var(--ink)} .spacer{flex:1} .noc{cursor:pointer;border:3px solid var(--ink)} .hotk{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;padding:0 4px;border-radius:12px;border:2px solid var(--ink,#1E2640);font:900 11px Nunito,sans-serif;margin-right:8px;color:#fff;background:#FF4D5E} @@ -24,7 +24,7 @@ .noc.hot{background:var(--bad);color:#fff;animation:throb 1s ease-in-out infinite} .noc.hot .lbl{color:#FFE1E4} #hCust .cnt{display:inline-block;min-width:18px;padding:0 5px;border-radius:9px;background:var(--bad);color:#fff;font-size:11px;line-height:18px;text-align:center;vertical-align:3px;margin-left:2px} -#hCust.hot{background:#FFE1E4} +#hCust.hot{background:var(--tint-r,#FFE1E4)} @keyframes throb{50%{transform:scale(1.05)}} .minibar{height:6px;border-radius:4px;background:var(--line);overflow:hidden;margin-top:2px;width:100%} .minibar i{display:block;height:100%;background:var(--ok)} diff --git a/src/styles/20-drawers.css b/src/styles/20-drawers.css index 31fc819..a34dfd1 100644 --- a/src/styles/20-drawers.css +++ b/src/styles/20-drawers.css @@ -20,8 +20,8 @@ .x{margin-left:auto;border:2.5px solid var(--ink);background:var(--paper);border-radius:10px;width:32px;height:32px;font-size:20px;line-height:1;cursor:pointer;font-weight:900;flex:none} .facts{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} .fact{background:var(--soft);border:2px solid var(--ink);border-radius:9px;padding:1px 8px;font-size:12px;font-weight:700} -.fact.bad{background:#FFE3E3}.latwarn{background:#FFF1F1;border:2px solid #FF5A5F;border-radius:10px;padding:8px 10px;margin:6px 0;font-size:13px;line-height:1.4} -.fact.ixf{background:#FFF3C4} +.fact.bad{background:var(--tint-r,#FFE3E3)}.latwarn{background:var(--tint-r,#FFF1F1);border:2px solid #FF5A5F;border-radius:10px;padding:8px 10px;margin:6px 0;font-size:13px;line-height:1.4} +.fact.ixf{background:var(--tint-y,#FFF3C4)} .fact.mine{background:var(--me);color:#fff} .fact.down{background:var(--bad);color:#fff} section{padding:10px 0;border-bottom:2px dashed var(--line)} @@ -37,13 +37,13 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .row .nm{font-weight:800;font-size:13.5px;line-height:1.2} .row .meta{font-size:11.5px;color:var(--ink2);line-height:1.3} .btns{display:flex;flex-wrap:wrap;gap:5px;margin-top:5px} -.why{font-size:11px;color:#B23A48;font-weight:700;margin-top:3px;line-height:1.3} +.why{font-size:11px;color:var(--tx-red,#B23A48);font-weight:700;margin-top:3px;line-height:1.3} -.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s} +.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s;color:var(--ink)} .b:hover{filter:brightness(1.05)} .b:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} .b:disabled{opacity:.42;cursor:not-allowed;transform:none;box-shadow:0 3px 0 var(--ink)} -.b.ghost{background:var(--paper)} +.b.ghost{background:var(--paper);color:var(--text)} .b.pink{background:var(--me);color:#fff} .b.red{background:var(--bad);color:#fff} .b.green{background:var(--ok);color:#fff} @@ -52,14 +52,14 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .b small{font-family:var(--body);font-weight:800;font-size:10.5px;opacity:.85;margin-left:3px} .logo{width:30px;height:30px;border-radius:50%;background:var(--c);border:2.5px solid var(--ink);display:grid;place-items:center;color:#fff;font-family:var(--display);font-weight:800;font-size:11px;flex:none;letter-spacing:-.02em} -.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:var(--ink2)} +.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:#55608A} .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)} +.tag.st{background:var(--paper);color:var(--text)} /* 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{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(--text);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} @@ -79,12 +79,12 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .goal .ck{width:22px;height:22px;border:2.5px solid var(--ink);border-radius:7px;flex:none;display:grid;place-items:center;font-weight:900;background:var(--paper);font-size:13px} .goal.done .ck{background:var(--ok);color:#fff} .goal.done .gt{text-decoration:line-through;color:var(--ink2)} -.goal.cur{background:#FFF6CF;margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)} +.goal.cur{background:var(--tint-y,#FFF6CF);margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)} .goal .gt{font-weight:900;font-size:13.5px} .goal .gd{font-size:12px;color:var(--ink2);line-height:1.4;margin-top:2px} .goal .gr{font-size:11px;font-weight:900;color:var(--eye);margin-top:2px} .empty{color:var(--ink2);font-size:12.5px;line-height:1.45;padding:6px 0} -.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:#FFF0F1} +.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:var(--tint-r,#FFF0F1)} .inc .nm{font-weight:900} .inc .meta{font-size:12px;color:var(--ink2);margin-top:2px;line-height:1.35} diff --git a/src/styles/30-toasts.css b/src/styles/30-toasts.css index 0086d63..c82aa74 100644 --- a/src/styles/30-toasts.css +++ b/src/styles/30-toasts.css @@ -1,15 +1,15 @@ /* toasts */ #toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 14px);display:flex;flex-direction:column-reverse;gap:8px;z-index:8;width:min(460px,calc(100% - 32px));pointer-events:none} .toast{pointer-events:none;background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:3px 3px 0 var(--ink);padding:9px 12px;display:flex;gap:10px;align-items:center;animation:pop .25s cubic-bezier(.3,1.6,.6,1)} -.toast.good{background:#DFFBEA} .toast.bad{background:#FFE1E4} .toast.goal{background:#FFF3C4} +.toast.good{background:var(--tint-g,#DFFBEA)} .toast.bad{background:var(--tint-r,#FFE1E4)} .toast.goal{background:var(--tint-y,#FFF3C4)} .toast .b{pointer-events:auto} .seg{display:flex;flex-wrap:wrap;gap:6px} .seg .b{white-space:normal;text-align:left} /* A segmented control: one framed row of equal tabs, the active one filled like the HUD's speed buttons (Pie Control). */ .segc{display:flex;gap:3px;padding:3px;margin:6px 0 10px;border:3px solid var(--ink);border-radius:14px;background:var(--soft);box-shadow:3px 3px 0 var(--ink)} -.segc button{flex:1 1 0;min-width:0;min-height:40px;padding:3px 2px;border:2.5px solid transparent;border-radius:10px;background:none;color:var(--ink);font-family:var(--display);font-weight:800;font-size:min(13.5px,3.6vw);line-height:1.1;cursor:pointer;overflow-wrap:anywhere;hyphens:auto} +.segc button{flex:1 1 0;min-width:0;min-height:40px;padding:3px 2px;border:2.5px solid transparent;border-radius:10px;background:none;color:var(--text);font-family:var(--display);font-weight:800;font-size:min(13.5px,3.6vw);line-height:1.1;cursor:pointer;overflow-wrap:anywhere;hyphens:auto} .segc button:hover{background:var(--paper)} -.segc button.on{background:var(--sun);border-color:var(--ink)} +.segc button.on{background:var(--sun);border-color:var(--ink);color:var(--ink)} .segc button:focus-visible{outline:3px solid var(--me);outline-offset:1px} .toast .tx{flex:1;font-size:13px;line-height:1.35} .toast .tx b{font-family:var(--display);font-size:14.5px} diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css index e00dd87..94ba823 100644 --- a/src/styles/36-ops.css +++ b/src/styles/36-ops.css @@ -1,5 +1,5 @@ /* 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{border:2px solid #8E5CF7;background:var(--tint-v,#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)} @@ -12,10 +12,10 @@ .ops-p .b{white-space:normal;text-align:left;min-height:36px} /* A setting is a list to pick from: two to a row on a phone, the list as wide as its column. */ .ops-sel{display:flex;flex-direction:column;gap:2px;flex:1 1 140px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)} -.ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--ink);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px} +.ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--text);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px} .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{border-left:3px solid #8E5CF7;background:var(--tint-v,#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} /* Pie Control's Company tab ends with the Founder's feed: a quiet section, older posts folded away. */ .pie-feed{border-top:2px solid var(--line);margin-top:12px;padding-top:4px} diff --git a/src/styles/38-pie-globe.css b/src/styles/38-pie-globe.css index 867140e..83ec44c 100644 --- a/src/styles/38-pie-globe.css +++ b/src/styles/38-pie-globe.css @@ -9,7 +9,7 @@ .pft-cr,.pft-d{margin:6px 0} .pft-cr .kv span,.pft-d .kv span{min-width:0;overflow-wrap:anywhere} .pft-list{display:flex;flex-direction:column;gap:6px} -.pft-row{display:flex;align-items:center;gap:8px;width:100%;min-height:44px;padding:6px 10px;border:2px solid var(--line);border-radius:12px;background:var(--paper);color:var(--ink);font:inherit;text-align:left;cursor:pointer;box-sizing:border-box} +.pft-row{display:flex;align-items:center;gap:8px;width:100%;min-height:44px;padding:6px 10px;border:2px solid var(--line);border-radius:12px;background:var(--paper);color:var(--text);font:inherit;text-align:left;cursor:pointer;box-sizing:border-box} .pft-row.on{border-color:var(--me);box-shadow:0 0 0 2px var(--me) inset} .pft-ic{font-size:20px;flex:none} .pft-m{flex:1;min-width:0;display:flex;flex-direction:column} diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 32acfbd..c07d336 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -2,13 +2,13 @@ .seg.site{margin-top:4px;align-items:center} .seg.site .meta{margin-right:4px} .badges{display:grid;grid-template-columns:repeat(auto-fill,minmax(118px,1fr));gap:6px} -.bdg{border:2px solid #C9CEDD;border-radius:12px;padding:6px 7px;background:#F3F4F8;opacity:.6;display:flex;flex-direction:column;gap:1px;min-width:0} +.bdg{border:2px solid var(--tint-nl,#C9CEDD);border-radius:12px;padding:6px 7px;background:var(--tint-n,#F3F4F8);opacity:.6;display:flex;flex-direction:column;gap:1px;min-width:0} .bdg .bi{font-size:20px;filter:grayscale(1)} -.bdg .bt{font:800 12.5px/1.2 "Baloo 2",sans-serif;color:var(--ink)} +.bdg .bt{font:800 12.5px/1.2 "Baloo 2",sans-serif;color:var(--text)} .bdg .br{font:900 10px Nunito,sans-serif;color:var(--rc);text-transform:uppercase;letter-spacing:.04em} -.bdg .bd{font-size:11px;color:#5A6280;line-height:1.25} +.bdg .bd{font-size:11px;color:var(--ink2);line-height:1.25} .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{opacity:1;border-color:var(--rc);background:var(--paper);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} @@ -17,19 +17,19 @@ .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{font:800 12px Nunito,sans-serif;border:2px solid var(--tint-nl,#C9CEDD);border-radius:999px;padding:2px 9px;background:var(--paper);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{display:flex;gap:10px;align-items:center;border:2px solid var(--tint-nl,#DDE1EC);border-radius:12px;padding:8px 10px;margin-top:8px} +.scn.wk{border-color:var(--me);background:var(--tint-p,#FFF0F6)} .scn .nm{font-weight:900} .term{background:#1E2640;color:#7CFFB2;font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;padding:10px 12px;border-radius:10px;overflow-x:auto;white-space:pre;margin:8px 0} .trsel{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end;margin-top:8px} .trsel label{display:flex;flex-direction:column;font:800 12px Nunito,sans-serif;gap:2px} .trsel select{font:700 14px Nunito,sans-serif;padding:4px 6px;border:2px solid var(--ink);border-radius:8px;max-width:240px} -.fact.trb{cursor:pointer;font:inherit;border:2px solid var(--ink);background:#fff} -#coach{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 74px);z-index:16;width:min(520px,calc(100% - 24px));background:#fff;border:3px solid var(--ink);border-radius:14px;box-shadow:0 4px 0 var(--ink);padding:8px 10px;display:flex;gap:8px;align-items:center} +.fact.trb{cursor:pointer;font:inherit;border:2px solid var(--ink);background:var(--paper)} +#coach{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 74px);z-index:16;width:min(520px,calc(100% - 24px));background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:0 4px 0 var(--ink);padding:8px 10px;display:flex;gap:8px;align-items:center} #coach .ct{flex:1;font-weight:800;font-size:14px;line-height:1.35} #coach .cs{display:block;font:900 10px Nunito,sans-serif;color:var(--me);text-transform:uppercase;letter-spacing:.05em} .coach-glow{animation:coachglow 1s ease-in-out infinite;position:relative;z-index:2} @@ -43,13 +43,13 @@ .btns.tcta .b{margin:0;display:flex;align-items:center;justify-content:center;text-align:center;line-height:1.15;white-space:normal;hyphens:auto;-webkit-hyphens:auto;min-height:40px;padding:4px 6px;font-size:14px} .btns.tcta .b.big{grid-column:1/-1;font-size:18px;padding:7px 18px 5px} /* Dropdowns that look like the game's buttons. 16px text: iOS zooms into anything smaller when it is tapped. */ -select.pick{-webkit-appearance:none;appearance:none;font:800 16px var(--display);color:var(--ink);background:var(--soft) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%231E2640' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;border:3px solid var(--ink);border-radius:12px;padding:6px 36px 6px 12px;min-height:44px;cursor:pointer;box-shadow:0 3px 0 var(--ink)} +select.pick{-webkit-appearance:none;appearance:none;font:800 16px var(--display);color:var(--text);background:var(--soft) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%231E2640' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;border:3px solid var(--ink);border-radius:12px;padding:6px 36px 6px 12px;min-height:44px;cursor:pointer;box-shadow:0 3px 0 var(--ink)} 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} -.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)} +.ttop{margin:4px 0;padding:4px 8px;border-left:3px solid #FF8A3D;background:var(--tint-o,#FFF6EC);border-radius:6px} +.ibx{border:2px solid var(--line,#DDE3EE);border-radius:12px;padding:8px 10px;margin:8px 0;background:var(--paper)}.ibx .nm{font-weight:800} +.aibtn{background:linear-gradient(90deg,#8E5CF7,#E84FA8);color:#fff}.aisay{background:var(--tint-v,#F3ECFF);border:2px solid #8E5CF7;border-radius:10px;padding:8px 10px;color:var(--text)} .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} .tecode{width:100%;box-sizing:border-box;font:600 13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#1E2640;color:#E6F0FF;border:3px solid var(--ink);border-radius:10px;padding:10px;margin-top:8px;resize:vertical;tab-size:2} @@ -79,7 +79,7 @@ label.f+select.pick{width:100%} .loan{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;margin-top:10px;display:flex;gap:10px;align-items:flex-start} .loan .grow{flex:1;min-width:0} .loan .terms{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0} -.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun)} +.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun);color:var(--ink)} #dash{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:15;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))} #dashCard{max-width:980px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)} .dgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin:10px 0} @@ -110,18 +110,18 @@ 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);color:var(--ink);-webkit-text-fill-color:var(--ink)} +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(--text);-webkit-text-fill-color:var(--text)} .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: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} +.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:var(--tint-r,#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} +.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(--text);text-decoration:none} +.plug:hover{background:var(--tint-y,#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}.starts .start:last-child:nth-child(odd){grid-column:1/-1} .start{border:3px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--paper);cursor:pointer;text-align:left;box-shadow:0 3px 0 var(--ink)} .starts.one{grid-template-columns:1fr} -.start.on{background:#FFE3F0;border-color:var(--me);box-shadow:0 3px 0 var(--me)} +.start.on{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 3px 0 var(--me)} .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. */ @@ -132,13 +132,13 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .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,.preset.on,.chs.on{background:var(--tint-p,#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(4,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)} +.preset[data-preset=bgp].on{background:var(--tint-o,#FFE9D6);border-color:#FF6A2B;box-shadow:0 4px 0 #FF6A2B}.preset[data-preset=bgp].on::after{color:#FF6A2B} +.preset[data-preset=freeze].on{background:var(--tint-b,#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} @@ -152,7 +152,7 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .setline select.pick{min-height:36px;padding:4px 30px 4px 10px;border-width:2px;border-radius:10px;box-shadow:0 2px 0 var(--ink);background-position:right 9px center} .tiers{display:grid;gap:7px;margin-top:10px} .tierbtn{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:13px;padding:8px 12px;background:var(--paper);cursor:pointer;box-shadow:0 3px 0 var(--ink);text-align:left} -.tierbtn:hover{background:#FFF6CF} +.tierbtn:hover{background:var(--tint-y,#FFF6CF)} .tierbtn:disabled{opacity:.4;cursor:not-allowed} .tierbtn .sz{font-family:var(--display);font-weight:800;font-size:22px;width:70px} .tierbtn .grow{flex:1} @@ -169,7 +169,7 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .slots{display:flex;flex-direction:column;gap:7px;margin-bottom:6px;max-height:min(46vh,330px);overflow:auto;padding:2px 2px 5px} .slot{display:flex;align-items:stretch;border:3px solid var(--ink);border-radius:16px;background:var(--paper);box-shadow:0 4px 0 var(--ink);flex:none;transition:transform .08s ease,box-shadow .08s ease} .slot:active{transform:translateY(3px);box-shadow:0 1px 0 var(--ink)} -.slot.top{background:#FFE3F0;border-color:var(--me);box-shadow:0 4px 0 var(--me)} +.slot.top{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 4px 0 var(--me)} .slot.busy{background:var(--soft);border-style:dashed} .slot.broken{opacity:.75;border-style:dashed} .slot-go{flex:1;min-width:0;display:flex;align-items:center;gap:10px;background:none;border:0;padding:8px 6px 8px 11px;font:inherit;color:inherit;text-align:left;cursor:pointer;min-height:52px} @@ -181,7 +181,7 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .slot.busy .tag{color:var(--ink2)} .slot .sm{flex:none;display:flex;flex-direction:column;align-items:flex-end;text-align:right} .slot .sm em{font:800 15px var(--display);font-style:normal} -.slot-more{flex:none;width:44px;border:0;border-left:2px dashed var(--line);background:none;font:900 22px var(--display);color:var(--ink);cursor:pointer;border-radius:0 13px 13px 0} +.slot-more{flex:none;width:44px;border:0;border-left:2px dashed var(--line);background:none;font:900 22px var(--display);color:var(--text);cursor:pointer;border-radius:0 13px 13px 0} .slot-more:hover,.slot-go:hover{background:rgba(255,79,154,.06)} .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} @@ -194,21 +194,21 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .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{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(--text);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} .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} +.mplug{border:2px solid var(--line);border-radius:12px;padding:8px 10px;font-weight:700;font-size:13px;line-height:1.25;color:var(--text);text-decoration:none;background:var(--soft);display:flex;align-items:center} /* Find a city: big tap targets, the first result (what Enter picks) highlighted. */ .findlist{margin-top:8px} -.findrow{width:100%;text-align:left;background:none;border:0;border-top:1px solid var(--line);font:inherit;color:var(--ink);min-height:48px;padding:6px 8px;cursor:pointer;border-radius:0} +.findrow{width:100%;text-align:left;background:none;border:0;border-top:1px solid var(--line);font:inherit;color:var(--text);min-height:48px;padding:6px 8px;cursor:pointer;border-radius:0} .findrow .nm,.findrow .meta{display:block} .findrow.on{background:var(--soft);border-radius:10px} .findrow:hover{background:var(--soft)} /* The charter picker (36-specialist.js): three big choices, one tap each, nothing else to close it with. */ .chpick h2{margin:2px 0 4px}.chpick .tagline{margin:0 0 6px} -.chopt{display:flex;align-items:flex-start;gap:12px;width:100%;margin-top:8px;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;background:var(--paper);box-shadow:0 3px 0 var(--ink);font:inherit;color:var(--ink);text-align:left;cursor:pointer} +.chopt{display:flex;align-items:flex-start;gap:12px;width:100%;margin-top:8px;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;background:var(--paper);box-shadow:0 3px 0 var(--ink);font:inherit;color:var(--text);text-align:left;cursor:pointer} .chopt:hover,.chopt:focus-visible{background:var(--soft)}.chopt:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} .chi{font-size:28px;line-height:1.1;flex:none}.cht{display:flex;flex-direction:column;gap:2px;min-width:0} .cht b{font:800 17px/1.2 var(--display)}.cht span{font-size:13px;line-height:1.35;color:var(--ink2)} diff --git a/src/styles/41-multiplayer.css b/src/styles/41-multiplayer.css index ccd50e6..2552670 100644 --- a/src/styles/41-multiplayer.css +++ b/src/styles/41-multiplayer.css @@ -12,7 +12,7 @@ .mpboard,.mpfeed{display:flex;flex-direction:column;gap:4px} .mpfeed{max-height:220px;overflow:auto;margin-top:6px} .mprow{display:flex;align-items:center;gap:8px;border:2px solid var(--line);border-radius:12px;padding:6px 10px;min-width:0} -.mprow.me{border-color:var(--me);background:#FFF2F8} +.mprow.me{border-color:var(--me);background:var(--tint-p,#FFF2F8)} .mprow .grow,.mpf .grow{min-width:0;overflow-wrap:anywhere} .mprow b{font-family:var(--display);font-size:15px} .mprk{font:900 15px var(--display);width:20px;text-align:center;flex:0 0 auto} @@ -27,7 +27,7 @@ /* No room for the chip on a phone (it is hide-sm), nor on a tablet whose top bar still wraps at fitHud's last step: where you stand shows as a badge on the menu button, which also opens the session. */ #hud .menubtn{position:relative} -.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--ink);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none} +.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--text);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none} #hud.fit3 .mpchip{display:none !important} #hud.fit3 .mpbadge{display:block} @media (max-width:760px){ diff --git a/src/styles/42-chart-tooltips.css b/src/styles/42-chart-tooltips.css index 34334c6..99b2712 100644 --- a/src/styles/42-chart-tooltips.css +++ b/src/styles/42-chart-tooltips.css @@ -8,7 +8,9 @@ .chtip div span{margin-left:auto;padding-left:10px;font-variant-numeric:tabular-nums} .chtip i{width:9px;height:9px;border-radius:3px;border:1px solid #fff} .chtip .tot{border-top:1px solid rgba(255,255,255,.35);margin-top:4px;padding-top:3px} -.chcur{position:fixed;z-index:59;pointer-events:none;width:0;border-left:1px dashed var(--ink)} +.chcur{position:fixed;z-index:59;pointer-events:none;width:0;border-left:1px dashed var(--text)} +/* The charts' grid and axis labels follow the theme (their attributes give the light look's colours). */ +.chart line{stroke:var(--line)}.chart text{fill:var(--ink2)} .mix[data-mix]{cursor:help} .nw-chart[data-ch]{touch-action:pan-y;cursor:crosshair} .noc-window .chtip{border:1px solid #3A4A78} diff --git a/src/styles/45-noc-window.css b/src/styles/45-noc-window.css index e215a87..03d3330 100644 --- a/src/styles/45-noc-window.css +++ b/src/styles/45-noc-window.css @@ -75,7 +75,7 @@ body.noc-window [data-act="dashClose"]{display:none} .nw-bar{height:7px;border-radius:9px;background:#26324F;overflow:hidden;margin:3px 0} .nw-bar i{display:block;height:100%;border-radius:9px} .nw-pc{font-family:var(--display);font-size:16px;min-width:42px;text-align:right} -.nw-btns{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:4px;--ink:#1E2640;--paper:#fff;color:#1E2640} +.nw-btns{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:4px;--ink:#1E2640;--paper:#fff;--soft:#EEF5FB;--text:#1E2640;color:#1E2640} .nw-btns .meta{color:#9FB0D3} .nw-row{display:flex;align-items:center;gap:8px;padding:4px 0} .nw-row .nw-pm{flex:1} diff --git a/src/styles/60-phone.css b/src/styles/60-phone.css index 8e28606..9cfe4ce 100644 --- a/src/styles/60-phone.css +++ b/src/styles/60-phone.css @@ -3,15 +3,15 @@ (play, speed, goals, deals, NOC, networks), and bottom sheets you drag up, down or away. */ html,body{overscroll-behavior:none} .dtabs{position:sticky;top:-12px;z-index:3;display:flex;gap:6px;overflow-x:auto;margin:10px -4px 4px;padding:8px 4px;background:var(--paper);border-bottom:2.5px solid var(--ink);scrollbar-width:none} -.dtabs button{flex:0 0 auto;font:800 13px Nunito,sans-serif;border:2.5px solid var(--ink);border-radius:999px;background:#fff;padding:5px 12px;cursor:pointer;color:var(--ink)} +.dtabs button{flex:0 0 auto;font:800 13px Nunito,sans-serif;border:2.5px solid var(--ink);border-radius:999px;background:var(--paper);padding:5px 12px;cursor:pointer;color:var(--text)} .dtabs button.on{background:var(--pink,#FF4F9A);color:#fff} .dtabs .cnt{display:inline-block;margin-left:5px;min-width:16px;padding:0 4px;border-radius:8px;background:var(--bad);color:#fff;font-size:10.5px;line-height:16px;text-align:center} -.pcard{border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;margin:0 0 10px;background:#FFF6CF} +.pcard{border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;margin:0 0 10px;background:var(--tint-y,#FFF6CF)} .pcard .pt{font-weight:900;font-size:15px;margin:1px 0 2px}.pcard .kv{margin-top:5px}.pcard .bar{margin-top:2px} -.pcard.lv{background:#EAF6FF} -.pitch{list-style:none;padding:0;margin:10px 0}.pitch li{margin:7px 0;line-height:1.38;font-size:14px}.pitch li.warn{background:#FFF4D6;border:2px solid var(--ink);border-radius:10px;padding:6px 8px} +.pcard.lv{background:var(--tint-b,#EAF6FF)} +.pitch{list-style:none;padding:0;margin:10px 0}.pitch li{margin:7px 0;line-height:1.38;font-size:14px}.pitch li.warn{background:var(--tint-y,#FFF4D6);border:2px solid var(--ink);border-radius:10px;padding:6px 8px} .isteps{padding-left:22px;margin:8px 0 4px}.isteps li{margin:5px 0;line-height:1.38;font-size:14px}.isteps svg{vertical-align:-3px} -.icard{margin:8px 0 10px;border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;background:#FFF4D6} +.icard{margin:8px 0 10px;border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--tint-y,#FFF4D6)} /* iPhone home-screen app with a viewport shorter than the screen: the page box takes the real screen height and becomes the containing block for everything fixed, so bottom-anchored UI reaches the bottom. */ html.iosfix,html.iosfix body{height:var(--app-h)} @@ -29,10 +29,10 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #leftToggle{display:none !important} #tabbar{display:flex;position:fixed;left:0;right:0;bottom:0;z-index:9;height:var(--tabbar);padding:6px max(6px,env(safe-area-inset-right,0px)) env(safe-area-inset-bottom,0px) max(6px,env(safe-area-inset-left,0px));background:var(--paper);border-top:3px solid var(--ink);box-sizing:border-box;gap:2px;align-items:stretch} #tabbar button{flex:1 1 0;min-width:0;border:0;background:transparent;border-radius:12px;font:inherit;font-weight:900;font-size:10.5px;color:var(--ink2);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px;padding:2px 0;position:relative} - #tabbar button .ic{font-size:19px;line-height:1.05;color:var(--ink)} - #tabbar button.on{background:var(--soft);color:var(--ink)} + #tabbar button .ic{font-size:19px;line-height:1.05;color:var(--text)} + #tabbar button.on{background:var(--soft);color:var(--text)} #tabbar button.play .ic{font-size:21px} - #tabbar button.play.paused{background:#FFE3F0} + #tabbar button.play.paused{background:var(--tint-p,#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)} @@ -85,7 +85,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar } /* Installed as an app: no browser chrome, so leave room for the notch and the home indicator. */ @media (display-mode: standalone){ - body{background:#57C4E5} + body{background:var(--sea)} } /* Whatever the language, the HUD stays on one row: fitHud() drops chips until it fits. */ #hud.fit1 .hide-md2,#hud.fit2 .hide-md{display:none !important} diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index ace2ce8..16ae092 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -4,20 +4,20 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB #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} +.pzs span small{font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em}.pzs span.on{filter:none;opacity:1;background:var(--tint-y,#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:var(--paper)} .pzc i{font-style:normal} -.pzc.s1{background:#FFE3F0}.pzc.s2{background:var(--ok);color:#fff} +.pzc.s1{background:var(--tint-p,#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} +.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:var(--tint-y,#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:var(--tint-y,#FFF3C4)} +.row.on{background:var(--tint-p,#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)} -.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)} +.pzn1.on{border-color:var(--ok);background:var(--tint-g,#DFFBEA);color:var(--text);animation:pzglow 1.6s ease-in-out infinite}.pzn1.bad{border-color:var(--warn);background:var(--tint-y,#FFF4D6);color:var(--text)} @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} @@ -30,9 +30,9 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzgi{width:24px;flex:none;text-align:center;font-size:16px}.pzgi i{font-style:normal;display:inline-block;width:20px;height:20px;border:2px solid var(--line);border-radius:50%;font:900 11px/16px var(--body);color:var(--ink2);box-sizing:border-box} .pzgv{font-size:12.5px;font-weight:800;color:var(--ink2);white-space:nowrap} .pzgoal.done b{font-weight:700;color:var(--ink2)}.pzgoal:not(.done):not(.cur){opacity:.6} -.pzgoal.cur{background:#FFF4D6;border:2px solid var(--warn);border-radius:12px;padding:6px 8px;margin:3px 0} +.pzgoal.cur{background:var(--tint-y,#FFF4D6);border:2px solid var(--warn);border-radius:12px;padding:6px 8px;margin:3px 0} .pzgh{font-size:13px;line-height:1.4;margin:3px 0 1px 32px}#pzBox .pzgh .pzshow{margin:2px 0 0 2px;padding:2px 10px;min-height:0;vertical-align:middle} -.pzchips{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0}.pzchip{font-size:12px;font-weight:800;border:2px solid var(--ok);border-radius:999px;padding:1px 9px;background:#fff;white-space:nowrap}.pzchip b{font-weight:900} +.pzchips{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0}.pzchip{font-size:12px;font-weight:800;border:2px solid var(--ok);border-radius:999px;padding:1px 9px;background:var(--paper);white-space:nowrap}.pzchip b{font-weight:900} .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} @@ -61,20 +61,20 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzd-nm{flex:1 1 auto;min-width:0;font:800 15px/1.2 var(--display);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .pzd-stars{display:flex;gap:2px;flex:none} .pzd-st{display:inline-grid;place-items:center;width:22px;height:22px;border:2px solid var(--line);border-radius:50%;font:900 11px var(--body);color:var(--ink2);box-sizing:border-box} - .pzd-st.on{border:0;font-size:17px}.pzd-st.cur{border-color:var(--warn);background:#FFF4D6;color:var(--ink)} + .pzd-st.on{border:0;font-size:17px}.pzd-st.cur{border-color:var(--warn);background:var(--tint-y,#FFF4D6);color:var(--text)} .pzd-bud{flex:none;font-weight:900;font-size:12.5px;font-variant-numeric:tabular-nums;white-space:nowrap}.pzd-bud.bad{color:var(--bad)} #pzBox.dock .pzd-bar .b.sm{min-width:36px;min-height:36px;padding:2px 8px;font-size:16px} - .pzd-goal{display:flex;align-items:center;gap:8px;margin-top:6px;padding:5px 8px;background:#FFF4D6;border:2px solid var(--warn);border-radius:12px} - .pzd-goal.done{background:#DFFBEA;border-color:var(--ok)}.pzd-goal.bad{background:#FFE6E9;border-color:var(--bad)} + .pzd-goal{display:flex;align-items:center;gap:8px;margin-top:6px;padding:5px 8px;background:var(--tint-y,#FFF4D6);border:2px solid var(--warn);border-radius:12px} + .pzd-goal.done{background:var(--tint-g,#DFFBEA);border-color:var(--ok)}.pzd-goal.bad{background:var(--tint-r,#FFE6E9);border-color:var(--bad)} #pzBox.dock .arsteps{margin:6px 0 4px}#pzBox.dock .arsteps i{height:6px}#pzBox.dock .arbrief{font-size:13px;margin:0 0 2px} #pzBox.dock .arsites{display:contents}#pzBox.dock .arsite{font-size:12px;padding:2px 8px} body.pz.sheet-open #pzBox.dock .arbrief,body.pz.sheet-open #pzBox.dock .arsteps{display:none} .pzd-goal{flex-wrap:wrap}.pzd-gi{flex:none;font-size:16px}.pzd-gt{flex:1 1 170px;min-width:0;font-size:13px;line-height:1.3}.pzd-gt b{font-weight:800} .pzd-ga{flex:none;display:flex;flex-direction:column;gap:4px}#pzBox.dock .pzd-ga{margin-left:auto}#pzBox.dock .pzd-ga .b{min-height:32px;padding:2px 10px;font-size:13px;white-space:nowrap} .pzd-chips{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px} - .pzd-chip{font:800 12px/1.2 var(--body);color:var(--ink);background:#fff;border:2px solid var(--line);border-radius:999px;padding:3px 8px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis;cursor:pointer} + .pzd-chip{font:800 12px/1.2 var(--body);color:var(--text);background:var(--paper);border:2px solid var(--line);border-radius:999px;padding:3px 8px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis;cursor:pointer} .pzd-chip b{font-weight:900;font-variant-numeric:tabular-nums}.pzd-chip .bad{color:var(--bad)} - .pzd-chip.ok{border-color:var(--ok);background:#DFFBEA}.pzd-chip.part{border-color:var(--warn);background:#FFF4D6}.pzd-chip.none{border-color:var(--bad);background:#FFE6E9} + .pzd-chip.ok{border-color:var(--ok);background:var(--tint-g,#DFFBEA)}.pzd-chip.part{border-color:var(--warn);background:var(--tint-y,#FFF4D6)}.pzd-chip.none{border-color:var(--bad);background:var(--tint-r,#FFE6E9)} .pzd-chip.rule{cursor:default;color:var(--ink2)} /* The card: as tall as its tab, under the bar at most; tabs keep each part short enough to need no scrolling. */ body.pz #panel{max-height:calc(100% - var(--pzdock,60px) - 18px - env(safe-area-inset-top,0px)) !important} @@ -85,14 +85,14 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzd-body{padding:0 14px calc(10px + env(safe-area-inset-bottom,0px))} .pzd-tabs{display:flex;gap:4px;margin:6px 0 8px;border-bottom:2px solid var(--line)} .pzd-tabs button{flex:1;font:800 13px var(--body);color:var(--ink2);background:none;border:0;border-bottom:3px solid transparent;margin-bottom:-2px;padding:6px 2px;min-height:36px} - .pzd-tabs button.on{color:var(--ink);border-bottom-color:var(--me)} - .pzd-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-bottom:1.5px dashed var(--line);font-size:13px}.pzd-row .grow{min-width:0}.pzd-row.on{background:#FFE3F0;border-radius:8px} + .pzd-tabs button.on{color:var(--text);border-bottom-color:var(--me)} + .pzd-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-bottom:1.5px dashed var(--line);font-size:13px}.pzd-row .grow{min-width:0}.pzd-row.on{background:var(--tint-p,#FFE3F0);border-radius:8px} .pzd-to{flex-wrap:wrap}.pzd-foot{justify-content:flex-end} .pzd-models{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:5px;margin-top:6px} - .pzd-model{display:flex;flex-direction:column;align-items:flex-start;gap:0;text-align:left;font:inherit;color:var(--ink);background:#fff;border:2px solid var(--ink);border-radius:10px;padding:3px 7px;min-width:0;cursor:pointer} + .pzd-model{display:flex;flex-direction:column;align-items:flex-start;gap:0;text-align:left;font:inherit;color:var(--text);background:var(--paper);border:2px solid var(--ink);border-radius:10px;padding:3px 7px;min-width:0;cursor:pointer} .pzd-mh{display:flex;gap:6px;width:100%;align-items:baseline}.pzd-mh b{flex:1 1 auto;min-width:0;font-size:12.5px;font-weight:900;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.pzd-mh span{flex:none;font-weight:900;font-size:12.5px} .pzd-model small{font-size:11px;color:var(--ink2);line-height:1.25;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} - .pzd-model.on{background:#FFE3F0;border-color:var(--me)}.pzd-model:disabled:not(.on){opacity:.45;border-color:var(--line)} + .pzd-model.on{background:var(--tint-p,#FFE3F0);border-color:var(--me)}.pzd-model:disabled:not(.on){opacity:.45;border-color:var(--line)} .pzd-rt{margin:6px 0 0}.pzd-rt .b{min-height:34px} .pzd-tiers{display:grid;grid-template-columns:1fr 1fr;gap:6px}.pzd-tiers .b{margin:0;display:flex;flex-direction:column;align-items:center;gap:0;white-space:normal;line-height:1.15;padding:4px 6px}.pzd-tiers .b small{font-size:11px} /* What a routing metric does, and the redundancy check's question, are on the desktop card; here the buttons speak. */ @@ -110,4 +110,4 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .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)} +.scn.wk{flex-wrap:wrap}.scn.wk .grow{min-width:0;flex:1 1 200px}.pzcd{font-weight:800;color:var(--text)} diff --git a/src/styles/71-architect.css b/src/styles/71-architect.css index e4f6d62..627673c 100644 --- a/src/styles/71-architect.css +++ b/src/styles/71-architect.css @@ -1,18 +1,18 @@ /* 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{display:flex;gap:4px;margin:4px 0 6px}.arsteps i{flex:1;height:7px;border:2px solid var(--ink);border-radius:99px;background:var(--paper)} .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:#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)} +.arsite{font-weight:900;font-size:12px;border:2px solid var(--line);border-radius:999px;padding:1px 8px;background:var(--paper);color:var(--ink2)} +.arsite.ok{border-color:var(--ok);color:var(--text)}.arsite.gold{border-color:#E5484D;background:var(--tint-r,#FFE8E8)} +.arline{font-size:12.5px;font-weight:800;margin:3px 0;color:var(--ink2)}.arline.ok{color:var(--text)}.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)} +.arrev.on{border-color:#FF8A3D;background:var(--tint-o,#FFF0E3);color:var(--text)}.arrev.ok{border-color:var(--ok);background:var(--tint-g,#DFFBEA);color:var(--text)} +.arrev.bad{border-color:var(--bad);background:var(--tint-r,#FFE6E9);color:var(--text)} #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} +.artubes em{font-style:normal;font-size:11.5px;letter-spacing:0;color:var(--tx-amber,#B86A00)}.artubes.over b{color:var(--tx-amber,#B86A00)} /* 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} @@ -24,4 +24,4 @@ #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)} +.arsite small{font-weight:800;opacity:.75}.arsite.thin{border-color:var(--bad);background:var(--tint-r,#FFE6E9);color:var(--text)} diff --git a/tests/build.test.js b/tests/build.test.js index 4b3b2c4..cbc6d78 100644 --- a/tests/build.test.js +++ b/tests/build.test.js @@ -52,7 +52,7 @@ test('src: partials follow the layout rules (docs/adr/0002-one-page-assembled-at for (const dev of [false, true]) { const { html, map } = assemble({ dev }); assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})'); - assert.equal([...new JSDOM(html).window.document.scripts].filter((s) => !s.attributes.length).length, 2, 'the language loader and the game: one inline game script'); + assert.equal([...new JSDOM(html).window.document.scripts].filter((s) => !s.attributes.length).length, 3, 'the theme, the language loader and the game: one inline game script'); assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial'); } }); diff --git a/tests/dark-mode.test.js b/tests/dark-mode.test.js new file mode 100644 index 0000000..59b7d41 --- /dev/null +++ b/tests/dark-mode.test.js @@ -0,0 +1,380 @@ +// Dark mode (#80): Settings › Theme is Auto (the device's light or dark setting), Light or Dark, a choice kept on the +// device (localStorage sot-theme), never in the save. The page's sets before the first paint; +// the panels follow through CSS custom properties, and the map paints its sea, land, clouds and labels in the night +// colours in both renderers, painting its cached layers again once when the theme changes (not on every frame). +// jsdom has no matchMedia: the tests lend the page one, before it is parsed (the harness's browser hook) or after. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { JSDOM } = require('jsdom'); +const { load, browser, flush } = require('./harness'); +const { assemble } = require('../scripts/lib/page'); + +// A device setting the test can flip: matchMedia('(prefers-color-scheme: dark)') with change listeners. +const device = (dark) => { + const q = { matches: dark, media: '(prefers-color-scheme: dark)', fns: [], + addEventListener(t, f) { if (t === 'change') this.fns.push(f); }, removeEventListener(t, f) { this.fns = this.fns.filter((x) => x !== f); }, + set(v) { this.matches = v; for (const f of this.fns.slice()) f({ matches: v }); } }; + return { q, attach(w) { w.matchMedia = (m) => (/prefers-color-scheme:\s*dark/.test(m) ? q : { matches: false, addEventListener() {}, removeEventListener() {} }); } }; +}; +const meta = (doc, n) => doc.querySelector(`meta[name="${n}"]`).getAttribute('content'); +// WCAG contrast between two #RRGGBB colours. +const lum = (h) => { h = h.replace('#', ''); const c = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)); return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; }; +const cr = (a, b) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); }; +// Only the page's , up to its styles, as the browser runs it before the first paint: the game script at the end +// of (which sets the theme as well, but late) is not there. ls: what window.localStorage gives, or throws. +const headOnly = (dark, ls) => { + const html = assemble().html, head = html.slice(0, html.indexOf('')); + const block = (sel) => { const i = css.indexOf(sel + '{'); assert.ok(i >= 0, sel); return css.slice(i, css.indexOf('}', i)); }; + const dark = block(':root[data-theme="dark"]'), light = block(':root'); + const val = (b, k) => { const m = new RegExp(`--${k}:\\s*([^;\\n]+);`).exec(b); return m && m[1].trim(); }; + // Every var(--tint-…, light) and var(--tx-…, light) in the styles and the game's own markup has a dark value. + const src = css + fs.readdirSync(path.join(__dirname, '..', 'src', 'game'), { recursive: true }).filter((f) => f.endsWith('.js')).map((f) => fs.readFileSync(path.join(__dirname, '..', 'src', 'game', f), 'utf8')).join('\n'); + const used = new Set([...src.matchAll(/var\(--((?:tint|tx)-[a-z]+),\s*#[0-9A-Fa-f]{3,6}\)/g)].map((m) => m[1])); + assert.ok(used.size >= 8, `tints in use (${[...used]})`); + for (const k of used) assert.ok(val(dark, k), `--${k} has a dark value`); + // Every plain var(--x) in the styles is defined for the light look (dark only overrides). + for (const m of css.matchAll(/var\(--([a-z0-9-]+)\)/g)) if (!/^(tabbar|app-h|c|rc|d|x|t|r|dl|pzdock)$/.test(m[1])) assert.ok(val(light, m[1]), `--${m[1]} is defined`); + const bgs = ['paper', 'soft', 'tint-y', 'tint-g', 'tint-r', 'tint-p', 'tint-b', 'tint-v', 'tint-o', 'tint-n'].map((k) => [k, val(dark, k)]); + for (const t of ['text', 'ink2', 'eye']) for (const [k, b] of bgs) assert.ok(cr(val(dark, t), b) >= 4.5, `--${t} on --${k}: ${cr(val(dark, t), b).toFixed(2)}`); + for (const t of ['tx-red', 'tx-amber']) assert.ok(cr(val(dark, t), val(dark, 'paper')) >= 4.5, `--${t} on the dark paper`); + // The outline stays dark in both looks, so text on bright fills (yellow buttons, warning tags) keeps reading. + assert.ok(cr(val(dark, 'ink'), '#FFD23F') >= 7, 'dark ink on the yellow buttons'); + // Badge labels (10px, so 4.5:1) on their night cards: each variant's gradient, and the dimmed card of one not earned now. + const rules = css.replace(/\/\*[\s\S]*?\*\//g, '').split('}').map((r) => { const i = r.indexOf('{'); return i < 0 ? null : { sel: r.slice(0, i).split(',').map((x) => x.trim()), body: r.slice(i + 1) }; }).filter(Boolean); + const decl = (sel, prop) => { let v = null; for (const r of rules) if (r.sel.includes(sel)) { const m = new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`).exec(r.body); if (m) v = m[1].trim(); } return v; }; + const D = ':root[data-theme="dark"] '; + for (const v of ['freeze', 'bgp']) { + const label = decl(D + `.bdg.v-${v} .bv`, 'color') || decl(`.bdg.v-${v} .bv`, 'color'), stops = decl(D + `.bdg.on.v-${v}`, 'background').match(/#[0-9A-Fa-f]{6}/g); + assert.ok(label && stops.length >= 2, v); + for (const b of [...stops, val(dark, 'tint-n')]) assert.ok(cr(label, b) >= 4.5, `the ${v} badge label ${label} on ${b}: ${cr(label, b).toFixed(2)}`); + } + // The dashboard's Demand key is an outline in its line's colour (--text): dark ink by day as before, light at night. + assert.equal(val(light, 'text'), val(light, 'ink'), 'by day the key looks as it always did'); + assert.ok(cr(val(dark, 'text'), val(dark, 'paper')) >= 3, 'at night the key\'s outline shows on the card'); +}); + +test('the dashboard\'s Demand key matches its dashed line, by night too', () => { + const { dom, ev, errors } = load({ storage: { 'sot-theme': 'dark' } }); + ev(started + "for(let i=0;i<3;i++)dayTick();ACT.dash({});"); + const card = dom.window.document.getElementById('dashCard'); + const line = card.querySelector('svg path[stroke-dasharray="5 4"]'); + assert.ok(line, 'the dashed Demand line'); + const stroke = /stroke:\s*([^;"]+)/.exec(line.getAttribute('style'))[1].trim(); + const key = [...card.querySelectorAll('.legend .lg')].find((b) => JSON.parse(b.dataset.args).k === 'dem').querySelector('i'); + assert.equal(key.style.borderStyle, 'dashed'); + assert.equal(key.style.borderColor, stroke, 'the key is outlined in the line\'s own colour'); + assert.equal(stroke, 'var(--text)'); + assert.deepEqual(errors, []); + dom.window.close(); +}); From eac06043002ad9f41515fe84c682b36883cf86b3 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:04:00 +0100 Subject: [PATCH 414/491] IPv4 address space: scarce, bought, leased, leased out; IPv6 is free (#150) A rule (ip4), on in On-call and BGP at 3 a.m., off in the gentler presets, sandbox and puzzles; scenarios only when they opt in. You start with a /21 from the registry, sized so the early game never notices (a gameplay-rules F1 test plays six start cities for 50 days). Business customers need a block by kind and size; broadband homes take what is left and the rest go behind CGNAT, which costs a box per home and annoys some customers. An offer that does not fit cannot be signed and says why, and a customer that cannot grow at renewal stays its size. The bank's Address space section buys and sells blocks on a transfer market with a gentle trend, leases blocks in, and leases spare blocks out for monthly income, in real CIDR sizes (/24 to /16), at most 256 blocks (what a save keeps). Old saves get what they already use, plus room, so nothing changes on load. The dashboard's AS box now lists the blocks you announce. --- .claude/skills/gameplay-rules/SKILL.md | 4 +- CHANGELOG.md | 1 + scripts/lib/fuzz-page.js | 5 +- scripts/lib/route-fuzz.js | 2 + site/i18n/de.js | 48 ++ site/i18n/es.js | 48 ++ site/i18n/fr.js | 48 ++ site/i18n/it.js | 48 ++ site/i18n/pt.js | 48 ++ src/agent/10-domains.js | 3 + src/agent/20-commands.js | 21 +- src/agent/30-docs.js | 3 +- src/game/40-progress/30-rules.js | 15 +- src/game/60-features/33-address-space.js | 89 ++++ src/game/60-features/38-sales-desk.js | 4 +- src/game/60-features/39-sales-auto.js | 2 +- src/game/60-features/80-new-game.js | 2 +- src/game/80-simulation/30-compute.js | 3 +- src/game/80-simulation/50-sanitize.js | 1 + .../80-simulation/75-customer-lifecycle.js | 14 +- src/game/88-days/10-day-tick.js | 1 + src/game/90-actions/50-customers.js | 2 +- src/game/90-actions/54-address-space.js | 29 ++ src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/70-link-panels.js | 2 +- src/game/94-dashboard/60-dashboard.js | 4 +- src/game/94-dashboard/70-bank.js | 2 +- src/game/94-dashboard/72-address-space.js | 22 + src/game/95-modals/40-title.js | 2 +- src/i18n/en.js | 48 ++ tests/address-space.test.js | 442 ++++++++++++++++++ tests/gameplay-rules.test.js | 20 +- tests/mcp-commands.test.js | 2 +- tests/sales-desk.test.js | 2 + 34 files changed, 957 insertions(+), 32 deletions(-) create mode 100644 src/game/60-features/33-address-space.js create mode 100644 src/game/90-actions/54-address-space.js create mode 100644 src/game/94-dashboard/72-address-space.js create mode 100644 tests/address-space.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 294d399..6f149f4 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -46,7 +46,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: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | 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, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | +| 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, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4 and CGNAT (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). 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. | | M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). | @@ -64,7 +64,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | 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. | +| 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. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | 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 e349380..e5f8d8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows - Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. +- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). ## [3.0.0] — 2026-11-06 diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 5b05a14..61f7ce9 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -185,5 +185,8 @@ return { a, b, c }; }; const acts = () => Object.keys(ACT); - window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen }; + // Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls + // it only while the base has no such rule, so the pages play the same game until it lands. + const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } }; + window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen, noIp4 }; })(); diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index dfca595..580dcac 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -95,6 +95,8 @@ function playGame(pages, seed, opts = {}) { preset: kind === 'sandbox' ? r.pick(['none', 'calm', 'normal', 'spicy']) : r.pick(PRESETS), id: kind === 'scenario' ? r.pick(L.scn) : kind === 'puzzle' ? r.pick(L.pz) : kind === 'architect' ? r.pick(L.ar) : undefined }; const [s0, s1] = both('start', st); + // A base without scarce IPv4 (#150) plays the classic game: both pages switch the rule off. Once it is on main, both play it. + if (!base.call('acts').includes('ip4Buy')) both('noIp4'); same('start', s0, s1); note('start ' + JSON.stringify(st)); // A normal game signs its charter first: a popup on newer pages (which seeded pages skip), a card on older ones. Both diff --git a/site/i18n/de.js b/site/i18n/de.js index 405ba56..a152ee3 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2640,6 +2640,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin ist auf dem Weg zu deinem Konto um {p} % gefallen.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin ist auf dem Weg zu deinem Konto um {p} % gestiegen.", "interface.you_bought_out_bank_they_flew":"Du hast {bank} ausbezahlt.
Sie sind weitergeflogen, um ein anderes Startup zu finden.", +"ip4.block_size":"Blockgröße", +"ip4.blocks":"Deine Blöcke", +"ip4.bought":"Einen {p}-Block ({n} Adressen) für {price} gekauft.", +"ip4.bought_on":"Gekauft {date}", +"ip4.business":"Von Geschäftskunden genutzt", +"ip4.buy":"Kaufen {price}", +"ip4.cgnat_boxes":"CGNAT-Boxen", +"ip4.cgnat_note":"Mehr Haushalte pro Adresse macht Platz für Kunden, aber Spiele und Portweiterleitungen leiden: {p} der Rechnung eines CGNAT-Haushalts gehen als Erstattung zurück.", +"ip4.cgnat_ratio":"CGNAT: Haushalte pro Adresse", +"ip4.costs_row":"IPv4-Mieten und CGNAT", +"ip4.free":"Frei für neue Kunden (Haushalte kommen zuerst hinter CGNAT)", +"ip4.from_rir":"Von der RIR", +"ip4.give_back":"Zurückgeben", +"ip4.held":"Die RIR überträgt diesen Block erst ab {date} wieder.", +"ip4.homes":"Breitband-Haushalte", +"ip4.homes_cgnat":"{n}, davon {p} hinter CGNAT", +"ip4.in_use":"Deine Kunden brauchen diese Adressen: steck mehr Haushalte hinter CGNAT oder hol dir erst einen weiteren Block.", +"ip4.lease":"Mieten {price}/Monat", +"ip4.lease_out":"Vermieten +{price}/Monat", +"ip4.leased_in":"Einen {p}-Block ({n} Adressen) für {price}/Monat gemietet.", +"ip4.leased_in_mo":"Gemietet · {price}/Monat", +"ip4.leased_out":"Dein {p}-Block ist vermietet: +{price}/Monat.", +"ip4.leased_out_mo":"Vermietet · +{price}/Monat", +"ip4.leases_in":"Gemietete Blöcke", +"ip4.leases_out":"Vermietete Blöcke", +"ip4.market":"Transfermarkt", +"ip4.market_note":"IPv4 kostet etwa {px} pro Adresse (große Blöcke etwas weniger), zur Miete {lin} pro Adresse und Monat, und vermietet bringt es nach dem Anteil des Brokers {lout}. Ein Verkauf bringt {p} des Preises, und ein Block darf erst zwei Jahre nach seinem letzten Transfer wieder übertragen werden.", +"ip4.movable_from":"wieder übertragbar ab {date}", +"ip4.n_addresses":{"one":"{n} Adresse","other":"{n} Adressen"}, +"ip4.n_homes_per_address":{"one":"{n} Haushalt pro Adresse","other":"{n} Haushalte pro Adresse"}, +"ip4.no_grow":"{name} ({city}) wollte auf {bw} wachsen, aber du hattest keine freien IPv4-Adressen dafür.", +"ip4.no_space":"{name} braucht einen IPv4-Block {p} ({n} Adressen), und nur {free} sind frei. Kauf oder miete einen Block oder steck mehr Haushalte hinter CGNAT.", +"ip4.note":"IPv6 ist kostenlos und unendlich. IPv4 ist seit Jahren aus: Geschäftskunden brauchen öffentliche Blöcke davon, und Haushalte, die nicht mehr reinpassen, teilen sich Adressen hinter CGNAT (IPv6-Traffic läuft an der Box vorbei).", +"ip4.off":"Nach den Regeln dieses Spiels gibt es IPv4 reichlich.", +"ip4.offer_needs":"Braucht einen IPv4-Block {p} ({n} Adressen); nur {free} frei.", +"ip4.preset_plenty":"IPv4 gibt es reichlich für alle.", +"ip4.preset_scarce":"IPv4 ist knapp: kaufen, mieten oder hinter CGNAT teilen.", +"ip4.really_sell":"Wirklich für {price} verkaufen?", +"ip4.refunds":"Erstattungen an genervte Gamer", +"ip4.section":"Adressraum", +"ip4.sell":"Verkaufen {price}", +"ip4.sold":"Dein {p}-Block ist für {price} verkauft.", +"ip4.squeezed":"Kein Platz mehr: {p} der Haushalte passen nicht mal bei {r} Haushalten pro Adresse rein. Ihre Verbindungen brechen ab und sie wollen Geld zurück: kauf oder miete einen Block.", +"ip4.take_back":"Zurückholen", +"ip4.toast_cgnat":"Dein IPv4 ist voll. {p} deiner Haushalte teilen sich jetzt Adressen hinter CGNAT, und ein paar Gamer haben schon geschrieben.", +"ip4.toast_out":"IPv4 ist aus. Selbst bei {r} Haushalten pro Adresse passt nicht jeder hinter CGNAT: kauf oder miete einen Block bei der Bank.", +"ip4.too_many":"Du hast {n} IPv4-Blöcke, mehr kann ein Netz nicht führen. Verkauf kleine Blöcke oder gib sie zurück, um Platz für einen größeren zu schaffen.", +"ip4.yours":"Deine IPv4-Adressen", "ix_downgrade.pni_downgraded":"Das PNI mit {net} in {city} ist jetzt {port}.", "ix_downgrade.port_downgraded_at_ix":"Der Port bei {ix} ist jetzt {port}.", "ix_downgrade.transit_downgraded":"{net}-Transit in {city} ist jetzt {port}.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 427ba64..1f8b28a 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin bajó un {p} % de camino a tu cuenta.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin subió un {p} % de camino a tu cuenta.", "interface.you_bought_out_bank_they_flew":"Compraste {bank}.
Se fueron volando a buscar otra startup.", +"ip4.block_size":"Tamaño del bloque", +"ip4.blocks":"Tus bloques", +"ip4.bought":"Has comprado un {p} ({n} direcciones) por {price}.", +"ip4.bought_on":"Comprado el {date}", +"ip4.business":"Usadas por clientes empresariales", +"ip4.buy":"Comprar {price}", +"ip4.cgnat_boxes":"Equipos CGNAT", +"ip4.cgnat_note":"Más hogares por dirección liberan espacio para clientes, pero los juegos y el port forwarding sufren: el {p} de la factura de un hogar con CGNAT se devuelve en reembolsos.", +"ip4.cgnat_ratio":"CGNAT: hogares por dirección", +"ip4.costs_row":"Alquiler de IPv4 y CGNAT", +"ip4.free":"Libres para nuevos clientes (los hogares pasan antes a CGNAT)", +"ip4.from_rir":"Del RIR", +"ip4.give_back":"Devolver", +"ip4.held":"El RIR no volverá a transferir ese bloque antes del {date}.", +"ip4.homes":"Hogares con banda ancha", +"ip4.homes_cgnat":"{n}, {p} detrás de CGNAT", +"ip4.in_use":"Tus clientes necesitan esas direcciones: pon más hogares detrás de CGNAT o consigue antes otro bloque.", +"ip4.lease":"Alquilar {price}/mes", +"ip4.lease_out":"Ceder en alquiler +{price}/mes", +"ip4.leased_in":"Has alquilado un {p} ({n} direcciones) por {price}/mes.", +"ip4.leased_in_mo":"Alquilado · {price}/mes", +"ip4.leased_out":"Tu {p} está cedido en alquiler: +{price}/mes.", +"ip4.leased_out_mo":"Cedido en alquiler · +{price}/mes", +"ip4.leases_in":"Bloques alquilados", +"ip4.leases_out":"Bloques cedidos en alquiler", +"ip4.market":"Mercado de transferencias", +"ip4.market_note":"IPv4 se vende a unos {px} por dirección (los bloques grandes, algo menos), se alquila a {lin} por dirección al mes y, cedido en alquiler, rinde {lout} tras la comisión del bróker. Una venta paga el {p} del precio, y un bloque solo puede volver a transferirse dos años después de su último traspaso.", +"ip4.movable_from":"transferible desde el {date}", +"ip4.n_addresses":{"one":"{n} dirección","other":"{n} direcciones"}, +"ip4.n_homes_per_address":{"one":"{n} hogar por dirección","other":"{n} hogares por dirección"}, +"ip4.no_grow":"{name} ({city}) quería crecer a {bw}, pero no tenías direcciones IPv4 libres para ello.", +"ip4.no_space":"{name} necesita un {p} de IPv4 ({n} direcciones) y solo hay {free} libres. Compra o alquila un bloque, o pon más hogares detrás de CGNAT.", +"ip4.note":"IPv6 es gratis e infinito. IPv4 se agotó hace años: los clientes empresariales necesitan bloques públicos, y los hogares que no caben comparten direcciones detrás de CGNAT (el tráfico IPv6 rodea la caja).", +"ip4.off":"Con las reglas de esta partida sobra IPv4.", +"ip4.offer_needs":"Necesita un {p} de IPv4 ({n} direcciones); solo hay {free} libres.", +"ip4.preset_plenty":"IPv4 de sobra para todos.", +"ip4.preset_scarce":"IPv4 escasea: cómpralo, alquílalo o compártelo detrás de CGNAT.", +"ip4.really_sell":"¿Vender de verdad por {price}?", +"ip4.refunds":"Reembolsos a gamers enfadados", +"ip4.section":"Espacio de direcciones", +"ip4.sell":"Vender {price}", +"ip4.sold":"Has vendido tu {p} por {price}.", +"ip4.squeezed":"Sin espacio: el {p} de los hogares no cabe ni con {r} hogares por dirección. Sus conexiones fallan y piden reembolsos: compra o alquila un bloque.", +"ip4.take_back":"Recuperar", +"ip4.toast_cgnat":"Tu IPv4 está lleno. El {p} de tus hogares comparte ahora direcciones detrás de CGNAT, y algunos gamers ya han escrito.", +"ip4.toast_out":"Sin IPv4. Ni con {r} hogares por dirección cabe todo el mundo en el CGNAT: compra o alquila un bloque en el banco.", +"ip4.too_many":"Tienes {n} bloques IPv4, el máximo que puede llevar una red. Vende o devuelve bloques pequeños para hacer sitio a uno más grande.", +"ip4.yours":"Tus direcciones IPv4", "ix_downgrade.pni_downgraded":"El PNI con {net} en {city} ahora es {port}.", "ix_downgrade.port_downgraded_at_ix":"El puerto en {ix} es ahora de {port}.", "ix_downgrade.transit_downgraded":"El tránsito de {net} en {city} ahora es {port}.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 2a134ae..7729036 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"Le TubeCoin a perdu {p} % en route vers ton compte.", "interface.tubecoin_moved_up_p_on_the":"Le TubeCoin a pris {p} % en route vers ton compte.", "interface.you_bought_out_bank_they_flew":"Tu as racheté la part de {bank}.
Ils se sont envolés à la recherche d’une autre startup.", +"ip4.block_size":"Taille du bloc", +"ip4.blocks":"Tes blocs", +"ip4.bought":"Tu as acheté un {p} ({n} adresses) pour {price}.", +"ip4.bought_on":"Acheté le {date}", +"ip4.business":"Utilisées par les clients pros", +"ip4.buy":"Acheter {price}", +"ip4.cgnat_boxes":"Boîtiers CGNAT", +"ip4.cgnat_note":"Plus de foyers par adresse libère de la place pour les clients, mais les jeux et la redirection de ports en pâtissent : {p} de la facture d’un foyer derrière le CGNAT repart en remboursements.", +"ip4.cgnat_ratio":"CGNAT : foyers par adresse", +"ip4.costs_row":"Locations IPv4 et CGNAT", +"ip4.free":"Libres pour de nouveaux clients (les foyers passent d’abord derrière le CGNAT)", +"ip4.from_rir":"Attribué par le RIR", +"ip4.give_back":"Le rendre", +"ip4.held":"Le RIR ne transférera pas ce bloc avant le {date}.", +"ip4.homes":"Foyers en haut débit", +"ip4.homes_cgnat":"{n}, dont {p} derrière le CGNAT", +"ip4.in_use":"Tes clients ont besoin de ces adresses : mets plus de foyers derrière le CGNAT ou trouve d’abord un autre bloc.", +"ip4.lease":"Louer {price}/mois", +"ip4.lease_out":"Mettre en location +{price}/mois", +"ip4.leased_in":"Tu as loué un {p} ({n} adresses) pour {price}/mois.", +"ip4.leased_in_mo":"Loué · {price}/mois", +"ip4.leased_out":"Ton {p} est en location : +{price}/mois.", +"ip4.leased_out_mo":"Mis en location · +{price}/mois", +"ip4.leases_in":"Blocs loués", +"ip4.leases_out":"Blocs mis en location", +"ip4.market":"Marché des transferts", +"ip4.market_note":"L’IPv4 se vend environ {px} l’adresse (un peu moins pour les gros blocs), se loue {lin} l’adresse par mois et, mis en location, rapporte {lout} après la part du courtier. Une vente rapporte {p} du prix, et un bloc ne peut être transféré à nouveau que deux ans après son dernier transfert.", +"ip4.movable_from":"transférable à partir du {date}", +"ip4.n_addresses":{"one":"{n} adresse","other":"{n} adresses"}, +"ip4.n_homes_per_address":{"one":"{n} foyer par adresse","other":"{n} foyers par adresse"}, +"ip4.no_grow":"{name} ({city}) voulait passer à {bw}, mais tu n’avais pas d’adresses IPv4 libres pour ça.", +"ip4.no_space":"{name} a besoin d’un {p} d’IPv4 ({n} adresses), et seulement {free} sont libres. Achète ou loue un bloc, ou mets plus de foyers derrière le CGNAT.", +"ip4.note":"L’IPv6 est gratuit et sans fin. L’IPv4 est épuisé depuis des années : les clients pros ont besoin de blocs publics, et les foyers qui ne rentrent plus partagent des adresses derrière le CGNAT (le trafic IPv6 contourne la boîte).", +"ip4.off":"Avec les règles de cette partie, l’IPv4 ne manque pas.", +"ip4.offer_needs":"Il lui faut un {p} d’IPv4 ({n} adresses) ; seulement {free} libres.", +"ip4.preset_plenty":"De l’IPv4 à volonté pour tout le monde.", +"ip4.preset_scarce":"L’IPv4 est rare : achète-le, loue-le ou partage-le derrière le CGNAT.", +"ip4.really_sell":"Vraiment vendre pour {price} ?", +"ip4.refunds":"Remboursements aux gamers grincheux", +"ip4.section":"Espace d’adressage", +"ip4.sell":"Vendre {price}", +"ip4.sold":"Ton {p} est vendu pour {price}.", +"ip4.squeezed":"Plus de place : {p} des foyers ne rentrent pas, même à {r} foyers par adresse. Leurs connexions lâchent et ils veulent être remboursés : achète ou loue un bloc.", +"ip4.take_back":"Le reprendre", +"ip4.toast_cgnat":"Ton IPv4 est plein. {p} de tes foyers partagent maintenant des adresses derrière le CGNAT, et quelques gamers ont déjà écrit.", +"ip4.toast_out":"Plus d’IPv4. Même à {r} foyers par adresse, le CGNAT ne suffit pas pour tout le monde : achète ou loue un bloc à la banque.", +"ip4.too_many":"Tu as {n} blocs IPv4, le maximum qu’un réseau peut garder. Vends ou rends de petits blocs pour faire de la place à un plus grand.", +"ip4.yours":"Tes adresses IPv4", "ix_downgrade.pni_downgraded":"Le PNI avec {net} à {city} est maintenant en {port}.", "ix_downgrade.port_downgraded_at_ix":"Le port chez {ix} est maintenant en {port}.", "ix_downgrade.transit_downgraded":"Le transit {net} à {city} est maintenant en {port}.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 2d75e8e..cc61779 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin è sceso del {p}% mentre arrivava sul tuo conto.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin è salito del {p}% mentre arrivava sul tuo conto.", "interface.you_bought_out_bank_they_flew":"Hai liquidato {bank}.
Sono volati via in cerca di un’altra startup.", +"ip4.block_size":"Dimensione del blocco", +"ip4.blocks":"I tuoi blocchi", +"ip4.bought":"Comprato un {p} ({n} indirizzi) per {price}.", +"ip4.bought_on":"Comprato il {date}", +"ip4.business":"Usati dai clienti business", +"ip4.buy":"Compra {price}", +"ip4.cgnat_boxes":"Apparati CGNAT", +"ip4.cgnat_note":"Più case per indirizzo liberano spazio per i clienti, ma giochi e port forwarding ne soffrono: il {p} della bolletta di una casa dietro il CGNAT torna indietro in rimborsi.", +"ip4.cgnat_ratio":"CGNAT: case per indirizzo", +"ip4.costs_row":"Affitti IPv4 e CGNAT", +"ip4.free":"Liberi per nuovi clienti (prima le case passano dietro il CGNAT)", +"ip4.from_rir":"Dal RIR", +"ip4.give_back":"Restituiscilo", +"ip4.held":"Il RIR non trasferisce di nuovo quel blocco prima del {date}.", +"ip4.homes":"Case in banda larga", +"ip4.homes_cgnat":"{n}, il {p} dietro il CGNAT", +"ip4.in_use":"I tuoi clienti hanno bisogno di quegli indirizzi: metti più case dietro il CGNAT o prendi prima un altro blocco.", +"ip4.lease":"Affitta {price}/mese", +"ip4.lease_out":"Dai in affitto +{price}/mese", +"ip4.leased_in":"Preso in affitto un {p} ({n} indirizzi) per {price}/mese.", +"ip4.leased_in_mo":"In affitto · {price}/mese", +"ip4.leased_out":"Il tuo {p} è dato in affitto: +{price}/mese.", +"ip4.leased_out_mo":"Dato in affitto · +{price}/mese", +"ip4.leases_in":"Blocchi presi in affitto", +"ip4.leases_out":"Blocchi dati in affitto", +"ip4.market":"Mercato dei trasferimenti", +"ip4.market_note":"IPv4 costa circa {px} a indirizzo (i blocchi grandi un po' meno), in affitto {lin} a indirizzo al mese, e dato in affitto rende {lout} dopo la quota del broker. Una vendita paga il {p} del prezzo, e un blocco si può trasferire di nuovo solo due anni dopo l'ultimo trasferimento.", +"ip4.movable_from":"trasferibile dal {date}", +"ip4.n_addresses":{"one":"{n} indirizzo","other":"{n} indirizzi"}, +"ip4.n_homes_per_address":{"one":"{n} casa per indirizzo","other":"{n} case per indirizzo"}, +"ip4.no_grow":"{name} ({city}) voleva crescere a {bw}, ma non avevi indirizzi IPv4 liberi per farlo.", +"ip4.no_space":"{name} ha bisogno di un {p} di IPv4 ({n} indirizzi), e ne restano liberi solo {free}. Compra o affitta un blocco, o metti più case dietro il CGNAT.", +"ip4.note":"IPv6 è gratis e infinito. IPv4 è finito anni fa: i clienti business hanno bisogno di blocchi pubblici, e le case che non ci stanno condividono gli indirizzi dietro il CGNAT (il traffico IPv6 gli passa accanto).", +"ip4.off":"Con le regole di questa partita l'IPv4 abbonda.", +"ip4.offer_needs":"Serve un {p} di IPv4 ({n} indirizzi); solo {free} liberi.", +"ip4.preset_plenty":"IPv4 in abbondanza per tutti.", +"ip4.preset_scarce":"IPv4 scarseggia: compralo, affittalo o condividilo dietro il CGNAT.", +"ip4.really_sell":"Vendere davvero per {price}?", +"ip4.refunds":"Rimborsi ai gamer arrabbiati", +"ip4.section":"Spazio di indirizzi", +"ip4.sell":"Vendi {price}", +"ip4.sold":"Venduto il tuo {p} per {price}.", +"ip4.squeezed":"Spazio esaurito: il {p} delle case non ci sta nemmeno con {r} case per indirizzo. Le connessioni saltano e vogliono un rimborso: compra o affitta un blocco.", +"ip4.take_back":"Riprendilo", +"ip4.toast_cgnat":"Il tuo IPv4 è pieno. Il {p} delle tue case ora condivide gli indirizzi dietro il CGNAT, e qualche gamer ha già scritto.", +"ip4.toast_out":"IPv4 esaurito. Nemmeno con {r} case per indirizzo il CGNAT basta per tutti: compra o affitta un blocco in banca.", +"ip4.too_many":"Hai {n} blocchi IPv4, il massimo che una rete può tenere. Vendi o restituisci qualche blocco piccolo per fare posto a uno più grande.", +"ip4.yours":"I tuoi indirizzi IPv4", "ix_downgrade.pni_downgraded":"Il PNI con {net} a {city} ora è {port}.", "ix_downgrade.port_downgraded_at_ix":"La porta su {ix} ora è da {port}.", "ix_downgrade.transit_downgraded":"Il transito {net} a {city} ora è {port}.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index f65faba..5fc3410 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"A TubeCoin caiu {p}% no caminho até sua conta.", "interface.tubecoin_moved_up_p_on_the":"A TubeCoin subiu {p}% no caminho até sua conta.", "interface.you_bought_out_bank_they_flew":"Você comprou a parte de {bank}.
Eles voaram em busca de outra startup.", +"ip4.block_size":"Tamanho do bloco", +"ip4.blocks":"Seus blocos", +"ip4.bought":"Você comprou um {p} ({n} endereços) por {price}.", +"ip4.bought_on":"Comprado em {date}", +"ip4.business":"Usados por clientes empresariais", +"ip4.buy":"Comprar {price}", +"ip4.cgnat_boxes":"Caixas de CGNAT", +"ip4.cgnat_note":"Mais casas por endereço liberam espaço para clientes, mas jogos e redirecionamento de portas sofrem: {p} da conta de uma casa atrás do CGNAT volta como reembolso.", +"ip4.cgnat_ratio":"CGNAT: casas por endereço", +"ip4.costs_row":"Aluguel de IPv4 e CGNAT", +"ip4.free":"Livres para novos clientes (as casas vão antes para trás do CGNAT)", +"ip4.from_rir":"Do RIR", +"ip4.give_back":"Devolver", +"ip4.held":"O RIR não transfere esse bloco de novo antes de {date}.", +"ip4.homes":"Casas com banda larga", +"ip4.homes_cgnat":"{n}, {p} atrás do CGNAT", +"ip4.in_use":"Seus clientes precisam desses endereços: coloque mais casas atrás do CGNAT ou arrume outro bloco antes.", +"ip4.lease":"Alugar {price}/mês", +"ip4.lease_out":"Alugar para terceiros +{price}/mês", +"ip4.leased_in":"Você alugou um {p} ({n} endereços) por {price}/mês.", +"ip4.leased_in_mo":"Alugado · {price}/mês", +"ip4.leased_out":"Seu {p} está alugado: +{price}/mês.", +"ip4.leased_out_mo":"Alugado para terceiros · +{price}/mês", +"ip4.leases_in":"Blocos alugados", +"ip4.leases_out":"Blocos alugados para terceiros", +"ip4.market":"Mercado de transferências", +"ip4.market_note":"IPv4 sai por cerca de {px} o endereço (blocos grandes, um pouco menos), aluga-se por {lin} o endereço por mês e, alugado para terceiros, rende {lout} depois da comissão do broker. Uma venda paga {p} do preço, e um bloco só pode ser transferido de novo dois anos depois da última transferência.", +"ip4.movable_from":"transferível a partir de {date}", +"ip4.n_addresses":{"one":"{n} endereço","other":"{n} endereços"}, +"ip4.n_homes_per_address":{"one":"{n} casa por endereço","other":"{n} casas por endereço"}, +"ip4.no_grow":"{name} ({city}) queria crescer para {bw}, mas você não tinha endereços IPv4 livres para isso.", +"ip4.no_space":"{name} precisa de um {p} de IPv4 ({n} endereços), e só {free} estão livres. Compre ou alugue um bloco, ou coloque mais casas atrás do CGNAT.", +"ip4.note":"IPv6 é grátis e infinito. IPv4 acabou há anos: clientes empresariais precisam de blocos públicos, e as casas que não cabem compartilham endereços atrás do CGNAT (o tráfego IPv6 passa por fora da caixa).", +"ip4.off":"Nas regras deste jogo, IPv4 não falta.", +"ip4.offer_needs":"Precisa de um {p} de IPv4 ({n} endereços); só {free} livres.", +"ip4.preset_plenty":"IPv4 de sobra para todo mundo.", +"ip4.preset_scarce":"IPv4 é escasso: compre, alugue ou compartilhe atrás do CGNAT.", +"ip4.really_sell":"Vender mesmo por {price}?", +"ip4.refunds":"Reembolsos para gamers irritados", +"ip4.section":"Espaço de endereços", +"ip4.sell":"Vender {price}", +"ip4.sold":"Seu {p} foi vendido por {price}.", +"ip4.squeezed":"Sem espaço: {p} das casas não cabem nem com {r} casas por endereço. As conexões caem e elas querem reembolso: compre ou alugue um bloco.", +"ip4.take_back":"Pegar de volta", +"ip4.toast_cgnat":"Seu IPv4 está cheio. {p} das suas casas agora compartilham endereços atrás do CGNAT, e alguns gamers já reclamaram.", +"ip4.toast_out":"Acabou o IPv4. Nem com {r} casas por endereço o CGNAT comporta todo mundo: compre ou alugue um bloco no banco.", +"ip4.too_many":"Você tem {n} blocos IPv4, o máximo que uma rede pode manter. Venda ou devolva blocos pequenos para abrir espaço para um maior.", +"ip4.yours":"Seus endereços IPv4", "ix_downgrade.pni_downgraded":"O PNI com {net} em {city} agora é {port}.", "ix_downgrade.port_downgraded_at_ix":"A porta em {ix} agora é de {port}.", "ix_downgrade.transit_downgraded":"O trânsito de {net} em {city} agora é {port}.", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index 4b199a2..3a51abb 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -86,6 +86,9 @@ const API_DOMAINS={ pieSpatId:{table:'PIE_SPAT_DEF',kind:'key'}, pieSpatChoice:{kind:'enum',values:[0,1]}, countryCode:{kind:'enum',values:()=>[...new Set(CITIES.map(c=>c.cc))].sort()}, + // Address space: an IPv4 prefix length the market sells, and the CGNAT ratios. + ip4Len:{kind:'enum',values:()=>Array.from({length:IP4_MAX-IP4_MIN+1},(_,i)=>IP4_MIN+i)}, + ip4Ratio:{kind:'enum',values:()=>IP4_NAT.slice()}, scnId:{table:'SCN',kind:'id'}, // A traceroute target in the modal's own terms. }; diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 6d3f47b..cfb4e36 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -232,7 +232,7 @@ const API_CMD={ doc:'Set how many channels of one optic model a dark-fiber span carries, in one change. Added optics come from the spares shelf when you have them (regen cards still cost their share); removed ones go back to the shelf.'}, /* ---------- customers ---------- */ accept:{args:[['id','entityId']], - doc:'Sign a pending offer. Rejected without a POP in every city it needs, without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, + doc:'Sign a pending offer. Rejected without a POP in every city it needs, without the IPv4 addresses it needs (rule ip4: see the bank\'s Address space), without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, decline:{args:[['id','entityId']], doc:'Throw an offer away.'}, salesHire:{args:[['id','salesPersona']], @@ -282,6 +282,23 @@ const API_CMD={ repayLoan:{args:[['id','entityId']],confirm:'double', quote:a=>{const l=S.loans.find(x=>x.id===a.id);return l?{setup:repayCost(l,BANKS[l.bank])}:{};}, doc:'Repay a loan early, or buy an equity investor out.'}, +/* ---------- address space (IPv4, rule ip4: On-call and BGP at 3 a.m.) ---------- */ + ip4Buy:{args:[['len','ip4Len']],watch:['ip4'], + quote:a=>({setup:ip4Cost(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}), + doc:'Buy an IPv4 block of this prefix length (24 = 256 addresses up to 16 = 65,536) on the transfer market at today\'s price. It can be sold again two years after this transfer. A network holds at most 256 blocks, bought, leased in and from the registry together.'}, + ip4Lease:{args:[['len','ip4Len']],watch:['ip4'], + quote:a=>({setup:0,monthly:ip4InMo(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}), + doc:'Lease an IPv4 block of this prefix length by the month, at today\'s rate (fixed for the lease). Hand it back with ip4Return. Refused at 256 blocks, like ip4Buy.'}, + ip4Sell:{args:[['id','entityId']],confirm:'double',watch:['ip4'], + doc:'Sell an owned block (not leased out) for 92% of the market price. Refused within two years of its last transfer, or when the customers signed would no longer fit with every home behind CGNAT.'}, + ip4Out:{args:[['id','entityId']],watch:['ip4'], + doc:'Lease an owned block out through a broker for a monthly income, while your own customers still fit without it.'}, + ip4Back:{args:[['id','entityId']],watch:['ip4'], + doc:'End the lease of a block you leased out; its addresses are yours to use again.'}, + ip4Return:{args:[['id','entityId']],watch:['ip4'], + doc:'Hand a leased-in block back, ending its monthly fee, when your customers still fit without it.'}, + ip4Nat:{args:[['v','ip4Ratio']],watch:['ip4'], + doc:'Set how many broadband homes share one IPv4 address behind CGNAT (8, 16, 32 or 64). More frees space for business customers but more gamers ask for refunds; fewer is refused when the customers signed would not fit.'}, /* ---------- security, China, incidents ---------- */ buildScrub:{args:[['city','cityId'],['tier','scrubTier',false]],watch:['scrubs'], quote:a=>{const T=SCRUB_TIERS[a.tier||0];return {setup:T?T.cost:undefined,monthly:T?T.mo:undefined};}, @@ -453,6 +470,8 @@ const API_CMD={ const API_VIEW={ pieOpen:{args:[],doc:'Open Pie Control, the rocket company\'s panel.'}, + ip4Open:{args:[],doc:'Open the bank at its Address space section: your IPv4 blocks, who uses them, CGNAT and the transfer market.'}, + ip4Pick:{args:[['v','ip4Len']],doc:'Pick the block size the Address space market quotes (a prefix length, 24 to 16).'}, pieGovOpen:{args:[],doc:'Open the bank at its Government money section: the rocket company\'s fund auctions, the Pitcairn grant and the Ex-Im Pie Bank (it used to be Pie Control\'s Gov tab).'}, pieTab:{args:[['t','pieTab']],doc:'Switch the Pie Control tab: traffic, co (the company, its books and the Founder\'s posts), fly (launches) or dish.'}, pieCity:{args:[['v','cityId']],doc:'Pick the POP the Dishes tab works on.'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index fb43b45..c3d1212 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -9,7 +9,7 @@ const API_STATE_DOC={ cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, - rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, + rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the later rules (sea, confs, broke, moods, pnis, and ip4 for scarce IPv4, off outside On-call and BGP at 3 a.m.), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, charter:{type:'string',doc:'The charter a normal game signed when it started: global | boutique | broker. chartSet is false until one is signed.'}, baronWon:{type:'number',doc:'The day a broker won Glass Baron, or 0.'}, chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, @@ -61,6 +61,7 @@ const API_STATE_DOC={ ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings (network work only: deals belong to the sales desk, slAuto), the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, + ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, w: which warnings were shown. What customers use is derived from their kind and size.'}, popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js index 0dce567..dfda734 100644 --- a/src/game/40-progress/30-rules.js +++ b/src/game/40-progress/30-rules.js @@ -6,17 +6,18 @@ // sea: cable ships sail out to subsea cuts, or (timer) a cut mends on its own clock. confs: conference season. // broke: deep in the red ends the game, or (rescue) a state loan keeps it going. moods: patient customers sour half as fast. // pnis: PNIs and their augments wait for the other network's team, or (instant) are up the moment they are ordered. -const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',sea:'ships',confs:true,broke:'lose',moods:'normal',pnis:'wait',mods:[]}; -const RULE_LATE=['sea','confs','broke','moods','pnis']; -const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open'],sea:['ships','timer'],confs:[true,false],broke:['lose','rescue'],moods:['normal','patient'],pnis:['wait','instant']}; +// ip4: IPv4 is scarce (#150, 33-address-space.js): customers need addresses, homes share them behind CGNAT. +const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',sea:'ships',confs:true,broke:'lose',moods:'normal',pnis:'wait',ip4:true,mods:[]}; +const RULE_LATE=['sea','confs','broke','moods','pnis','ip4']; +const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open'],sea:['ships','timer'],confs:[true,false],broke:['lose','rescue'],moods:['normal','patient'],pnis:['wait','instant'],ip4:[true,false]}; // i: icon, n: name, d: the one-line joke, x: what is different, in small print. const PRESETS={ - soft:{i:'☕',n:tr('rules.best_effort'),d:tr('rules.no_sla_no_pager_no_promises'),x:tr('rules.rare_outages_no_ddos_pnis_at_once'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',sea:'timer',confs:false,broke:'rescue',moods:'patient',pnis:'instant'}, - 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'}, + soft:{i:'☕',n:tr('rules.best_effort'),d:tr('rules.no_sla_no_pager_no_promises'),x:tr('rules.rare_outages_no_ddos_pnis_at_once'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',sea:'timer',confs:false,broke:'rescue',moods:'patient',pnis:'instant',ip4:false}, + 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',ip4:false}, 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'}, + 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',ip4:false}, + 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',ip4:false}, }; const NORMAL_PRESETS=['soft','freeze','oncall','bgp']; // How often things break, against the classic game. Spicy outages also last half as long again. diff --git a/src/game/60-features/33-address-space.js b/src/game/60-features/33-address-space.js new file mode 100644 index 0000000..8d91812 --- /dev/null +++ b/src/game/60-features/33-address-space.js @@ -0,0 +1,89 @@ +/* ---------- Address space (#150): IPv6 is free for everyone, IPv4 ran out years ago ---------- + The network holds IPv4 blocks in real CIDR sizes (/24 to /16): its first allocation from the RIR, blocks bought on + the transfer market and blocks leased in by the month. Owned blocks can be leased out (a broker finds the tenant) or + sold, once two years have passed since they last moved (the RIRs' holding period, which also stops flipping). + Business customers on IP service take a public block each, sized by kind and port (a /29 for a small DIA port, a /23 + for a big hosting company); broadband homes take what is left, and the homes that do not fit share addresses behind + CGNAT at the player's ratio. CGNAT costs a little per Gbps it carries (IPv6 goes around the box) and some gamers want + their money back. An offer that needs more than is free, with every home already behind CGNAT, cannot be signed, and a + customer renewing bigger stays at its size when the bigger block is not free (clGrow). + Nothing is stored per customer: what each one needs follows from its kind and size, so growing customers and old saves + need no new fields. On in On-call and BGP at 3 a.m. (rule ip4), off in the gentler presets, sandbox and puzzles; + scenarios only when they opt in (S.scn.rules.ip4). No random draws: the market price is a function of the day. + The first allocation is a /21: one transit's worth of broadband levels off at about 1,300 homes in every start city, + so the first months fit with room for a few customers (gameplay rule F1). */ +// IP4_BLK: the most blocks a network holds; buying and leasing stop there, and a save keeps that many. +const IP4_START=21,IP4_MIN=16,IP4_MAX=24,IP4_HOLD=730,IP4_NAT=[8,16,32,64],IP4_NAT0=16,IP4_BLK=256; +// Public addresses per Gbps of busy-hour broadband (a home each), and the part of it CGNAT still carries: the rest is IPv6. +const IP4_BB=10,IP4_V4=0.55,IP4_CGN=2; +// The market: dollars per address, flat for half a year, then +3% a year on a slow four-year swing. Leases are by the +// month (a broker keeps a cut of what yours earn), sales pay 92% of the price after the broker's fee. +const IP4_PX=38,IP4_FREE=180,IP4_YR=0.03,IP4_IN=0.5,IP4_OUT=0.4,IP4_SELL=0.92; +// Of the bill of a home behind CGNAT, the share that comes back as refunds (gamers, mostly): more homes per address, more +// grumbling. Homes squeezed past the ratio (port exhaustion) are worse. +const IP4_ANNOY={8:0.01,16:0.015,32:0.025,64:0.04},IP4_SQZ=0.15; +// Per kind of customer: addresses per Gbps of port, and the smallest block it takes. Circuits, waves and fiber carry no +// addresses of yours; downstream ISPs and universities bring their own (universities sit on legacy /16s); orbit +// terminals sit behind the satellite operator's own CGNAT. +const IP4_BIZ={cgame:[0.5,256],dia:[2,8],fabip:[2,8],game:[2,16],gpu:[0.5,64],host:[4,64],metav:[0.25,256],scrub:[2,8],stream:[1,32]}; +const ip4Sz=len=>2**(32-len),ip4LenOk=len=>Number.isInteger(len)&&len>=IP4_MIN&&len<=IP4_MAX; +const ip4Cidr=n=>'/'+(32-Math.ceil(Math.log2(Math.max(1,n)))),ip4N=n=>Math.round(n).toLocaleString(); +function ip4On(){return !!S&&!!S.ip4&&rule('ip4')===true&&(S.scn?scnRule('ip4'):S.mode==='normal');} +function ip4Need(b){const k=b&&IP4_BIZ[b.type];if(!k||!(b.bw>0))return 0;return Math.min(4096,2**Math.ceil(Math.log2(Math.max(k[1],b.bw*k[0]))));} +/* Who uses what. T: usable addresses (owned and leased in, without what is leased out); B: business customers; H: homes; + cg: homes behind CGNAT; over: the share of homes that do not fit even at the ratio; free: what a new customer can have + with every home behind CGNAT. */ +function ip4Use(s=S){const I=s.ip4,r=I.nat;let own=0,inn=0,out=0,B=0,H=0; + for(const b of I.b){const n=ip4Sz(b.len);if(b.k==='in')inn+=n;else if(b.out)out+=n;else own+=n;} + for(const b of s.biz)B+=ip4Need(b); + for(const c in s.pops){const p=s.pops[c];if(p.bb)H+=p.bb.d*IP4_BB;} + H=Math.ceil(H);const T=own+inn,A=Math.max(0,T-B),min=Math.ceil(H/r);let cg=0,over=0; + if(A=min)cg=Math.min(H,Math.ceil((H-A)*r/(r-1)));else{cg=H;over=min?1-A/min:0;}} + return {T,own,inn,out,B,H,cg,over,free:T-B-min,r};} +const ip4Fits=o=>!ip4On()||ip4Need(o)<=Math.max(0,ip4Use().free); +// A customer renewing at bw: does the bigger block it needs fit what is free? +const ip4GrowOk=(b,bw)=>!ip4On()||ip4Need({type:b.type,bw})-ip4Need(b)<=Math.max(0,ip4Use().free); +const ip4Full=()=>S.ip4.b.length>=IP4_BLK; +// What you announce, as the AS box shows it: your blocks by prefix length, without the ones leased out to others. +const ip4Pfx=()=>{const c={};for(const b of S.ip4.b)if(!b.out)c[b.len]=(c[b.len]||0)+1;return Object.keys(c).sort((a,b)=>a-b).map(l=>`${c[l]} × /${l}`).join(', ');}; +// Would giving this block up (selling, leasing it out, handing it back) still leave room for everyone? +const ip4Spare=b=>ip4Use().free>=ip4Sz(b.len); +const ip4Held=b=>b.k!=='in'&&S.day-b.dMath.round(ip4Sz(len)*ip4Px()*(1-0.015*(IP4_MAX-len))/100)*100; +const ip4Value=len=>Math.round(ip4Cost(len)*IP4_SELL/100)*100; +const ip4InMo=len=>Math.round(ip4Sz(len)*IP4_IN*ip4Px()/IP4_PX),ip4OutMo=len=>Math.round(ip4Sz(len)*IP4_OUT*ip4Px()/IP4_PX); +// The month's IPv4 bill: leases in and out, CGNAT boxes, refunds (eye: what broadband earns a month). +function ip4Bill(eye){const u=ip4Use();let lin=0,lout=0;for(const b of S.ip4.b){if(b.k==='in')lin+=b.mo||0;else if(b.out)lout+=b.mo||0;} + const cgS=u.H?u.cg/u.H:0;return {u,lin,lout,box:u.cg/IP4_BB*IP4_V4*IP4_CGN,refund:eye*(cgS*IP4_ANNOY[u.r]+u.over*IP4_SQZ)};} +// computeMoney: only what is there, so a network with nothing to pay keeps its money rows as they were. +function ip4Money(C,V){if(!ip4On())return;const b=ip4Bill(V.eyeballs||0),c=Math.round(b.lin+b.box+b.refund);if(c>0)C.ip4=c;if(b.lout>0)V.ip4=b.lout;} +/* A new network gets its /21 from the RIR. An older save gets what it already uses registered to it and a quarter more to + grow into (about a month for a big, fast-growing network), rounded up to /24s in real CIDR blocks (a /21 at the + least), so nothing changes on load; those blocks move like any other two years on. + Their ids are fixed (rir0, rir1…), not uid(): a new game draws no id, so every id after it stays as it was. */ +function ip4Grant(s){const d=s.day||0,b=[],add=len=>b.push({id:'rir'+b.length,len,k:'rir',d});let need=0; + for(const x of s.biz||[])need+=ip4Need(x); + for(const c in s.pops||{}){const p=s.pops[c];if(p&&p.bb&&p.bb.d>0)need+=p.bb.d*IP4_BB;} + need=Math.max(ip4Sz(IP4_START),Math.ceil(need*1.25/256)*256); + while(need>=ip4Sz(IP4_MIN)&&b.length<200){add(IP4_MIN);need-=ip4Sz(IP4_MIN);} + for(let len=IP4_MIN+1;len<=IP4_MAX;len++)if(need>=ip4Sz(len)){add(len);need-=ip4Sz(len);} + return {b,nat:IP4_NAT0,w:0};} +const ip4New=()=>ip4Grant({}); +function ip4Fix(s){const I=s.ip4&&typeof s.ip4==='object'&&!Array.isArray(s.ip4)?s.ip4:null;if(!I){s.ip4=ip4Grant(s);return;} + const day=Math.max(0,num(s.day,0)),mo=v=>Math.round(Math.min(1e8,Math.max(0,num(v,0)))); + const b=(Array.isArray(I.b)?I.b:[]).filter(x=>x&&typeof x==='object'&&ip4LenOk(x.len)&&['rir','buy','in'].includes(x.k)).slice(0,IP4_BLK).map(x=>{ + const o={id:typeof x.id==='string'&&x.id&&x.id.length<=40?x.id:uid(),len:x.len,k:x.k,d:int(x.d,0,day,0)}; + if(x.k==='in')o.mo=mo(x.mo);else if(x.out===true){o.out=true;o.mo=mo(x.mo);}return o;}); + s.ip4={b,nat:IP4_NAT.includes(I.nat)?I.nat:IP4_NAT0,w:int(I.w,0,3,0)};} +/* Once a day: say so when homes go behind CGNAT (a percent of them at least), and when even CGNAT cannot fit them all + (w: what was said). Each rearms only with room to spare again, so homes hovering at the limit hear it once. */ +function ip4Day(d){if(!ip4On())return;const I=S.ip4,u=ip4Use(),A=u.T-u.B,go=[{l:tr('ip4.section'),act:'ip4Open'}]; + if(u.cg>=Math.max(1,u.H*0.01)){if(!(I.w&1)){I.w|=1;toast(tr('ip4.toast_cgnat',{p:pct(u.cg/u.H)}),'',go);}}else if(A>=u.H*1.05)I.w&=~1; + if(u.over>0){if(!(I.w&2)){I.w|=2;toast(tr('ip4.toast_out',{r:u.r}),'bad',go);sfx('err');}}else if(A>=Math.ceil(u.H/u.r)*1.1)I.w&=~2;} +// Renewals that wanted a bigger block than is free (clGrow, [customer, bandwidth]): they stay as they are, and hear why. +function ip4News(l=[]){for(const [b,bw] of l.slice(0,3))toast(tr('ip4.no_grow',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(bw)}),'',[{l:tr('ip4.section'),act:'ip4Open'}]);} +// The line under an offer that cannot be signed for want of addresses. +function ip4Why(o){if(ip4Fits(o))return '';const n=ip4Need(o); + return `
${tr('ip4.offer_needs',{p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))})} ${btn(tr('ip4.section'),'ip4Open',{},'ghost sm')}
`;} diff --git a/src/game/60-features/38-sales-desk.js b/src/game/60-features/38-sales-desk.js index ff2efd0..9c68f86 100644 --- a/src/game/60-features/38-sales-desk.js +++ b/src/game/60-features/38-sales-desk.js @@ -65,13 +65,13 @@ function salesDay(d){const L=S.sales;if(!L)return; // With a rocket company, every other game is with the Founder, and in orbit (pieGolf, 99-pie-sales.js). const SALES_GOLF=['metav','cgame','gpu','stream','isp','edu','host','dia']; function salesGolf(d){if(pieGolf(d))return;const mine=Object.keys(S.pops).filter(c=>popUp(c)&&bizCity(c));if(!mine.length)return; - const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl());if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name); const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40}; const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b)); toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');} // Declining an offer the CEO likes: about one in three, he already shook hands on it. -function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||slR('veto|'+slKey(o))>=0.33)return false; +function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||!ip4Fits(o)||slR('veto|'+slKey(o))>=0.33)return false; const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;} // Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer. function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null; diff --git a/src/game/60-features/39-sales-auto.js b/src/game/60-features/39-sales-auto.js index 11f3b81..7251224 100644 --- a/src/game/60-features/39-sales-auto.js +++ b/src/game/60-features/39-sales-auto.js @@ -32,7 +32,7 @@ function slAutoDay(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floo const won=o=>{if(S.offers.includes(o))return false;W.n++;W.rev+=Math.round(bizMo(o));dirty=true;return true;}; opsQuiet(()=>{for(const o of S.offers.slice()){if(!S.offers.includes(o))continue;const T=BIZ_T[o.type];if(!T||!(o.exp>d))continue;const v=T.event?(o.fee||0):bizMo(o); if(A.min&&vb0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}continue;} - if(!A.on)continue; + if(!A.on||!ip4Fits(o))continue; if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cashd)))continue;ACT.accept({id:o.id});won(o);continue;} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 3559593..7903fdd 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:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),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:{}, + ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),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:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null}; } diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 6b28350..4829518 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -374,10 +374,11 @@ function computeMoney(R2,PX=null){ C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c)*(R2.bbF[c]??1),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)||BIZ_T[b.type].orbit)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)*(R2.tgtF[b.id]??1);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; + ip4Money(C,V); if(PX)pieMoney(PX,R2,V); // The UK grant for Pitcairn, its satellite tier once orbit is known; the Rural Digital Pie Fund (99-pie-subsidies.js). {const on=grantOn(R2),sky=!on&&!!PX&&grantSky(R2);V.grant=on?GRANT_MO:sky?GRANT_SKY_MO:0;if(PX)V.gov=pieGovMo();if(PX)R2.pie.gov={rdf:V.gov||0,sky:sky?GRANT_SKY_MO:0};} 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+(V.orbit||0)); R2.costMo=Object.values(C).reduce((a,b)=>a+b,0); - R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0); + R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0)+(V.ip4||0); } diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index e6c94b3..b18f5b9 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -112,6 +112,7 @@ function sanitize(s){ 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);mpSanitize(s); pieSanitize(s);pieIncFix(s); + ip4Fix(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/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index 97a5d5d..2bba376 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -58,14 +58,16 @@ function clRenew(b,rate){b.rate=Math.max(0,Math.round(rate));b.mk=mkt();delete b function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);} const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ '); -// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. -function clGrow(b){const T=BIZ_T[b.type];if(T.fiber)return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=up||b.bw*2;return true;} +// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. Not +// when the bigger IPv4 block it needs is not free (#150): out.v4 lists them for the day's news. +function clGrow(b,out){const T=BIZ_T[b.type];if(T.fiber)return false;const bw=(T.opts||[]).find(x=>x>b.bw)||b.bw*2; + if(!ip4GrowOk(b,bw)){if(out)out.v4.push([b,bw]);return false;}b.bw=bw;return true;} // Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says. function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))}; if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;} const C=S.cl;if(d-C.odd>=CL_ODD_GAP&&clR(b,'odd')<0.25){C.odd=d;clGone(b,'odd');out.lost.push(tr('lifecycle.left_odd',{...v,why:tr(clPick(CL_ODD,b,'oddline'))}));return;} const ks=Object.keys(CL_WHY).filter(k=>CL_WHY[k].ok(b.type)),k=clPick(ks,b,'why'); - if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;} + if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;} if(k==='moved'){const reg=CITY[b.city].reg,to=Object.keys(S.pops).filter(c=>c!==b.city&&CITY[c].reg===reg&&bizCity(c)).sort(); const c2=to.length&&clR(b,'stay')<0.5?clPick(to,b,'to'):null; if(c2){const from=CITY[b.city].name;b.city=c2;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.moved_stays',{name:v.name,from:esc(from),to:esc(CITY[c2].name)}));return;}} @@ -75,7 +77,7 @@ function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clW /* A day of contracts, after the moods. 30 days before a term ends a customer with competitors around may ask for a discount (at most three open at a time); at the end, the rest renew, grow or leave. An unanswered haggle renews at the asked price. */ -function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0); +function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[],v4:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0); const pat=rule('moods')==='patient'?0.5:1; for(const b of S.biz.slice()){if(!b.te||!clOn(b))continue; if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;} @@ -86,7 +88,7 @@ function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],l continue;} const cf=Math.min(1,clComp(b)/6),u=(100-b.mood)/100,leave=(0.04+0.08*cf+0.35*u*u)*pat*salesLeaveMul(b); if(clR(b,'leave')=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}} + const g=clR(b,'grow');if((b.mood>=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}} clRenew(b,clFair(b));clNote('ren');out.ren++;} clNews(out);clReferral(d);} // What the day says: haggles one by one (they want an answer), the rest in a few lines so a big network is not a wall of toasts. @@ -94,7 +96,7 @@ function clNews(out){ for(const b of out.hag){const was=bizMo(b),now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate; toast(tr('lifecycle.haggle',{name:esc(b.name),city:esc(clWhere(b)),price:fmt$(now),p:pct(1-now/Math.max(1,was)),n:b.hag.until-S.day}),'',[{l:tr('common.deals'),act:'leftTab',args:{t:'deals'}}],{a:'cust',v:b.id});} const few=(list,kind)=>{for(const t of list.slice(0,3))toast(t,kind);if(list.length>3)toast(trn('lifecycle.n_more',list.length-3),kind);}; - few(out.ok,'good');few(out.lost,''); + few(out.ok,'good');ip4News(out.v4);few(out.lost,''); if(out.ren)toast(trn('lifecycle.n_renewed',out.ren,{p:mktTxt()}),'');} const mktTxt=()=>{const m=mkt();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});}; diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 2f008db..7c2a989 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -94,6 +94,7 @@ function dayPost(d){ scnTick(d); confTick(d); specDay(d); + ip4Day(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; diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index aa5e4c8..d683de8 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -4,7 +4,7 @@ Object.assign(ACT,{ if(!w&&!p){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}const L=l.list||(l.list={w:0,p:0});L.w+=w;L.p+=p; toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();}, unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();}, - 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;} + accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o);toast(tr('ip4.no_space',{name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))}),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');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/54-address-space.js b/src/game/90-actions/54-address-space.js new file mode 100644 index 0000000..e2c934f --- /dev/null +++ b/src/game/90-actions/54-address-space.js @@ -0,0 +1,29 @@ +/* Address space (#150, 33-address-space.js): buy, lease in, lease out, sell, hand back, and the CGNAT ratio. Every block + change keeps room for the customers already signed, with every home behind CGNAT. */ +const ip4Re=()=>{after();renderBank();}; +function ip4Can(){if(ip4On())return true;toast(tr('ip4.off'),'bad');sfx('err');return false;} +const ip4Blk=id=>S.ip4.b.find(b=>b.id===id); +function ip4Busy(){toast(tr('ip4.in_use'),'bad');sfx('err');} +// No more blocks than a save keeps (IP4_BLK): a new one is refused with the way out. +function ip4Room(){if(!ip4Full())return true;toast(tr('ip4.too_many',{n:IP4_BLK}),'bad');sfx('err');return false;} +Object.assign(ACT,{ + ip4Open:()=>{if(!S||pzOn()||!ip4On())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankIp4');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});}, + // The size the market rows quote (a dropdown: v is the prefix length). + ip4Pick:({v})=>{const len=Number(v);if(ip4LenOk(len))UI.ip4Len=len;renderBank();}, + ip4Buy:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const c=ip4Cost(len);if(!spend(c))return; + S.ip4.b.push({id:uid(),len,k:'buy',d:S.day});toast(tr('ip4.bought',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(c)}),'good');sfx('coin');ip4Re();}, + ip4Lease:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const mo=ip4InMo(len); + S.ip4.b.push({id:uid(),len,k:'in',d:S.day,mo});toast(tr('ip4.leased_in',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(mo)}),'good');sfx('click');ip4Re();}, + ip4Sell:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return; + if(ip4Held(b)){toast(tr('ip4.held',{date:dateStr(b.d+IP4_HOLD)}),'bad');sfx('err');return;}if(!ip4Spare(b)){ip4Busy();return;} + if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;const v=ip4Value(b.len);S.ip4.b=S.ip4.b.filter(x=>x!==b);S.cash+=v; + toast(tr('ip4.sold',{p:'/'+b.len,price:fmt$(v)}),'good');sfx('coin');ip4Re();}, + ip4Out:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return;if(!ip4Spare(b)){ip4Busy();return;} + b.out=true;b.mo=ip4OutMo(b.len);toast(tr('ip4.leased_out',{p:'/'+b.len,price:fmt$(b.mo)}),'good');sfx('coin');ip4Re();}, + ip4Back:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||!b.out)return;delete b.out;delete b.mo;sfx('click');ip4Re();}, + ip4Return:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k!=='in')return;if(!ip4Spare(b)){ip4Busy();return;} + S.ip4.b=S.ip4.b.filter(x=>x!==b);sfx('click');ip4Re();}, + // Fewer homes per address needs more addresses: refused when the customers already signed would not fit. + ip4Nat:({v})=>{if(!ip4Can())return;const r=Number(v);if(!IP4_NAT.includes(r)||r===S.ip4.nat)return;const u=ip4Use(); + if(r
${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)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${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)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${ip4Why(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')}${pieNocBtn()}${btn(`⚙️ ${tr('routing.routing_and_ddos')}${S.te&&!coreTE()?'':''}`,'routingOpen',{},'')}
`; diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 43a2309..249a97f 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -140,7 +140,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})}
${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('')}
`; + 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')}
`:''}${ip4Why(o)}${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 b1e662f..b1ede29 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -9,7 +9,7 @@ function renderDash(){checkLayer();
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')} -

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; +

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0; // The legend above the table picks which ways in count; "lost" still looks at everything the network gets. @@ -28,7 +28,7 @@ function renderDash(){checkLayer(); 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); if(DT==='infra')h+=`

${tr('common.busiest_links')}

${ls.length?ls.map(({l,u})=>`
${CITY[l.a].name} ⇄ ${CITY[l.b].name} ${capName(l)} · ${linkLat(l).toFixed(1)} ms
${pct(u)}${btn(tr('common.open'),'dashLink',{id:l.id},'ghost sm')}
`).join(''):'

'+tr('common.no_links_yet')+'

'}

${tr('common.router_load')}

${rs.map(({c,u})=>`
${CITY[c].name} ${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}
${pct(u)}
`).join('')} -

${tr('common.your_as')}

${tr('common.as_number')}AS${S.asn}
${tr('common.prefixes')}${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6
${tr('common.bgp_sessions')}${R.sessions}
${tr('common.upstreams')}${new Set(S.transit.map(t=>t.net)).size}
${tr('common.reach')}${pct(R.reach)}
${tr('common.customers')}${tr('dashboard.n_businesses',{n:S.biz.length})}
`; +

${tr('common.your_as')}

${tr('common.as_number')}AS${S.asn}
${tr('common.prefixes')}${(ip4On()&&ip4Pfx())||Math.max(1,Math.ceil(Object.keys(S.pops).length/3))+' × /22'} IPv4, 1 × /32 IPv6
${tr('common.bgp_sessions')}${R.sessions}
${tr('common.upstreams')}${new Set(S.transit.map(t=>t.net)).size}
${tr('common.reach')}${pct(R.reach)}
${tr('common.customers')}${tr('dashboard.n_businesses',{n:S.biz.length})}
`; if(DT==='pops')h+=popsSection(); if(DT==='lease')h+=leaseTab(); if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);} diff --git a/src/game/94-dashboard/70-bank.js b/src/game/94-dashboard/70-bank.js index 9affb05..72566a4 100644 --- a/src/game/94-dashboard/70-bank.js +++ b/src/game/94-dashboard/70-bank.js @@ -29,6 +29,6 @@ function renderBank(){ ${B.equity?`
${tr('bank.taking_pct_of_your_revenue_every',{pct:pct(l.share)})}
`:`
${tr('common.still_owed')}${fmt$(l.bal)}
${loanLine(l)}
`} ${covList(l)}${l.breach>=1?`
${trn('bank.condition_broken_for_n_day',l.breach)} ${l.breach<10?tr('bank.penalty_in_n_days',{n:10-l.breach}):tr('bank.penalties_are_running')}
`:''}
${btn(UI.confirm===l.id?tr('bank.really_pay_price',{price:fmt$(cost)}):B.equity?tr('bank.buy_them_out_price',{price:fmt$(cost)}):tr('bank.repay_early_price_incl_2_fee',{price:fmt$(cost)}),'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash
`;} - h+=pieGovBank(); + h+=pieGovBank()+ip4Bank(); if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;} } diff --git a/src/game/94-dashboard/72-address-space.js b/src/game/94-dashboard/72-address-space.js new file mode 100644 index 0000000..149689c --- /dev/null +++ b/src/game/94-dashboard/72-address-space.js @@ -0,0 +1,22 @@ +/* The bank's Address space section (#150, 33-address-space.js): what you hold and who uses it, the CGNAT ratio, your + blocks, and the transfer market. Phones: the boxes are full width, the dropdowns stack and every button row wraps. */ +const ip4Pc=x=>(x*100).toFixed(1).replace(/\.0$/,'')+'%'; +function ip4Bank(){if(!S||!ip4On())return '';const I=S.ip4,B=ip4Bill((R.rev&&R.rev.eyeballs)||0),u=B.u,len=ip4LenOk(UI.ip4Len)?UI.ip4Len:IP4_MAX,px=ip4Px(),full=ip4Full(); + const kv=(l,v,bad)=>`
${l}${v}
`,mo=v=>tr('common.price_mo',{price:fmt$(v)}); + let h=`

🔢 ${tr('ip4.section')}

${tr('ip4.note')}

`; + h+=`
${kv(tr('ip4.yours'),ip4N(u.T))}${kv(tr('ip4.business'),ip4N(u.B))}${kv(tr('ip4.homes'),u.cg?tr('ip4.homes_cgnat',{n:ip4N(u.H),p:pct(u.cg/u.H)}):ip4N(u.H))}${kv(tr('ip4.free'),ip4N(Math.max(0,u.free)),u.free<=0)}`; + if(u.over>0)h+=`
${tr('ip4.squeezed',{p:pct(u.over),r:u.r})}
`; + if(B.lin>0)h+=kv(tr('ip4.leases_in'),mo(B.lin));if(B.box>=1)h+=kv(tr('ip4.cgnat_boxes'),mo(B.box));if(B.refund>=1)h+=kv(tr('ip4.refunds'),mo(B.refund));if(B.lout>0)h+=kv(tr('ip4.leases_out'),'+'+mo(B.lout)); + h+=` +

${tr('ip4.cgnat_note',{p:ip4Pc(IP4_ANNOY[I.nat])})}

`; + h+=`
${tr('ip4.blocks')}
`; + for(const b of I.b){const n=ip4Sz(b.len),spare=u.free>=n,held=ip4Held(b),sure=UI.confirm===b.id; + const what=b.k==='in'?tr('ip4.leased_in_mo',{price:fmt$(b.mo||0)}):b.out?tr('ip4.leased_out_mo',{price:fmt$(b.mo||0)}):b.k==='buy'?tr('ip4.bought_on',{date:dateStr(b.d)}):tr('ip4.from_rir'); + const btns=b.k==='in'?btn(tr('ip4.give_back'),'ip4Return',{id:b.id},'ghost sm',!spare):b.out?btn(tr('ip4.take_back'),'ip4Back',{id:b.id},'ghost sm') + :btn(tr('ip4.lease_out',{price:fmt$(ip4OutMo(b.len))}),'ip4Out',{id:b.id},'sm',!spare)+btn(sure?tr('ip4.really_sell',{price:fmt$(ip4Value(b.len))}):tr('ip4.sell',{price:fmt$(ip4Value(b.len))}),'ip4Sell',{id:b.id},sure?'red sm':'ghost sm',held||!spare); + // Greyed for want of room: say so (a disabled button never gets to show ip4Busy's toast). + h+=`
/${b.len} · ${trn('ip4.n_addresses',n,{n:ip4N(n)})}
${what}${held&&!b.out?' · '+tr('ip4.movable_from',{date:dateStr(b.d+IP4_HOLD)}):''}
${!spare&&!b.out?`
${tr('ip4.in_use')}
`:''}
${btns}
`;} + h+=`
${tr('ip4.market')}

${tr('ip4.market_note',{px:fmt$(px),lin:'$'+(IP4_IN*px/IP4_PX).toFixed(2),lout:'$'+(IP4_OUT*px/IP4_PX).toFixed(2),p:pct(IP4_SELL)})}

+ + ${full?`
${tr('ip4.too_many',{n:IP4_BLK})}
`:''}
${btn(tr('ip4.buy',{price:fmt$(ip4Cost(len))}),'ip4Buy',{len},'pink sm',full||S.cash
`; + return h;} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index e71afef..e582aae 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -43,7 +43,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'}; // The chosen preset in one line: its joke, then what actually changes. -const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)}`; +const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)} ${PRESETS[k].ip4===false?tr('ip4.preset_plenty'):tr('ip4.preset_scarce')}`; // The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js). const presetBtns=pr=>`
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

`; 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'; diff --git a/src/i18n/en.js b/src/i18n/en.js index 0c4838e..c580cf8 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2639,6 +2639,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin moved down {p}% on the way to your account.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin moved up {p}% on the way to your account.", "interface.you_bought_out_bank_they_flew":"You bought out {bank}.
They flew off to find another startup.", +"ip4.block_size":"Block size", +"ip4.blocks":"Your blocks", +"ip4.bought":"Bought a {p} ({n} addresses) for {price}.", +"ip4.bought_on":"Bought {date}", +"ip4.business":"Used by business customers", +"ip4.buy":"Buy {price}", +"ip4.cgnat_boxes":"CGNAT boxes", +"ip4.cgnat_note":"More homes per address frees space for customers, but games and port forwarding suffer: {p} of a CGNAT home's bill comes back as refunds.", +"ip4.cgnat_ratio":"CGNAT: homes sharing one address", +"ip4.costs_row":"IPv4 leases and CGNAT", +"ip4.free":"Free for new customers (homes move behind CGNAT first)", +"ip4.from_rir":"From the RIR", +"ip4.give_back":"Give it back", +"ip4.held":"The RIR won't transfer that block again before {date}.", +"ip4.homes":"Broadband homes", +"ip4.homes_cgnat":"{n}, {p} behind CGNAT", +"ip4.in_use":"Your customers need those addresses: put more homes behind CGNAT or get another block first.", +"ip4.lease":"Lease {price}/mo", +"ip4.lease_out":"Lease out +{price}/mo", +"ip4.leased_in":"Leased a {p} ({n} addresses) for {price}/mo.", +"ip4.leased_in_mo":"Leased in · {price}/mo", +"ip4.leased_out":"Your {p} is leased out: +{price}/mo.", +"ip4.leased_out_mo":"Leased out · +{price}/mo", +"ip4.leases_in":"Blocks leased in", +"ip4.leases_out":"Blocks leased out", +"ip4.market":"Transfer market", +"ip4.market_note":"IPv4 sells for about {px} an address (big blocks a little less), leases for {lin} an address a month, and earns {lout} leased out after the broker's cut. A sale pays {p} of the price, and a block can only move again two years after its last transfer.", +"ip4.movable_from":"can move again from {date}", +"ip4.n_addresses":{"one":"{n} address","other":"{n} addresses"}, +"ip4.n_homes_per_address":{"one":"{n} home per address","other":"{n} homes per address"}, +"ip4.no_grow":"{name} ({city}) wanted to grow to {bw}, but you had no IPv4 addresses free for it.", +"ip4.no_space":"{name} needs a {p} of IPv4 ({n} addresses), and only {free} are free. Buy or lease a block, or put more homes behind CGNAT.", +"ip4.note":"IPv6 is free and endless. IPv4 ran out years ago: business customers need public blocks of it, and homes that don't fit share addresses behind CGNAT (IPv6 traffic goes around the box).", +"ip4.off":"IPv4 is plentiful under this game's rules.", +"ip4.offer_needs":"Needs a {p} of IPv4 ({n} addresses); only {free} free.", +"ip4.preset_plenty":"Plenty of IPv4 for everyone.", +"ip4.preset_scarce":"IPv4 is scarce: buy it, lease it or share it behind CGNAT.", +"ip4.really_sell":"Really sell for {price}?", +"ip4.refunds":"Refunds to grumpy gamers", +"ip4.section":"Address space", +"ip4.sell":"Sell {price}", +"ip4.sold":"Sold your {p} for {price}.", +"ip4.squeezed":"Out of space: {p} of homes don't fit even at {r} homes per address. Their connections break and they want refunds: buy or lease a block.", +"ip4.take_back":"Take it back", +"ip4.toast_cgnat":"Your IPv4 is full. {p} of your homes now share addresses behind CGNAT, and a few gamers have already written in.", +"ip4.toast_out":"Out of IPv4. Even at {r} homes per address, CGNAT can't fit everyone: buy or lease a block at the bank.", +"ip4.too_many":"You hold {n} IPv4 blocks, the most one network can keep track of. Sell or give back small ones to make room for a bigger block.", +"ip4.yours":"Your IPv4 addresses", "ix_downgrade.pni_downgraded":"The PNI with {net} in {city} is now {port}.", "ix_downgrade.port_downgraded_at_ix":"Port at {ix} is now {port}.", "ix_downgrade.transit_downgraded":"{net} transit in {city} is now {port}.", diff --git a/tests/address-space.test.js b/tests/address-space.test.js new file mode 100644 index 0000000..92fafdf --- /dev/null +++ b/tests/address-space.test.js @@ -0,0 +1,442 @@ +// IPv4 address space (#150, src/game/60-features/33-address-space.js): business customers need public blocks, broadband +// homes share addresses behind CGNAT when they do not fit, blocks are bought, sold, leased in and leased out, and the +// whole thing is a rule (ip4): On-call and BGP at 3 a.m. only, scenarios when they opt in. +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 { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt on On-call, plenty of cash, nothing breaking, level 9 so every kind of customer can turn up. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall');S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=9;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.offers=[];S.biz=[];" + + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:3});compute()"; +function game(t, opts) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE); + return h; +} +const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); +const homes = (ev, g) => ev(`S.pops.fra.bb.d=${g};compute()`); +const biz = (ev, b) => ev(`S.biz.push(${lit({ id: b.id || 'b' + Math.random().toString(36).slice(2), city: 'fra', city2: null, reqs: [], name: 'X', type: 'host', bw: 10, rate: 60, mood: 100, since: 0, ...b })});compute()`); + +test('what each customer needs: a block by kind and size, nothing for circuits, fiber, downstream ISPs or orbit', (t) => { + const { ev, errors } = game(t); + const need = (type, bw) => ev(`ip4Need({type:${lit(type)},bw:${bw}})`); + assert.equal(need('dia', 1), 8, 'a small DIA port gets a /29'); + assert.equal(need('dia', 10), 32); + assert.equal(need('game', 5), 16); + assert.equal(need('host', 10), 64); + assert.equal(need('host', 80), 512, 'a big hosting company a /23'); + assert.equal(need('cgame', 3200), 2048); + assert.equal(need('metav', 6400), 2048); + assert.equal(need('host', 1e6), 4096, 'capped at a /20'); + for (const k of ['l2vpn', 'hyper', 'wwave', 'dfpair', 'isp', 'edu', 'provedor', 'event', 'pizza', 'flywifi']) assert.equal(need(k, 100), 0, k); + assert.equal(ev('ip4Cidr(8)'), '/29'); + assert.equal(ev('ip4Cidr(512)'), '/23'); + // Every IPv4 kind is a real kind of customer that pays by the Gbps. + assert.deepEqual(J(ev, 'Object.keys(IP4_BIZ).filter(k=>!BIZ_T[k]||!(BIZ_T[k].rate>0)||BIZ_T[k].l2||BIZ_T[k].fiber||BIZ_T[k].orbit)'), []); + assert.deepEqual(errors, []); +}); + +test('consumption: business first, homes take the rest, and the ones that do not fit go behind CGNAT', (t) => { + const { ev, errors } = game(t); + // A new network: one /21 from the RIR, held two years before it can move. + assert.deepEqual(J(ev, 'S.ip4.b.map(b=>[b.len,b.k,b.d])'), [[21, 'rir', 0]]); + assert.equal(ev('S.ip4.nat'), 16); + homes(ev, 50); + let u = J(ev, 'ip4Use()'); + assert.deepEqual([u.T, u.B, u.H, u.cg, u.over, u.free], [2048, 0, 500, 0, 0, 2048 - 32], '500 homes all public; a new customer could push them all behind CGNAT'); + assert.equal(ev('R.cost.ip4'), undefined, 'nothing to pay while everyone has an address'); + biz(ev, { type: 'host', bw: 80 }); // a /23 + homes(ev, 150); + u = J(ev, 'ip4Use()'); + // 1,536 left for 1,500 homes: all public. 1,600 homes: (1600-1536)*16/15 rounded up go behind CGNAT. + assert.deepEqual([u.B, u.cg], [512, 0]); + homes(ev, 160); + u = J(ev, 'ip4Use()'); + assert.equal(u.cg, Math.ceil((1600 - 1536) * 16 / 15)); + assert.ok(u.H - u.cg + Math.ceil(u.cg / 16) <= 1536, 'public homes plus the CGNAT pool fit the space'); + const c = J(ev, 'ip4Bill(R.rev.eyeballs)'); + assert.ok(c.box > 0 && c.refund > 0, 'CGNAT boxes and refunds cost money'); + assert.equal(ev('R.cost.ip4'), Math.round(c.box + c.refund)); + assert.ok(Math.abs(c.refund - ev('R.rev.eyeballs') * (u.cg / u.H) * 0.015) < 1e-6, 'refunds: 1.5% of the CGNAT share of what homes pay at 1:16'); + // A wider ratio frees addresses and annoys more gamers. + const free16 = u.free; + ev("ACT.ip4Nat({v:'64'})"); + assert.equal(ev('S.ip4.nat'), 64); + assert.ok(J(ev, 'ip4Use()').free > free16); + assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund > c.refund); + ev("ACT.ip4Nat({v:'16'})"); + // Business customers squeeze the homes: past the ratio, homes are squeezed out (port exhaustion) and it shows. + biz(ev, { type: 'host', bw: 80, id: 'h2' }); + biz(ev, { type: 'host', bw: 1e6, id: 'h3' }); + u = J(ev, 'ip4Use()'); + assert.equal(u.cg, u.H); + assert.ok(u.over > 0 && u.free < 0); + assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund >= ev('R.rev.eyeballs*ip4Use().over') * 0.15, 'squeezed homes want real money back'); + // Narrowing the ratio is refused when the signed customers would not fit. + ev("ACT.ip4Nat({v:'8'})"); + assert.equal(ev('S.ip4.nat'), 16); + assert.deepEqual(errors, []); +}); + +test('an offer that needs more IPv4 than is free cannot be signed, and says why; a block fixes it', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 50); + ev(`S.offers.push({id:'big',city:'fra',name:'Pixel Palace',type:'cgame',bw:3200,rate:45,reqs:[],exp:S.day+30},{id:'small',city:'fra',name:'Tiny DIA',type:'dia',bw:1,rate:600,reqs:[],exp:S.day+30})`); + assert.equal(ev("ip4Fits(S.offers[0])"), false, 'a /21 does not fit the starting /21 with homes on it'); + assert.equal(ev("ip4Fits(S.offers[1])"), true); + // The deals list and the city panel say why, with a way to the address space. + ev("UI.left='deals';UI.leftOpen=true;renderLeft();selectCity('fra');UI.tab='cust';renderPanel()"); + const left = dom.window.document.getElementById('leftBody').textContent; + assert.match(left, /Needs a \/21 of IPv4 \(2,048 addresses\); only 2,016 free\./); + assert.ok(dom.window.document.querySelector('#leftBody [data-act="ip4Open"]'), 'a button to the address space'); + ev("ACT.accept({id:'big'})"); + assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'not signed'); + assert.equal(ev('S.biz.length'), 0); + assert.match(dom.window.document.getElementById('toasts').textContent, /Pixel Palace needs a \/21 of IPv4/); + ev("ACT.accept({id:'small'})"); + assert.equal(ev('S.biz.length'), 1, 'a small one fits'); + // Buy a /21 and the big one signs. + const cash = ev('S.cash'); + ev("ACT.ip4Buy({len:21})"); + assert.equal(ev('S.cash'), cash - ev('ip4Cost(21)')); + assert.equal(ev('ip4Cost(21)'), Math.round(2048 * 38 * (1 - 0.015 * 3) / 100) * 100, 'about $38 an address, a little less for a bigger block'); + ev("ACT.accept({id:'big'})"); + assert.equal(ev('S.biz.length'), 2); + assert.equal(J(ev, 'ip4Use()').B, 8 + 2048); + // The bank opens at the section. + ev("ACT.ip4Open()"); + assert.equal(dom.window.document.getElementById('bankBox').hidden, false); + assert.ok(dom.window.document.getElementById('bankIp4')); + assert.deepEqual(errors, []); +}); + +test('the sales desk and the CEO do not sign what does not fit', (t) => { + const { ev, errors } = game(t); + homes(ev, 50); + ev("ACT.salesHire({id:'shark'});closeModal();S.slAuto.on=true"); + ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); + ev('slAutoDay(S.day)'); + assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'the shark leaves it'); + ev("ACT.salesFire({});ACT.salesFire({});closeModal();ACT.salesHire({id:'ceo'});closeModal()"); + assert.equal(ev("salesOverride(S.offers.find(o=>o.id==='big'))"), false, 'no handshake on addresses you do not have'); + assert.equal(ev("(()=>{const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));return t;})()"), 'gpu', 'the golf deal is the biggest that fits (a /23 for an AI data center, not a /21 for cloud gaming)'); + assert.deepEqual(errors, []); +}); + +test('buying, leasing in, leasing out and selling move the right money', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 20); + const rev0 = ev('R.revMo'), cost0 = ev('R.costMo'); + ev("ACT.ip4Lease({len:22})"); + const lin = ev("S.ip4.b.find(b=>b.k==='in').mo"); + assert.equal(lin, 512, 'a /22 leases for $0.50 an address a month'); + assert.equal(ev('R.costMo'), cost0 + lin); + assert.equal(ev('ip4Use().T'), 3072); + ev("ACT.ip4Buy({len:24})"); + const bought = ev("S.ip4.b.find(b=>b.k==='buy').id"); + ev(`ACT.ip4Out({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.find(b=>b.id===${lit(bought)}).mo`), Math.round(256 * 0.4)); + assert.equal(ev('R.revMo'), rev0 + Math.round(256 * 0.4), 'leased out: income every month'); + assert.equal(ev('R.rev.ip4'), Math.round(256 * 0.4)); + // A leased-out block cannot be sold; take it back first. A fresh block cannot move for two years. + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true); + ev(`ACT.ip4Back({id:${lit(bought)}})`); + assert.equal(ev('R.rev.ip4'), undefined); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.match(dom.window.document.getElementById('toasts').textContent, /won't transfer that block again/); + ev('S.day+=730'); + const cash = ev('S.cash'); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true, 'the first click only asks'); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), false); + assert.equal(ev('S.cash'), cash + ev('ip4Value(24)')); + assert.ok(ev('ip4Value(24)') < ev('ip4Cost(24)'), 'the broker keeps a cut'); + // Hand the leased block back: the fee stops. + ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id})"); + assert.equal(ev("S.ip4.b.some(b=>b.k==='in')"), false); + assert.equal(ev('R.cost.ip4'), undefined); + // Space in use cannot be given away: with customers on every address, leasing out or selling the /21 is refused. + biz(ev, { type: 'host', bw: 80 }); + biz(ev, { type: 'host', bw: 40, id: 'h2' }); + const rir = ev("S.ip4.b.find(b=>b.k==='rir').id"); + ev(`ACT.ip4Out({id:${lit(rir)}})`); + assert.equal(ev(`!!S.ip4.b.find(b=>b.id===${lit(rir)}).out`), false); + assert.match(dom.window.document.getElementById('toasts').textContent, /Your customers need those addresses/); + assert.deepEqual(errors, []); +}); + +test('a list of blocks stops where a save keeps them: buying and leasing past it is refused, and a full save loads whole', (t) => { + const { ev, dom, errors } = load({ agent: true }); + t.after(() => dom.window.close()); + ev(BASE); + homes(ev, 20); + // The market's default size, clicked over and over (or an agent in a loop): bought and leased /24s. + ev('for(let i=0;i<150;i++)ACT.ip4Buy({len:24});for(let i=0;i<150;i++)ACT.ip4Lease({len:24})'); + assert.equal(ev('S.ip4.b.length'), ev('IP4_BLK'), 'stops at the most a save keeps'); + assert.equal(ev('IP4_BLK'), 256); + assert.match(dom.window.document.getElementById('toasts').textContent, /You hold 256 IPv4 blocks/); + const cash = ev('S.cash'), T = ev('ip4Use().T'), mo = ev('R.cost.ip4'); + ev('ACT.ip4Buy({len:16});ACT.ip4Lease({len:16})'); + assert.deepEqual([ev('S.ip4.b.length'), ev('S.cash'), ev('ip4Use().T')], [256, cash, T], 'refused: no money spent, nothing added'); + // The bank says so and greys the market out; an agent's quote says why. + ev('ACT.ip4Open()'); + const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.match(sec.textContent, /the most one network can keep track of/); + assert.equal(sec.querySelector('[data-act="ip4Buy"]').disabled, true); + assert.equal(sec.querySelector('[data-act="ip4Lease"]').disabled, true); + assert.match(J(ev, 'API_CMD.ip4Buy.quote({len:24}).blocked')[0], /256 IPv4 blocks/); + assert.match(J(ev, 'API_CMD.ip4Lease.quote({len:24}).blocked')[0], /256 IPv4 blocks/); + // Saved and loaded: every block, every lease, the same space and bill. + const before = ev('JSON.stringify(S.ip4)'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('JSON.stringify(S.ip4)'), before); + assert.deepEqual([ev('ip4Use().T'), ev('R.cost.ip4')], [T, mo]); + // Handing one back makes room for a bigger block. + ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id});ACT.ip4Buy({len:16})"); + assert.deepEqual([ev('S.ip4.b.length'), ev('S.ip4.b[255].len')], [256, 16]); + assert.deepEqual(errors, []); +}); + +test('a customer renewing bigger stays at its size when the bigger block is not free, and says why', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 0); + // Eight 40G hosts (a /24 each) fill the /21; the ninth is refused at the door. + for (let i = 0; i < 9; i++) ev(`S.offers.push({id:'o${i}',city:'fra',name:'Host ${i}',type:'host',bw:40,rate:60,reqs:[],exp:S.day+30});ACT.accept({id:'o${i}'})`); + assert.equal(ev('S.biz.length'), 8); + assert.equal(J(ev, 'ip4Use()').free, 0); + // The next term of host 0 on a day its own rolls say: stay, and grow (to 80G, a /23). + const renew = () => J(ev, `(()=>{const b=S.biz[0];for(const x of S.biz)if(x!==b)x.te=1e6; + for(let k=Math.max(S.day,b.te)+1;k=(0.04+0.08*Math.min(1,clComp(b)/6))*salesLeaveMul(b)){S.day=k;document.getElementById('toasts').innerHTML='';clDay(k);compute(); + return {bw:b.bw,te:b.te,in:S.biz.includes(b),free:ip4Use().free,toasts:document.getElementById('toasts').textContent};}}return null;})()`); + let r = renew(); + assert.ok(r, 'a growing renewal turns up'); + assert.deepEqual([r.bw, r.in, r.free], [40, true, 0], 'renewed at the size it has: nobody runs on addresses you do not have'); + assert.ok(r.te > ev('S.day'), 'a new term'); + assert.match(r.toasts, /Host 0 \(Frankfurt\) wanted to grow to 80(\.0)? Gbps, but you had no IPv4 addresses free for it\./); + assert.match(r.toasts, /renewed/); + // The acquisition that would stay bigger goes through the same door. + assert.equal(ev('(()=>{const out={v4:[]};return clGrow(S.biz[0],out)===false&&out.v4.length===1&&S.biz[0].bw===40;})()'), true); + // A block bought, the next growing renewal grows. + ev('ACT.ip4Buy({len:24})'); + r = renew(); + assert.deepEqual([r.bw, r.free], [80, 0]); + assert.match(r.toasts, /renewed and grew to 80(\.0)? Gbps/); + // Without the rule, growth is as it always was. + ev("S.rules=makeRules('freeze');compute()"); + r = renew(); + assert.equal(r.bw, 160); + assert.doesNotMatch(r.toasts, /IPv4/); + assert.deepEqual(errors, []); +}); + +test('the address space says what its numbers mean: free counts homes behind CGNAT, blocks in use say why they stay', (t) => { + const { ev, dom, errors } = game(t); + ev('S.day=800'); + homes(ev, 50); + ev('ACT.ip4Open()'); + const sec = () => dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.match(sec().textContent, /Free for new customers \(homes move behind CGNAT first\)2,016/); + // The /21 is out of its holding period, but 500 homes use it: greyed out, and the row says why. + let row = sec().querySelector('[data-act="ip4Out"]').closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, true); + assert.equal(row.querySelector('[data-act="ip4Sell"]').disabled, true); + assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); + // A leased-in /24 the customers need too: Give it back is greyed, with the reason. + ev("ACT.ip4Lease({len:24})"); + biz(ev, { type: 'host', bw: 80, id: 'h1' }); + biz(ev, { type: 'host', bw: 80, id: 'h2' }); + biz(ev, { type: 'host', bw: 80, id: 'h3' }); + biz(ev, { type: 'host', bw: 80, id: 'h4' }); + assert.equal(J(ev, 'ip4Use()').free, 224, 'fewer free than the /24 holds'); + ev('UI._bh=null;renderBank()'); + row = sec().querySelector('[data-act="ip4Return"]').closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Return"]').disabled, true); + assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); + // With room to spare, no reason is shown and the buttons work. + ev("S.biz=[];compute();ACT.ip4Buy({len:24});UI._bh=null;renderBank()"); + row = [...sec().querySelectorAll('[data-act="ip4Out"]')].pop().closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, false); + assert.equal(row.querySelector('.why'), null); + assert.deepEqual(errors, []); +}); + +test('the AS box on the dashboard lists the blocks you announce, not a made-up count', (t) => { + const { ev, dom, errors } = game(t); + const asBox = () => { ev("ACT.dash({});ACT.dashTab({k:'infra'})"); const k = [...dom.window.document.querySelectorAll('.kv')].map(e => e.textContent).find(x => /IPv6/.test(x)); ev('ACT.dashClose()'); return k; }; + assert.match(asBox(), /1 × \/21 IPv4, 1 × \/32 IPv6/, 'the starting allocation'); + ev("ACT.ip4Lease({len:22});ACT.ip4Buy({len:24})"); + assert.match(asBox(), /1 × \/21, 1 × \/22, 1 × \/24 IPv4/, 'bought and leased-in blocks are announced too'); + ev("S.rules=makeRules('freeze');compute()"); + assert.match(asBox(), /1 × \/22 IPv4/, 'without the rule it stays as it always was'); + assert.deepEqual(errors, []); +}); + +test('the market price drifts gently with the day, and holds still without the market rule', (t) => { + const { ev, errors } = game(t); + assert.equal(ev('ip4Px(0)'), 38); + assert.equal(ev('ip4Px(180)'), 38, 'flat for half a year'); + const px = [400, 900, 1500, 2200].map((d) => ev(`ip4Px(${d})`)); + assert.ok(px.every((p) => p > 30 && p < 50), 'realistic: $30 to $50 an address: ' + px); + assert.ok(Math.abs(ev('ip4Px(546)') - ev('ip4Px(545)')) < 0.1, 'a gentle trend, not a jump'); + assert.ok(ev('ip4Cost(16)') / 65536 < ev('ip4Cost(24)') / 256, 'bigger blocks a little cheaper per address'); + ev("S.rules=makeRules('oncall',{market:false})"); + assert.equal(ev('ip4Px(1500)'), 38); + assert.deepEqual(errors, []); +}); + +test('the day says it once when homes go behind CGNAT, and when even CGNAT cannot fit them', (t) => { + const { ev, dom, errors } = game(t); + const said = () => dom.window.document.getElementById('toasts').textContent; + // A handful of homes over the edge (under a percent of them) is not news yet. + homes(ev, 205.3); + ev('ip4Day(S.day)'); + const few = J(ev, 'ip4Use()'); + assert.ok(few.cg > 0 && few.cg < few.H / 100, JSON.stringify(few)); + assert.equal(ev('S.ip4.w'), 0); + assert.doesNotMatch(said(), /IPv4/); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.match(said(), /Your IPv4 is full\.\s*19% of your homes now share addresses behind CGNAT/); + assert.equal(ev('S.ip4.w'), 1); + ev("document.getElementById('toasts').innerHTML='';ip4Day(S.day)"); + assert.equal(said(), '', 'only once'); + // Homes hovering at the limit hear it once: dipping just under does not rearm it, real room again does. + homes(ev, 204); + ev('ip4Day(S.day)'); + assert.deepEqual([J(ev, 'ip4Use()').cg, ev('S.ip4.w')], [0, 1]); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.equal(said(), '', 'not again while hovering'); + homes(ev, 150); + ev('ip4Day(S.day)'); + assert.equal(ev('S.ip4.w'), 0, 'room to spare: it rearms'); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.match(said(), /Your IPv4 is full/); + ev("document.getElementById('toasts').innerHTML=''"); + biz(ev, { type: 'host', bw: 1e6 }); + ev('ip4Day(S.day)'); + assert.match(dom.window.document.getElementById('toasts').textContent, /Out of IPv4/); + assert.equal(ev('S.ip4.w'), 3); + ev("S.biz=[];S.pops.fra.bb.d=10;compute();ip4Day(S.day)"); + assert.equal(ev('S.ip4.w'), 0, 'fixed: the warnings rearm'); + assert.deepEqual(errors, []); +}); + +test('rule off means no effect: gentler presets, sandbox, puzzles and scenarios unless they opt in', (t) => { + const { ev, dom, errors } = game(t); + assert.deepEqual(J(ev, "['soft','freeze','oncall','bgp','sandbox','puzzle'].map(p=>makeRules(p).ip4)"), [false, false, null, null, false, false], 'On-call and BGP keep the default (on), written nowhere'); + assert.equal(ev('RULE_DEF.ip4'), true); + ev("S.rules=makeRules('freeze');S.pops.fra.bb.d=500;compute()"); + assert.equal(ev('ip4On()'), false); + ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); + assert.equal(ev("ip4Why(S.offers[0])"), ''); + ev("ACT.accept({id:'big'})"); + assert.equal(ev('S.biz.length'), 1, 'signed: IPv4 is plentiful here'); + assert.equal(ev('R.cost.ip4'), undefined); + ev("ACT.ip4Buy({len:24})"); + assert.equal(ev('S.ip4.b.length'), 1, 'the market is closed'); + ev("ACT.bank()"); + assert.equal(dom.window.document.getElementById('bankIp4'), null, 'no address space in the bank'); + ev("ACT.bankClose()"); + // Sandbox and scenarios. + ev("beginGame('Box','fra',{mode:'sandbox'});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('ip4On()'), false, 'sandbox'); + ev("beginGame('S','fra',{mode:'normal',preset:'oncall',scn:SCN.find(x=>x.city==='fra')||SCN[0]});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev("S.mode"), 'scenario'); + assert.equal(ev('ip4On()'), false, 'scenarios run On-call but stay as they were'); + ev('S.scn.rules.ip4=true'); + assert.equal(ev('ip4On()'), true, 'unless they opt in'); + ev("beginGame('B','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('ip4On()'), true, 'BGP at 3 a.m.'); + assert.deepEqual(errors, []); +}); + +test('old saves: what they already use is registered to them, so nothing changes on load', (t) => { + const { ev, errors } = game(t); + homes(ev, 300); + biz(ev, { type: 'host', bw: 80 }); + biz(ev, { type: 'dia', bw: 10, id: 'd1' }); + biz(ev, { type: 'l2vpn', bw: 10, id: 'l1' }); + // The same network without the rule, for its money. + ev("window.__r=S.rules;S.rules=makeRules('freeze');compute();window.__m=[R.revMo,R.costMo];S.rules=__r"); + ev('S.day=400;delete S.ip4;S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + const u = J(ev, 'ip4Use()'); + assert.equal(u.cg, 0, 'no home behind CGNAT'); + const want = (u.B + u.H) * 1.25; + assert.ok(u.T >= want && u.T - want < 256, 'what they use and a quarter more to grow into, rounded up to whole /24s: ' + JSON.stringify(u)); + assert.ok(J(ev, 'S.ip4.b').every((b) => b.k === 'rir' && b.d === 400 && b.len >= 16 && b.len <= 24)); + assert.deepEqual([ev('R.revMo'), ev('R.costMo')], J(ev, '__m'), 'the same money as before the feature'); + // A tiny old save still gets the /21 a new one starts with. + ev("S.biz=[];S.pops.fra.bb.d=1;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.deepEqual(J(ev, 'S.ip4.b.map(b=>b.len)'), [21]); + // A big old network: whole /16s. + ev("S.pops.fra.bb.d=20000;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); + const big = J(ev, 'ip4Use()'); + assert.ok(big.T >= 200000 && big.cg === 0 && J(ev, 'S.ip4.b.filter(b=>b.len===16).length') === 3); + assert.deepEqual(errors, []); +}); + +test('the big network loads with its usage granted: routing and money as before', (t) => { + const { ev, dom, errors } = load({ seed: 3 }); + t.after(() => dom.window.close()); + const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`); + const on = ev('ip4On()'); + const digest = 'JSON.stringify([R.served,R.revMo,R.costMo,R.cost,R.rev])'; + const a = ev(digest); + ev("window.__r=S.rules;S.rules=Object.assign({},S.rules,{ip4:false});compute()"); + assert.equal(ev(digest), a, 'the grant covers it all (rule ' + (on ? 'on' : 'off') + ')'); + assert.equal(J(ev, 'S.ip4.b.length') > 0, true); + assert.deepEqual(errors, []); +}); + +test('saves: garbage is repaired, and the state round-trips', (t) => { + const { ev, errors } = game(t); + ev("ACT.ip4Lease({len:23});ACT.ip4Nat({v:'32'})"); + const before = ev('JSON.stringify(S.ip4)'); + ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('JSON.stringify(S.ip4)'), before); + ev(`S.ip4={b:[{id:'a',len:12,k:'rir',d:0},{id:'b',len:24,k:'stolen',d:0},{id:'c',len:24,k:'buy',d:-5,out:'yes',mo:5},{id:'d',len:23,k:'in',d:1e9,mo:-3},null,{id:'e',len:24,k:'rir',d:0,out:true,mo:'x'}],nat:7,w:99};S=sanitize(JSON.parse(JSON.stringify(S)))`); + assert.deepEqual(J(ev, 'S.ip4'), { b: [{ id: 'c', len: 24, k: 'buy', d: 0 }, { id: 'd', len: 23, k: 'in', d: ev('S.day'), mo: 0 }, { id: 'e', len: 24, k: 'rir', d: 0, out: true, mo: 0 }], nat: 16, w: 3 }); + ev("S.ip4='nope';S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.ok(J(ev, 'S.ip4.b.length') >= 1, 'a broken field is granted afresh'); + assert.deepEqual(errors, []); +}); + +test('the address space works on a phone: one column, wrapping buttons, the dropdowns stacked', (t) => { + const { ev, dom, errors } = game(t); + ev("window.innerWidth=360;window.innerHeight=740;S.pops.fra.bb.d=250;compute();ACT.ip4Lease({len:24});ACT.ip4Open()"); + const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.ok(sec, 'the section is in the bank'); + assert.equal(sec.querySelectorAll('select').length, 2, 'the CGNAT ratio and the block size'); + for (const s of sec.querySelectorAll('select')) assert.ok(s.closest('.ops-sel'), 'each dropdown in a stacking label'); + for (const b of sec.querySelectorAll('button')) assert.ok(b.closest('.btns'), 'every button in a wrapping row: ' + b.textContent); + assert.match(sec.textContent, /2,500, \d+% behind CGNAT/); + // The dropdown picks the size the buttons quote. + ev("ACT.ip4Pick({v:'18'})"); + assert.ok(dom.window.document.querySelector('#bankCard [data-act="ip4Buy"]').dataset.args.includes('"len":18')); + assert.deepEqual(errors, []); +}); + +test('no raw labels in the address space, in every language', (t) => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); + ev(BASE); + ev("S.pops.fra.bb.d=300;compute();ACT.ip4Lease({len:24});ACT.ip4Buy({len:24});S.ip4.b[2].out=true;S.ip4.b[2].mo=99;S.biz.push({id:'z',city:'fra',city2:null,reqs:[],name:'Z',type:'host',bw:1e6,rate:1,mood:100,since:0});compute();ip4Day(S.day);ACT.ip4Open()"); + ev("S.offers.push({id:'o',city:'fra',name:'O',type:'host',bw:80,rate:60,reqs:[],exp:S.day+30});UI.left='deals';renderLeft()"); + ev("for(let i=S.ip4.b.length;i 2, lang + ': the full list and the blocks in use say why'); + const txt = dom.window.document.getElementById('bankCard').textContent + dom.window.document.getElementById('leftBody').textContent + dom.window.document.getElementById('toasts').textContent; + assert.doesNotMatch(txt, /\bip4\.[a-z_]+|\{[a-z]+\}|undefined|NaN/, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 91e9080..7d1f3e3 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -256,7 +256,8 @@ test('M3: every subsystem that can annoy the player reads a rule', () => { const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], ['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'], - ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()']]; + ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()'], + ['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()']]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(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 and no market means a quiet year const g = load(); @@ -372,6 +373,23 @@ test('F1: new players get a gentle start: nothing breaks for 45 days, no sold-ou assert.deepEqual(g.errors, []); }); +test('F1: the first IPv4 block covers the start: no CGNAT, no IPv4 bill and no IPv4 warning before day 50', () => { + // The F2 reference build, signing every offer that fits, in the F2 cities and the fastest-growing big homes (Asia). + const bad = []; + for (const city of ['fra', 'nyc', 'sin', 'jnb', 'tok', 'del']) { + 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});}})()`); + assert.equal(g.ev('ip4On()'), true, 'On-call has scarce IPv4'); + const hit = g.ev(`(()=>{for(let d=0;d<50;d++){for(const o of S.offers.slice())if(bHas(o)&&ip4Fits(o))ACT.accept({id:o.id});dayTick(); + const u=ip4Use();if(u.cg>0||S.ip4.w||R.cost.ip4)return 'day '+S.day+': '+u.cg+' of '+u.H+' homes behind CGNAT, bill '+(R.cost.ip4||0);}return '';})()`); + if (hit) bad.push(`${city}: ${hit}`); + assert.deepEqual(g.errors, []); + } + fail('F1', bad, 'size the first allocation (IP4_START, src/game/60-features/33-address-space.js) so the start fits'); +}); + 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 = []; diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 91cce81..71230db 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -227,7 +227,7 @@ test('a dry run prices every command that has a price, and changes nothing', () fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key }, opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, - pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, + pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, ip4Buy: { len: 24 }, ip4Lease: { len: 22 }, }; const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required)); assert.deepEqual(missing, [], 'every priced command with arguments has a sample here'); diff --git a/tests/sales-desk.test.js b/tests/sales-desk.test.js index 1a3190b..d633a6b 100644 --- a/tests/sales-desk.test.js +++ b/tests/sales-desk.test.js @@ -80,6 +80,8 @@ test('the shark: bigger deals at a quarter more, oversold promises, no nerds, a test('the CEO: golf deals at 30% off, the odd declined offer signed anyway, opinions; all from hashes, not Math.random', () => { const { ev, errors } = load(); ev(start); + // Room for every deal he signs (#150: nobody signs what the network has no IPv4 addresses for), so this counts handshakes. + ev("S.ip4.b.push({id:'room',len:16,k:'buy',d:0})"); ev("ACT.salesHire({id:'ceo'})"); ev('window.__r=0;window.__r0=Math.random;Math.random=()=>{__r++;return __r0();};'); const n0 = ev('S.biz.length'); From 8e1f2d66a5ffe42945b7cd4e5182beec9939f200 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:06:30 +0100 Subject: [PATCH 415/491] Express fiber: light a wave through a city without its router (#58) An express lightpath runs from A to C over your own or IRU dark fibers A-B, B-C (up to six) and passes B through its ROADM as light: ports only at its two ends, no hop in B, the fibers' latency added up. It takes one channel slot on every fiber it rides, needs a ROADM line system on each, and an optic that makes the whole run between regen sites. Routing, the route worker, traceroute, diverse paths and saves see it as a link A-C. A cut, a build, an amp or ROADM failure or a line system swap on any fiber under it darkens it; backhoes and the chaos monkey still find fibers that only carry expresses. "Express to..." on a fiber and an Express tab in the link window plan one, with reach, slots per fiber and the price. The intern's optics order leaves fibers that only carry expresses bare, decom never hands one back, and the build standard keeps a fiber's line system while an express on it carries traffic. --- CHANGELOG.md | 1 + 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/agent/20-commands.js | 10 +- src/agent/30-docs.js | 2 +- src/game/10-catalog/40-ports.js | 4 +- src/game/10-catalog/60-reach-and-subsea.js | 6 +- src/game/60-features/20-scenarios.js | 2 +- src/game/60-features/50-traceroute.js | 2 +- src/game/60-features/95-standing-orders.js | 5 +- src/game/60-features/96-pop-standard.js | 5 +- src/game/80-simulation/30-compute.js | 7 +- src/game/80-simulation/40-billing.js | 4 +- src/game/80-simulation/50-sanitize.js | 3 +- src/game/80-simulation/60-requirements.js | 6 +- src/game/80-simulation/65-express.js | 87 ++++ .../80-simulation/80-geography-and-latency.js | 2 +- src/game/85-incidents/20-failures.js | 15 +- src/game/85-incidents/40-chaos-monkey.js | 4 +- src/game/90-actions/50-customers.js | 2 +- src/game/90-actions/60-links.js | 4 +- src/game/90-actions/87-express.js | 22 + src/game/90-actions/87-fiber-and-hardware.js | 8 +- src/game/90-actions/88-optic-counts.js | 2 +- src/game/90-actions/90-action-helpers.js | 6 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/60-decommission.js | 3 +- src/game/93-ui/70-link-panels.js | 4 +- src/game/93-ui/72-express.js | 48 +++ src/game/94-dashboard/50-lease-swaps.js | 4 +- src/game/95-modals/70-link-modal.js | 7 +- src/game/96-map/50-link-geometry.js | 2 + src/game/96-map/51-express-geometry.js | 5 + src/game/96-map/55-link-look.js | 10 +- src/i18n/en.js | 40 ++ src/styles/40-modal.css | 2 + tests/express-fiber.test.js | 398 ++++++++++++++++++ tests/mcp-commands.test.js | 2 +- 41 files changed, 883 insertions(+), 53 deletions(-) create mode 100644 src/game/80-simulation/65-express.js create mode 100644 src/game/90-actions/87-express.js create mode 100644 src/game/93-ui/72-express.js create mode 100644 src/game/96-map/51-express-geometry.js create mode 100644 tests/express-fiber.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e5f8d8e..639dbf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project are documented here. The project follows - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. - Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). +- Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58) - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. - IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). diff --git a/site/i18n/de.js b/site/i18n/de.js index a152ee3..bccdbe8 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2020,6 +2020,46 @@ "exchanges.20_peering_sessions_n":"20+ Peering-Sessions ({n})", "exchanges.pops_on_3_continents":"POPs auf 3+ Kontinenten", "exchanges.serve_1_5_tbps_v":"1,5 Tbps ausliefern ({v})", +"express.already":{"one":"Auf diesem Weg läuft schon ein Express mit {n} Kanal: Das hier kommt dazu.","other":"Auf diesem Weg läuft schon ein Express mit {n} Kanälen: Das hier kommt dazu."}, +"express.cannot":"{optic} geht auf diesem Express nicht.
{why}", +"express.cap":"{cap} Express", +"express.city_via":"Express über {via}", +"express.dark_building":{"one":"{span} wird noch gebaut: noch {n} Tag.","other":"{span} wird noch gebaut: noch {n} Tage."}, +"express.dark_cut":"{span} ist gekappt.", +"express.dark_gone":"Eine der Glasfasern darunter gibt es nicht mehr.", +"express.dark_reach":"Keine ihrer Optiken schafft diese Strecke.", +"express.dark_system":"Auf {span} ist das Line System down.", +"express.express_to":"Express nach …", +"express.eyebrow":"Express-Lightpath · {km} km", +"express.fiber_busy":{"one":"Über diese Glasfaser läuft ein Express-Lightpath.
Bau ihn zuerst ab: Öffne ihn im Express-Abschnitt dieser Glasfaser.","other":"Über diese Glasfaser laufen {n} Express-Lightpaths.
Bau sie zuerst ab: Öffne sie im Express-Abschnitt dieser Glasfaser."}, +"express.fiber_full":"{a} ⇄ {b} hat keinen freien Kanal-Slot mehr ({max} im Line System).", +"express.free_slots":"{n} von {max} Slots frei", +"express.its_fibers":"Die Glasfasern darunter", +"express.last_channel":"Das ist der letzte Kanal des Express. Wenn du ihn loswerden willst, bau den Express ab.", +"express.lead":"Schick eine Wave am anderen Ende direkt durch den ROADM auf deine nächste Glasfaser: keine Router-Ports in der Stadt dazwischen, weniger Latenz, ein Kanal-Slot auf jeder Glasfaser, über die sie läuft.", +"express.lit":"Express leuchtet: {a} ⇄ {b}.
{optic} läuft direkt durch {via}: Kein Router dort bekommt sie zu sehen.", +"express.modal_lead":"Schick eine Wave von {a} nach {b} durch die ROADMs unterwegs: Die Städte dazwischen sehen sie auf keinem Router.", +"express.modal_note":"Der erste Kanal zahlt außerdem {price} pro Stadt unterwegs, damit er dort durch den ROADM gepatcht wird. Optiken aus dem Ersatzteilregal sind gratis; jeder Regen-Standort unterwegs braucht eine Karte.", +"express.n_carry_expresses":{"one":"{n} trägt einen Express","other":"{n} tragen Express-Lightpaths"}, +"express.n_channels":{"one":"{n} Kanal","other":"{n} Kanäle"}, +"express.needs_roadm":"Jede Glasfaser unter einem Express braucht ein ROADMaster-Line-System (oben unter Line System upgraden).", +"express.no_such_path":"Diese Glasfasern führen nicht mehr von der einen Stadt zur anderen.", +"express.one_more":"Noch eine {optic} auf dem Express {a} ⇄ {b}: jetzt {n} Kanäle.", +"express.optical_run":"Längste Strecke ohne Regen", +"express.out_of_reach":"außer Reichweite", +"express.passes":"Läuft als Licht durch den ROADM in {via}: Dort kein Router-Port, kein Hop im Traceroute.", +"express.plan":"Planen", +"express.riding_here":"Auf dieser Glasfaser", +"express.riding_note":"Bau sie ab, bevor du die Glasfaser aufgibst. Ein Schnitt oder ein Line-System-Tausch hier macht sie auch dunkel.", +"express.runs_at":"läuft mit {g}", +"express.slot_note":"Jeder Kanal belegt einen Slot auf jeder dieser Glasfasern. Ein Schnitt, ein Bau oder ein Line-System-Tausch auf einer davon macht den Express dunkel.", +"express.tab":"Express", +"express.tear_down":"Express abbauen", +"express.tear_down_note":"Seine Optiken kommen ins Ersatzteilregal.", +"express.title":"Express-Lightpaths", +"express.too_far":"Zu weit: Das Licht läuft {run} km ohne Regen-Standort, und diese Optik schafft selbst im langsamsten Modus nur {max} km. Bau Regen-Standorte auf den Glasfasern.", +"express.trace_hop":"Express-Lightpath, durchquert {via} nur als Licht", +"express.via_km":"über {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Eine Hitzewelle mit 45 °C in {city}: Das Stromnetz hat Last abgeworfen, die Kältemaschinen haben aufgegeben, und der Generator bei {dc} auch.", "failures.a_b_is_down_same_cable":"{a}–{b} ist down. Gleiches Kabel, neuer Anker. Der Reparaturtrupp hat eine Stempelkarte angelegt.", "failures.a_backhoe_cut_the_metro_ring":"Ein Bagger hat den Metro-Ring zwischen deinen beiden Standorten in {city} gekappt. Wie sich herausstellt, liefen beide Glasfaserwege durch dieselbe Straße.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 1f8b28a..9ec154f 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sesiones de peering ({n})", "exchanges.pops_on_3_continents":"POPs en 3+ continentes", "exchanges.serve_1_5_tbps_v":"sirve 1,5 Tbps ({v})", +"express.already":{"one":"Ya tienes un exprés por este camino con {n} canal: esto añade otro.","other":"Ya tienes un exprés por este camino con {n} canales: esto añade otro."}, +"express.cannot":"No se puede encender {optic} en este exprés.
{why}", +"express.cap":"{cap} exprés", +"express.city_via":"exprés por {via}", +"express.dark_building":{"one":"{span} todavía se está construyendo: queda {n} día.","other":"{span} todavía se está construyendo: quedan {n} días."}, +"express.dark_cut":"{span} está cortada.", +"express.dark_gone":"Una de las fibras por debajo ya no existe.", +"express.dark_reach":"Ninguna de sus ópticas llega tan lejos.", +"express.dark_system":"{span} tiene el sistema de línea caído.", +"express.express_to":"Exprés a…", +"express.eyebrow":"Lightpath exprés · {km} km", +"express.fiber_busy":{"one":"Un lightpath exprés va por esta fibra.
Desmóntalo primero: ábrelo desde la sección Exprés de esta fibra.","other":"{n} lightpaths exprés van por esta fibra.
Desmóntalos primero: ábrelos desde la sección Exprés de esta fibra."}, +"express.fiber_full":"{a} ⇄ {b} no tiene ningún hueco de canal libre ({max} en su sistema de línea).", +"express.free_slots":"{n} de {max} huecos libres", +"express.its_fibers":"Las fibras por las que va", +"express.last_channel":"Es el último canal del exprés. Para quitarlo, desmonta el exprés.", +"express.lead":"Manda una onda directo por el ROADM del otro extremo a tu siguiente fibra: sin puertos de router en la ciudad de en medio, menos latencia, un hueco de canal en cada fibra que recorre.", +"express.lit":"Exprés encendido: {a} ⇄ {b}.
{optic} pasa directo por {via}: ningún router de allí la ve.", +"express.modal_lead":"Enciende una onda de {a} a {b} a través de los ROADMs del camino: las ciudades de en medio nunca la ven en un router.", +"express.modal_note":"El primer canal paga además {price} por cada ciudad por la que pasa, para cruzarlo por el ROADM de allí. Las ópticas del estante de repuestos salen gratis; cada sitio regenerador del camino necesita una tarjeta.", +"express.n_carry_expresses":{"one":"{n} lleva un exprés","other":"{n} llevan lightpaths exprés"}, +"express.n_channels":{"one":"{n} canal","other":"{n} canales"}, +"express.needs_roadm":"Cada fibra por la que va un exprés necesita un sistema de línea ROADMaster (mejóralo arriba, en Sistema de línea).", +"express.no_such_path":"Esas fibras ya no enlazan una ciudad con la otra.", +"express.one_more":"Otra {optic} en el exprés {a} ⇄ {b}: ahora {n} canales.", +"express.optical_run":"Tramo más largo sin regenerar", +"express.out_of_reach":"fuera de alcance", +"express.passes":"Pasa por {via} como luz, a través del ROADM: allí ni puerto de router ni salto en un traceroute.", +"express.plan":"Planear", +"express.riding_here":"Por esta fibra", +"express.riding_note":"Desmóntalos antes de dejar la fibra. Un corte o un cambio de sistema de línea aquí también los apaga.", +"express.runs_at":"va a {g}", +"express.slot_note":"Cada canal ocupa un hueco en cada una de estas fibras. Un corte, una obra o un cambio de sistema de línea en cualquiera de ellas apaga el exprés.", +"express.tab":"Exprés", +"express.tear_down":"Desmontar el exprés", +"express.tear_down_note":"Sus ópticas vuelven al estante de repuestos.", +"express.title":"Lightpaths exprés", +"express.too_far":"Demasiado lejos: la luz recorre {run} km sin sitio regenerador y esta óptica llega a {max} km en su modo más lento. Añade sitios regeneradores en las fibras.", +"express.trace_hop":"lightpath exprés, cruza {via} solo como luz", +"express.via_km":"por {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Una ola de calor de 45 °C en {city}: la red recortó carga, los enfriadores se rindieron y también el generador de {dc}.", "failures.a_b_is_down_same_cable":"{a}–{b} está caído. Mismo cable, ancla nueva. El equipo de reparación ya tiene tarjeta de fidelidad.", "failures.a_backhoe_cut_the_metro_ring":"Una retroexcavadora cortó el anillo metropolitano entre tus dos sedes en {city}. Resulta que ambas rutas de fibra pasaban por la misma calle.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 7729036..ec461d3 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sessions de peering ({n})", "exchanges.pops_on_3_continents":"POP sur 3+ continents", "exchanges.serve_1_5_tbps_v":"servir 1,5 Tbps ({v})", +"express.already":{"one":"Tu as déjà un express sur ce chemin avec {n} canal : ceci en ajoute un.","other":"Tu as déjà un express sur ce chemin avec {n} canaux : ceci en ajoute un."}, +"express.cannot":"Impossible d’allumer {optic} sur cet express.
{why}", +"express.cap":"{cap} express", +"express.city_via":"express via {via}", +"express.dark_building":{"one":"{span} est encore en construction : encore {n} jour.","other":"{span} est encore en construction : encore {n} jours."}, +"express.dark_cut":"{span} est coupée.", +"express.dark_gone":"Une des fibres en dessous n’existe plus.", +"express.dark_reach":"Aucune de ses optiques ne porte aussi loin.", +"express.dark_system":"{span} a son système de ligne en panne.", +"express.express_to":"Express vers…", +"express.eyebrow":"Lightpath express · {km} km", +"express.fiber_busy":{"one":"Un lightpath express passe par cette fibre.
Démonte-le d’abord : ouvre-le depuis la section Express de cette fibre.","other":"{n} lightpaths express passent par cette fibre.
Démonte-les d’abord : ouvre-les depuis la section Express de cette fibre."}, +"express.fiber_full":"{a} ⇄ {b} n’a plus d’emplacement de canal libre ({max} sur son système de ligne).", +"express.free_slots":"{n} emplacements libres sur {max}", +"express.its_fibers":"Les fibres qu’il emprunte", +"express.last_channel":"C’est le dernier canal de l’express. Pour l’arrêter, démonte l’express.", +"express.lead":"Envoie une onde tout droit à travers le ROADM du bout opposé, sur ta fibre suivante : aucun port de routeur dans la ville du milieu, moins de latence, un emplacement de canal sur chaque fibre empruntée.", +"express.lit":"Express allumé : {a} ⇄ {b}.
{optic} traverse {via} tout droit : aucun routeur là-bas ne la voit.", +"express.modal_lead":"Allume une onde de {a} à {b} à travers les ROADM du chemin : les villes du milieu ne la voient jamais sur un routeur.", +"express.modal_note":"Le premier canal paie aussi {price} pour chaque ville traversée, pour le brasser dans le ROADM sur place. Les optiques de l’étagère de rechange sont gratuites ; chaque site de régénération du chemin demande une carte.", +"express.n_carry_expresses":{"one":"{n} porte un express","other":"{n} portent des lightpaths express"}, +"express.n_channels":{"one":"{n} canal","other":"{n} canaux"}, +"express.needs_roadm":"Chaque fibre empruntée par un express a besoin d’un système de ligne ROADMaster (mets-le à niveau plus haut, dans Système de ligne).", +"express.no_such_path":"Ces fibres ne relient plus une ville à l’autre.", +"express.one_more":"Une {optic} de plus sur l’express {a} ⇄ {b} : {n} canaux maintenant.", +"express.optical_run":"Plus longue portée sans régénération", +"express.out_of_reach":"hors de portée", +"express.passes":"Traverse {via} sous forme de lumière, par le ROADM : aucun port de routeur là-bas, aucun saut dans un traceroute.", +"express.plan":"Préparer", +"express.riding_here":"Sur cette fibre", +"express.riding_note":"Démonte-les avant d’abandonner la fibre. Une coupure ou un changement de système de ligne ici les éteint aussi.", +"express.runs_at":"tourne à {g}", +"express.slot_note":"Chaque canal prend un emplacement sur chacune de ces fibres. Une coupure, un chantier ou un changement de système de ligne sur l’une d’elles éteint l’express.", +"express.tab":"Express", +"express.tear_down":"Démonter l’express", +"express.tear_down_note":"Ses optiques retournent sur l’étagère de rechange.", +"express.title":"Lightpaths express", +"express.too_far":"Trop loin : la lumière parcourt {run} km sans site de régénération et cette optique porte à {max} km dans son mode le plus lent. Ajoute des sites de régénération sur les fibres.", +"express.trace_hop":"lightpath express, traverse {via} sous forme de lumière", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Canicule à 45 °C à {city} : le réseau a délesté, les groupes froids ont lâché, et le groupe électrogène de {dc} aussi.", "failures.a_b_is_down_same_cable":"{a}–{b} est en panne. Même câble, nouvelle ancre. L’équipe de réparation a créé une carte de fidélité.", "failures.a_backhoe_cut_the_metro_ring":"Une pelleteuse a coupé l’anneau métropolitain entre tes deux sites à {city}. En fait, les deux chemins de fibre passaient par la même rue.", diff --git a/site/i18n/it.js b/site/i18n/it.js index cc61779..06d88d6 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sessioni di peering ({n})", "exchanges.pops_on_3_continents":"POP in 3+ continenti", "exchanges.serve_1_5_tbps_v":"servire 1,5 Tbps ({v})", +"express.already":{"one":"Su questo percorso hai già un express con {n} canale: così ne aggiungi un altro.","other":"Su questo percorso hai già un express con {n} canali: così ne aggiungi un altro."}, +"express.cannot":"Impossibile accendere {optic} su questo express.
{why}", +"express.cap":"{cap} express", +"express.city_via":"express via {via}", +"express.dark_building":{"one":"{span} è ancora in costruzione: manca {n} giorno.","other":"{span} è ancora in costruzione: mancano {n} giorni."}, +"express.dark_cut":"{span} è tranciata.", +"express.dark_gone":"Una delle fibre sotto non c’è più.", +"express.dark_reach":"Nessuna delle sue ottiche arriva così lontano.", +"express.dark_system":"{span} ha il line system giù.", +"express.express_to":"Express verso…", +"express.eyebrow":"Lightpath express · {km} km", +"express.fiber_busy":{"one":"Su questa fibra passa un lightpath express.
Smontalo prima: aprilo dalla sezione Express di questa fibra.","other":"Su questa fibra passano {n} lightpath express.
Smontali prima: aprili dalla sezione Express di questa fibra."}, +"express.fiber_full":"{a} ⇄ {b} non ha più slot di canale liberi ({max} sul suo line system).", +"express.free_slots":"{n} slot liberi su {max}", +"express.its_fibers":"Le fibre su cui viaggia", +"express.last_channel":"È l’ultimo canale dell’express. Per fermarlo, smonta l’express.", +"express.lead":"Manda una wave dritta attraverso il ROADM all’altro capo, sulla tua fibra successiva: niente porte router nella città in mezzo, meno latenza, uno slot di canale su ogni fibra che percorre.", +"express.lit":"Express acceso: {a} ⇄ {b}.
{optic} passa dritta per {via}: nessun router lì la vede.", +"express.modal_lead":"Accendi una wave da {a} a {b} attraverso i ROADM lungo la strada: le città in mezzo non la vedono mai su un router.", +"express.modal_note":"Il primo canale paga anche {price} per ogni città che attraversa, per farlo passare nel ROADM lì. Le ottiche dallo scaffale dei ricambi sono gratis; ogni sito di rigenerazione lungo la strada vuole una scheda.", +"express.n_carry_expresses":{"one":"{n} porta un express","other":"{n} portano lightpath express"}, +"express.n_channels":{"one":"{n} canale","other":"{n} canali"}, +"express.needs_roadm":"Ogni fibra su cui viaggia un express ha bisogno di un line system ROADMaster (aggiornalo qui sopra, in Sistema di linea).", +"express.no_such_path":"Quelle fibre non collegano più una città all’altra.", +"express.one_more":"Un’altra {optic} sull’express {a} ⇄ {b}: ora {n} canali.", +"express.optical_run":"Tratta più lunga senza rigenerazione", +"express.out_of_reach":"fuori portata", +"express.passes":"Attraversa {via} come luce, dentro il ROADM: lì niente porta router, niente hop in un traceroute.", +"express.plan":"Pianifica", +"express.riding_here":"Su questa fibra", +"express.riding_note":"Smontali prima di abbandonare la fibra. Un taglio o un cambio di line system qui spegne anche loro.", +"express.runs_at":"va a {g}", +"express.slot_note":"Ogni canale occupa uno slot su ciascuna di queste fibre. Un taglio, un cantiere o un cambio di line system su una qualsiasi di esse spegne l’express.", +"express.tab":"Express", +"express.tear_down":"Smonta l’express", +"express.tear_down_note":"Le sue ottiche tornano sullo scaffale dei ricambi.", +"express.title":"Lightpath express", +"express.too_far":"Troppo lontano: la luce percorre {run} km senza un sito di rigenerazione e questa ottica arriva a {max} km nella modalità più lenta. Aggiungi siti di rigenerazione sulle fibre.", +"express.trace_hop":"lightpath express, attraversa {via} solo come luce", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Ondata di caldo a 45 °C a {city}: la rete ha staccato carichi, i chiller si sono arresi e anche il generatore di {dc}.", "failures.a_b_is_down_same_cable":"{a}–{b} è giù. Stesso cavo, ancora nuova. La squadra di riparazione ha aperto una tessera fedeltà.", "failures.a_backhoe_cut_the_metro_ring":"Una ruspa ha tagliato il ring metropolitano tra i tuoi due siti a {city}. A quanto pare entrambe le tratte in fibra passavano per la stessa strada.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 5fc3410..4714044 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sessões de peering ({n})", "exchanges.pops_on_3_continents":"POPs em 3+ continentes", "exchanges.serve_1_5_tbps_v":"entregar 1,5 Tbps ({v})", +"express.already":{"one":"Você já tem um expresso neste caminho com {n} canal: isto adiciona mais um.","other":"Você já tem um expresso neste caminho com {n} canais: isto adiciona mais um."}, +"express.cannot":"Não dá para acender {optic} neste expresso.
{why}", +"express.cap":"{cap} expresso", +"express.city_via":"expresso via {via}", +"express.dark_building":{"one":"{span} ainda está em construção: falta {n} dia.","other":"{span} ainda está em construção: faltam {n} dias."}, +"express.dark_cut":"{span} está cortada.", +"express.dark_gone":"Uma das fibras por baixo não existe mais.", +"express.dark_reach":"Nenhuma das suas ópticas alcança essa distância.", +"express.dark_system":"{span} está com o line system fora do ar.", +"express.express_to":"Expresso para…", +"express.eyebrow":"Lightpath expresso · {km} km", +"express.fiber_busy":{"one":"Um lightpath expresso passa por esta fibra.
Desmonte-o primeiro: abra-o na seção Expresso desta fibra.","other":"{n} lightpaths expressos passam por esta fibra.
Desmonte-os primeiro: abra-os na seção Expresso desta fibra."}, +"express.fiber_full":"{a} ⇄ {b} não tem mais slot de canal livre ({max} no seu line system).", +"express.free_slots":"{n} de {max} slots livres", +"express.its_fibers":"As fibras por onde ele passa", +"express.last_channel":"Esse é o último canal do expresso. Para parar, desmonte o expresso.", +"express.lead":"Mande uma onda direto pelo ROADM da outra ponta para a sua próxima fibra: sem portas de router na cidade do meio, menos latência, um slot de canal em cada fibra que ela percorre.", +"express.lit":"Expresso aceso: {a} ⇄ {b}.
{optic} passa direto por {via}: nenhum router lá a vê.", +"express.modal_lead":"Acenda uma onda de {a} a {b} pelos ROADMs do caminho: as cidades do meio nunca a veem num router.", +"express.modal_note":"O primeiro canal também paga {price} por cidade que atravessa, para passá-lo pelo ROADM de lá. Ópticas da prateleira de reservas saem de graça; cada site de regeneração no caminho precisa de uma placa.", +"express.n_carry_expresses":{"one":"{n} leva um expresso","other":"{n} levam lightpaths expressos"}, +"express.n_channels":{"one":"{n} canal","other":"{n} canais"}, +"express.needs_roadm":"Cada fibra por onde um expresso passa precisa de um line system ROADMaster (faça o upgrade acima, em Sistema de linha).", +"express.no_such_path":"Essas fibras não ligam mais uma cidade à outra.", +"express.one_more":"Mais uma {optic} no expresso {a} ⇄ {b}: agora {n} canais.", +"express.optical_run":"Maior trecho sem regeneração", +"express.out_of_reach":"fora de alcance", +"express.passes":"Atravessa {via} como luz, pelo ROADM: lá não usa porta de router nem aparece como salto no traceroute.", +"express.plan":"Planejar", +"express.riding_here":"Nesta fibra", +"express.riding_note":"Desmonte-os antes de abrir mão da fibra. Um corte ou uma troca do line system aqui também os apaga.", +"express.runs_at":"roda a {g}", +"express.slot_note":"Cada canal ocupa um slot em cada uma destas fibras. Um corte, uma obra ou uma troca do line system em qualquer uma delas apaga o expresso.", +"express.tab":"Expresso", +"express.tear_down":"Desmontar o expresso", +"express.tear_down_note":"As ópticas dele voltam para a prateleira de reservas.", +"express.title":"Lightpaths expressos", +"express.too_far":"Longe demais: a luz percorre {run} km sem site de regeneração e esta óptica alcança {max} km no modo mais lento. Adicione sites de regeneração nas fibras.", +"express.trace_hop":"lightpath expresso, passa por {via} só como luz", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Onda de calor de 45 °C em {city}: a rede cortou carga, os chillers desistiram e o gerador do {dc} também.", "failures.a_b_is_down_same_cable":"{a}–{b} caiu. Mesmo cabo, âncora nova. A equipe de reparo criou um cartão fidelidade.", "failures.a_backhoe_cut_the_metro_ring":"Uma retroescavadeira cortou o anel metropolitano entre seus dois sites em {city}. Pelo visto, as duas rotas de fibra passavam pela mesma rua.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index cfb4e36..8ea9a36 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -123,7 +123,7 @@ const API_CMD={ quote:a=>{const A=a.a,B=a.b,tier=a.tier; if(!S.pops[A])return {blocked:[linkFromWhy(A)]}; if(!waveOk(A,B,tier))return {blocked:[tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:waveNeed(tier)})]}; - const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); + const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1); const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]}; const blocked=[],so=soldOut(A,B,tier,wr.cab); @@ -230,6 +230,13 @@ const API_CMD={ setChCount:{args:[['id','entityId'],['o','opticId'],['n','integer']],watch:['links.#id'], quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:opticCountCost(l,a.o,a.n)}:{};}, doc:'Set how many channels of one optic model a dark-fiber span carries, in one change. Added optics come from the spares shelf when you have them (regen cards still cost their share); removed ones go back to the shelf.'}, + xpBuild:{args:[['a','cityId'],['b','cityId'],['via','string'],['o','opticId']], + quote:a=>{const sp=xpParse(a.a,a.b,a.via);if(!sp||!OPT[a.o])return {setup:0,blocked:[tr('express.no_such_path')]};const old=xpFind(a.a,a.b,sp.map(s=>s.id)); + return {setup:xpCost(sp,a.o,!old),blocked:[xpWhy(a.a,a.b,sp,a.o)].filter(Boolean)};}, + doc:'Light an express lightpath from a to b straight through the ROADMs of the cities between: via is the ids of your ROADM dark fibers (land, own or IRU) in order from a, comma-separated, 2 to 6 of them. One optic, one channel slot on every fiber, ports only at a and b, and the light must reach the whole run between regen sites. The same path again adds a channel to that express. Give one up with rmLink.'}, + xpCh:{args:[['id','entityId'],['o','opticId'],['d','step']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id),sp=l&&l.kind==='xp'&&xpSpans(l);if(!sp||!OPT[a.o]||a.d<0)return {setup:0};return {setup:xpCost(sp,a.o,false),blocked:[xpWhy(l.a,l.b,sp,a.o)].filter(Boolean)};}, + doc:'Add (d:1) or unplug (d:-1) one channel of an optic on an express lightpath; unplugged optics go on the spares shelf. The last channel stays: rmLink gives the express up.'}, /* ---------- customers ---------- */ accept:{args:[['id','entityId']], doc:'Sign a pending offer. Rejected without a POP in every city it needs, without the IPv4 addresses it needs (rule ip4: see the bank\'s Address space), without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, @@ -574,6 +581,7 @@ const API_BOUND={ via:{command:'buildLink',arg:'cable'}, route:{command:'buildLink',arg:'route'}, dfMode:{command:'orderDf',note:'opens the dark-fiber modal',arg:'a/b'}, + xpOpen:{command:'xpBuild',note:'opens the link window on its Express tab: the ways your ROADM fibers chain from a to b (via, fiber ids comma-separated, puts that path first)',arg:'a/b/via'}, dfSrc:{command:'orderDf',arg:'source'}, dfSys:{command:'orderDf',arg:'system'}, seaDesign:{command:'orderCable',arg:'design'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index c3d1212..12d573e 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -20,7 +20,7 @@ const API_STATE_DOC={ auV:{type:'integer',doc:'Australia content level gate.'}, seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, - links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc) and express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics), each with an entity id.'}, transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, rs:{type:'map',doc:'Route-server sessions by exchange city.'}, diff --git a/src/game/10-catalog/40-ports.js b/src/game/10-catalog/40-ports.js index 8712607..a8cf7d0 100644 --- a/src/game/10-catalog/40-ports.js +++ b/src/game/10-catalog/40-ports.js @@ -15,7 +15,7 @@ const cachePortsAdd=(c,adds)=>cachePorts(c,adds)-cachePorts(c); in one port, but a 1.6T transponder shelf hands off to an 800G router as two 800G clients. */ const chPorts=(o,c,g)=>{const p=S.pops[c];return p&&OPT[o]?Math.max(1,Math.ceil(OPT[o].g/portG(g===undefined?(p.rgen||0):g)-1e-9)):1;}; function portsUsed(c,g){let u=0; - for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);} + for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'&&l.kind!=='xp'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);} // 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); @@ -33,5 +33,5 @@ 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,...(S.nni||[])].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(S.links.some(l=>(l.a===c||l.b===c)&&(l.kind==='df'||l.kind==='xp')&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this'); if(portsUsed(c,g)>portsMax(c,g))return tr('ports.you_use_u_ports_here_and',{u:fmtPorts(portsUsed(c,g)),r:p.routers||1,model:G.n,max:portsMax(c,g)});return '';} diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index d4f368f..4f0835e 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -69,9 +69,9 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1) let DFC=null; const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; const dfCap0=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; -const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); +const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):l.kind==='xp'?xpG(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); // A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); -const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; -const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; +const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; +const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index e6e4956..17cebc0 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -2,7 +2,7 @@ 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();}; -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; +const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='xp'?xpHopG(l):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)P.dist[e.city]!==undefined); lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`); diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index ce0dffb..3277d96 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -204,8 +204,9 @@ const OPS_RUN={ optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o); 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; + // New fiber gets its first channel; lit fiber gets more while it runs hot. A fiber that only carries expresses is + // not new: it was left bare so the city in the middle needs no router ports. + for(let step=0;step<8&&(cap<=0?!(l.ch||[]).length&&!xpSlots(l):load>=cap*at);step++){if(chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(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. Told to go big (#262), the intern // picks the most Gbps per channel it can afford for a new kind of optic, but never swaps what is already lit. diff --git a/src/game/60-features/96-pop-standard.js b/src/game/60-features/96-pop-standard.js index ae8aa3e..425caa5 100644 --- a/src/game/60-features/96-pop-standard.js +++ b/src/game/60-features/96-pop-standard.js @@ -182,7 +182,10 @@ function bstdOptJobs(l,sys,sp,V,take,ch){const rg=c=>V[c]?V[c].g:(S.pops[c].rgen // ex: fibers already going dark today (id → whether they carry traffic): they carry nothing for this one, and one whose // traffic leans on its parallel links keeps them lit. const bstdBusy=l=>((R.load&&R.load[l.id])||0)>Math.max(1,capOf(l)*0.1); -function bstdDarkOk(l,ex){const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; +// Express lightpaths (#58) ride the fiber's glass: its own load says nothing about them, and its parallel links do not +// carry them, so an express with any traffic at all keeps the fiber lit (the line system waits, as for a busy fiber). +const bstdXpBusy=l=>xpSlots(l)>0&&xpOver(l.id).some(x=>((R.load&&R.load[x.id])||0)>1e-6); +function bstdDarkOk(l,ex){if(bstdXpBusy(l))return false;const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; return P.filter(x=>!linkDown(x)&&!x.standby&&!(ex&&ex.has(x.id))).reduce((a,x)=>a+Math.max(0,capOf(x)-((R.load&&R.load[x.id])||0)),0)>=((R.load&&R.load[l.id])||0);} // Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took. // one: at most one fiber goes dark (the intern's shift); max: at most that many jobs tried, done or failed, so a shift's diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 4829518..1a4cf12 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -140,11 +140,12 @@ function compute(){RW.gen++; const fastSP={},divMemo={},cityIds=ni=>ni.map(i=>CITIES[i].id); // disjointRoutes() over today's live links, on city indices: the links are listed per city once, not twice per customer. const LA=[];for(const l of live){const ai=CIDX[l.a],bi=CIDX[l.b];(LA[ai]||(LA[ai]=[])).push([bi,l]);(LA[bi]||(LA[bi]=[])).push([ai,l]);} - const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); + // An express runs in the trenches of every fiber it rides: one backhoe in any of them takes it out. + const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id),hitR=(s,l)=>l.kind==='xp'?xpRisk(l).some(r=>s.has(r)):s.has(srlg(l)); const bfsI=(a,b,skip)=>{const prev=[],seen=new Uint8Array(NC),q=[a];seen[a]=1; - for(let h=0;h{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.map(srlg)));}; + const disjointI=(A,B)=>{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.flatMap(l=>l.kind==='xp'?xpRisk(l):[srlg(l)])));}; for(const k in edges){const e=edges[k];let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;e.pl=ld;} const l2Routes=(A,B,b)=>{const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B]; if(PX&&m==='fast')return pieFast(PX,fastSP,A,B,b,wLat); diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index b7dae0d..87d5139 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -2,7 +2,9 @@ // 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);} +// Cut, or cut off by an event between its two countries, whatever runs on it (an express asks this of each fiber it rides). +function linkCut(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))));} +function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0)||(l.kind==='xp'&&xpDown(l));} 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. diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index b18f5b9..ed6494c 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -21,8 +21,9 @@ function sanitize(s){ 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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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;}); + s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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!=='xp')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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); + xpSanitize(s); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */ {const pm=s.pairMet,lo={};for(const l of s.links){if(l.metric!==undefined){const k=edgeKey(l),m=own(MET,l.metric)?l.metric:'normal';if(!lo[k]||MET[m].f{const ok=REQS[k].ok(o),lab=typeo function diversePaths(a,b){ const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c); return disjointRoutes(a,b,S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b)));} -function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); +function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?['fab:'+l.prov]:l.kind==='xp'?xpRisk(l):[l.trench||l.id]; const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);} const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}} if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;}; - const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));} + const p1=bfs(live);if(!p1)return false;const used=new Set(p1.flatMap(srlg));return !!bfs(live.filter(l=>!srlg(l).some(r=>used.has(r))));} // Check buildable geography, not today's POPs, capacity or outages. Parallel land // routes can use separate trenches; all segments of one cable share its risk. let diversityMap=null; @@ -75,7 +75,7 @@ function fiberOk(b,ids){const l=ids?ids.get(b.link):S.links.find(x=>x.id===b.lin function soldSlots(l,u){return u?u.sold.get(l.id)||0:S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);} // Spare capacity other carriers can rent on a dark fiber (#51): free channels for alien waves, and on your own build // a spare pair in the trench. Random offers and broker listings follow the same rules and the same prices. -const freeCh=(l,u)=>chMax(l)-(l.ch||[]).length-soldSlots(l,u),pairFree=(l,u)=>!!l.own&&(u?u.dfp.get(l.id)||0:S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length)<2&&!(u?u.pairs.has(l.id):S.biz.some(b=>(b.type==='pairs'||b.type==='capfib')&&b.link===l.id)); +const freeCh=(l,u)=>chMax(l)-(l.ch||[]).length-soldSlots(l,u)-xpSlots(l),pairFree=(l,u)=>!!l.own&&(u?u.dfp.get(l.id)||0:S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length)<2&&!(u?u.pairs.has(l.id):S.biz.some(b=>(b.type==='pairs'||b.type==='capfib')&&b.link===l.id)); const wwWhat=(l,n)=>trn('requirements.n_400g_alien_wave_on_your',n,{a:CITY[l.a].name,b:CITY[l.b].name}); function fiberOffer(t,l,nm,cut=1){ if(t==='wwave'){const slots=1+Math.floor(Math.random()*Math.min(4,freeCh(l))); diff --git a/src/game/80-simulation/65-express.js b/src/game/80-simulation/65-express.js new file mode 100644 index 0000000..d10ac7b --- /dev/null +++ b/src/game/80-simulation/65-express.js @@ -0,0 +1,87 @@ +/* Express lightpaths (#58): a wave from A to C over your own (or leased) dark fibers A–B, B–C… that passes B through its + ROADM as light, so B's routers never see it: no ports there, no hop, a little less latency. It is a link of its own + (kind 'xp') between A and C: via lists the fibers it rides in order from a, ch its optics. Every channel takes one + slot on each of those fibers, and the light has to make the whole run between regen sites in one go. */ +const XP_HOPS=6,XP_PASS=5000,XP_BUDGET=4000,XP_CH=64; +// The fibers an express can ride: dark fiber on land with a ROADMaster (your own build or an IRU). Subsea line +// systems end at the landing station, so a wave never runs through one into the land network. +const xpSpanOk=s=>!!s&&s.kind==='df'&&!s.sub&&isRdm(s.sys); +/* What the expresses take on each fiber, and the links by id, kept while S.links and every express's optics and path + are the same: the map, compute() and the free-channel checks ask often, and most networks have no express at all. */ +const XPX={L:null,n:-1,xs:[],m:null,ids:null}; +function xpIdx(){const L=S.links;let ok=XPX.L===L&&XPX.n===L.length; + if(ok)for(const x of XPX.xs)if((x[0].ch||[]).length!==x[1]||x[0].via!==x[2]){ok=false;break;} + if(!ok){const m=new Map(),xs=[];for(const l of L)if(l.kind==='xp'){const n=(l.ch||[]).length;xs.push([l,n,l.via]);for(const id of l.via||[])m.set(id,(m.get(id)||0)+n);} + XPX.L=L;XPX.n=L.length;XPX.xs=xs;XPX.m=m;XPX.ids=null;} + return XPX;} +function xpLink(id){const X=xpIdx();if(!X.ids){X.ids=new Map();for(const l of S.links)if(!X.ids.has(l.id))X.ids.set(l.id,l);}return X.ids.get(id);} +// Channel slots express channels take on fiber l. +function xpSlots(l){return xpIdx().m.get(l.id)||0;} +// The expresses riding fiber id, and a list of links with every express that rides one of them added. +const xpOver=id=>xpIdx().xs.filter(x=>(x[0].via||[]).includes(id)).map(x=>x[0]); +function xpWith(ls){const ids=new Set(ls.map(l=>l.id)),out=ls.slice();for(const [x] of xpIdx().xs)if(!ids.has(x.id)&&(x.via||[]).some(id=>ids.has(id))){out.push(x);ids.add(x.id);}return out;} +// The fibers of an express, in order (null when one is gone). +function xpSpans(l){const v=l.via;if(!Array.isArray(v)||!v.length)return null;const out=[];for(const id of v){const s=xpLink(id);if(!xpSpanOk(s))return null;out.push(s);}return out;} +// The cities a chain of fibers passes from a, end included; null when they do not chain or come back to a city. +function xpCities(a,sp){const cs=[a];let c=a;for(const s of sp){const n=s.a===c?s.b:s.b===c?s.a:null;if(!n||cs.includes(n))return null;cs.push(n);c=n;}return cs;} +// Free slots on a fiber for one more express channel: what its line system holds, less lit, sold and express channels. +const xpFree=s=>chMax(s)-(s.ch||[]).length-soldSlots(s)-xpSlots(s); +/* The longest stretch the light runs without being regenerated. Regen sites split each fiber into equal spans, as for + its own channels; through a city the light goes on, so the last span of one fiber and the first of the next add up. */ +function xpRunKm(sp){let cur=0,mx=0;for(const s of sp){const r=s.regen|0,p=s.km/(r+1);if(!r){cur+=s.km;continue;}cur+=p;if(cur>mx)mx=cur;if(p>mx)mx=p;cur=p;}return Math.ceil(Math.max(mx,cur));} +// What optic o carries over that run (0: out of reach), cached like every channel (optG). +const xpOptG=(o,run)=>OPT[o]?optG(o,{km:run}):0; +function xpG(l){const sp=xpSpans(l);if(!sp)return 0;const run=xpRunKm(sp);let g=0;for(const o of l.ch||[])g+=xpOptG(o,run);return g;} +// The fastest single channel, as a scenario's fast path asks of every hop. +function xpHopG(l){const sp=xpSpans(l);if(!sp)return 0;const run=xpRunKm(sp);return Math.max(0,...(l.ch||[]).map(o=>xpOptG(o,run)));} +// Dark when a fiber under it is cut, still being built or has its line system down, or nothing lit reaches. +function xpDown(l){const sp=xpSpans(l);if(!sp)return true;const d=S.day;for(const s of sp)if(linkCut(s)||s.ready>d||s.eqDown>d)return true;return xpG(l)<=0;} +// The cities an express passes without touching a router, for its labels. +function xpVia(l){const sp=xpSpans(l),cs=sp&&xpCities(l.a,sp);return cs?cs.slice(1,-1).map(c=>CITY[c].name).join(', '):'';} +// A fiber that carries only expresses is dark as a link of its own, but there is light in it: a backhoe or a monkey +// that cuts fibers still finds it. Fibers only: linkDown() of an express asks xpDown(), never this. +const xpBare=l=>l.kind==='df'&&!l.sub&&xpSlots(l)>0&&linkDown(l)&&!linkCut(l)&&!(l.ready>S.day)&&!(l.eqDown>S.day); +// The light runs the whole way in glass: the fibers' own latency added up, and no router in between. +function xpLat(l){const sp=xpSpans(l);return sp?sp.reduce((a,s)=>a+linkLat(s),0):l.km*1.1/200;} +// What one backhoe can take out: every trench the express runs in (diverse paths and redundancy checks). +function xpRisk(l){const sp=xpSpans(l);return sp?sp.map(s=>s.trench||s.id):[l.id];} +// The furthest any optic reaches at its slowest setting: a longer run is never worth listing. +let XP_REACH=0;const xpReachMax=()=>XP_REACH||(XP_REACH=Math.max(...Object.values(OPT).map(O=>O.modes.at(-1)[1]))); +/* Ways to chain ROADM fibers from city a: to b (every path, shortest first, k of them) or, with b null, the shortest + path to each city two or more fibers away. first: the path starts on that fiber. The search is bounded: a few dozen + fibers is a big optical network, and XP_HOPS and XP_BUDGET keep it small on the biggest. */ +function xpPaths(a,b,first,k=3){const adj=new Map();for(const s of S.links)if(xpSpanOk(s))for(const c of [s.a,s.b]){let L=adj.get(c);if(!L)adj.set(c,L=[]);L.push(s);} + if(!adj.has(a))return [];for(const L of adj.values())L.sort((x,y)=>x.km-y.km); + const out=[],best=new Map(),seen=new Set([a]),path=[];let budget=XP_BUDGET; + const go=(c,km)=>{for(const s of adj.get(c)||[]){if(--budget<0)return;if(!path.length&&first&&s!==first)continue;const n=s.a===c?s.b:s.a;if(seen.has(n))continue; + const d=km+s.km;path.push(s);seen.add(n); + if(path.length>=2){if(b==null){const o=best.get(n);if(!o||dx.km-y.km||x.sp.length-y.sp.length).slice(0,k);} +// The express already lit on this path, either way round. +function xpFind(a,b,ids){const k=ids.join(','),r=ids.slice().reverse().join(',');return xpIdx().xs.map(x=>x[0]).find(x=>(x.a===a&&x.b===b&&(x.via||[]).join(',')===k)||(x.a===b&&x.b===a&&(x.via||[]).join(',')===r))||null;} +// A typed order's path: fiber ids, comma-separated, chaining from a to b (null when it does not). +function xpParse(a,b,via){if(!isCity(a)||!isCity(b)||a===b||!S.pops[a]||!S.pops[b]||typeof via!=='string')return null;const ids=via.split(','); + if(ids.length<2||ids.length>XP_HOPS||new Set(ids).size!==ids.length)return null;const sp=ids.map(id=>S.links.find(x=>x.id===id)); + if(!sp.every(xpSpanOk))return null;const cs=xpCities(a,sp);return cs&&cs[cs.length-1]===b?sp:null;} +// Why one more channel of optic o cannot run from a to b over these fibers ('' when it can). +function xpWhy(a,b,sp,o){const O=OPT[o];if(!O)return '';if(!techOk('opt',o,O.lvl))return tr('action_helpers.unlocks_at_customer_level_n',{n:O.lvl}); + const run=xpRunKm(sp);if(!xpOptG(o,run))return tr('express.too_far',{run:run.toLocaleString(),max:O.modes.at(-1)[1].toLocaleString()}); + for(const s of sp)if(xpFree(s)<1)return tr('express.fiber_full',{a:CITY[s.a].name,b:CITY[s.b].name,max:chMax(s)}); + for(const c of [a,b]){const p=S.pops[c];if(!p)return linkFromWhy(c);if(RG[p.rgen||0].clsa+(s.regen|0),0);return Math.round(optCost(o)*(spareN(o)>0?r:1+r))+(fresh?XP_PASS*(sp.length-1):0);} +// Taking a regen site off fiber l (to n sites) must leave every express on it in reach. +function xpRegenBad(l,n){return xpOver(l.id).some(x=>{const sp=xpSpans(x);if(!sp)return false;const run=xpRunKm(sp.map(s=>s===l?{km:s.km,regen:n}:s));return (x.ch||[]).some(o=>!xpOptG(o,run));});} +/* Saves: an express must ride fibers that are still there, chain from a to b and carry real optics; anything else is + dropped and its optics go back on the shelf. km is worked out again from the fibers. */ +function xpSanitize(s){const ids=new Map();for(const l of s.links)if(!ids.has(l.id))ids.set(l.id,l);const drop=new Set(); + for(const l of s.links){if(l.kind!=='xp')continue;const via=Array.isArray(l.via)?l.via.map(String):[],sp=via.map(id=>ids.get(id)),ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)).slice(0,XP_CH):[]; + let ok=via.length>=2&&via.length<=XP_HOPS&&new Set(via).size===via.length&&sp.every(xpSpanOk)&&ch.length>0; + if(ok){const cs=xpCities(l.a,sp);ok=!!cs&&cs[cs.length-1]===l.b;} + if(!ok){drop.add(l);if(ch.length){if(!s.spares||typeof s.spares!=='object'||Array.isArray(s.spares))s.spares={};for(const o of ch)s.spares[o]=(Math.floor(+s.spares[o])||0)+1;}continue;} + for(const k of ['cable','trench','seat','own','list','regen','sys','ready','eqDown','chFail','pairs','tier','premium','border','mult','prov','vt','spares','sub'])delete l[k]; + l.via=via;l.ch=ch;l.km=Math.max(1,Math.round(sp.reduce((a,x)=>a+num(x.km,0),0)));l.mo=0;} + if(drop.size)s.links=s.links.filter(l=>!drop.has(l));} diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index 72c8f0f..f48a5fd 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -30,7 +30,7 @@ const LAND_X=45,landX=(a,b)=>!isSub(a,b)&&CITY[a].reg!==CITY[b].reg&&CITY[a].cc! function landMult(a,b){if(isSub(a,b))return 1;if(uaePair(a,b))return 3;return (landX(a,b)?LAND_X:1)*(andesPair(a,b)?2:1)*(nullPair(a,b)?NULLARBOR:1)*(rainPair(a,b)?2:1)*(borderPair(a,b)?2:1);} function landWhy(a,b){if(isSub(a,b))return '';if(uaePair(a,b))return tr('geography_and_latency.inside_the_uae_only_the_two'); const r=[];if(landX(a,b))r.push(tr('geography_and_latency.overland_between_continents_crosses',{x:LAND_X}));if(andesPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_andes_2'));if(nullPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_nullarbor_x',{x:NULLARBOR}));if(borderPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_a_border_in'));if(rainPair(a,b))r.push(tr('geography_and_latency.this_route_goes_into_the_amazon'));return r.join(' ');} -function linkLat(l){const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} +function linkLat(l){if(l.kind==='xp')return xpLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} /* Wave prices differ a lot by market (TeleGeography): Europe's dense, competitive metro and long-haul routes are cheap (Frankfurt–London 100G ≈ $1,150/mo), the US costs more, and routes into Africa are several times dearer (Africa–Europe ≈ 5.9× London–New York). diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 9266616..b4e3650 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -4,15 +4,18 @@ const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair( const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason(); 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)]);} + const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; + // A fiber that only carries expresses is dark as a link of its own, but there is light in it: a backhoe still finds it. + const bare=S.links.filter(xpBare),dug=live.concat(bare); + if(dug.length){opts.push(['cut',2+Math.min(6,dug.length/2)]);} if(Object.keys(S.pops).length)opts.push(['crash',3],['power',2]); if(Object.values(S.pops).some(p=>p.site2))opts.push(['ring',1.2]); 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(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]); + // Amp huts and ROADMs carry every channel in the glass, the expresses' too; an optic of its own needs a channel of its own. + const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l)),amps=lit.concat(bare);if(amps.length)opts.push(['amp',1.5+amps.length*0.3]);if(lit.length)opts.push(['optic',1.5+lit.length*0.3]); // Two vendors' idea of the same protocol: the higher the backbone runs, the more often they disagree. const iop=coreIopRisk()?coreIopLinks(live):[];if(iop.length)opts.push(['interop',3*coreIopRisk()]); opts.push(['funny',4]); @@ -20,7 +23,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(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(amps.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; @@ -75,7 +78,7 @@ function fireFailure(only){ }else if(type==='rpki'){ S.ev.rpki={until:S.day+3,nets:NETS.map(n=>n.id).filter(()=>Math.random()<0.5)};addInc({type,ref:'rpki',until:S.day+3,msg:tr('failures.your_roa_expired_over_the_weekend'),cost:1000,fix:tr('failures.renew_the_roa')}); }else if(type==='amp'||type==='roadmff'){ - const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,dur=type==='roadmff'?1:(l.spares?1:2+Math.floor(Math.random()*3));l.eqDown=S.day+dur; + if(!amps.length)return;const l=pick(amps),A=CITY[l.a].name,B=CITY[l.b].name,dur=type==='roadmff'?1:(l.spares?1:2+Math.floor(Math.random()*3));l.eqDown=S.day+dur; const msg=type==='roadmff'?tr('failures.you_fat_fingered_the_channel_plan',{a:A,b:B}):pick([tr('failures.an_in_line_amplifier_hut_between',{a:A,b:B}),tr('failures.someone_stole_the_copper_grounding',{a:A,b:B}),tr('failures.a_firmware_bug_in_the_sys',{sys:DF_SYS[l.sys].n,a:A}),tr('failures.lightning_hit_an_amp_site_on',{a:A,b:B})]); addInc({type,ref:l.id,until:l.eqDown,msg:msg+(type==='amp'&&l.spares?' '+tr('failures.your_spares_kit_gets_it_back'):''),cost:type==='amp'&&!l.spares?AMP_COST:0,fix:tr('failures.truck_a_spare_amp_out')}); }else if(type==='optic'){ @@ -83,7 +86,7 @@ function fireFailure(only){ 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=cal(S.day).m,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))*(wetCut(l)?2:1),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 pool=only&&scnRule('anchors')?dug.filter(anchorProne):dug;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))*(wetCut(l)?2:1),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=wetCut(l)?N_('failures.the_wet_season_washed_out_the'):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); diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 513979b..668478e 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -22,7 +22,7 @@ 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(!M.on){if(dl.kind!=='vxc'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(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); @@ -30,7 +30,7 @@ function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint( 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; +function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(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; diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index d683de8..19aa159 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -5,7 +5,7 @@ Object.assign(ACT,{ toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();}, unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();}, accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o);toast(tr('ip4.no_space',{name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))}),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');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)x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(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, // instead of a new customer for every few waves (a big fiber business otherwise fills the save with tiny contracts). diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index 9848304..cf98a50 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -3,7 +3,7 @@ Object.assign(ACT,{ decomOpen:({city})=>{UI.decom=new Set(city&&S.pops[city]?[city]:[]);decomModal();}, 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');} + rmLink:({id})=>{{const n=xpOver(id).length;if(n){toast(trn('express.fiber_busy',n),'bad');sfx('err');UI.confirm=null;renderPanel();return;}}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');} const n=chBack(l?[l]:[]);if(n)toast(trn('links.n_optic_back_on_the_spares_shelf',n),'good');}S.links=S.links.filter(l=>l.id!==id);prunePairMet();UI.sel=null;UI.confirm=null;after();}, // The chaos monkey takes a banana and goes home early (no bonus). mkBanana:()=>{if(!mkOn())return;if(!spend(mkBananaCost()))return;S.stats.bananas=(S.stats.bananas||0)+1;mkLeave('banana');track('monkey_banana');after();}, @@ -14,7 +14,7 @@ Object.assign(ACT,{ myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name; S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();}, - buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); + buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return; if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;} const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;} diff --git a/src/game/90-actions/87-express.js b/src/game/90-actions/87-express.js new file mode 100644 index 0000000..2ab83e9 --- /dev/null +++ b/src/game/90-actions/87-express.js @@ -0,0 +1,22 @@ +// Express lightpaths (#58, 65-express.js): light a wave from a to b over a chain of your ROADM fibers, or one more +// channel on it; giving one up is rmLink, like any link. Every check is made here: tools and the NOC window send raw args. +Object.assign(ACT,{ + // The link window on its Express tab, from a fiber's panel or the tab itself. via: the path a fiber's panel offered, + // listed first even when shorter ones exist (the window checks it with xpParse). + xpOpen:({a,b,via})=>{if(!isCity(a)||!isCity(b)||a===b||!S.pops[a])return;UI.lmode='xp';UI.xpPath=typeof via==='string'?via.slice(0,400):null;openLinkModal(a,b);}, + // via: the fibers' ids in order from a, comma-separated. The same path again adds a channel to the express already there. + xpBuild:({a,b,via,o})=>{const sp=xpParse(a,b,via);if(!sp||!OPT[o]){toast(tr('express.no_such_path'),'bad');sfx('err');return;} + const ids=sp.map(s=>s.id),old=xpFind(a,b,ids),why=xpWhy(a,b,sp,o);if(why){toast(tr('express.cannot',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + if(old&&(old.ch=old.ch||[]).length>=XP_CH)return;if(!portGate(a,chPorts(o,a))||!portGate(b,chPorts(o,b)))return;const spare=spareN(o)>0;if(!spend(xpCost(sp,o,!old)))return;if(spare)S.spares[o]--; + let l=old;if(l)l.ch.push(o);else{l={id:uid(),a,b,kind:'xp',via:ids,ch:[o],km:Math.round(sp.reduce((x,s)=>x+s.km,0)),mo:0,cut:0,day:S.day};S.links.push(l);} + closeModal();UI.sel={type:'link',id:l.id};UI.confirm=null; + toast(old?tr('express.one_more',{optic:OPT[o].n,a:CITY[l.a].name,b:CITY[l.b].name,n:l.ch.length}):tr('express.lit',{optic:OPT[o].n,a:CITY[a].name,b:CITY[b].name,via:esc(xpVia(l))}),'good');sfx('build');after();}, + // One channel more (d:1) or less (d:-1) on an express; an unplugged optic goes on the spares shelf. The last one stays: + // giving the express up is the link's own button. + xpCh:({id,o,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='xp'||!OPT[o]||(d!==1&&d!==-1))return;l.ch=l.ch||[];const mid=[(CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20]; + if(d<0){const i=l.ch.lastIndexOf(o);if(i<0)return;if(l.ch.length<2){toast(tr('express.last_channel'),'bad');sfx('err');return;} + l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater(mid[0],mid[1],tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();return;} + const sp=xpSpans(l);if(!sp||l.ch.length>=XP_CH)return;const why=xpWhy(l.a,l.b,sp,o);if(why){toast(tr('express.cannot',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + if(!portGate(l.a,chPorts(o,l.a))||!portGate(l.b,chPorts(o,l.b)))return;const spare=spareN(o)>0;if(!spend(xpCost(sp,o,false)))return;if(spare)S.spares[o]--; + l.ch.push(o);floater(mid[0],mid[1],`+${OPT[o].n}`,'#FF4F9A');after();}, +}); diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index 7eb2919..75b81db 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -18,19 +18,19 @@ Object.assign(ACT,{ const own=UI.dfSrc==='build'&&!sc,sys=DF_SYS[UI.dfSys]&&techOk('sys',UI.dfSys,DF_SYS[UI.dfSys].lvl)?UI.dfSys:'lite';if(glassLvl()<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};popStdApply(b);} - const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),id=uid(); + const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),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}; 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&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return; - if(d<0&&(l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;} + if(d<0&&((l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))||xpRegenBad(l,n))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;} if(d>0&&!spend(REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH)))return;l.regen=n;toast(d>0?tr('fiber_and_hardware.regen_site_n_is_up_optical',{n,a:CITY[l.a].name,b:CITY[l.b].name,km:spanKm(l).toLocaleString()}):tr('fiber_and_hardware.regen_site_removed'),'good');sfx('build');after();}, 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,chPorts(o,l.a))||!portGate(l.b,chPorts(o,l.b)))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();}, + rmCh:({id,o})=>{const l=S.links.find(x=>x.id===id);if(!l||!OPT[o]||l.kind==='xp')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]||!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);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)+xpSlots(l){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();}, // Your own subsea cable: book a second lay ship before laying starts; it lays from the other end (50-cable-ships.js). diff --git a/src/game/90-actions/88-optic-counts.js b/src/game/90-actions/88-optic-counts.js index 6215bd5..8a4db1c 100644 --- a/src/game/90-actions/88-optic-counts.js +++ b/src/game/90-actions/88-optic-counts.js @@ -12,7 +12,7 @@ Object.assign(ACT,{ 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); + const free=chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l); if(d>free){toast(tr('optic_counts.only_n_channels_free',{n:free}),'bad');sfx('err');return;} if(!portGate(l.a,d*chPorts(o,l.a))||!portGate(l.b,d*chPorts(o,l.b))||!spend(opticCountCost(l,o,n)))return; const sp=Math.min(d,spareN(o));if(sp)S.spares[o]-=sp; diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 735a4da..31b06aa 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -1,6 +1,6 @@ // Overland routes already dug between two cities, in the order they were built (#77). The first is the // main route; every other one was a diverse route and keeps that price when you add waves to it. -function landTrenches(a,b){const out=[];for(const l of pairLinks(a,b)){if(l.kind==='vxc'||l.cable||l.sub)continue;const k=l.trench||l.id;let t=out.find(x=>x.k===k);if(!t)out.push(t={k,n:0,caps:[]});t.n++;t.caps.push(capName(l));}return out;} +function landTrenches(a,b){const out=[];for(const l of pairLinks(a,b)){if(l.kind==='vxc'||l.kind==='xp'||l.cable||l.sub)continue;const k=l.trench||l.id;let t=out.find(x=>x.k===k);if(!t)out.push(t={k,n:0,caps:[]});t.n++;t.caps.push(capName(l));}return out;} // Which route a new wave joins: null = a new diverse route. 'same' is the old two-way choice (the main route). function routeJoin(a,b){const ts=landTrenches(a,b),r=UI.route||'';if(r==='same')return ts[0]||null;if(r.startsWith('t:'))return ts.find(t=>t.k===r.slice(2))||null;return null;} function pairLinks(a,b){return S.links.filter(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));} @@ -32,12 +32,12 @@ function optCost(o){return Math.round(OPT[o].cost*techMul(OPT[o].lvl)*hwMul('opt // 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?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.cash=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.cash(OPT[x].sys!=='roadm'||isRdm(l.sys))&&optMode(x,withSubUps(l))).map(x=>OPT[x].n);if(alt.length)return tr('action_helpers.upgrades_cannot_stretch_this_optic',{...v,optics:alt.join(', ')});} return tr('action_helpers.this_channel_reaches_max_km_on',v);}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)}); + if((l.ch||[]).length+soldSlots(l)+xpSlots(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

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

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

${tr('common.no_links_yet')}

`; for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l); - h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} h+=``; if(Object.keys(S.pops).length>1)h+=`

${tr('common.decommission')}

${tr('city_panel.shut_this_pop_down_its_links')}

${btn(tr('city_panel.decommission_city',{city:C.name}),'decomOpen',{city:c},'ghost sm')}${btn(tr('city_panel.decommission_several_pops'),'decomOpen',{},'ghost sm')}
`; } diff --git a/src/game/93-ui/60-decommission.js b/src/game/93-ui/60-decommission.js index d8df5df..6b3024a 100644 --- a/src/game/93-ui/60-decommission.js +++ b/src/game/93-ui/60-decommission.js @@ -1,7 +1,8 @@ /* Decommissioning POPs. Customers that touch a decommissioned city, or ride a removed link, are let go with an early-termination penalty of three months of their contract. */ const DECOM_MONTHS=3; -function decomImpact(cities){const set=new Set(cities),links=S.links.filter(l=>set.has(l.a)||set.has(l.b)),lids=new Set(links.map(l=>l.id)); +// An express riding a fiber that goes is decommissioned with it. +function decomImpact(cities){const set=new Set(cities),links=xpWith(S.links.filter(l=>set.has(l.a)||set.has(l.b))),lids=new Set(links.map(l=>l.id)); const biz=S.biz.filter(b=>bCities(b).some(c=>set.has(c))||(b.link&&lids.has(b.link))); const pen=b=>Math.max(2000,Math.round(b.fee?b.fee*0.5:b.bw*b.rate*DECOM_MONTHS)); return {links,biz,pen,fee:biz.reduce((a,b)=>a+pen(b),0),eye:cities.reduce((a,c)=>a+(R.cityEye[c]||0),0)};} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 249a97f..200de31 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -117,7 +117,7 @@ function dfPanel(l){ if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); 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&&l.sub?layPanel(l):l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash${!crewSteps(l)&&l.ready>S.day+1?`

${tr('link_panels.crews_can_halve_a_build_at_most')}

`:''}`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

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

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${shipNote(inc)}${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)}
+ 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)})}`:''}${xpSlots(l)?` · ${trn('express.n_carry_expresses',xpSlots(l))}`:''}${fmtG(load)} / ${fmtG(cap)}
${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); @@ -134,6 +134,7 @@ function dfPanel(l){ 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.seat?`

${tr('broker.seat_regen_note')}

`:''}${l.sub&&l.own&&!l.seat?`

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

`; + h+=xpDfSection(l); {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; @@ -146,6 +147,7 @@ function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} if(l.kind==='vxc')return vxcPanel(l); if(l.kind==='df')return dfPanel(l); + if(l.kind==='xp')return xpPanel(l); const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk); let h=`
${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; if(cut)h+=`

${tr('common.cut_2e50')}

${inc?esc(inc.msg):''} ${inc&&shipSea(inc)?'':tr('link_panels.back_in_n_days',{n:l.cut-S.day})}

${shipNote(inc)}${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; diff --git a/src/game/93-ui/72-express.js b/src/game/93-ui/72-express.js new file mode 100644 index 0000000..86633fd --- /dev/null +++ b/src/game/93-ui/72-express.js @@ -0,0 +1,48 @@ +/* Express lightpaths (#58): the panel of one, the section on a dark fiber's panel (what rides it, where it chains on) + and the Express tab of the link window (70-link-modal.js). The rules are in 80-simulation/65-express.js. */ +const xpSpanName=s=>`${CITY[s.a].name} ⇄ ${CITY[s.b].name}`; +// Why an express is dark today, fiber by fiber. +function xpDarkWhy(l){const sp=xpSpans(l);if(!sp)return [tr('express.dark_gone')];const d=S.day,out=[]; + for(const s of sp){const n=xpSpanName(s);if(linkCut(s))out.push(tr('express.dark_cut',{span:n}));else if(s.ready>d)out.push(trn('express.dark_building',s.ready-d,{span:n}));else if(s.eqDown>d)out.push(tr('express.dark_system',{span:n}));} + if(!out.length)out.push(tr('express.dark_reach'));return out;} +// One fiber of a path: whose it is, how long, the slots left for express channels. +const xpSpanMeta=s=>`${s.own?tr('common.own_dark_fiber'):tr('common.leased_iru')} · ${Math.round(s.km).toLocaleString()} km · ${tr('express.free_slots',{n:Math.max(0,xpFree(s)),max:chMax(s)})}`; +// An optic's settings over a run, as the fiber panel lists them. +const xpModes=(o,run)=>OPT[o].modes.map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')+` · ${xpOptG(o,run)?tr('express.runs_at',{g:fmtG(xpOptG(o,run))}):tr('express.out_of_reach')}`; +function xpPanel(l){const sp=xpSpans(l),load=R.load[l.id]||0,cap=capOf(l),u=cap?load/cap:0,down=linkDown(l),A=CITY[l.a].name,B=CITY[l.b].name,run=sp?xpRunKm(sp):0,ch=l.ch||[]; + let h=`
${tr('express.eyebrow',{km:Math.round(l.km).toLocaleString()})}

${A} ⇄ ${B}

`; + if(down)h+=`

${tr('common.dark_6bf5')}

${xpDarkWhy(l).map(t=>`

${t}

`).join('')}
`; + h+=`

${tr('common.capacity')}

${trn('express.n_channels',ch.length)}${fmtG(load)} / ${fmtG(cap)}
+
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${tr('express.optical_run')}${run.toLocaleString()} km
+

${tr('express.passes',{via:esc(xpVia(l))})}

`; + if(sp)h+=`

${tr('express.its_fibers')}

${sp.map(s=>`
${xpSpanName(s)} ${linkCut(s)?''+tr('common.cut')+'':''}
${xpSpanMeta(s)}
${btn(tr('common.open'),'selLink',{id:s.id},'ghost sm')}
`).join('')}

${tr('express.slot_note')}

`; + if(sp){h+=`

${tr('common.optics')}

`; + for(const k of Object.keys(OPT)){const O=OPT[k],n=ch.filter(x=>x===k).length;if(!n&&!techOk('opt',k,O.lvl))continue;const why=xpWhy(l.a,l.b,sp,k),c=xpCost(sp,k,false),spn=spareN(k); + h+=`
${O.n}
${xpModes(k,run)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${spn?` · ${trn('link_panels.n_spare_on_the_shelf',spn)}`:''}
${why?`
${esc(why)}
`:''}
${n&&ch.length>1?btn('−','xpCh',{id:l.id,o:k,d:-1},'ghost sm'):''}${btn(`+ ${spn?tr('link_panels.spare_price',{price:fmt$(c)}):fmt$(c)}`,'xpCh',{id:l.id,o:k,d:1},'sm',!!why||S.cash`;} + h+=`

${tr('link_panels.unplugged_optics_go_on_the_spares')}

`;} + h+=`${trafficSection(l)}${metricSection(l)}
${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):tr('express.tear_down'),'rmLink',{id:l.id},'ghost sm')}

${tr('express.tear_down_note')}

`; + return h;} +// Where an express can go from this fiber: through either end and on over your other ROADM fibers. +function xpTargets(l){const out=[];for(const [x,y] of [[l.a,l.b],[l.b,l.a]])for(const p of xpPaths(x,null,l,6))if(xpRunKm(p.sp)<=xpReachMax())out.push({from:x,...p}); + return out.sort((p,q)=>p.km-q.km).slice(0,6);} +// On a dark fiber's panel: the expresses riding it, and where one could go from here. +function xpDfSection(l){if(l.sub)return '';const on=xpOver(l.id),rdm=isRdm(l.sys),tg=rdm?xpTargets(l):[]; + // Without a ROADMaster the hint is only worth showing where another fiber of yours meets this one. + const near=!rdm&&S.links.some(x=>x!==l&&x.kind==='df'&&!x.sub&&[x.a,x.b].some(c=>c===l.a||c===l.b)); + if(!on.length&&!tg.length&&!near)return ''; + let h=`

${tr('express.title')}

${tr('express.lead')}

`; + if(!rdm)h+=`

${tr('express.needs_roadm')}

`; + if(on.length)h+=`

${tr('express.riding_here')}

`+on.map(x=>`
${CITY[x.a].name} ⇄ ${CITY[x.b].name} ${linkDown(x)?''+tr('common.dark')+'':''}
${capName(x)} · ${trn('express.n_channels',(x.ch||[]).length)} · ${tr('express.city_via',{via:esc(xpVia(x))})}
${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('')+`

${tr('express.riding_note')}

`; + if(tg.length)h+=`

${tr('express.express_to')}

`+tg.map(t=>{const cs=xpCities(t.from,t.sp);return `
${CITY[t.from].name} → ${CITY[t.to].name}
${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(t.km).toLocaleString()})}
${btn(tr('express.plan'),'xpOpen',{a:t.from,b:t.to,via:t.sp.map(s=>s.id).join(',')},'pink sm')}
`;}).join(''); + return h+`
`;} +// The link window's Express tab: the ways your fibers chain from a to b, shortest first, an optic per button. Optic +// names are long: they go above the reason, not in the narrow column a wave's '400G' fits in. +function xpModalBody(a,b,routes){let h=`

${tr('express.modal_lead',{a:CITY[a].name,b:CITY[b].name})}

`; + for(const r of routes){const sp=r.sp,ids=sp.map(s=>s.id),cs=xpCities(a,sp),run=xpRunKm(sp),old=xpFind(a,b,ids),lat=sp.reduce((x,s)=>x+linkLat(s),0); + h+=`

${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(r.km).toLocaleString()})}

+ ${sp.map(s=>`
${xpSpanName(s)} · ${xpSpanMeta(s)}
`).join('')} +
${tr('express.optical_run')}${run.toLocaleString()} km
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:lat.toFixed(1)})}
+ ${old?`

${trn('express.already',(old.ch||[]).length)}

`:''} +
${Object.keys(OPT).filter(k=>techOk('opt',k,OPT[k].lvl)).map(k=>{const O=OPT[k],why=xpWhy(a,b,sp,k),c=xpCost(sp,k,!old),g=xpOptG(k,run); + return ``;}).join('')}
`;} + return h+`

${tr('express.modal_note',{price:fmt$(XP_PASS)})}

`;} diff --git a/src/game/94-dashboard/50-lease-swaps.js b/src/game/94-dashboard/50-lease-swaps.js index eb74159..c5e56ab 100644 --- a/src/game/94-dashboard/50-lease-swaps.js +++ b/src/game/94-dashboard/50-lease-swaps.js @@ -6,11 +6,11 @@ function swapOptics(km,cap,sub,sys){for(let r=0;r<=(sub?0:REGEN_MAX);r++){const const leaseCap=ls=>ls.reduce((s,l)=>s+(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?(l.ch||[]).reduce((t,o)=>t+optG(o,l),0):LT[l.tier].g),0); const swapOpt=(k,up,omo,days,mo)=>{const save=mo-omo;return {k,up,omo,days,save,pay:save>0?Math.ceil(up/save):0};}; // Lighting leased capacity on a fiber you already have (#72 review): needs free channels, and optics cost money. -function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L);let b=null; +function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L)-xpSlots(L);let b=null; for(const o in OPT){const O=OPT[o];if(O.lvl>glassLvl()||(O.sys==='roadm'&&!isRdm(L.sys))||[L.a,L.b].some(c=>S.pops[c]&&RG[S.pops[c].rgen||0].cls{const [a,b]=k.split('|'),sub=isSub(a,b),mo=ls.reduce((s,l)=>s+(l.mo||0),0),cap=leaseCap(ls); const x={a,b,sub,ls,mo,cap,opts:[],own:pairLinks(a,b).find(l=>l.kind==='df'&&l.own&&l.ready<=S.day)};if(x.own){x.fit=litOn(x.own,cap);if(x.fit.fits)x.best=mo;return x;} // Waves and fabric circuits can also move onto a leased fiber pair: cheaper glass, but you buy the gear. diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js index a7b5c25..daf9830 100644 --- a/src/game/95-modals/70-link-modal.js +++ b/src/game/95-modals/70-link-modal.js @@ -1,14 +1,17 @@ function openLinkModal(a,b){ {const nt=noTalk(a,b);if(nt){openModal(`

${tr('common.not_happening')}

${tr(nt)}

`);return;}} if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`

${tr('link_modal.not_without_a_license')}

${tr('link_modal.building_into_mainland_china_needs_a',{city:CITY[cnCity(a)?a:b].name})}

`);return;} - let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'); + let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'); if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),jn=sib.length?routeJoin(a,b):null,ts=landTrenches(a,b),mult=(sib.length&&!(jn&&jn.k===(ts[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(border)route+=`

${tr('link_modal.cross_border_circuits_into_mainland')}

${a==='hkg'||b==='hkg'?`
${btn(tr('common.regular_crossing'),'cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn(tr('link_modal.premium_crossing_60_3_loss'),'cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}
`:`

${tr('link_modal.premium_crossings_are_only_sold_in')}

`}`; if(sib.length&&!(isSub(a,b)&&cablesFor(a,b).length)&&!(UI.via&&UI.via!=='land'&&cablesFor(a,b).some(c=>c.cid===UI.via))){route+=`

${trn('link_modal.you_already_have_n_link_here',sib.length,{list:sib.map(l=>capName(l)).join(', ')})}

${ts.length>1?ts.map((t,i)=>btn(`${i?tr('link_modal.diverse_route_n',{n:i}):tr('common.main_route')} ${esc(t.caps.join(', '))}${i?' · +40%':''}`,'route',{r:'t:'+t.k},jn&&jn.k===t.k?'pink':'ghost')).join('')+btn(tr('link_modal.new_diverse_route_40_survives_cuts'),'route',{r:'diverse'},!jn?'pink':'ghost'):btn(tr('link_modal.diverse_route_40_survives_cuts_alone'),'route',{r:'diverse'},!jn?'pink':'ghost')+btn(tr('link_modal.same_trench_cheaper_one_backhoe_cuts'),'route',{r:'same'},jn?'pink':'ghost')}
${ts.length>1?`

${tr('link_modal.waves_on_the_same_route_share')}

`:''}`;} - 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')}
`; + // Express (#58): only where your ROADM fibers already chain from a to b. The path a fiber's panel offered comes first. + const xp1=UI.xpPath?xpParse(a,b,UI.xpPath):null,xr0=xpPaths(a,b),xr=xp1&&!xr0.some(r=>r.sp.length===xp1.length&&r.sp.every((s,i)=>s===xp1[i]))?[{to:b,sp:xp1,km:xp1.reduce((x,s)=>x+s.km,0)},...xr0.slice(0,2)]:xr0; + const mode=UI.lmode==='df'?'df':UI.lmode==='xp'&&xr.length?'xp':'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')}${xr.length?btn(tr('express.tab'),'xpOpen',xp1?{a,b,via:UI.xpPath}:{a,b},mode==='xp'?'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(mode==='xp'){openModal(head+xpModalBody(a,b,xr));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)}

`; diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index b792d3b..b7f2a4c 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -14,6 +14,8 @@ function linkGeom(l,pl){const i=lineIdx(l,pl);const key=l.id+'|'+i+'|'+(l.cable| if(!pts&&l.kind==='df'&&l.own&&l.sub){const k=pairLinks(l.a,l.b).filter(x=>x.kind==='df'&&x.own&&x.sub).indexOf(l),c0=cablesFor(l.a,l.b).slice().sort((x,y)=>x.km-y.km)[0],cp=c0&&cablePair(c0.cid,l.a,l.b); if(cp)pts=besideLine(cp.pts,2+k*1.5); else{const g=bezGeom(l,k);pts=[];for(let j=0;j<=20;j++)pts.push(qpt(g,j/20));}} + // An express follows the fibers it rides, a little to one side, so it shows passing the cities on the way. + if(!pts&&l.kind==='xp')pts=xpGeom(l); if(!pts){const g=bezGeom(l);pts=[];for(let j=0;j<=20;j++)pts.push(qpt(g,j/20));} const cum=[0];let L=0;for(let j=1;j{let q=linkGeom(s).pts;if(s.a!==cs[i])q=q.slice().reverse();for(let j=pts.length?1:0;j1?besideLine(pts,4):null;} diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js index 32c636c..b0d354d 100644 --- a/src/game/96-map/55-link-look.js +++ b/src/game/96-map/55-link-look.js @@ -1,13 +1,13 @@ /* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in 58-webgl-links.js), so they cannot drift apart. */ // Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable, -// 7 a link being dragged out. -const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12]]; +// 7 a link being dragged out, 8 an express lightpath. +const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12],[14,5]]; // A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; - const 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); - return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), - col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:bld?3:idle?4:0, + const 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',xp=l.kind==='xp',bld=df&&l.ready>day,cut=!bld&&!xp&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length||xp&&linkDown(l),vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); + return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx||xp?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), + col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:xp?8:bld?3:idle?4:0, pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills // The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the // links and with the day's routing (R), not with the camera, so it is kept until one of those changes. diff --git a/src/i18n/en.js b/src/i18n/en.js index c580cf8..46cf379 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2019,6 +2019,46 @@ "exchanges.20_peering_sessions_n":"20+ peering sessions ({n})", "exchanges.pops_on_3_continents":"POPs on 3+ continents", "exchanges.serve_1_5_tbps_v":"serve 1.5 Tbps ({v})", +"express.already":{"one":"You already run an express on this path with {n} channel: this adds another.","other":"You already run an express on this path with {n} channels: this adds another."}, +"express.cannot":"Can't light {optic} on this express.
{why}", +"express.cap":"{cap} express", +"express.city_via":"express via {via}", +"express.dark_building":{"one":"{span} is still being built: {n} day left.","other":"{span} is still being built: {n} days left."}, +"express.dark_cut":"{span} is cut.", +"express.dark_gone":"One of the fibers under it is gone.", +"express.dark_reach":"None of its optics reach over this run.", +"express.dark_system":"{span} has its line system down.", +"express.express_to":"Express to…", +"express.eyebrow":"Express lightpath · {km} km", +"express.fiber_busy":{"one":"An express lightpath rides this fiber.
Tear it down first: open it from this fiber's Express section.","other":"{n} express lightpaths ride this fiber.
Tear them down first: open them from this fiber's Express section."}, +"express.fiber_full":"{a} ⇄ {b} has no free channel slot ({max} on its line system).", +"express.free_slots":"{n} of {max} slots free", +"express.its_fibers":"The fibers it rides", +"express.last_channel":"That is the express's last channel. To stop it, tear the express down.", +"express.lead":"Send a wave straight through the ROADM at the far end onto your next fiber: no router ports in the city between, less latency, one channel slot on every fiber it rides.", +"express.lit":"Express lit: {a} ⇄ {b}.
{optic} goes straight through {via}: no router there sees it.", +"express.modal_lead":"Light a wave from {a} to {b} through the ROADMs on the way: the cities between never see it on a router.", +"express.modal_note":"The first channel also pays {price} for every city it passes, to patch it through the ROADM there. Optics from the spares shelf are free; every regen site on the way needs a card.", +"express.n_carry_expresses":{"one":"{n} carries an express","other":"{n} carry expresses"}, +"express.n_channels":{"one":"{n} channel","other":"{n} channels"}, +"express.needs_roadm":"Every fiber an express rides needs a ROADMaster line system (upgrade it under Line system above).", +"express.no_such_path":"Those fibers no longer chain from one city to the other.", +"express.one_more":"Another {optic} on the {a} ⇄ {b} express: {n} channels now.", +"express.optical_run":"Longest run without a regen", +"express.out_of_reach":"out of reach", +"express.passes":"Passes {via} as light, through the ROADM: no router port there, no hop in a traceroute.", +"express.plan":"Plan", +"express.riding_here":"Riding this fiber", +"express.riding_note":"Tear these down before you give up the fiber. A cut or a line system swap here darkens them too.", +"express.runs_at":"runs at {g}", +"express.slot_note":"Each channel takes one slot on every one of these fibers. A cut, a build or a line system swap on any of them darkens the express.", +"express.tab":"Express", +"express.tear_down":"Tear down the express", +"express.tear_down_note":"Its optics go back on the spares shelf.", +"express.title":"Express lightpaths", +"express.too_far":"Too far: the light runs {run} km without a regen site and this optic reaches {max} km at its slowest. Add regen sites on the fibers.", +"express.trace_hop":"express lightpath, optically past {via}", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"A 45 °C heatwave in {city}: the grid shed load, the chillers gave up and so did the generator at {dc}.", "failures.a_b_is_down_same_cable":"{a}–{b} is down. Same cable, new anchor. The repair crew has started a loyalty card.", "failures.a_backhoe_cut_the_metro_ring":"A backhoe cut the metro ring between your two sites in {city}. Turns out both fiber routes ran down the same street.", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index c07d336..71e682c 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -157,6 +157,8 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .tierbtn .sz{font-family:var(--display);font-weight:800;font-size:22px;width:70px} .tierbtn .grow{flex:1} .tierbtn .pr{font-family:var(--display);font-weight:800;font-size:18px} +/* A name too long for .sz (an optic on the Express tab) goes on its own line above the reason. */ +.tierbtn .onm{display:block;font-family:var(--display);font-weight:800;font-size:17px;line-height:1.15;margin-bottom:2px}.tierbtn .onm~.meta{display:block} .gl dt{font-family:var(--display);font-weight:800;font-size:16px;margin-top:10px} .gl dd{margin:2px 0 0;color:var(--ink2);line-height:1.45;font-size:13px} .kbd{display:inline-block;border:2px solid var(--ink);border-radius:6px;padding:0 5px;font-weight:900;font-size:11px;background:var(--soft)} diff --git a/tests/express-fiber.test.js b/tests/express-fiber.test.js new file mode 100644 index 0000000..4847cf5 --- /dev/null +++ b/tests/express-fiber.test.js @@ -0,0 +1,398 @@ +// Express lightpaths (#58): a wave from Frankfurt to Paris over your own dark fibers Frankfurt–Brussels and +// Brussels–Paris that passes Brussels as light, through its ROADM. Routing sees a Frankfurt–Paris edge; Brussels' +// router never sees the traffic. Change Freeze, no random failures: nothing here depends on luck. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Three POPs on routers that take 400G optics, broadband in Paris, transit in Frankfurt, and two ROADM fibers +// (s1 Frankfurt–Brussels, s2 Brussels–Paris), finished and dark. df(a,b,extra) lays another one. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=8;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');closeModal();" + + "for(const c of ['bru','par'])ACT.buildPop({city:c});for(const c of ['fra','bru','par'])S.pops[c].rgen=1;ACT.launchBB({city:'par'});ACT.buyTransit({city:'fra',net:'cog',tier:2});" + + "window.df=(a,b,o={})=>{const id=uid();S.links.push(Object.assign({id,a,b,kind:'df',own:true,sys:'roadm',ch:[],km:kmBetween(a,b),sub:false,cable:null,mo:100,trench:id,cut:0,day:S.day,ready:S.day,spares:false,pairs:1},o));return id;};" + + "window.L=id=>S.links.find(l=>l.id===id);"; +const SPANS = "window.s1=df('fra','bru');window.s2=df('bru','par');compute();"; +const BUILD = "ACT.xpBuild({a:'fra',b:'par',via:s1+','+s2,o:'zr4'});window.x=(S.links.find(l=>l.kind==='xp')||{}).id;compute();"; +function game(t, extra = SPANS, opts = {}) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE + extra); + return h; +} +const xps = (ev) => ev("S.links.filter(l=>l.kind==='xp').length"); + +test('an express is a Frankfurt–Paris edge: traffic rides it, ports at both ends, and Brussels never sees it', (t) => { + const { ev, errors } = game(t); + assert.equal(ev("JSON.stringify(xpPaths('fra','par').map(p=>p.sp.map(s=>s.id)))"), ev('JSON.stringify([[s1,s2]])'), 'the two fibers chain'); + const ports = () => JSON.parse(ev("JSON.stringify(['fra','bru','par'].map(c=>portsUsed(c)))")); + const p0 = ports(), cash = ev('S.cash'); + ev(BUILD); + assert.equal(xps(ev), 1); + assert.deepEqual(JSON.parse(ev('JSON.stringify(L(x))')), { id: ev('x'), a: 'fra', b: 'par', kind: 'xp', via: [ev('s1'), ev('s2')], ch: ['zr4'], km: ev('L(s1).km+L(s2).km'), mo: 0, cut: 0, day: ev('S.day') }); + assert.equal(cash - ev('S.cash'), ev("optCost('zr4')+XP_PASS"), 'the optic, and patching it through Brussels'); + const p1 = ports(); + assert.equal(p1[0] - p0[0], ev("chPorts('zr4','fra')"), 'a port in Frankfurt'); + assert.equal(p1[2] - p0[2], ev("chPorts('zr4','par')"), 'a port in Paris'); + assert.equal(p1[1], p0[1], 'none in Brussels'); + assert.equal(ev('capOf(L(x))'), 400); + assert.ok(ev('R.load[x]') > 1, 'Paris reaches its transit over the express'); + assert.ok(!ev('R.nodeLoad.bru'), "Brussels' router carries nothing"); + assert.equal(ev('linkLat(L(x))'), ev('linkLat(L(s1))+linkLat(L(s2))'), 'the latency of the fibers it rides, with no router in between'); + // With channels of their own on both fibers there is a path through Brussels too: the express is one hop shorter. + ev("L(s1).ch=['zr4'];L(s2).ch=['zr4'];compute()"); + assert.ok(ev('R.load[x]') > 1); + assert.equal(ev('(R.load[s1]||0)+(R.load[s2]||0)'), 0, 'the hop through Brussels stays idle'); + assert.ok(!ev('R.nodeLoad.bru')); + // Without the express the same traffic goes through Brussels' router. + ev('L(x).standby=true;S.pairMet[edgeKey(L(x))]="backup";compute()'); + assert.ok(ev('R.nodeLoad.bru') > 1, 'the router in Brussels works when the light does not pass it'); + assert.deepEqual(errors, []); +}); + +test('a cut, a build or a line system swap on any fiber darkens the express; a fiber under one stays', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.equal(ev('linkDown(L(x))'), false); + ev('L(s2).cut=S.day+5;compute()'); + assert.equal(ev('linkDown(L(x))'), true, 'a cut fiber'); + assert.equal(ev('R.load[x]||0'), 0); + assert.match(ev("xpDarkWhy(L(x)).join(' ')"), /Brussels ⇄ Paris is cut/); + assert.equal(ev('(o=>o.dark&&!o.cut&&o.dash===8)(linkLook([L(x)],S.day))'), true, 'drawn dark, no backhoe of its own'); + ev('L(s2).cut=0;L(s2).ready=S.day+10;compute()'); + assert.equal(ev('linkDown(L(x))'), true, 'a fiber still being built'); + assert.match(ev("xpDarkWhy(L(x)).join(' ')"), /Brussels ⇄ Paris is still being built: 10 days left\./); + ev('L(s2).ready=S.day+1'); + assert.match(ev("xpDarkWhy(L(x)).join(' ')"), /still being built: 1 day left\./, 'one day, not one days'); + ev('L(s2).ready=S.day;compute()'); + assert.equal(ev('linkDown(L(x))'), false); + ev('ACT.upSys({id:s1})'); + assert.equal(ev("L(s1).sys"), 'cl'); + assert.equal(ev('linkDown(L(x))'), true, 'the line system swap takes the express down for the day'); + ev('S.day++;compute()'); + assert.equal(ev('linkDown(L(x))'), false, 'and it is back the next day, on the new line system'); + // A fiber under an express cannot be given up; the express can, and its optic goes on the shelf. + ev('ACT.rmLink({id:s1});ACT.rmLink({id:s1})'); + assert.ok(ev('!!L(s1)'), 'the fiber is still there'); + assert.match(ev('S.log[0].t'), /express lightpath rides this fiber/); + const sp = ev("spareN('zr4')"); + ev('ACT.rmLink({id:x});ACT.rmLink({id:x})'); + assert.equal(xps(ev), 0); + assert.equal(ev("spareN('zr4')"), sp + 1); + ev('ACT.rmLink({id:s1});ACT.rmLink({id:s1})'); + assert.ok(!ev('L(s1)'), 'then the fiber goes'); + assert.deepEqual(errors, []); +}); + +test('a backhoe or the chaos monkey still finds a fiber that only carries expresses, never the express itself', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.equal(ev('linkDown(L(s1))&&linkDown(L(s2))'), true, 'dark as links of their own: no channels of their own'); + assert.equal(ev('xpBare(L(s1))&&xpBare(L(s2))'), true); + ev("fireFailure('cut');compute()"); + assert.equal(ev("S.links.filter(l=>l.cut>S.day).map(l=>l.kind).join()"), 'df', 'one fiber cut, not the express'); + assert.equal(ev('linkDown(L(x))'), true); + assert.equal(ev("S.inc.filter(i=>i.type==='cut').length"), 1); + ev("for(const l of S.links)l.cut=0;S.inc=[];compute();mkSnip()"); + assert.equal(ev("S.links.filter(l=>l.cut>S.day).map(l=>l.kind).join()"), 'df', 'the monkey snips a fiber too'); + assert.deepEqual(errors, []); +}); + +test("the intern's decom order counts an express as a link between its cities, and never hands one back", (t) => { + const { ev, errors } = game(t); + ev(BUILD + "UI.pending={a:'fra',b:'par'};UI.route='diverse';ACT.buildLink({tier:1});compute()"); + ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.decom=true;S.ops.cap.decom=0;compute();opsDay(S.day)"); + assert.equal(ev("S.links.filter(l=>l.kind==='wave').length"), 1, 'kept as the spare: its trench is not one the express runs in'); + ev("S.ops.p.decom={keep:false};S.day++;compute();opsDay(S.day)"); + assert.equal(ev("S.links.map(l=>l.kind).join()"), 'df,df,xp', 'the express carries the pair with room to spare: the wave goes back'); + assert.deepEqual(errors, []); +}); + +test('decommissioning the city in the middle takes its fibers and the expresses riding them', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.equal(ev("decomImpact(['bru']).links.length"), 3, 'both fibers and the express'); + const sp = ev("spareN('zr4')"); + ev("decommission(['bru']);compute()"); + assert.equal(ev('S.links.length'), 0); + assert.equal(ev("spareN('zr4')"), sp + 1, 'the express optic is on the shelf'); + assert.deepEqual(errors, []); +}); + +test('reach: the light must make the whole run between regen sites, through Brussels too', (t) => { + const { ev, errors } = game(t, "window.s1=df('fra','bru',{km:2000});window.s2=df('bru','par',{km:2000});compute();"); + assert.equal(ev('xpRunKm([L(s1),L(s2)])'), 4000, 'no regen anywhere: one 4,000 km run'); + assert.match(ev("xpWhy('fra','par',[L(s1),L(s2)],'zr4')"), /Too far: the light runs 4,000 km/); + ev(BUILD); + assert.equal(xps(ev), 0, 'refused'); + ev('ACT.regen({id:s1,d:1})'); + assert.equal(ev('xpRunKm([L(s1),L(s2)])'), 3000, 'the last 1,000 km of the first fiber and all of the second'); + const cash = ev('S.cash'); + ev(BUILD); + assert.equal(xps(ev), 1); + assert.equal(cash - ev('S.cash'), ev("Math.round(optCost('zr4')*1.5)+XP_PASS"), 'a regen card at the one regen site'); + assert.equal(ev('capOf(L(x))'), 200, 'a 400ZR+ at 3,000 km runs its slow setting'); + ev('ACT.regen({id:s1,d:-1})'); + assert.equal(ev('L(s1).regen'), 1, 'the express needs that regen site: it stays'); + ev('L(s1).regen=2;L(s2).regen=2;compute()'); + assert.equal(ev('xpRunKm([L(s1),L(s2)])'), 1334); + assert.equal(ev('capOf(L(x))'), 400, 'short runs everywhere: full rate'); + assert.deepEqual(errors, []); +}); + +test('slots: lit channels, sold alien waves and express channels share every line system', (t) => { + const { ev, errors } = game(t); + ev("L(s1).ch=Array(10).fill('zr4');S.biz.push({id:uid(),city:'fra',city2:'bru',link:s1,slots:53,type:'wwave',name:'Alien Co',bw:1,rate:1000,reqs:[],mood:100,since:S.day});for(const c of ['fra','bru','par'])S.pops[c].routers=4;compute()"); + assert.equal(ev('freeCh(L(s1))'), 1); + ev(BUILD); + assert.equal(xps(ev), 1); + assert.equal(ev('xpSlots(L(s1))'), 1); + assert.equal(ev('xpSlots(L(s2))'), 1); + assert.equal(ev('freeCh(L(s1))'), 0, 'the sold waves and the express take the last slots'); + assert.equal(ev('freeCh(L(s2))'), 63); + assert.match(ev("chWhy(L(s1),'zr4')"), /is full/, 'no more channels of its own either'); + assert.match(ev("xpWhy('fra','par',[L(s1),L(s2)],'zr4')"), /Frankfurt ⇄ Brussels has no free channel slot/); + ev("ACT.xpCh({id:x,o:'zr4',d:1})"); + assert.equal(ev('L(x).ch.length'), 1, 'refused'); + // A full pair lets you light the next one, and the express grows into it. + ev('ACT.addPair({id:s1})'); + assert.equal(ev('L(s1).pairs'), 2); + ev("ACT.xpCh({id:x,o:'zr4',d:1})"); + assert.equal(ev('L(x).ch.length'), 2); + assert.equal(ev('xpSlots(L(s2))'), 2); + assert.equal(ev('capOf(L(x))'), 800); + // The intern lights optics on hot fibers: never into the slots expresses and alien waves hold. + ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();S.ops.on.optics=true;S.ops.cap.optics=0;compute();for(const l of S.links)if(l.kind==='df')R.load[l.id]=1e6;opsDay(S.day)"); + assert.equal(ev("S.links.filter(l=>l.kind==='df').every(l=>(l.ch||[]).length+soldSlots(l)+xpSlots(l)<=chMax(l))"), true); + assert.ok(ev('L(s1).ch.length') > 10, 'the intern did light the hot fiber with room'); + assert.equal(ev('L(s2).ch.length'), 0, 'a fiber that only carries the express is not new fiber: it stays bare'); + // Unplugging: never the last channel. + ev("ACT.xpCh({id:x,o:'zr4',d:-1})"); + assert.equal(ev('L(x).ch.length'), 1); + ev("ACT.xpCh({id:x,o:'zr4',d:-1})"); + assert.equal(ev('L(x).ch.length'), 1, 'the last channel stays'); + ev("ACT.rmCh({id:x,o:'zr4'})"); + assert.equal(ev('L(x).ch.length'), 1, "a fiber's unplug button does not work on an express"); + assert.deepEqual(errors, []); +}); + +test('saves: an express survives a round trip; one whose fibers are gone is dropped and its optics go on the shelf', (t) => { + const { ev, errors } = game(t); + // A save from before expresses existed loads as it always did. + const old = ev('JSON.stringify(S)'); + ev(`S=migrate(JSON.parse(${JSON.stringify(old)}));compute()`); + assert.equal(ev('S.links.length'), 2); + assert.equal(ev('freeCh(L(s1))'), 64); + ev(BUILD); + ev('S=sanitize(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev("L(x).kind"), 'xp', 'still an express, not a wave'); + assert.equal(ev("L(x).via.join(',')"), ev("s1+','+s2")); + assert.ok(ev('R.load[x]') > 1); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(xps(ev), 1); + const sp = ev("spareN('zr4')"); + // Its second fiber gone (a hand-edited file): dropped, the optic back on the shelf. + ev('{const o=JSON.parse(JSON.stringify(S));o.links=o.links.filter(l=>l.id!==s2);S=sanitize(o);compute();}'); + assert.equal(xps(ev), 0); + assert.equal(ev("spareN('zr4')"), sp + 1); + // Fibers that do not chain from a, a fiber without a ROADM, no optic: all dropped. + for (const bad of ["x.via=[s2,s1]", "o.links.find(l=>l.id===s1).sys='lite'", "x.ch=['nope']", "x.via=[s1]", "x.b='ams'"]) { + ev(`{S=migrate(JSON.parse(${JSON.stringify(old)}));${BUILD}const o=JSON.parse(JSON.stringify(S)),x=o.links.find(l=>l.kind==='xp');${bad};S=sanitize(o);compute();}`); + assert.equal(xps(ev), 0, bad); + } + assert.deepEqual(errors, []); +}); + +test('the route worker routes an express as the page does; traceroute skips Brussels; diverse paths count its trenches', (t) => { + const h = game(t); + const { ev, errors } = h; + h.dom.window.structuredClone = globalThis.structuredClone; + ev(BUILD + "L(s1).ch=['zr4'];L(s2).ch=['zr4'];compute()"); + const SIG = "JSON.stringify({load:R.load,served:R.served,node:R.nodeLoad,ef:Object.keys(R.ef).sort().map(k=>[k,R.ef[k]])})"; + ev('window.__got=null;window.postMessage=(m)=>{window.__got=m;};'); + ev('{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}'); + ev('R=rwUnpack(structuredClone(__got.R),__got.ef)'); + const fromWorker = ev(SIG); + assert.ok(ev('R.load[x]') > 1, 'the worker routed over the express'); + ev('R=__R0;S=JSON.parse(__S0);compute()'); + assert.equal(ev(SIG), fromWorker); + const tr = ev("traceroute('par',{city:'fra'}).text"); + assert.match(tr, /express lightpath, optically past Brussels/); + assert.doesNotMatch(tr, /cr1\.bru\./, 'no hop in Brussels'); + // The express runs in the trenches of the fibers it rides: with them it is no second path. + assert.equal(ev("diversePaths('fra','par')"), false); + ev("S.biz.push({id:'div1',city:'fra',city2:'par',type:'ai',name:'Skynot Compute',bw:400,rate:10,reqs:['diverse'],mood:100,since:S.day});compute()"); + assert.equal(ev("R.div['div1']"), false, 'compute() agrees'); + ev("UI.pending={a:'fra',b:'par'};UI.route='diverse';ACT.buildLink({tier:1});compute()"); + assert.equal(ev("diversePaths('fra','par')"), true, 'a wave in a trench of its own is'); + assert.equal(ev("R.div['div1']"), true); + assert.deepEqual(errors, []); +}); + +test('on a phone: the fiber offers an express, the link window has an Express tab, the express has its panel, the map draws it', (t) => { + const h = load(); + t.after(() => h.dom.window.close()); + const { ev, errors } = h; + ev('window.innerWidth=360;window.innerHeight=740;' + BASE + SPANS); + assert.equal(ev('isPhone()'), true); + ev('selectLink(s1)'); + const panel = ev("$('panel').innerHTML"); + assert.match(panel, /Express lightpaths/); + assert.match(panel, /data-act="xpOpen"/); + ev("ACT.xpOpen({a:'fra',b:'par'})"); + const modal = ev("$('modal').innerHTML"), text = ev("$('modal').textContent"); + assert.match(modal, /data-act="xpBuild"/); + assert.match(text, /via Brussels · 581 km/); + // Optic names are long ('Sienna WaveMagic 1.6T'): never in the 70px column a wave's '400G' fits in. + assert.equal(ev(`[...$('modal').querySelectorAll('[data-act="xpBuild"]')].filter(b=>b.querySelector('.sz')||!b.querySelector('.grow .onm+.meta')).length`), 0); + assert.equal(ev(`$('modal').querySelector('[data-act="xpBuild"] .onm').textContent`), ev('OPT.zr4.n')); + assert.doesNotMatch(text, /express\.[a-z_]{3,}|undefined|NaN/); + // The other tabs are one tap away, and the Express tab only shows where fibers chain. + ev("ACT.dfMode({m:'wave'})"); + assert.match(ev("$('modal').innerHTML"), /data-act="xpOpen"/); + ev("closeModal();UI.lmode='xp';openLinkModal('fra','ams')"); + assert.doesNotMatch(ev("$('modal').innerHTML"), /data-act="xpOpen"|data-act="xpBuild"/); + ev('closeModal();' + BUILD + 'selectLink(s1)'); + assert.match(ev("$('panel').textContent"), /0 of 64 channels lit · 1 carries an express/, 'the slot the express takes, next to the lit ones'); + // Without a ROADMaster the hint points at the Line system section, which comes before it. + ev("L(s1).sys='lite';selectLink(s1)"); + const lp = ev("$('panel').innerHTML"), hint = lp.indexOf('upgrade it under Line system above'); + assert.ok(hint > 0 && lp.indexOf('

Line system

') < hint, 'the upgrade is above the hint'); + ev("L(s1).sys='roadm';selectLink(x)"); + const xp = ev("$('panel').textContent"); + assert.match(xp, /Express lightpath · 581 km/); + assert.match(xp, /Tear down the express/); + assert.doesNotMatch(xp, /express\.[a-z_]{3,}|undefined|NaN/); + assert.match(ev('capName(L(x))'), /400G express/); + // Drawn along its fibers, a little to one side: it passes Brussels without landing there. + const g = JSON.parse(ev("JSON.stringify(linkGeom(L(x)).pts)")), B = JSON.parse(ev("JSON.stringify([CITY.bru.x,CITY.bru.y])")); + const near = Math.min(...g.map(([x, y]) => Math.hypot(x - B[0], y - B[1]))); + assert.ok(near > 1 && near < 12, 'beside Brussels: ' + near); + ev('UI.started=true;UI.pitched=true;for(const z of [0.6,1.5,3]){cam.z=z;draw(performance.now());}'); + assert.deepEqual(errors, []); +}); + +test('in German, every express screen is translated', (t) => { + const h = load({ lang: 'de' }); + t.after(() => h.dom.window.close()); + const { ev, errors } = h; + ev('window.innerWidth=360;' + BASE + SPANS + BUILD + 'selectLink(s1)'); + assert.match(ev("$('panel').textContent"), /Express-Lightpaths/); + ev("ACT.xpOpen({a:'fra',b:'par'})"); + assert.doesNotMatch(ev("$('modal').textContent"), /express\.[a-z_]{3,}|undefined|NaN/); + ev('closeModal();selectLink(x)'); + assert.match(ev("$('panel').textContent"), /Express abbauen/); + assert.deepEqual(errors, []); +}); + +test('amp huts, ROADM slips and backhoes find fibers that only carry expresses, forced or at random', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + ev("fireFailure('amp');compute()"); + assert.equal(ev('[s1,s2].filter(id=>L(id).eqDown>S.day).length'), 1, 'an amp hut on one of the fibers goes'); + assert.equal(ev('linkDown(L(x))'), true, 'and the express with it'); + assert.equal(ev('S.inc.at(-1).type'), 'amp'); + assert.equal(ev('S.inc.at(-1).cost'), ev('AMP_COST'), 'no spares kit: a truck and a new amp'); + ev("for(const l of S.links)l.eqDown=0;S.inc=[];compute();fireFailure('roadmff');compute()"); + assert.equal(ev('[s1,s2].filter(id=>L(id).eqDown>S.day).length'), 1, 'a fat-fingered channel plan too'); + // The glass under the express is the only glass here: the dice still find it (seeded, so always the same draws). + ev(`window.__n={};for(let i=0;i<400;i++){for(const l of S.links){l.cut=0;l.eqDown=0;}for(const p of Object.values(S.pops)){p.down=0;p.rdown=0;}for(const x of S.transit)x.down=0;S.inc=[];compute(); + fireFailure();for(const c of S.inc)if([s1,s2].includes(c.ref))__n[c.type]=(__n[c.type]||0)+1;if(S.links.some(l=>l.kind==='xp'&&(l.cut>S.day||l.eqDown>S.day)))__n.xp=(__n.xp||0)+1;}`); + const n = JSON.parse(ev('JSON.stringify(__n)')); + assert.ok(n.cut > 0, 'a backhoe: ' + JSON.stringify(n)); + assert.ok(n.amp > 0, 'an amp hut: ' + JSON.stringify(n)); + assert.ok(!n.xp, 'never the express itself'); + assert.deepEqual(errors, []); +}); + +test('the chaos monkey counts fibers that only carry expresses when it decides whether to visit', (t) => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;window.s1=df('fra','bru');window.s2=df('bru','par');window.s3=df('bru','ams');compute();"); + ev(BUILD + "ACT.xpBuild({a:'fra',b:'ams',via:s1+','+s3,o:'zr4'});compute()"); + assert.equal(ev('xps=S.links.filter(l=>l.kind==="xp").length'), 2); + assert.equal(ev('[s1,s2,s3].every(id=>xpBare(L(id)))'), true); + ev("S.rules=makeRules('oncall');S.monkey={next:S.day};mkTick(S.day)"); + assert.equal(ev('!!S.monkey.on'), true, 'three fibers in the ground: enough network for a visit'); + assert.deepEqual(errors, []); +}); + +test("the intern's optics order leaves fibers that only carry expresses bare: no ports in the city they bypass", (t) => { + const { ev, errors } = game(t, SPANS + "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;window.s3=df('fra','ams');compute();"); + ev(BUILD); + const ports = () => JSON.parse(ev("JSON.stringify(['bru','par'].map(c=>portsUsed(c)))")); + const p0 = ports(); + ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.optics=true;S.ops.cap.optics=0;compute();opsDay(S.day)"); + assert.equal(ev('L(s1).ch.length+L(s2).ch.length'), 0, 'both fibers under the express stay bare'); + assert.deepEqual(ports(), p0, 'no router port in Brussels, none more in Paris'); + assert.ok(ev('L(s3).ch.length') > 0, 'new fiber with nothing on it still gets its first channel'); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(ev('L(s1).ch.length+L(s2).ch.length'), 0, 'and on the next shift'); + assert.deepEqual(errors, []); +}); + +test('an express is no link between its ends for a new wave: the first one pays the usual price and gets no route question', (t) => { + const wave = (extra) => { + const { ev, errors } = game(t, SPANS + extra, { agent: true }); + const quote = ev("API_CMD.buildLink.quote({a:'fra',b:'par',tier:1}).monthly"); + ev("UI.lmode='wave';openLinkModal('fra','par')"); + const modal = ev("$('modal').innerHTML"); + ev("UI.route='same';ACT.buildLink({tier:1});compute()"); + const w = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.kind==='wave'))")); + assert.deepEqual(errors, []); + return { quote, modal, mo: w.mo, mult: w.mult }; + }; + const plain = wave(''), xp = wave(BUILD); + assert.ok(plain.mo > 0); + assert.equal(xp.mo, plain.mo, 'the same monthly price as without the express'); + assert.equal(xp.mult, plain.mult); + assert.equal(xp.quote, plain.quote, 'and the same quote for tools'); + assert.doesNotMatch(xp.modal, /data-act="route"/, 'no same-trench or diverse choice: there is no wave here yet'); +}); + +test("a fiber's 'Express to…' opens the window on the path it offered, even with shorter ones elsewhere", (t) => { + // Frankfurt to Paris: via Bettembourg, via Brussels, via Düsseldorf and Brussels are all shorter than via Amsterdam. + const { ev, errors } = game(t, SPANS + "ACT.buildPop({city:'ams'});for(const c of ['bet','dus']){ACT.buildPop({city:c});S.pops[c].rgen=1;}S.pops.ams.rgen=1;" + + "df('fra','bet');df('bet','par');df('fra','dus');df('dus','bru');window.fa=df('fra','ams');df('ams','par');compute();"); + ev('selectLink(fa)'); + const plans = JSON.parse(ev(`JSON.stringify([...$('panel').querySelectorAll('[data-act="xpOpen"]')].map(b=>JSON.parse(b.dataset.args)))`)); + const offer = plans.find((p) => p.a === 'fra' && p.b === 'par'); + assert.ok(offer, 'the fiber offers Frankfurt → Paris: ' + JSON.stringify(plans)); + assert.equal(offer.via.split(',')[0], ev('fa'), 'starting on this fiber'); + assert.equal(ev(`xpPaths('fra','par').some(r=>r.sp[0].id===fa)`), false, 'not among the three shortest'); + ev(`ACT.xpOpen(${JSON.stringify(offer)})`); + const heads = () => JSON.parse(ev(`JSON.stringify([...$('modal').querySelectorAll('h4')].map(h=>h.textContent))`)); + assert.match(heads()[0], /^via Amsterdam · /, 'the offered path comes first: ' + heads().join(' | ')); + assert.ok(ev(`[...$('modal').querySelectorAll('[data-act="xpBuild"]')].some(b=>JSON.parse(b.dataset.args).via===${JSON.stringify(offer.via)}&&!b.disabled)`), 'and it can be lit from here'); + // Switching tabs and back keeps it; the Express tab of a fresh window shows the shortest three. + ev("ACT.dfMode({m:'wave'})"); + ev(`ACT.xpOpen(JSON.parse($('modal').querySelector('[data-act="xpOpen"]').dataset.args))`); + assert.match(heads()[0], /^via Amsterdam · /); + ev("closeModal();ACT.xpOpen({a:'fra',b:'par'})"); + assert.ok(!heads().some((h) => /Amsterdam/.test(h)), heads().join(' | ')); + ev(`ACT.xpBuild({a:'fra',b:'par',via:${JSON.stringify(offer.via)},o:'zr4'});compute()`); + assert.equal(ev("S.links.filter(l=>l.kind==='xp').map(l=>l.via[0]).join()"), ev('fa')); + assert.deepEqual(errors, []); +}); + +test('the build standard keeps a fiber lit while an express on it carries traffic, and swaps it once the express is idle', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.ok(ev('R.load[x]') > 1, 'Paris rides the express'); + assert.equal(ev('(R.load[s1]||0)+(R.load[s2]||0)'), 0, 'the fibers carry nothing of their own'); + ev("S.popStd=bstdPut(Object.assign(bstd(),{sys:'cl'}));compute()"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false).held)')).sort(), ['bru|par', 'fra|bru'], 'both fibers wait'); + ev('ACT.bstdApply()'); + assert.equal(ev("L(s1).sys+','+L(s2).sys"), 'roadm,roadm', 'no line system swap under a busy express'); + assert.equal(ev('xpDown(L(x))'), false, 'the express stays up'); + // Idle (Paris has no users left), the express no longer holds its fibers back. + ev('S.pops.par.bb=null;compute()'); + assert.equal(ev('R.load[x]||0'), 0); + ev('ACT.bstdApply()'); + assert.equal(ev("L(s1).sys+','+L(s2).sys"), 'cl,cl', 'both fibers move up to C+L'); + assert.deepEqual(errors, []); +}); + +test('in Spanish, every express label says exprés', () => { + const es = require('fs').readFileSync(require('path').join(__dirname, '..', 'site', 'i18n', 'es.js'), 'utf8'); + const lines = es.split('\n').filter((l) => l.startsWith('"express.')); + assert.ok(lines.length > 30); + assert.deepEqual(lines.filter((l) => /\bexpress\b/i.test(l.slice(l.indexOf(':')))), []); +}); diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 71230db..50bf647 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -223,7 +223,7 @@ test('a dry run prices every command that has a price, and changes nothing', () rmLink: { id: wave }, buyNni: { city: 'fra', prov: fab, tier: 0 }, lagNni: { city: 'fra', prov: fab, d: 1 }, buyVxc: { a: 'fra', b: 'ams', prov: fab, t: 0 }, upVxc: { id: wave, t: 1 }, orderDf: { a: 'fra', b: 'ams', source: 'lease', system: 'lite' }, orderCable: { a: 'lis', b: 'nyc' }, subUpgrade: { id: df, k: 'terminal' }, crews: { id: df }, addCh: { id: df, o: 'zr4' }, addPair: { id: df }, upSys: { id: df }, regen: { id: df, d: 1 }, buySpare: { o: 'zr4' }, sellSpare: { o: 'zr4' }, - setChCount: { id: df, o: 'zr4', n: 2 }, repayLoan: { id: 'none' }, buildScrub: { city: 'ams', tier: 1 }, scrubUp: { city: 'fra', tier: 1 }, + setChCount: { id: df, o: 'zr4', n: 2 }, xpBuild: { a: 'fra', b: 'par', via: df + ',' + df, o: 'zr4' }, xpCh: { id: df, o: 'zr4', d: 1 }, repayLoan: { id: 'none' }, buildScrub: { city: 'ams', tier: 1 }, scrubUp: { city: 'fra', tier: 1 }, fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key }, opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, From e1ae8e0164cbda1bbe662aacea51ddfc7e78189d Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:12:23 +0100 Subject: [PATCH 416/491] Satellite teleports: GEO and MEO circuits for islands and remote towns (#83) The early and mid-game satellite option, before Pie in the Sky. Build a teleport at a POP that a satellite sees, then rent capacity from it to a remote POP: GEO (Intelsplat, Kacophony) needs no capex but costs a lot a month per Gbps, 1-10 Gbps at about 600 ms; MEO (O3bservant) needs tracking antennas at the teleport and gives multi-Gbps at about 130 ms where both ends are under its ring, at least 5 degrees up. Coverage follows each bird's footprint by ocean region. Latency feeds the latency model: users who ride a satellite notice, in proportion to the share. A circuit beside a cable goes on standby, whichever came first, and carries only what the cable cannot: the classic single-cable island backup. Satellites are not subsea links for covenants, scenario goals or subsidies (Pitcairn's UK grant needs a cable). Express fiber and the build standard leave satellite circuits alone. --- .claude/skills/gameplay-rules/SKILL.md | 4 +- CHANGELOG.md | 1 + site/i18n/de.js | 70 +++ site/i18n/es.js | 70 +++ site/i18n/fr.js | 70 +++ site/i18n/it.js | 70 +++ site/i18n/pt.js | 70 +++ src/agent/10-domains.js | 2 + src/agent/20-commands.js | 19 +- src/agent/30-docs.js | 5 +- src/agent/40-read.js | 2 +- src/game/10-catalog/60-reach-and-subsea.js | 6 +- src/game/10-catalog/75-satellites.js | 61 +++ src/game/60-features/10-banks.js | 4 +- src/game/60-features/20-scenarios.js | 4 +- src/game/60-features/45-teleports.js | 73 +++ src/game/60-features/50-traceroute.js | 2 +- src/game/60-features/85-pitcairn.js | 11 +- src/game/60-features/95-standing-orders.js | 2 +- src/game/60-features/96-pop-standard.js | 2 +- src/game/60-features/99-pie-subsidies.js | 2 +- src/game/80-simulation/10-dijkstra.js | 2 +- src/game/80-simulation/30-compute.js | 21 +- src/game/80-simulation/40-billing.js | 2 +- src/game/80-simulation/50-sanitize.js | 3 +- .../80-simulation/80-geography-and-latency.js | 2 +- src/game/85-incidents/20-failures.js | 2 +- src/game/85-incidents/40-chaos-monkey.js | 4 +- src/game/88-days/10-day-tick.js | 2 +- src/game/90-actions/10-interface.js | 2 +- src/game/90-actions/60-links.js | 6 +- src/game/90-actions/86-specialist.js | 2 +- src/game/90-actions/87-fiber-and-hardware.js | 4 +- src/game/90-actions/87-teleports.js | 27 ++ src/game/93-ui/50-city-panel.js | 7 +- src/game/93-ui/70-link-panels.js | 1 + src/game/93-ui/72-teleport-panels.js | 60 +++ src/game/94-dashboard/50-lease-swaps.js | 2 +- src/game/94-dashboard/60-dashboard.js | 2 +- src/game/94-dashboard/70-bank.js | 2 +- src/game/95-modals/70-link-modal.js | 2 +- src/game/96-map/55-link-look.js | 4 +- src/i18n/en.js | 70 +++ tests/gameplay-rules.test.js | 6 +- tests/mcp-commands.test.js | 1 + tests/satellites.test.js | 445 ++++++++++++++++++ 46 files changed, 1176 insertions(+), 55 deletions(-) create mode 100644 src/game/10-catalog/75-satellites.js create mode 100644 src/game/60-features/45-teleports.js create mode 100644 src/game/90-actions/87-teleports.js create mode 100644 src/game/93-ui/72-teleport-panels.js create mode 100644 tests/satellites.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 6f149f4..619584b 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -24,7 +24,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | --- | --- | --- | | 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 1 or 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, or reach it through a pie dish; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. | +| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, reach it through a pie dish, or rent a satellite circuit from a teleport; 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. | @@ -33,7 +33,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | Id | Rule | Why | | --- | --- | --- | | N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. | -| N2 | Names are puns: no network, cable, exchange, data center, router, optic, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. | +| N2 | Names are puns: no network, cable, exchange, data center, router, optic, satellite or satellite operator, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. | | N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. | | N4 | No upstream cycles. | Cones must be trees, not loops. | | N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 639dbf4..af60927 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows - Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. - Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). - Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58) +- Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order. - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. - IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). diff --git a/site/i18n/de.js b/site/i18n/de.js index bccdbe8..8e8c786 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3927,6 +3927,7 @@ "pie_traffic.via_dishes":"hoch in {up}, runter in {down}", "pitcairn.uk_grant_mo":"Zuschuss aus UK {mo}/Monat", "pitcairn.uk_grant_mo_once_islanders":"Zuschuss aus UK {mo}/Monat, sobald die Inselbewohner online sind", +"pitcairn.uk_grant_needs_a_cable":"Zuschuss aus UK {mo}/Monat nur mit Kabel: gemietete Satellitenkapazität zählt nicht", "pitcairn.uk_sky_grant_mo":"Satelliten-Zuschuss aus UK {mo}/Monat (Glasfaser bekommt {full})", "pni_all.additional_per_month":"Zusätzliche Kosten pro Monat", "pni_all.all_at_port":"Mit allen Netzen peeren · {port}", @@ -4534,6 +4535,75 @@ "sales.w_last":"Letzte Woche: {name} {list}.", "sales.w_now":"Diese Woche: {name} {list}.", "sales.w_signed":{"one":"hat einen Kunden gewonnen ({rev}/Monat)","other":"hat {n} Kunden gewonnen ({rev}/Monat)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Ein Teleport ist ein Satelliten-Gateway: große Schüsseln an diesem POP, die Kapazität auf fremden Satelliten mieten, für kleine Inseln und abgelegene Orte, die kein Kabel erreicht, oder die an einem Kabel und einem Stoßgebet hängen.", +"satellites.add_tracking_antennas_cost_mo":"MEO-Nachführantennen {cost} + {mo}/Monat", +"satellites.being_commissioned":"Wird in Betrieb genommen", +"satellites.build_a_teleport_cost_mo":"Teleport bauen {cost} + {mo}/Monat", +"satellites.by_satellite":"Per Satellit", +"satellites.cancel_n_circuits_first":{"one":"Kündige zuerst seine Satellitenverbindung.","other":"Kündige zuerst seine {n} Satellitenverbindungen."}, +"satellites.choose":"Wählen", +"satellites.circuit_ordered":{"one":"{cap} auf {bird} bestellt. {a} ⇄ {b} wird ausgerichtet und getestet: läuft in {n} Tag.","other":"{cap} auf {bird} bestellt. {a} ⇄ {b} wird ausgerichtet und getestet: läuft in {n} Tagen."}, +"satellites.close_the_teleport":"Teleport schließen", +"satellites.costs_row":"Teleports und Satelliten", +"satellites.geo_dishes":"GEO-Schüsseln", +"satellites.geo_dishes_and_meo_tracking":"GEO-Schüsseln und MEO-Nachführantennen", +"satellites.geo_users_notice":"Aus 36.000 km Höhe dauert die Runde etwa 600 ms: Videocalls und Games ruckeln, und die Nutzer werten {p} des Service als schlecht.", +"satellites.grow_to":"Auf {cap} vergrößern", +"satellites.in_view_list":"In Sicht: {list}.", +"satellites.it_waits_on_standby":"Zwischen den beiden hast du schon einen Link: Der Satellit wartet im Standby und trägt Traffic nur, wenn dieser Link ausfällt.", +"satellites.its_blurb":"Klassische C- und Ku-Band-Strahlen, die einen ganzen Ozean abdecken. Zuverlässig, überall, und so bepreist.", +"satellites.kac_blurb":"Ka-Band-Spotbeams über dem Westpazifik: das billigste Gbps im Orbit, wenn deine Insel unter einem Beam liegt.", +"satellites.meo_comes_at_level":"Der MEO-Ring (etwa 130 ms hin und zurück) kommt auf Level {lv}.", +"satellites.meo_ring_misses_city":"Der MEO-Ring sieht {city} nicht: Er deckt {lat}° beiderseits des Äquators ab.", +"satellites.meo_users_notice":"Viel näher am Boden, etwa 130 ms hin und zurück: Die Nutzer merken kaum etwas ({p} des Service gilt als schlecht).", +"satellites.more_islands_and_towns":"Weitere Inseln und Orte in Sicht", +"satellites.ms_one_way_rtt":"{ms} ms pro Richtung, {rtt} ms hin und zurück", +"satellites.ms_round_trip":"{ms} ms hin und zurück", +"satellites.n_birds_see_both":{"one":"{n} Satellit sieht beide","other":"{n} Satelliten sehen beide"}, +"satellites.n_circuits_go_on_standby":{"one":"Deine Satellitenverbindung zwischen {a} und {b} geht neben dem neuen Link in Standby: Sie trägt Traffic nur, wenn dieser Link ausfällt.","other":"Deine {n} Satellitenverbindungen zwischen {a} und {b} gehen neben dem neuen Link in Standby: Sie tragen Traffic nur, wenn dieser Link ausfällt."}, +"satellites.n_places_in_reach":{"one":"{n} Insel oder abgelegener Ort in Reichweite auf deinem Level.","other":"{n} Inseln und abgelegene Orte in Reichweite auf deinem Level."}, +"satellites.needs_tracking_antennas":"Der MEO-Ring braucht Nachführantennen an deinem Teleport in {city}.", +"satellites.new_pop_cost":"neuer POP {cost}", +"satellites.no_bird_sees_both":"Kein Satellit im Angebot sieht {a} und {b} zugleich.", +"satellites.no_bird_sees_this_city":"Kein Satellit im Angebot sieht diese Stadt.", +"satellites.no_cable_needed_a_pop_here":"Kein Kabel nötig: Eine Satellitenverbindung von einem deiner Teleports bringt einen POP in {city} online.", +"satellites.no_pop_in_city":"Du hast keinen POP in {city}.", +"satellites.no_pop_there_yet":"Noch kein POP in {city}: Der wird gleich mitgebaut ({cost}).", +"satellites.no_such_circuit":"Diese Satellitenverbindung gibt es nicht.", +"satellites.no_teleport_in_city":"Du hast keinen Teleport in {city}.", +"satellites.no_teleport_reaches_city":"Keiner deiner Teleports erreicht {city}. Bau einen an einem POP, dessen Satelliten die Stadt sehen.", +"satellites.not_remote":"{city} ist ein zu großer Markt für Satellitenkapazität: Die ist für kleine Inseln und abgelegene Orte da.", +"satellites.nothing_in_view_from_here":"Von hier ist keine Insel und kein abgelegener Ort in Sicht.", +"satellites.on_standby_beside_your_link":"Er wartet im Standby neben deinem Link zwischen den beiden und trägt Traffic nur, wenn dieser Link ausfällt.", +"satellites.orbit_unlocks_at_level":"{orb}-Satelliten gibt es ab Level {lv}.", +"satellites.out_of_footprint":"{bird} sieht nicht {a} und {b} zugleich.", +"satellites.pointing_dishes_and_testing":"Schüsseln ausrichten und testen", +"satellites.radio_path":"Funkweg, hoch und runter", +"satellites.reachable_from_your_teleports":"Deine Teleports erreichen {city} per Satellit:", +"satellites.really_close_it":"Wirklich schließen?", +"satellites.rent":"Miete", +"satellites.rent_satellite_capacity":"Satellitenkapazität mieten", +"satellites.satellite_capacity":"Satellitenkapazität", +"satellites.satellites":"Satelliten", +"satellites.sea_americas":"Amerika", +"satellites.sea_atlantic":"Atlantik", +"satellites.sea_indian":"Indischer Ozean", +"satellites.sea_pacific":"Pazifik", +"satellites.sea_tropics":"bis 50° um den Äquator", +"satellites.sea_west_pacific":"Westpazifik", +"satellites.sesa_blurb":"Ein Ring aus Satelliten 8.000 km über dem Äquator, für die anderen drei Milliarden. Sesam, öffne dich: etwa 130 ms hin und zurück.", +"satellites.shrink_to":"Auf {cap} verkleinern", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"Der Teleport in {city} ist geschlossen.", +"satellites.teleport_up_in_city":"Teleport in {city} läuft. Große Schüsseln auf dem Dach, ab in den Himmel: Miete von hier Kapazität zu den Inseln in Sicht.", +"satellites.teleports_unlock_at_level":"Teleports gibt es ab Level {lv}.", +"satellites.tracking_antennas_up":"Nachführantennen in {city} laufen. Sie folgen dem MEO-Ring über den Himmel.", +"satellites.up_in_n_days":{"one":"läuft in {n} Tag","other":"läuft in {n} Tagen"}, +"satellites.users_notice_geo_meo":"Die Nutzer merken die Verzögerung: Breitband über GEO zählt als halber Service, über MEO fast als ganzer. Ein Kabel gewinnt immer, deine Router schicken Traffic also nur nach oben, wenn es keinen anderen Weg gibt.", +"satellites.users_ride_a_satellite":"Nutzer hängen am Satelliten", +"satellites.via_bird":"über {bird}", +"satellites.who_a_satellite_serves":"Satelliten bedienen kleine Inseln und abgelegene Orte, die derselbe Satellit sieht wie dein Teleport. Wähle das Ziel.", +"satellites.your_pops_in_view":"Deine POPs in Sicht", "save.cash_in_the_bank":"{cash} auf der Bank", "save.import_failed_err":"Import fehlgeschlagen.
{err}", "save.load_name":"{name} laden?", diff --git a/site/i18n/es.js b/site/i18n/es.js index 9ec154f..a416061 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"sube en {up}, baja en {down}", "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", +"pitcairn.uk_grant_needs_a_cable":"Subvención británica {mo}/mes solo con cable: la capacidad satelital alquilada no cuenta", "pitcairn.uk_sky_grant_mo":"Subvención británica por satélite {mo}/mes (la fibra recibe {full})", "pni_all.additional_per_month":"Coste mensual adicional", "pni_all.all_at_port":"Peering con todas las redes · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"La semana pasada {name} {list}.", "sales.w_now":"Esta semana {name} {list}.", "sales.w_signed":{"one":"firmó un cliente ({rev}/mes)","other":"firmó {n} clientes ({rev}/mes)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Un teleport es una pasarela satelital: antenas grandes en este POP que alquilan capacidad en satélites ajenos, para islas pequeñas y pueblos remotos a los que no llega ningún cable, o que cuelgan de un solo cable y una plegaria.", +"satellites.add_tracking_antennas_cost_mo":"Antenas de seguimiento MEO {cost} + {mo}/mes", +"satellites.being_commissioned":"En puesta en servicio", +"satellites.build_a_teleport_cost_mo":"Construir un teleport {cost} + {mo}/mes", +"satellites.by_satellite":"Por satélite", +"satellites.cancel_n_circuits_first":{"one":"Primero cancela su circuito satelital.","other":"Primero cancela sus {n} circuitos satelitales."}, +"satellites.choose":"Elegir", +"satellites.circuit_ordered":{"one":"{cap} en {bird} pedidos. {a} ⇄ {b} se está apuntando y probando: listo en {n} día.","other":"{cap} en {bird} pedidos. {a} ⇄ {b} se está apuntando y probando: listo en {n} días."}, +"satellites.close_the_teleport":"Cerrar el teleport", +"satellites.costs_row":"Teleports y satélites", +"satellites.geo_dishes":"Antenas GEO", +"satellites.geo_dishes_and_meo_tracking":"Antenas GEO y antenas de seguimiento MEO", +"satellites.geo_users_notice":"Desde 36.000 km de altura la ida y vuelta tarda unos 600 ms: las videollamadas y los juegos se traban, y los usuarios cuentan {p} del servicio como malo.", +"satellites.grow_to":"Ampliar a {cap}", +"satellites.in_view_list":"A la vista: {list}.", +"satellites.it_waits_on_standby":"Ya tienes un enlace entre estas dos: el satélite espera en reserva y solo lleva tráfico cuando ese enlace cae.", +"satellites.its_blurb":"Haces de banda C y Ku de toda la vida que cubren un océano entero. Fiables, en todas partes, y con precio a juego.", +"satellites.kac_blurb":"Haces puntuales en banda Ka sobre el Pacífico occidental: el Gbps más barato en órbita, si tu isla queda bajo un haz.", +"satellites.meo_comes_at_level":"El anillo MEO (unos 130 ms de ida y vuelta) llega en el nivel {lv}.", +"satellites.meo_ring_misses_city":"El anillo MEO no ve {city}: cubre {lat}° a cada lado del ecuador.", +"satellites.meo_users_notice":"Mucho más cerca del suelo, unos 130 ms de ida y vuelta: los usuarios apenas lo notan ({p} del servicio cuenta como malo).", +"satellites.more_islands_and_towns":"Más islas y pueblos a la vista", +"satellites.ms_one_way_rtt":"{ms} ms de ida, {rtt} ms de ida y vuelta", +"satellites.ms_round_trip":"{ms} ms de ida y vuelta", +"satellites.n_birds_see_both":{"one":"{n} satélite ve los dos","other":"{n} satélites ven los dos"}, +"satellites.n_circuits_go_on_standby":{"one":"Tu circuito satelital entre {a} y {b} pasa a reserva junto al nuevo enlace: solo lleva tráfico cuando ese enlace cae.","other":"Tus {n} circuitos satelitales entre {a} y {b} pasan a reserva junto al nuevo enlace: solo llevan tráfico cuando ese enlace cae."}, +"satellites.n_places_in_reach":{"one":"{n} isla o pueblo remoto a tu alcance en tu nivel.","other":"{n} islas y pueblos remotos a tu alcance en tu nivel."}, +"satellites.needs_tracking_antennas":"El anillo MEO necesita antenas de seguimiento en tu teleport de {city}.", +"satellites.new_pop_cost":"POP nuevo {cost}", +"satellites.no_bird_sees_both":"Ningún satélite a la venta ve a la vez {a} y {b}.", +"satellites.no_bird_sees_this_city":"Ningún satélite a la venta ve esta ciudad.", +"satellites.no_cable_needed_a_pop_here":"Sin cable: un circuito satelital desde uno de tus teleports pone en línea un POP en {city}.", +"satellites.no_pop_in_city":"No tienes POP en {city}.", +"satellites.no_pop_there_yet":"Aún no hay POP en {city}: esto también construye uno ({cost}).", +"satellites.no_such_circuit":"Ese circuito satelital no existe.", +"satellites.no_teleport_in_city":"No tienes teleport en {city}.", +"satellites.no_teleport_reaches_city":"Ninguno de tus teleports llega a {city}. Construye uno en un POP cuyos satélites la vean.", +"satellites.not_remote":"{city} es un mercado demasiado grande para capacidad satelital: es para islas pequeñas y pueblos remotos.", +"satellites.nothing_in_view_from_here":"Desde aquí no hay ninguna isla ni pueblo remoto a la vista.", +"satellites.on_standby_beside_your_link":"Espera en reserva junto a tu enlace entre las dos y solo lleva tráfico cuando ese enlace cae.", +"satellites.orbit_unlocks_at_level":"Los satélites {orb} se desbloquean en el nivel {lv}.", +"satellites.out_of_footprint":"{bird} no ve a la vez {a} y {b}.", +"satellites.pointing_dishes_and_testing":"Apuntando antenas y probando", +"satellites.radio_path":"Trayecto de radio, subida y bajada", +"satellites.reachable_from_your_teleports":"Tus teleports llegan a {city} por satélite:", +"satellites.really_close_it":"¿Cerrarlo de verdad?", +"satellites.rent":"Alquiler", +"satellites.rent_satellite_capacity":"Alquilar capacidad satelital", +"satellites.satellite_capacity":"Capacidad satelital", +"satellites.satellites":"Satélites", +"satellites.sea_americas":"Américas", +"satellites.sea_atlantic":"Atlántico", +"satellites.sea_indian":"Océano Índico", +"satellites.sea_pacific":"Pacífico", +"satellites.sea_tropics":"hasta 50° del ecuador", +"satellites.sea_west_pacific":"Pacífico occidental", +"satellites.sesa_blurb":"Un anillo de satélites a 8.000 km sobre el ecuador, para los otros tres mil millones. Ábrete, sésamo: unos 130 ms de ida y vuelta.", +"satellites.shrink_to":"Reducir a {cap}", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"El teleport de {city} está cerrado.", +"satellites.teleport_up_in_city":"Teleport en marcha en {city}. Antenas enormes en la azotea, apuntando al cielo: alquila desde aquí capacidad hacia las islas a la vista.", +"satellites.teleports_unlock_at_level":"Los teleports se desbloquean en el nivel {lv}.", +"satellites.tracking_antennas_up":"Antenas de seguimiento en marcha en {city}. Siguen el anillo MEO por el cielo.", +"satellites.up_in_n_days":{"one":"listo en {n} día","other":"listo en {n} días"}, +"satellites.users_notice_geo_meo":"Los usuarios notan el retardo: la banda ancha por GEO cuenta como medio servicio, por MEO casi como el servicio entero. Un cable siempre gana, así que tus routers solo mandan tráfico arriba cuando no hay otro camino.", +"satellites.users_ride_a_satellite":"usuarios vía satélite", +"satellites.via_bird":"vía {bird}", +"satellites.who_a_satellite_serves":"Los satélites sirven a islas pequeñas y pueblos remotos que ve el mismo satélite que tu teleport. Elige el destino.", +"satellites.your_pops_in_view":"Tus POP a la vista", "save.cash_in_the_bank":"{cash} en el banco", "save.import_failed_err":"Falló la importación.
{err}", "save.load_name":"¿Cargar {name}?", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index ec461d3..6ca08cf 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"monte à {up}, descend à {down}", "pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois", "pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne", +"pitcairn.uk_grant_needs_a_cable":"Subvention britannique {mo}/mois seulement avec un câble : la capacité satellite louée ne compte pas", "pitcairn.uk_sky_grant_mo":"Subvention britannique satellite {mo}/mois (la fibre touche {full})", "pni_all.additional_per_month":"Coût mensuel supplémentaire", "pni_all.all_at_port":"Peering avec tous les réseaux · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"La semaine dernière, {name} {list}.", "sales.w_now":"Cette semaine, {name} {list}.", "sales.w_signed":{"one":"a signé un client ({rev}/mois)","other":"a signé {n} clients ({rev}/mois)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Un téléport est une passerelle satellite : de grandes paraboles sur ce POP qui louent de la capacité sur les satellites des autres, vers les petites îles et les villes isolées qu’aucun câble ne dessert, ou qui ne tiennent qu’à un câble et une prière.", +"satellites.add_tracking_antennas_cost_mo":"Antennes de poursuite MEO {cost} + {mo}/mois", +"satellites.being_commissioned":"Mise en service", +"satellites.build_a_teleport_cost_mo":"Construire un téléport {cost} + {mo}/mois", +"satellites.by_satellite":"Par satellite", +"satellites.cancel_n_circuits_first":{"one":"Résilie d’abord son circuit satellite.","other":"Résilie d’abord ses {n} circuits satellite."}, +"satellites.choose":"Choisir", +"satellites.circuit_ordered":{"one":"{cap} sur {bird} commandé. {a} ⇄ {b} est en cours de pointage et de test : en service dans {n} jour.","other":"{cap} sur {bird} commandé. {a} ⇄ {b} est en cours de pointage et de test : en service dans {n} jours."}, +"satellites.close_the_teleport":"Fermer le téléport", +"satellites.costs_row":"Téléports et satellites", +"satellites.geo_dishes":"Paraboles GEO", +"satellites.geo_dishes_and_meo_tracking":"Paraboles GEO et antennes de poursuite MEO", +"satellites.geo_users_notice":"Depuis 36 000 km d’altitude, l’aller-retour prend environ 600 ms : visios et jeux saccadent, et les utilisateurs comptent {p} du service comme mauvais.", +"satellites.grow_to":"Passer à {cap}", +"satellites.in_view_list":"En vue : {list}.", +"satellites.it_waits_on_standby":"Tu as déjà un lien entre ces deux villes : le satellite attend en réserve et ne porte du trafic que quand ce lien tombe.", +"satellites.its_blurb":"De bons vieux faisceaux en bande C et Ku qui couvrent tout un océan. Fiables, partout, et facturés en conséquence.", +"satellites.kac_blurb":"Des spots en bande Ka sur le Pacifique occidental : le Gbps le moins cher en orbite, si ton île est sous un spot.", +"satellites.meo_comes_at_level":"L’anneau MEO (environ 130 ms aller-retour) arrive au niveau {lv}.", +"satellites.meo_ring_misses_city":"L’anneau MEO ne voit pas {city} : il couvre {lat}° de part et d’autre de l’équateur.", +"satellites.meo_users_notice":"Bien plus près du sol, environ 130 ms aller-retour : les utilisateurs le remarquent à peine ({p} du service compte comme mauvais).", +"satellites.more_islands_and_towns":"Autres îles et villes en vue", +"satellites.ms_one_way_rtt":"{ms} ms aller, {rtt} ms aller-retour", +"satellites.ms_round_trip":"{ms} ms aller-retour", +"satellites.n_birds_see_both":{"one":"{n} satellite voit les deux","other":"{n} satellites voient les deux"}, +"satellites.n_circuits_go_on_standby":{"one":"Ton circuit satellite entre {a} et {b} passe en réserve à côté du nouveau lien : il ne porte du trafic que quand ce lien tombe.","other":"Tes {n} circuits satellite entre {a} et {b} passent en réserve à côté du nouveau lien : ils ne portent du trafic que quand ce lien tombe."}, +"satellites.n_places_in_reach":{"one":"{n} île ou ville isolée à portée à ton niveau.","other":"{n} îles et villes isolées à portée à ton niveau."}, +"satellites.needs_tracking_antennas":"L’anneau MEO a besoin d’antennes de poursuite à ton téléport de {city}.", +"satellites.new_pop_cost":"nouveau POP {cost}", +"satellites.no_bird_sees_both":"Aucun satellite en vente ne voit à la fois {a} et {b}.", +"satellites.no_bird_sees_this_city":"Aucun satellite en vente ne voit cette ville.", +"satellites.no_cable_needed_a_pop_here":"Pas besoin de câble : un circuit satellite depuis un de tes téléports met un POP à {city} en ligne.", +"satellites.no_pop_in_city":"Tu n’as pas de POP à {city}.", +"satellites.no_pop_there_yet":"Pas encore de POP à {city} : on en construit un au passage ({cost}).", +"satellites.no_such_circuit":"Ce circuit satellite n’existe pas.", +"satellites.no_teleport_in_city":"Tu n’as pas de téléport à {city}.", +"satellites.no_teleport_reaches_city":"Aucun de tes téléports n’atteint {city}. Construis-en un sur un POP dont les satellites la voient.", +"satellites.not_remote":"{city} est un trop gros marché pour de la capacité satellite : elle sert les petites îles et les villes isolées.", +"satellites.nothing_in_view_from_here":"Aucune île ni ville isolée en vue d’ici.", +"satellites.on_standby_beside_your_link":"Il attend en réserve à côté de ton lien entre les deux et ne porte du trafic que quand ce lien tombe.", +"satellites.orbit_unlocks_at_level":"Les satellites {orb} se débloquent au niveau {lv}.", +"satellites.out_of_footprint":"{bird} ne voit pas à la fois {a} et {b}.", +"satellites.pointing_dishes_and_testing":"Pointage des paraboles et tests", +"satellites.radio_path":"Trajet radio, montée et descente", +"satellites.reachable_from_your_teleports":"Tes téléports atteignent {city} par satellite :", +"satellites.really_close_it":"Vraiment le fermer ?", +"satellites.rent":"Location", +"satellites.rent_satellite_capacity":"Louer de la capacité satellite", +"satellites.satellite_capacity":"Capacité satellite", +"satellites.satellites":"Satellites", +"satellites.sea_americas":"Amériques", +"satellites.sea_atlantic":"Atlantique", +"satellites.sea_indian":"Océan Indien", +"satellites.sea_pacific":"Pacifique", +"satellites.sea_tropics":"jusqu’à 50° de l’équateur", +"satellites.sea_west_pacific":"Pacifique occidental", +"satellites.sesa_blurb":"Un anneau de satellites à 8 000 km au-dessus de l’équateur, pour les trois autres milliards. Sésame, ouvre-toi : environ 130 ms aller-retour.", +"satellites.shrink_to":"Réduire à {cap}", +"satellites.teleport":"Téléport", +"satellites.teleport_closed":"Le téléport de {city} est fermé.", +"satellites.teleport_up_in_city":"Téléport en service à {city}. De grandes paraboles sur le toit, pointées vers le ciel : loue d’ici de la capacité vers les îles en vue.", +"satellites.teleports_unlock_at_level":"Les téléports se débloquent au niveau {lv}.", +"satellites.tracking_antennas_up":"Antennes de poursuite en service à {city}. Elles suivent l’anneau MEO dans le ciel.", +"satellites.up_in_n_days":{"one":"en service dans {n} jour","other":"en service dans {n} jours"}, +"satellites.users_notice_geo_meo":"Les utilisateurs sentent le délai : le haut débit par GEO compte pour la moitié du service, par MEO presque pour tout. Un câble gagne toujours, donc tes routeurs n’envoient du trafic là-haut que s’il n’y a pas d’autre chemin.", +"satellites.users_ride_a_satellite":"utilisateurs sur satellite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"Les satellites desservent les petites îles et les villes isolées que voit le même satellite que ton téléport. Choisis la destination.", +"satellites.your_pops_in_view":"Tes POP en vue", "save.cash_in_the_bank":"{cash} en banque", "save.import_failed_err":"Échec de l’import.
{err}", "save.load_name":"Charger {name} ?", diff --git a/site/i18n/it.js b/site/i18n/it.js index 06d88d6..e0b0bf0 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"su a {up}, giù a {down}", "pitcairn.uk_grant_mo":"Contributo UK {mo}/mese", "pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online", +"pitcairn.uk_grant_needs_a_cable":"Contributo UK {mo}/mese solo con un cavo: la capacità satellitare in affitto non conta", "pitcairn.uk_sky_grant_mo":"Contributo UK via satellite {mo}/mese (la fibra prende {full})", "pni_all.additional_per_month":"Costo mensile aggiuntivo", "pni_all.all_at_port":"Peering con tutte le reti · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"La settimana scorsa {name} {list}.", "sales.w_now":"Questa settimana {name} {list}.", "sales.w_signed":{"one":"ha firmato un cliente ({rev}/mese)","other":"ha firmato {n} clienti ({rev}/mese)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Un teleport è un gateway satellitare: grandi parabole in questo POP che noleggiano capacità sui satelliti di altri, verso piccole isole e città remote che nessun cavo raggiunge, o che stanno appese a un solo cavo e a una preghiera.", +"satellites.add_tracking_antennas_cost_mo":"Antenne a inseguimento MEO {cost} + {mo}/mese", +"satellites.being_commissioned":"In attivazione", +"satellites.build_a_teleport_cost_mo":"Costruisci un teleport {cost} + {mo}/mese", +"satellites.by_satellite":"Via satellite", +"satellites.cancel_n_circuits_first":{"one":"Prima disdici il suo circuito satellitare.","other":"Prima disdici i suoi {n} circuiti satellitari."}, +"satellites.choose":"Scegli", +"satellites.circuit_ordered":{"one":"{cap} su {bird} ordinati. {a} ⇄ {b} si sta puntando e testando: attivo tra {n} giorno.","other":"{cap} su {bird} ordinati. {a} ⇄ {b} si sta puntando e testando: attivo tra {n} giorni."}, +"satellites.close_the_teleport":"Chiudi il teleport", +"satellites.costs_row":"Teleport e satelliti", +"satellites.geo_dishes":"Parabole GEO", +"satellites.geo_dishes_and_meo_tracking":"Parabole GEO e antenne a inseguimento MEO", +"satellites.geo_users_notice":"Da 36.000 km di quota il giro dura circa 600 ms: videochiamate e giochi scattano, e gli utenti contano {p} del servizio come pessimo.", +"satellites.grow_to":"Porta a {cap}", +"satellites.in_view_list":"In vista: {list}.", +"satellites.it_waits_on_standby":"Tra queste due hai già un link: il satellite aspetta in standby e porta traffico solo quando quel link cade.", +"satellites.its_blurb":"I classici fasci in banda C e Ku che coprono un oceano intero. Affidabili, ovunque, e con il prezzo che ne consegue.", +"satellites.kac_blurb":"Spot beam in banda Ka sul Pacifico occidentale: il Gbps più economico in orbita, se la tua isola sta sotto un fascio.", +"satellites.meo_comes_at_level":"L’anello MEO (circa 130 ms andata e ritorno) arriva al livello {lv}.", +"satellites.meo_ring_misses_city":"L’anello MEO non vede {city}: copre {lat}° a nord e a sud dell’equatore.", +"satellites.meo_users_notice":"Molto più vicino a terra, circa 130 ms andata e ritorno: gli utenti se ne accorgono appena ({p} del servizio conta come pessimo).", +"satellites.more_islands_and_towns":"Altre isole e città in vista", +"satellites.ms_one_way_rtt":"{ms} ms solo andata, {rtt} ms andata e ritorno", +"satellites.ms_round_trip":"{ms} ms andata e ritorno", +"satellites.n_birds_see_both":{"one":"{n} satellite vede entrambe","other":"{n} satelliti vedono entrambe"}, +"satellites.n_circuits_go_on_standby":{"one":"Il tuo circuito satellitare tra {a} e {b} va in standby accanto al nuovo link: porta traffico solo quando quel link cade.","other":"I tuoi {n} circuiti satellitari tra {a} e {b} vanno in standby accanto al nuovo link: portano traffico solo quando quel link cade."}, +"satellites.n_places_in_reach":{"one":"{n} isola o città remota a portata al tuo livello.","other":"{n} isole e città remote a portata al tuo livello."}, +"satellites.needs_tracking_antennas":"L’anello MEO vuole antenne a inseguimento al tuo teleport di {city}.", +"satellites.new_pop_cost":"nuovo POP {cost}", +"satellites.no_bird_sees_both":"Nessun satellite in vendita vede insieme {a} e {b}.", +"satellites.no_bird_sees_this_city":"Nessun satellite in vendita vede questa città.", +"satellites.no_cable_needed_a_pop_here":"Niente cavo: un circuito satellitare da uno dei tuoi teleport mette online un POP a {city}.", +"satellites.no_pop_in_city":"Non hai un POP a {city}.", +"satellites.no_pop_there_yet":"A {city} non c’è ancora un POP: così ne costruisci anche uno ({cost}).", +"satellites.no_such_circuit":"Questo circuito satellitare non esiste.", +"satellites.no_teleport_in_city":"Non hai un teleport a {city}.", +"satellites.no_teleport_reaches_city":"Nessuno dei tuoi teleport raggiunge {city}. Costruiscine uno in un POP i cui satelliti la vedano.", +"satellites.not_remote":"{city} è un mercato troppo grande per la capacità satellitare: quella serve piccole isole e città remote.", +"satellites.nothing_in_view_from_here":"Da qui non si vede nessuna isola né città remota.", +"satellites.on_standby_beside_your_link":"Aspetta in standby accanto al tuo link tra le due e porta traffico solo quando quel link cade.", +"satellites.orbit_unlocks_at_level":"I satelliti {orb} si sbloccano al livello {lv}.", +"satellites.out_of_footprint":"{bird} non vede insieme {a} e {b}.", +"satellites.pointing_dishes_and_testing":"Puntamento delle parabole e test", +"satellites.radio_path":"Percorso radio, su e giù", +"satellites.reachable_from_your_teleports":"I tuoi teleport raggiungono {city} via satellite:", +"satellites.really_close_it":"Lo chiudi davvero?", +"satellites.rent":"Noleggio", +"satellites.rent_satellite_capacity":"Noleggia capacità satellitare", +"satellites.satellite_capacity":"Capacità satellitare", +"satellites.satellites":"Satelliti", +"satellites.sea_americas":"Americhe", +"satellites.sea_atlantic":"Atlantico", +"satellites.sea_indian":"Oceano Indiano", +"satellites.sea_pacific":"Pacifico", +"satellites.sea_tropics":"entro 50° dall’equatore", +"satellites.sea_west_pacific":"Pacifico occidentale", +"satellites.sesa_blurb":"Un anello di satelliti a 8.000 km sopra l’equatore, per gli altri tre miliardi. Apriti sesamo: circa 130 ms andata e ritorno.", +"satellites.shrink_to":"Riduci a {cap}", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"Il teleport di {city} è chiuso.", +"satellites.teleport_up_in_city":"Teleport attivo a {city}. Grandi parabole sul tetto, puntate al cielo: da qui noleggi capacità verso le isole in vista.", +"satellites.teleports_unlock_at_level":"I teleport si sbloccano al livello {lv}.", +"satellites.tracking_antennas_up":"Antenne a inseguimento attive a {city}. Seguono l’anello MEO nel cielo.", +"satellites.up_in_n_days":{"one":"attivo tra {n} giorno","other":"attivo tra {n} giorni"}, +"satellites.users_notice_geo_meo":"Gli utenti sentono il ritardo: la banda larga via GEO conta come mezzo servizio, via MEO quasi come tutto. Un cavo vince sempre, quindi i tuoi router mandano traffico lassù solo se non c’è altra strada.", +"satellites.users_ride_a_satellite":"utenti via satellite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"I satelliti servono piccole isole e città remote che lo stesso satellite vede insieme al tuo teleport. Scegli la destinazione.", +"satellites.your_pops_in_view":"I tuoi POP in vista", "save.cash_in_the_bank":"{cash} in cassa", "save.import_failed_err":"Importazione fallita.
{err}", "save.load_name":"Caricare {name}?", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 4714044..a8014bf 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"sobe em {up}, desce em {down}", "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", +"pitcairn.uk_grant_needs_a_cable":"Subsídio do Reino Unido {mo}/mês só com cabo: capacidade de satélite alugada não conta", "pitcairn.uk_sky_grant_mo":"Subsídio britânico por satélite {mo}/mês (a fibra recebe {full})", "pni_all.additional_per_month":"Custo mensal adicional", "pni_all.all_at_port":"Peering com todas as redes · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"Semana passada {name} {list}.", "sales.w_now":"Esta semana {name} {list}.", "sales.w_signed":{"one":"assinou um cliente ({rev}/mês)","other":"assinou {n} clientes ({rev}/mês)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Um teleporto é um gateway de satélite: antenas grandes neste POP que alugam capacidade nos satélites dos outros, para ilhas pequenas e cidades remotas aonde nenhum cabo chega, ou que dependem de um só cabo e de uma reza.", +"satellites.add_tracking_antennas_cost_mo":"Antenas de rastreamento MEO {cost} + {mo}/mês", +"satellites.being_commissioned":"Em comissionamento", +"satellites.build_a_teleport_cost_mo":"Construir um teleporto {cost} + {mo}/mês", +"satellites.by_satellite":"Por satélite", +"satellites.cancel_n_circuits_first":{"one":"Cancele primeiro o circuito de satélite dele.","other":"Cancele primeiro os {n} circuitos de satélite dele."}, +"satellites.choose":"Escolher", +"satellites.circuit_ordered":{"one":"{cap} no {bird} encomendados. {a} ⇄ {b} está sendo apontado e testado: no ar em {n} dia.","other":"{cap} no {bird} encomendados. {a} ⇄ {b} está sendo apontado e testado: no ar em {n} dias."}, +"satellites.close_the_teleport":"Fechar o teleporto", +"satellites.costs_row":"Teleportos e satélites", +"satellites.geo_dishes":"Antenas GEO", +"satellites.geo_dishes_and_meo_tracking":"Antenas GEO e antenas de rastreamento MEO", +"satellites.geo_users_notice":"De 36.000 km de altura a ida e volta leva uns 600 ms: chamadas de vídeo e jogos travam, e os usuários contam {p} do serviço como ruim.", +"satellites.grow_to":"Aumentar para {cap}", +"satellites.in_view_list":"À vista: {list}.", +"satellites.it_waits_on_standby":"Você já tem um link entre as duas: o satélite espera de reserva e só leva tráfego quando esse link cai.", +"satellites.its_blurb":"Feixes clássicos em banda C e Ku que cobrem um oceano inteiro. Confiáveis, em todo lugar, e com preço à altura.", +"satellites.kac_blurb":"Feixes pontuais em banda Ka sobre o Pacífico ocidental: o Gbps mais barato em órbita, se a sua ilha estiver debaixo de um feixe.", +"satellites.meo_comes_at_level":"O anel MEO (uns 130 ms de ida e volta) chega no nível {lv}.", +"satellites.meo_ring_misses_city":"O anel MEO não vê {city}: ele cobre {lat}° de cada lado do equador.", +"satellites.meo_users_notice":"Muito mais perto do chão, uns 130 ms de ida e volta: os usuários mal percebem ({p} do serviço conta como ruim).", +"satellites.more_islands_and_towns":"Mais ilhas e cidades à vista", +"satellites.ms_one_way_rtt":"{ms} ms só de ida, {rtt} ms de ida e volta", +"satellites.ms_round_trip":"{ms} ms de ida e volta", +"satellites.n_birds_see_both":{"one":"{n} satélite vê as duas","other":"{n} satélites veem as duas"}, +"satellites.n_circuits_go_on_standby":{"one":"Seu circuito de satélite entre {a} e {b} fica de reserva ao lado do novo link: só leva tráfego quando esse link cai.","other":"Seus {n} circuitos de satélite entre {a} e {b} ficam de reserva ao lado do novo link: só levam tráfego quando esse link cai."}, +"satellites.n_places_in_reach":{"one":"{n} ilha ou cidade remota ao alcance no seu nível.","other":"{n} ilhas e cidades remotas ao alcance no seu nível."}, +"satellites.needs_tracking_antennas":"O anel MEO precisa de antenas de rastreamento no seu teleporto em {city}.", +"satellites.new_pop_cost":"POP novo {cost}", +"satellites.no_bird_sees_both":"Nenhum satélite à venda vê {a} e {b} ao mesmo tempo.", +"satellites.no_bird_sees_this_city":"Nenhum satélite à venda vê esta cidade.", +"satellites.no_cable_needed_a_pop_here":"Sem cabo: um circuito de satélite de um dos seus teleportos coloca um POP em {city} no ar.", +"satellites.no_pop_in_city":"Você não tem POP em {city}.", +"satellites.no_pop_there_yet":"Ainda não há POP em {city}: isto também constrói um ({cost}).", +"satellites.no_such_circuit":"Esse circuito de satélite não existe.", +"satellites.no_teleport_in_city":"Você não tem teleporto em {city}.", +"satellites.no_teleport_reaches_city":"Nenhum dos seus teleportos alcança {city}. Construa um num POP cujos satélites a vejam.", +"satellites.not_remote":"{city} é um mercado grande demais para capacidade de satélite: ela é para ilhas pequenas e cidades remotas.", +"satellites.nothing_in_view_from_here":"Daqui não há nenhuma ilha nem cidade remota à vista.", +"satellites.on_standby_beside_your_link":"Ele espera de reserva ao lado do seu link entre as duas e só leva tráfego quando esse link cai.", +"satellites.orbit_unlocks_at_level":"Satélites {orb} são liberados no nível {lv}.", +"satellites.out_of_footprint":"{bird} não vê {a} e {b} ao mesmo tempo.", +"satellites.pointing_dishes_and_testing":"Apontando antenas e testando", +"satellites.radio_path":"Caminho de rádio, subida e descida", +"satellites.reachable_from_your_teleports":"Seus teleportos alcançam {city} por satélite:", +"satellites.really_close_it":"Fechar mesmo?", +"satellites.rent":"Aluguel", +"satellites.rent_satellite_capacity":"Alugar capacidade de satélite", +"satellites.satellite_capacity":"Capacidade de satélite", +"satellites.satellites":"Satélites", +"satellites.sea_americas":"Américas", +"satellites.sea_atlantic":"Atlântico", +"satellites.sea_indian":"Oceano Índico", +"satellites.sea_pacific":"Pacífico", +"satellites.sea_tropics":"até 50° do equador", +"satellites.sea_west_pacific":"Pacífico ocidental", +"satellites.sesa_blurb":"Um anel de satélites a 8.000 km acima do equador, para os outros três bilhões. Abre-te, sésamo: uns 130 ms de ida e volta.", +"satellites.shrink_to":"Reduzir para {cap}", +"satellites.teleport":"Teleporto", +"satellites.teleport_closed":"O teleporto em {city} foi fechado.", +"satellites.teleport_up_in_city":"Teleporto no ar em {city}. Antenas enormes no telhado, apontadas para o céu: alugue daqui capacidade para as ilhas à vista.", +"satellites.teleports_unlock_at_level":"Teleportos são liberados no nível {lv}.", +"satellites.tracking_antennas_up":"Antenas de rastreamento no ar em {city}. Elas seguem o anel MEO pelo céu.", +"satellites.up_in_n_days":{"one":"no ar em {n} dia","other":"no ar em {n} dias"}, +"satellites.users_notice_geo_meo":"Os usuários sentem o atraso: banda larga por GEO conta como meio serviço, por MEO quase como o serviço inteiro. Um cabo sempre ganha, então seus roteadores só mandam tráfego para cima quando não há outro caminho.", +"satellites.users_ride_a_satellite":"usuários via satélite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"Satélites atendem ilhas pequenas e cidades remotas que o mesmo satélite vê junto com o seu teleporto. Escolha o destino.", +"satellites.your_pops_in_view":"Seus POPs à vista", "save.cash_in_the_bank":"{cash} no banco", "save.import_failed_err":"Falha na importação.
{err}", "save.load_name":"Carregar {name}?", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index 3a51abb..1d3d9a7 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -22,6 +22,8 @@ const API_DOMAINS={ vxcTier:{table:'VXC',kind:'index'}, routerModel:{table:'RG',kind:'index'}, scrubTier:{table:'SCRUB_TIERS',kind:'index'}, + satBird:{table:'SATS',kind:'key'}, + satG:{kind:'enum',values:()=>[...new Set(Object.values(SAT_ORB).flatMap(o=>o.g))].sort((a,b)=>a-b)}, // Small fixed vocabularies the game itself checks by list membership. // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 8ea9a36..25cb8db 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -123,7 +123,7 @@ const API_CMD={ quote:a=>{const A=a.a,B=a.b,tier=a.tier; if(!S.pops[A])return {blocked:[linkFromWhy(A)]}; if(!waveOk(A,B,tier))return {blocked:[tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:waveNeed(tier)})]}; - const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); + const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1); const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]}; const blocked=[],so=soldOut(A,B,tier,wr.cab); @@ -167,6 +167,22 @@ const API_CMD={ doc:'Egress preference for one exit: high sends more traffic that way, low keeps it for backup.'}, siteSet:{args:[['k','connKind'],['id','entityId'],['s','site']],watch:['transit.#id','pni.#id'], doc:'Put a transit port, PNI or IX port in building A, B or both. Choosing both with a single member adds a LAG member first, and charges for it.'}, +/* ---------- teleports and satellite capacity (#83) ---------- */ + teleBuild:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:TPORT_COST,monthly:TPORT_MO,blocked:[teleOf(a.city)?'there is a teleport here already':teleWhy(a.city)].filter(Boolean)}), + doc:'Build a teleport (a satellite gateway) at one of your POPs: it rents circuits on GEO birds to small islands and remote towns in their footprint. Refused where no satellite on sale at your level sees the city.'}, + teleTrk:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:TRK_COST,monthly:TRK_MO,blocked:[teleOf(a.city)===2?'this teleport has tracking antennas already':trkWhy(a.city)].filter(Boolean)}), + doc:'Add tracking antennas to a teleport, so it can work the MEO ring (about 130 ms round trip instead of GEO\'s 600). Only within 50 degrees of the equator, where the ring is in view.'}, + teleRm:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'], + doc:'Close a teleport. Refused while circuits still start there.'}, + buySat:{args:[['a','cityId'],['b','cityId'],['bird','satBird'],['g','satG']], + quote:a=>{const ok=own(SATS,a.bird),mo=ok?satMo(a.bird,+a.g):0;return {setup:mo+(S.pops[a.b]||!CITY[a.b]?0:popCost(a.b)),monthly:mo,days:ok?leadDays(SAT_ORB[SATS[a.bird].orb].days):0,blocked:[satWhy(a.a,a.b,a.bird,+a.g)].filter(Boolean)};}, + doc:'Rent a satellite circuit from your teleport in a to b (a small island or a remote town) on a bird that sees both: GEO 1-10 Gbps, MEO 2-20 with tracking antennas. The first month up front; builds a POP at b if there is none. Next to an existing link between the two it goes on standby, as backup; a link built later between the two puts it on standby too. Cancel with rmLink.'}, + satSize:{args:[['id','entityId'],['g','satG']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id&&x.kind==='sat'),g=+a.g,ok=!!l&&g!==l.g&&SAT_ORB[SATS[l.bird].orb].g.includes(g),mo=ok?satMo(l.bird,g):0; + return {setup:ok&&g>l.g?mo:0,monthly:mo,blocked:!l?['not a satellite circuit']:ok?[]:[tr('satellites.no_such_circuit')]};}, + doc:'Resize a satellite circuit on the same bird. A bigger one pays its new month up front.'}, /* ---------- dark fiber and own cable ---------- */ orderDf:{args:[['a','cityId'],['b','cityId'],['source','dfSource'],['system','systemId']], bindsUI:['pending','dfSrc','dfSys'],bind:a=>{UI.pending={a:a.a,b:a.b};UI.dfSrc=a.source;UI.dfSys=a.system;}, @@ -574,6 +590,7 @@ const API_BOUND={ teRecipe:{command:'teDeploy',arg:'script',note:'a recipe from catalog(\'TE_RECIPES\')'}, trace:{command:'traceRun',arg:'from'}, decomToggle:{command:'decomGo',arg:'cities'}, + satOpen:{command:'buySat',note:'opens the satellite order sheet from a teleport (a) or for a city (b); buySat takes a, b, bird and g itself'}, openVxc:{command:'buyVxc',note:'opens the circuit picker from a fabric port ({from, prov}); buyVxc takes a, b, prov and t itself'}, connCancel:{command:'cancelTransit',note:'the connections list\'s cancel button: it arms, then dispatches cancelTransit, cancelPni, cancelIx, rmCache or rmNni'}, cnPrem:{command:'buildLink',arg:'premiumCrossing'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 12d573e..e75ae3c 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -19,8 +19,8 @@ const API_STATE_DOC={ t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, auV:{type:'integer',doc:'Australia content level gate.'}, seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, - pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, - links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc) and express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics), each with an entity id.'}, + pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site, teleport (tele: 1 GEO dishes, 2 with MEO tracking antennas).'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc), express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics) and rented satellite circuits (sat: bird, g Gbps, km of radio path, ready day), each with an entity id.'}, transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, rs:{type:'map',doc:'Route-server sessions by exchange city.'}, @@ -130,6 +130,7 @@ const API_RESULTS_DOC={ cityEye:{type:'map',doc:'Eyeballs online per city.'}, latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, + satU:{type:'map',doc:'Of each city\'s served traffic, the Gbps that rode a rented satellite circuit (its users notice the orbit\'s latency on that share). Only there while you have a satellite circuit up.'}, demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, served:{type:'number',doc:'Total traffic served, in Gbps.'}, demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, diff --git a/src/agent/40-read.js b/src/agent/40-read.js index e767e2d..5ca278a 100644 --- a/src/agent/40-read.js +++ b/src/agent/40-read.js @@ -26,7 +26,7 @@ function apiJson(v){ carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders each recipe's script, because the source is a function and some read the live network. The recipes' relevance score is not exposed: judging which one fits is the agent's job. */ -const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SATS,SAT_ORB,SAT_PROV,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; const API_MADE={ BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index 4f0835e..4fb1915 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -69,9 +69,9 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1) let DFC=null; const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; const dfCap0=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; -const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):l.kind==='xp'?xpG(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); +const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):l.kind==='xp'?xpG(l):l.kind==='sat'?l.g:LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); // A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); -const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; -const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; +const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc'||l.kind==='sat')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; +const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='sat'?fmtCap(l.g)+' '+SAT_ORB[SATS[l.bird].orb].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; diff --git a/src/game/10-catalog/75-satellites.js b/src/game/10-catalog/75-satellites.js new file mode 100644 index 0000000..b30143a --- /dev/null +++ b/src/game/10-catalog/75-satellites.js @@ -0,0 +1,61 @@ +/* ---------- Satellites (#83): capacity rented on someone else's birds ---------- + A teleport (a satellite gateway at one of your POPs) links to a small island or a remote town over rented capacity: + the early answer to "no cable lands there", and the warm backup for an island hanging on one cable. Geostationary + birds (GEO, 35,786 km up) see a whole ocean from one dish: no build, dear per Gbps, about 600 ms there and back. A + medium-orbit ring over the equator (MEO, 8,062 km up) gets that down to about 130 ms, but a teleport needs tracking + antennas to follow its satellites across the sky. Your own constellation (LEO, Pie in the Sky) comes much later. + The providers are vendors, like the fabrics: they sell you capacity, they are not networks you route to. */ +// h: km up; proc: ms of modems and error correction each way; loss: the share of a city's service its users stop counting +// once their traffic rides it (half for GEO, like any haul past 50 ms; MEO feels almost like fiber); days: to point and +// commission a new circuit; lv: the level it unlocks at; g: the sizes sold (Gbps). A MEO ring covers |lat| <= lat, and a +// circuit's two ends must see the same satellite at once: at most km apart, and at least el degrees above both horizons +// (what a ground terminal needs to clear the trees; far north, two ends 7,000 km apart lose it below the horizon). +const SAT_ORB={ + geo:{n:'GEO',h:35786,proc:25,loss:0.5,days:10,lv:2,g:[1,2,5,10]}, + meo:{n:'MEO',h:8062,proc:7,loss:0.08,days:21,lv:3,g:[2,5,10,20],lat:50,km:7500,el:5}, +}; +// pg: dollars a month for the first Gbps; bigger circuits cost less per Gbps (satMo). +const SAT_PROV={ + its:{n:'Intelsplat',col:'#2F8CFF',pg:2500,blurb:tr('satellites.its_blurb')}, + kac:{n:'Kacophony',col:'#FF8A3D',pg:1400,blurb:tr('satellites.kac_blurb')}, + sesa:{n:'SESame',col:'#16A866',pg:2000,blurb:tr('satellites.sesa_blurb')}, +}; +// The birds. A GEO sits over the equator at lon; r is how far its beams reach, in degrees of arc from the point under it +// (72: a global beam, down to about 5 degrees above the horizon; Kacophony's Ka-band spot beams cover less, for less). +const SATS={ + is18:{n:'Intelsplat 18',p:'its',orb:'geo',lon:180,r:72,sea:N_('satellites.sea_pacific')}, + is20:{n:'Intelsplat 20',p:'its',orb:'geo',lon:68.5,r:72,sea:N_('satellites.sea_indian')}, + is37:{n:'Intelsplat 37e',p:'its',orb:'geo',lon:-18,r:72,sea:N_('satellites.sea_atlantic')}, + kac1:{n:'Kacophony-1',p:'kac',orb:'geo',lon:150,r:50,sea:N_('satellites.sea_west_pacific')}, + gx19:{n:'Intelsplat 19',p:'its',orb:'geo',lon:-97,r:72,sea:N_('satellites.sea_americas')}, + o3b:{n:'O3bservant',p:'sesa',orb:'meo',sea:N_('satellites.sea_tropics')}, +}; +// The teleport itself (dishes, a building, the licences), and the MEO tracking antennas it may add. +const TPORT_COST=90000,TPORT_MO=2500,TRK_COST=250000,TRK_MO=3000; +// Who a satellite serves: a small island off the big continents, or a remote town anywhere, never a big city's market. +const SAT_MAIN=['af','am','eu','oc','sa'],SAT_ISLE_P=150,SAT_TOWN_P=5; +const SAT_RE=6371,SAT_C=300; +// The arc between two points on the globe, in degrees. +function satArc(la1,lo1,la2,lo2){const r=Math.PI/180,c=Math.sin(la1*r)*Math.sin(la2*r)+Math.cos(la1*r)*Math.cos(la2*r)*Math.cos((lo2-lo1)*r);return Math.acos(Math.max(-1,Math.min(1,c)))/r;} +// From a dish to a satellite h km up over a point arc degrees away, in a straight line. +function satSlant(arc,h){const Q=SAT_RE+h,a=arc*Math.PI/180;return Math.sqrt(SAT_RE*SAT_RE+Q*Q-2*SAT_RE*Q*Math.cos(a));} +// How high above a dish's horizon that satellite stands, in degrees (negative: below it, behind the Earth). +function satElev(arc,h){const a=arc*Math.PI/180;return Math.atan2(Math.cos(a)-SAT_RE/(SAT_RE+h),Math.sin(a))*180/Math.PI;} +// The longitude the bird sits over for a circuit: a GEO's slot; a MEO ring's satellite halfway between the two ends. +function satLon(id,a,b){const B=SATS[id];if(B.orb==='geo')return B.lon;const r=Math.PI/180,A=CITY[a],C=CITY[b]; + return Math.atan2(Math.sin(A.lon*r)+Math.sin(C.lon*r),Math.cos(A.lon*r)+Math.cos(C.lon*r))/r;} +// Whether bird id sees city c. +function satSees(id,c){const B=SATS[id],C=CITY[c];if(!B||!C)return false;return B.orb==='meo'?Math.abs(C.lat)<=SAT_ORB.meo.lat:satArc(0,B.lon,C.lat,C.lon)<=B.r;} +function satPairOk(id,a,b){if(a===b||!satSees(id,a)||!satSees(id,b))return false;if(SATS[id].orb!=='meo')return true;const O=SAT_ORB.meo; + if(kmBetween(a,b)>O.km)return false;const lon=satLon(id,a,b);return [a,b].every(c=>satElev(satArc(0,lon,CITY[c].lat,CITY[c].lon),O.h)>=O.el);} +// The radio path: up from one dish and down to the other, the km the signal really travels. It is the link's km, so the +// routers' metric (pairW) sees a satellite as the long way round it is, and a cable wins whenever there is one. +function satKm(id,a,b){const h=SAT_ORB[SATS[id].orb].h,lon=satLon(id,a,b),A=CITY[a],C=CITY[b]; + return Math.round(satSlant(satArc(0,lon,A.lat,A.lon),h)+satSlant(satArc(0,lon,C.lat,C.lon),h));} +// One way: the radio path at the speed of light in vacuum, plus the modems at both ends. +const satLat=l=>l.km/SAT_C+SAT_ORB[SATS[l.bird].orb].proc; +const satMo=(id,g)=>Math.round(SAT_PROV[SATS[id].p].pg*Math.pow(g,0.85)/10)*10; +const satRemote=c=>{const C=CITY[c];return !!C&&(C.P<=SAT_TOWN_P||C.P<=SAT_ISLE_P&&!SAT_MAIN.includes(C.land));}; +const satName=l=>SATS[l.bird]?SATS[l.bird].n:'?'; +// A subsea cable: a satellite circuit is stored as sub (never a land route) but is no cable on the seabed. +const seaLink=l=>!!l.sub&&l.kind!=='sat'; diff --git a/src/game/60-features/10-banks.js b/src/game/60-features/10-banks.js index 7795eb3..774e7a3 100644 --- a/src/game/60-features/10-banks.js +++ b/src/game/60-features/10-banks.js @@ -34,7 +34,7 @@ const COVS={ logo:{l:tr('banks.our_logo_goes_on_every_router'),ok:()=>true}, cash50:{l:tr('banks.never_let_cash_drop_below_50k'),ok:()=>S.cash>=50000}, nochina:{l:tr('banks.stay_out_of_mainland_china'),ok:()=>!Object.keys(S.pops).some(cnCity)}, - nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(x=>x.sub).length<=(l.base&&l.base.sub||0)}, + nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(seaLink).length<=(l.base&&l.base.sub||0)}, spaetzle:{l:tr('banks.peer_at_the_spatzle_ix_in'),ok:()=>S.ixp.stg!==undefined}, kehrwoche:{l:tr('banks.do_the_kehrwoche_keep_your_noc'),ok:()=>!S.inc.some(i=>S.day-i.start>7)}, app:{l:tr('banks.download_our_app_and_enable_all'),ok:()=>true}, @@ -102,7 +102,7 @@ function callOffer(amount){const T=CALL_TERMS[rating()];if(!T||!CALL_AMTS.includ const RESCUE_APR=0.02,RESCUE_TERM=60; function rescueLoan(){const amount=niceAmt(Math.max(250000,-S.cash+Math.max(150000,(R.costMo||0)*2))); S.cash+=amount;S.stats.rescues=(S.stats.rescues||0)+1;S.neg=0; - S.loans.push({id:uid(),bank:'gov',start:S.day,amount,got:amount,bal:amount,apr:RESCUE_APR,apr0:RESCUE_APR,pay:Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)),left:RESCUE_TERM,term:RESCUE_TERM,share:0,covs:[],base:{sub:S.links.filter(x=>x.sub).length}}); + S.loans.push({id:uid(),bank:'gov',start:S.day,amount,got:amount,bal:amount,apr:RESCUE_APR,apr0:RESCUE_APR,pay:Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)),left:RESCUE_TERM,term:RESCUE_TERM,share:0,covs:[],base:{sub:S.links.filter(seaLink).length}}); track('rescue');toast(`${tr('banks.bank_stepped_in',{bank:esc(BANKS.gov.name)})}
${tr('banks.a_rescue_loan_of_amount_keeps',{amount:fmt$(amount),pay:fmt$(Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)))})}`,'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]);sfx('coin');} function loanTick(d){ // conditions: 15-day grace, then a penalty every 30 days while broken diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 17cebc0..f7e52ed 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -2,12 +2,12 @@ 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();}; -const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='xp'?xpHopG(l):l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; +const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='sat'?l.g:l.kind==='xp'?xpHopG(l):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.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 AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>seaLink(l)&&!!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. diff --git a/src/game/60-features/45-teleports.js b/src/game/60-features/45-teleports.js new file mode 100644 index 0000000..ff2b9a6 --- /dev/null +++ b/src/game/60-features/45-teleports.js @@ -0,0 +1,73 @@ +/* ---------- Teleports and rented satellite capacity (#83) ---------- + The rules, the money and save repair. Catalog and physics: 10-catalog/75-satellites.js; actions: 90-actions/87-teleports.js; + panels: 93-ui/72-teleport-panels.js. A circuit is a link (kind 'sat'): routing, standby, metrics and the map treat it like + any other, with the radio path as its km and its orbit's latency. */ +// A POP's teleport (S.pops[c].tele): 0 none, 1 dishes for GEO birds, 2 with tracking antennas for the MEO ring too. +const teleOf=c=>{const p=S&&S.pops[c];return p&&(p.tele===1||p.tele===2)?p.tele:0;}; +const teleCities=()=>Object.keys(S.pops).filter(teleOf); +// The birds that see city c, whatever your level. +const teleSees=c=>Object.keys(SATS).filter(id=>satSees(id,c)); +// Why no teleport can go up at city c (nothing on sale sees it at your level, or no POP); '' when it can. +function teleWhy(c){if(!isCity(c)||!S.pops[c])return tr('satellites.no_pop_in_city',{city:isCity(c)?CITY[c].name:'?'}); + if(lvl()lvl()>=SAT_ORB[SATS[id].orb].lv)){const O=SAT_ORB[SATS[ids[0]].orb];return tr('satellites.orbit_unlocks_at_level',{orb:O.n,lv:O.lv});} + return '';} +// Why the teleport at c cannot add MEO tracking antennas; '' when it can. +function trkWhy(c){const O=SAT_ORB.meo;if(lvl()SATS[id].orb==='meo'))return tr('satellites.meo_ring_misses_city',{city:CITY[c].name,lat:O.lat}); + return '';} +// The birds that see both ends of a circuit: GEO first, then the cheapest. +function satBirds(a,b){return Object.keys(SATS).filter(id=>satPairOk(id,a,b)).sort((x,y)=>(SATS[x].orb>SATS[y].orb)-(SATS[x].orbC.id!==a&&satRemote(C.id)&&(S.pops[C.id]||cityOn(C.id))&&satBirds(a,C.id).length).map(C=>C.id) + .sort((x,y)=>(!S.pops[x])-(!S.pops[y])||kmBetween(a,x)-kmBetween(a,y));} +// Your teleports that can reach city b. +const satFrom=b=>satRemote(b)?teleCities().filter(a=>a!==b&&satBirds(a,b).length):[]; +// A new link between a and b (a wave, fiber, a fabric circuit, a cable): the circuits already there go on standby beside +// it, as one ordered next to a link does, and the player hears about it. Without this the pair's load is shared with orbit. +function satBeside(a,b){const ls=pairLinks(a,b).filter(l=>l.kind==='sat'&&!l.standby);for(const l of ls)l.standby=true; + if(ls.length)toast(trn('satellites.n_circuits_go_on_standby',ls.length,{a:CITY[a].name,b:CITY[b].name}));return ls.length;} +// What the teleports and their circuits cost a month (R.cost.sat). +function satMoAll(){let m=0;for(const c in S.pops){const t=teleOf(c);if(t)m+=TPORT_MO+(t>1?TRK_MO:0);}for(const l of S.links)if(l.kind==='sat')m+=l.mo||0;return m;} +/* compute(): what users notice on the edges a satellite circuit is on. sv: the losses of the orbits there; sx: the edge's + latency is the satellite's (no cable carries ahead of it), so it is no haul to transit on the ground. Returns how many + edges there were, for compute() to know a satellite is in the picture at all. */ +function satEdges(SE){for(const e of SE){let ta=false,ts=false,act=false;const v=e.sv; + for(const l of e.links){const sb=!!l.standby;if(!sb)act=true;if(l.kind==='sat'){const x=SAT_ORB[SATS[l.bird].orb].loss;if(!v.includes(x))v.push(x);}else if(sb)ts=true;else ta=true;} + e.sx=act?!ta:!ts;} + return SE.length;} +// A flow of ok Gbps from city index ci crossed these edges: keep it, and what each orbit would cost it beyond the tl its +// haul to transit already does (users count the worse of the two, not both). +function satNote(se,ci,ok,tl){for(let k=0;ktl)a[1+j]+=ok*(v[j]-tl);}} +/* After routing: each orbit's share of the edge's traffic, split as compute() splits it (active links by capacity, standby + ones the overflow). A satellite on standby beside a cable that has room carries nothing and costs nobody anything; one + that takes the overflow, or shares the load, costs the users of that share. LATP gets the lost service and SATU the + Gbps that rode a satellite, by city index. */ +function satAfter(SE,LATP,SATU){for(const e of SE){const ld=e.ld||0;if(!e.sa||ld<=1e-9)continue; + const v=e.sv,sh=new Float64Array(v.length),ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;let only=true,all=0; + for(const l of e.links){if(l.kind!=='sat'){only=false;continue;}const c=capOf(l);sh[v.indexOf(SAT_ORB[SATS[l.bird].orb].loss)]+=(l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0))/ld;} + if(only&&v.length===1)sh[0]=1;for(let j=0;jr&&r.satU&&r.citySrv&&r.citySrv[c]>0?Math.min(1,(r.satU[c]||0)/r.citySrv[c]):0; +// Saves: a teleport is 1 or 2; a circuit needs a known bird that sees both POPs, a teleport able to work it, a size it sells. +function satSanitize(s){ + for(const c of Object.keys(s.pops)){const p=s.pops[c];if(p.tele!==undefined&&p.tele!==1&&p.tele!==2)delete p.tele;} + s.links=s.links.filter(l=>{if(l.kind!=='sat')return true;const B=typeof l.bird==='string'&&own(SATS,l.bird)?SATS[l.bird]:null,p=s.pops[l.a]; + if(!B||!p||!p.tele||B.orb==='meo'&&p.tele<2||!s.pops[l.b]||!satPairOk(l.bird,l.a,l.b))return false; + const G=SAT_ORB[B.orb].g;if(!G.includes(l.g))l.g=G.reduce((x,v)=>v<=num(l.g,0)?v:x,G[0]); + l.km=satKm(l.bird,l.a,l.b);l.sub=true;l.ready=num(l.ready,0);l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of ['tier','cable','trench','mult','border','premium','vt','prov','own','sys','ch'])delete l[k];return true;});} diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js index 3a4e1da..a190234 100644 --- a/src/game/60-features/50-traceroute.js +++ b/src/game/60-features/50-traceroute.js @@ -32,7 +32,7 @@ function traceroute(src,to,mode){mode=TR_MODES.includes(mode)?mode:'normal';cons for(const x of pieBhHops(e,h.from===b.city)){const ms=x.ms*2+0.05;if(x.k==='up')hop(`dish.${x.city}.${me}`,ip(hstr(x.city),5),ms,tr('traceroute.sky_up',{city:CITY[x.city].name,crust:tr(cr.n)})); else if(x.k==='las')hop(`laser.${b.cr}.${me}`,`10.255.${hstr(b.cr)%250}.${(x.km|0)%250}`,ms,tr('traceroute.sky_laser',{km:Math.round(x.km).toLocaleString()})); else hop(`dish.${x.city}.${me}`,ip(hstr(x.city),6),ms,tr('traceroute.sky_down',{city:CITY[x.city].name}));}continue;} - const lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.kind==='xp'?tr('express.trace_hop',{via:xpVia(l)}):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}}; + const lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.kind==='xp'?tr('express.trace_hop',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:satName(l)}):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}}; if(to.city){const path=P.path(to.city);lines.unshift(`traceroute to ${to.city}.${me} (${CITY[to.city].name}), 30 hops max`);if(!path){lines.push(' 2 * * * ← '+tr('traceroute.no_working_path_between_these_pops'));return {text:lines.join('\n'),why:tr('traceroute.no_path_every_route_between_these')};}walk(path);const bw=trBhWhy(bh,path);return {text:lines.join('\n'),why:bw+(S.te&&S.te.on?trn('traceroute.internal_path_over_n_link_chosen',path.length):trn('traceroute.internal_path_over_n_link_chosen_8620',path.length))};} const N=NET[to.net],ex=trExits(to.net).filter(e=>P.dist[e.city]!==undefined); lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`); diff --git a/src/game/60-features/85-pitcairn.js b/src/game/60-features/85-pitcairn.js index c220a47..ea026a9 100644 --- a/src/game/60-features/85-pitcairn.js +++ b/src/game/60-features/85-pitcairn.js @@ -1,12 +1,13 @@ /* Pitcairn (#124): no cable lands there yet, but you may land your own, and the UK pays a monthly grant while the - islanders are online through you: a POP with broadband, up and nearly fully served. */ -const GRANT_MO=300000; -const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9); + islanders are online through you: a POP with broadband, up and nearly fully served. The money is for a cable: with more + than GRANT_SAT of their traffic on a rented satellite circuit (#83) it never comes, however well MEO serves them. */ +const GRANT_MO=300000,GRANT_SAT=0.1; +const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9&&satShare(r,'pcn')<=GRANT_SAT); /* Satellite tier: Pitcairn online through your pies (its POP on backhaul, or home terminals there) is good enough for the UK at a lower bar, orbit's latency forgiven (sfOf() counts it, so the fiber grant never comes), for less money. */ const GRANT_SKY_MO=120000,GRANT_SKY_Q=0.9; function grantSky(r){if(!S||!S.pie||!r||!r.pie||grantOn(r))return false;const p=S.pops.pcn; if(p&&p.bb&&!(p.down>S.day)&&r.pie.bh.some(b=>b.city==='pcn'&&b.g>0)){const d=r.cityDem.pcn||0;if(d>1e-6&&(r.citySrv.pcn||0)/d>=GRANT_SKY_Q)return true;} return S.biz.some(b=>b.city==='pcn'&&b.type==='pizza'&&(r.pie.sf[b.id]||0)>=GRANT_SKY_Q);} -function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R); - return `${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}`;} +function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R),sat=!on&&!sky&&satShare(R,'pcn')>GRANT_SAT; + return `${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):sat?tr('pitcairn.uk_grant_needs_a_cable',{mo:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}`;} diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 3277d96..9f944c6 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -260,7 +260,7 @@ const OPS_RUN={ 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 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);} + decom(X){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'&&l.kind!=='sat'){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())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}, diff --git a/src/game/60-features/96-pop-standard.js b/src/game/60-features/96-pop-standard.js index 425caa5..752d2d0 100644 --- a/src/game/60-features/96-pop-standard.js +++ b/src/game/60-features/96-pop-standard.js @@ -116,7 +116,7 @@ function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J // the sizes these upgrades give: never pay a month's rent on one it is about to return. if(D.wv!=='keep'){for(const {l} of ls)if(l.kind==='wave'&&l.tierl.tier;t--){if(subWaveWhy(t,l.km,l.sub)||soldOut(l.a,l.b,t,l.cable)||!waveOk(l.a,l.b,t))continue;wv.set(l,t);break;} if(wv.size&&opsHired()&&S.ops.on.decom){const by=new Map(),cf=x=>wv.has(x)?capOf(x)*LT[wv.get(x)].g/LT[x.tier].g:capOf(x); - for(const x of S.links)if(x.kind!=='vxc'){const k=edgeKey(x);(by.get(k)||by.set(k,[]).get(k)).push(x);} + for(const x of S.links)if(x.kind!=='vxc'&&x.kind!=='sat'){const k=edgeKey(x);(by.get(k)||by.set(k,[]).get(k)).push(x);} for(const k of new Set([...wv.keys()].map(edgeKey)))for(const x of opsDecomPick(by.get(k),cf))wv.delete(x);}} for(const {l} of ls){const ch='l:'+l.id; if(l.kind==='wave'){const t=wv.get(l);if(t){const nm=Math.round(waveMo(l.km,l.sub,t)*(l.mult||1));job('fiber','wv',ch,l.a+'|'+l.b,nm,nm-(l.mo||0),()=>{ACT.upLink({id:l.id,tier:t});return l.tier===t;},{l});}continue;} diff --git a/src/game/60-features/99-pie-subsidies.js b/src/game/60-features/99-pie-subsidies.js index 6cd366d..703a46b 100644 --- a/src/game/60-features/99-pie-subsidies.js +++ b/src/game/60-features/99-pie-subsidies.js @@ -61,7 +61,7 @@ function pieEximOffer(d){const P=S.pie,G=P.gov;if(!P.fac||pieEximLoan()||!pieCan // Taking it: a loan like any other, plus its space covenants. function pieEximTake(){const P=S.pie,o=P.gov.ex;if(!o||pieEximLoan())return false;const pay=Math.round(annuity(o.amt,o.apr,o.term)); S.cash+=o.amt;S.stats.loans=(S.stats.loans||0)+1; - S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(x=>x.sub).length}, + S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(seaLink).length}, pie:{cc:o.cc,n:o.n,by:S.day+PIE_EXIM_BY,flown:0,br:0}}); P.gov.ex=null;track('loan_taken');return true;} // A breach (loanTick(), after the bank's own penalty): tighter terms, the launch target rescheduled, and a spat. diff --git a/src/game/80-simulation/10-dijkstra.js b/src/game/80-simulation/10-dijkstra.js index 5b53685..09df642 100644 --- a/src/game/80-simulation/10-dijkstra.js +++ b/src/game/80-simulation/10-dijkstra.js @@ -16,4 +16,4 @@ function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n) // The edges of a dijkstra() path back from city index B to A, and the cities on it (B first), as indices. function walkI(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni};} // The same for compute()'s sender, with the marks it keeps on a path (full, its latency, its far-exit traffic) there from the start: one object shape. -function walkP(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni,dead:0,ms:-1,fg:0};} +function walkP(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni,dead:0,ms:-1,fg:0,mt:0,se:null};} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 1a4cf12..8ad4924 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -29,12 +29,14 @@ function compute(){RW.gen++; 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. const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]); - const edges={},EA=[],TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={}; + const edges={},EA=[],TRX=teRules(),live=[];let NE=0,SE=null;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,RCON=RC.on,GK=RCON?rcGraphKey(pops,remote,EA):null, @@ -245,8 +247,11 @@ function compute(){RW.gen++; // 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 (#…). Under sender pays, // Korean users notice any exit far away, transit or not, and much sooner. - if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr)){let ms=P.ms;if(ms<0){ms=0;for(let k=0;k(kl?KR_LAT_OK:LAT_OK)){LATP[ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok; + // Over a satellite users notice too, whatever the exit: the path's edges with one (se) keep what this flow would lose + // on each orbit, and satAfter() charges the share the satellite really carried. The haul to transit counts on the ground (mt). + if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr||SATN)){if(P.ms<0){let ms=0,mt=0,se=null;for(let k=0;k(kl?KR_LAT_OK:LAT_OK)?(kl?krLatLoss(rtt):latLoss(rtt)):0; + if(tl>0){LATP[ci]+=ok*tl;if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}if(P.se)satNote(P.se,ci,ok,tl);}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok; // Where each flow left (the PNI list asks what a PNI here would take over, #175). if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);} if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}} @@ -339,8 +344,10 @@ function compute(){RW.gen++; if(DD){let rem=0,jf=0;for(let i=0;i1e-6)rem+=FREM[i];if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;} ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf), lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});} + // R.satU only when a circuit is in the graph, so R stays as it was for networks without one. + const SATU=SATN?new Float64Array(NC):null;if(SATU){R2.satU={};satAfter(SE,LATP,SATU);} for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i]; - if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);} + if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);if(SATU&&SATU[i]>1e-9)R2.satU[c]=SATU[i];} // Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did. {const G=new Map();for(let k=0;kcur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}} @@ -362,7 +369,7 @@ function computeMoney(R2,PX=null){ const C=R2.cost,V=R2.rev,pm=S.priceMul; C.pops=Object.entries(S.pops).reduce((a,[c,p])=>a+popMo(c)+((p.routers||1)-1)*ROUTER_MO+cageMo(p.routers)+(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.links=S.links.reduce((a,l)=>a+(l.kind==='sat'?0:l.mo||0),0);{const m=satMoAll();if(m)C.sat=m;} C.nni=(S.nni||[]).reduce((a,x)=>a+nniMo(x),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); diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index 87d5139..1a7e557 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -4,7 +4,7 @@ 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)];} // Cut, or cut off by an event between its two countries, whatever runs on it (an express asks this of each fiber it rides). function linkCut(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))));} -function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0)||(l.kind==='xp'&&xpDown(l));} +function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0)||(l.kind==='xp'&&xpDown(l))||(l.kind==='sat'&&l.ready>S.day);} 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. diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index ed6494c..3c25690 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -21,7 +21,7 @@ function sanitize(s){ 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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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!=='xp')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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;}); + s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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!=='xp'&&l.kind!=='sat')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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); xpSanitize(s); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its @@ -114,6 +114,7 @@ function sanitize(s){ specSanitize(s);mpSanitize(s); pieSanitize(s);pieIncFix(s); ip4Fix(s); + satSanitize(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 f48a5fd..f633eae 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -30,7 +30,7 @@ const LAND_X=45,landX=(a,b)=>!isSub(a,b)&&CITY[a].reg!==CITY[b].reg&&CITY[a].cc! function landMult(a,b){if(isSub(a,b))return 1;if(uaePair(a,b))return 3;return (landX(a,b)?LAND_X:1)*(andesPair(a,b)?2:1)*(nullPair(a,b)?NULLARBOR:1)*(rainPair(a,b)?2:1)*(borderPair(a,b)?2:1);} function landWhy(a,b){if(isSub(a,b))return '';if(uaePair(a,b))return tr('geography_and_latency.inside_the_uae_only_the_two'); const r=[];if(landX(a,b))r.push(tr('geography_and_latency.overland_between_continents_crosses',{x:LAND_X}));if(andesPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_andes_2'));if(nullPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_nullarbor_x',{x:NULLARBOR}));if(borderPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_a_border_in'));if(rainPair(a,b))r.push(tr('geography_and_latency.this_route_goes_into_the_amazon'));return r.join(' ');} -function linkLat(l){if(l.kind==='xp')return xpLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} +function linkLat(l){if(l.kind==='xp')return xpLat(l);if(l.kind==='sat')return satLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} /* Wave prices differ a lot by market (TeleGeography): Europe's dense, competitive metro and long-haul routes are cheap (Frankfurt–London 100G ≈ $1,150/mo), the US costs more, and routes into Africa are several times dearer (Africa–Europe ≈ 5.9× London–New York). diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index b4e3650..607cc6a 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -4,7 +4,7 @@ const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair( const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason(); function fireFailure(only){ const opts=[]; - const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; + const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; // A fiber that only carries expresses is dark as a link of its own, but there is light in it: a backhoe still finds it. const bare=S.links.filter(xpBare),dug=live.concat(bare); if(dug.length){opts.push(['cut',2+Math.min(6,dug.length/2)]);} diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 668478e..28d6afc 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -22,7 +22,7 @@ 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'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(l))).length<3){M.next=d+30;return;}mkArrive(d);return;} + if(!M.on){if(dl.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(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); @@ -30,7 +30,7 @@ function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint( 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'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(l)));if(!live.length)return; +function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(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; diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 7c2a989..ba7417b 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -81,7 +81,7 @@ function dayPost(d){ 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()45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='sat'&&!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(); // the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 80ec9fc..3bd9588 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -13,7 +13,7 @@ const ACT={ 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)}));} S.cash+=got;S.loanOffers=S.loanOffers.filter(x=>x!==o); - S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(x=>x.sub).length}}); + S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(seaLink).length}}); track('loan_taken');toast(`${tr('interface.amt_from_bank_has_landed',{amt:fmt$(got),bank:esc(B.name)})}
${B.equity?tr('interface.they_now_own_p_of_your',{p:pct(o.share)}):loanSummary(o)}${note}`,'good');sfx('coin');after();renderBank();}, callBank:({amount})=>{if(!callOffer(amount))return;track('loan_called');sfx('click');renderBank();renderHUD();save();}, declineLoan:({id})=>{S.loanOffers=S.loanOffers.filter(x=>x.id!==id);sfx('click');renderBank();renderHUD();save();}, diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index cf98a50..b99dcdf 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -14,13 +14,13 @@ Object.assign(ACT,{ myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name; S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();}, - buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); + buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return; if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;} const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;} {const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b)); if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);} - const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);closeModal(); + const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);satBeside(a,b);closeModal(); if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';} 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');after();}, // A new fabric port, or every member of one upgraded to a faster speed (#140): as fast as the router takes. @@ -36,7 +36,7 @@ Object.assign(ACT,{ openVxc:(a)=>openVxcModal(a), buyVxc:({a,b,prov,t})=>{t=+t;if(!CITY[a]||!CITY[b]||noTalk(a,b))return;const g=VXC[t].g,pa=nniPort(a,prov);if(!pa||nniUsed(a,prov)+g>nniCap(pa)+1e-9){toast(tr('links.not_enough_room_on_your_fabric'),'bad');sfx('err');return;} if(S.pops[b]){const pb=nniPort(b,prov);if(!pb||nniUsed(b,prov)+g>nniCap(pb)+1e-9){toast(tr('links.not_enough_room_on_your_fab',{fab:esc(FAB[prov].name),city:CITY[b].name}),'bad');sfx('err');return;}} - const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});closeModal(); + const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});satBeside(a,b);closeModal(); toast(tr('links.circuit_up_in_59_seconds_vxc',{vxc:VXC[t].n,fab:esc(FAB[prov].name),a:CITY[a].name,b:CITY[b].name})+(S.pops[b]?'':' '+tr('links.now_grab_an_ix_port_there')),'good');if(!S.pops[b])selectCity(b);after();}, 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>nniCap(pt)+1e-9){toast(tr('links.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);prunePairMet();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();}, diff --git a/src/game/90-actions/86-specialist.js b/src/game/90-actions/86-specialist.js index 089794d..5d1e315 100644 --- a/src/game/90-actions/86-specialist.js +++ b/src/game/90-actions/86-specialist.js @@ -3,7 +3,7 @@ Object.assign(ACT,{ 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};popStdApply(c);} - 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)}); + 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)});satBeside(o.a,o.b); 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();}, diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index 75b81db..d43e135 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -10,7 +10,7 @@ Object.assign(ACT,{ orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(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};popStdApply(b);} 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}`,id=uid(),ship=layName({id}),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}); + 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});satBeside(a,b); const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false; 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();}, @@ -20,7 +20,7 @@ Object.assign(ACT,{ if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),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}; - S.links.push(l);closeModal();UI.sel={type:'link',id}; + S.links.push(l);satBeside(a,b);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&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return; if(d<0&&((l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))||xpRegenBad(l,n))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;} diff --git a/src/game/90-actions/87-teleports.js b/src/game/90-actions/87-teleports.js new file mode 100644 index 0000000..542bde1 --- /dev/null +++ b/src/game/90-actions/87-teleports.js @@ -0,0 +1,27 @@ +// Teleports and satellite capacity (#83): build the gateway, rent circuits on its birds, resize them. Cancel is rmLink. +Object.assign(ACT,{ + teleBuild:({city})=>{const p=S.pops[city];if(!p||teleOf(city))return; + const why=teleWhy(city);if(why){toast(why,'bad');sfx('err');return;} + if(!spend(TPORT_COST))return;p.tele=1;toast(tr('satellites.teleport_up_in_city',{city:CITY[city].name}),'good');after();}, + teleTrk:({city})=>{const p=S.pops[city];if(!p||teleOf(city)!==1)return; + const why=trkWhy(city);if(why){toast(why,'bad');sfx('err');return;} + if(!spend(TRK_COST))return;p.tele=2;toast(tr('satellites.tracking_antennas_up',{city:CITY[city].name}),'good');after();}, + // Closing a teleport asks twice, and never while circuits still start there. + teleRm:({city})=>{const p=S.pops[city];if(!p||!teleOf(city))return;const n=S.links.filter(l=>l.kind==='sat'&&l.a===city).length; + if(n){toast(trn('satellites.cancel_n_circuits_first',n),'bad');sfx('err');return;} + if(UI.confirm!=='tele:'+city){UI.confirm='tele:'+city;renderPanel();return;} + delete p.tele;UI.confirm=null;toast(tr('satellites.teleport_closed',{city:CITY[city].name}));after();}, + satOpen:({a,b})=>satModal(a,b), + // Rent a circuit from teleport a to b: the first month up front, like a wave; a POP at b comes with it if there is none. + // Next to a link you already have between the two, it goes on standby: the backup that carries only when the cable is down. + buySat:({a,b,bird,g})=>{g=+g;const why=satWhy(a,b,bird,g);if(why){toast(why,'bad');sfx('err');return;} + if(!portGate(a,1)||!portGate(b,1))return;const mo=satMo(bird,g),pop=!S.pops[b];if(!spend(mo+(pop?popCost(b):0)))return; + if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);} + const sb=pairLinks(a,b).some(l=>l.kind!=='sat'),n=leadDays(SAT_ORB[SATS[bird].orb].days),id=uid(); + S.links.push({id,a,b,kind:'sat',bird,g,km:satKm(bird,a,b),sub:true,mo,cut:0,day:S.day,ready:S.day+n,...(sb?{standby:true}:{})}); + closeModal();UI.sel={type:'link',id}; + toast(trn('satellites.circuit_ordered',n,{cap:fmtCap(g),bird:esc(SATS[bird].n),a:CITY[a].name,b:CITY[b].name})+(sb?' '+tr('satellites.on_standby_beside_your_link'):''),'good');after();}, + // Bigger or smaller on the same bird: a bigger one pays its new month up front, as a wave upgrade does. + satSize:({id,g})=>{g=+g;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='sat'||g===l.g||!SAT_ORB[SATS[l.bird].orb].g.includes(g))return; + const mo=satMo(l.bird,g);if(g>l.g&&!spend(mo))return;l.g=g;l.mo=mo;sfx('click');after();}, +}); diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index e104b38..fd7fbd6 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -3,14 +3,14 @@ function cityPanel(c){ // 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`:''}
+
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}${grantFact(c)}${satFact(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)}

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

`:''}${(q=>btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)+(q?q.cost:0)),mo:fmt$(popMo(c)+(q?q.mo:0))}),'buildPop',{city:c},'pink big',S.cash${q.site2||q.gen?tr('pop_std.includes_the_build_standard',{list:esc(bstdPopParts({g:q.g,rt:q.rt,site2:q.site2,gen:q.gen}).join(', ')),cost:fmt$(q.cost),mo:fmt$(q.mo)}):tr('pop_std.includes_the_standard_n_model',{n:q.rt,model:esc(RG[q.g].n),cost:fmt$(q.cost),mo:fmt$(q.mo)})}

`:''))(popStdQuote())}

${tr('city_panel.or_drag_from_one_of_your')}

${opsTplHtml(c)}`}`; - h+=offersHere(c); + h+=offersHere(c)+satNoPop(c); const trs=NETS.filter(n=>sellsAt(n,c)); const fh=FABS.filter(f=>f.cities.includes(c)); if(ix&&fh.length){if(remoteCities().includes(c))h+=ixSection(c).replace('

'+tr('common.internet_exchange')+'

','

'+tr('city_panel.remote_peering_at_the_ix')+'

'); @@ -103,10 +103,11 @@ function cityPanel(c){ else h+=`
${NNI.map((N,i)=>portShown(i)?btn(tr('city_panel.port_port_price_mo_197d',{port:N.n,price:fmt$(N.mo)}),'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash`; h+=`
`;} h+=``;} + h+=teleHtml(c); h+=`

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

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

${tr('common.no_links_yet')}

`; for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l); - h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:esc(satName(l))})+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} h+=`
`; if(Object.keys(S.pops).length>1)h+=`

${tr('common.decommission')}

${tr('city_panel.shut_this_pop_down_its_links')}

${btn(tr('city_panel.decommission_city',{city:C.name}),'decomOpen',{city:c},'ghost sm')}${btn(tr('city_panel.decommission_several_pops'),'decomOpen',{},'ghost sm')}
`; } diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 200de31..48cb752 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -146,6 +146,7 @@ function offersHere(c){ function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} if(l.kind==='vxc')return vxcPanel(l); + if(l.kind==='sat')return satPanel(l); if(l.kind==='df')return dfPanel(l); if(l.kind==='xp')return xpPanel(l); const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk); diff --git a/src/game/93-ui/72-teleport-panels.js b/src/game/93-ui/72-teleport-panels.js new file mode 100644 index 0000000..1a7f3c8 --- /dev/null +++ b/src/game/93-ui/72-teleport-panels.js @@ -0,0 +1,60 @@ +// Teleports and satellite circuits on screen (#83): a POP's section, the order sheet, a circuit's panel. +const satLogo=P=>``; +// Round trip over bird id between a and b, in whole ms. +const satRtt=(id,a,b)=>Math.round(2*satLat({bird:id,km:satKm(id,a,b)})); +const satModalHead=(eye,title)=>`
🛰️ ${eye}

${title}

`; +// In a city's facts: its own users' traffic rides a satellite today (R.satU), and they count part of the service as bad (sfOf, R.latF). +const satFact=c=>R&&R.latF&&R.latF[c]<1&&R.satU&&R.satU[c]>1e-3?`🛰️ ${tr('satellites.users_ride_a_satellite')}`:''; +// The birds a dish at c sees, in words. +const satInView=c=>{const ids=teleSees(c);return ids.length?tr('satellites.in_view_list',{list:ids.map(id=>`${esc(SATS[id].n)} (${tr(SATS[id].sea)})`).join(', ')}):tr('satellites.no_bird_sees_this_city');}; +// In a POP's Infra tab: its teleport (build it, what it sees, its circuits), and the teleports that can reach it. +function teleHtml(c){if(pzOn())return '';const t=teleOf(c),from=satFrom(c),open=lvl()>=SAT_ORB.geo.lv;if(!t&&!open&&!from.length)return ''; + let h=`

🛰️ ${tr('satellites.satellites')}

`; + if(t){const out=S.links.filter(l=>l.kind==='sat'&&l.a===c),cf=UI.confirm==='tele:'+c,meo=teleSees(c).some(id=>SATS[id].orb==='meo'); + h+=`
${tr('satellites.teleport')}${t>1?tr('satellites.geo_dishes_and_meo_tracking'):tr('satellites.geo_dishes')} · ${tr('common.price_mo',{price:fmt$(TPORT_MO+(t>1?TRK_MO:0))})}
+
${satInView(c)}
`; + for(const l of out){const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0; + h+=`
→ ${CITY[l.b].name}${l.standby?' '+tr('common.standby')+'':''}
${capName(l)} · ${esc(satName(l))}${l.ready>S.day?' · '+tr('city_panel.ready_in_n_d',{n:l.ready-S.day}):''} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
${btn(tr('satellites.rent_satellite_capacity'),'satOpen',{a:c},'pink sm')}${t===1&&lvl()>=SAT_ORB.meo.lv&&meo?btn(tr('satellites.add_tracking_antennas_cost_mo',{cost:fmt$(TRK_COST),mo:fmt$(TRK_MO)}),'teleTrk',{city:c},'sm',S.cash + ${t===1&&lvl()${tr('satellites.meo_comes_at_level',{lv:SAT_ORB.meo.lv})}

`:''}`;} + // Before the build: what its dishes would see and reach at your level, and no button to a teleport that reaches nothing. + else if(open){const why=teleWhy(c),n=why?0:satTargets(c).filter(x=>satBirds(c,x).some(id=>lvl()>=SAT_ORB[SATS[id].orb].lv)).length; + h+=`

${tr('satellites.a_teleport_is_a_satellite_gateway')}

${satInView(c)}${why?'':' '+trn('satellites.n_places_in_reach',n)}
${why&&teleSees(c).length?`
${esc(why)}
`:''} +
${btn(tr('satellites.build_a_teleport_cost_mo',{cost:fmt$(TPORT_COST),mo:fmt$(TPORT_MO)}),'teleBuild',{city:c},'sm',S.cash`;} + if(from.length)h+=satReach(c,from); + return h+`
`;} +// Teleports that reach city c: a button each, to the order sheet. +const satReach=(c,from)=>`

${tr('satellites.reachable_from_your_teleports',{city:CITY[c].name})}

${from.slice(0,4).map(a=>btn(tr('fiber_modals.from_city',{city:CITY[a].name}),'satOpen',{a,b:c},'ghost sm')).join('')}
`; +// A city without a POP of yours, that a teleport of yours reaches: a POP and a circuit in one go. +function satNoPop(c){if(pzOn()||S.pops[c])return '';const from=satFrom(c);if(!from.length)return ''; + return `

🛰️ ${tr('satellites.by_satellite')}

${tr('satellites.no_cable_needed_a_pop_here',{city:CITY[c].name})}

${satReach(c,from)}
`;} +// The order sheet: from teleport a to b. With one end missing it lists the choices first. +function satModal(a,b){a=isCity(a)?a:null;b=isCity(b)?b:null; + if(!a&&b){const fr=satFrom(b);if(fr.length===1)a=fr[0]; + else{openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.to_city',{city:CITY[b].name}))+(fr.length?fr.map(x=>`
${CITY[x].name}
${tr('satellites.teleport')} · ${trn('satellites.n_birds_see_both',satBirds(x,b).length)}
${btn(tr('satellites.choose'),'satOpen',{a:x,b},'sm')}
`).join(''):`

${tr('satellites.no_teleport_reaches_city',{city:CITY[b].name})}

`));return;}} + if(!a||!teleOf(a))return; + if(!b){const ts=satTargets(a),mine=ts.filter(x=>S.pops[x]),more=ts.filter(x=>!S.pops[x]).slice(0,12); + const row=x=>`
${CITY[x].name}
${S.pops[x]?tr('common.your_pop'):tr('satellites.new_pop_cost',{cost:fmt$(newPopCost(x))})} · ${kmBetween(a,x).toLocaleString()} km · ${trn('satellites.n_birds_see_both',satBirds(a,x).length)}
${btn(tr('satellites.choose'),'satOpen',{a,b:x},'sm')}
`; + openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.from_city',{city:CITY[a].name}))+`

${tr('satellites.who_a_satellite_serves')}

` + +(mine.length?`

${tr('satellites.your_pops_in_view')}

`+mine.map(row).join(''):'')+(more.length?`

${tr('satellites.more_islands_and_towns')}

`+more.map(row).join(''):'')+(ts.length?'':`

${tr('satellites.nothing_in_view_from_here')}

`));return;} + const pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).some(l=>l.kind!=='sat'),birds=satBirds(a,b); + const rows=birds.map(id=>{const B=SATS[id],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],why=satWhy(a,b,id); + return `
${satLogo(P)}
${esc(B.n)} ${O.n}
${esc(P.n)} · ${tr(B.sea)} · ${tr('satellites.ms_round_trip',{ms:satRtt(id,a,b)})} · ${trn('satellites.up_in_n_days',leadDays(O.days))}
${esc(P.blurb)}
${why?`
${esc(why)}
`:''} +
${O.g.map(g=>btn(`${fmtCap(g)} ${tr('common.price_mo',{price:fmt$(satMo(id,g))})}`,'buySat',{a,b,bird:id,g},'sm',!!why||S.cash
`;}).join(''); + openModal(satModalHead(tr('satellites.satellite_capacity'),`${CITY[a].name} → ${CITY[b].name}`)+`

${tr('satellites.users_notice_geo_meo')}

` + +(pop?`

${tr('satellites.no_pop_there_yet',{city:CITY[b].name,cost:fmt$(pop)})}

`:'')+(sib?`

${tr('satellites.it_waits_on_standby')}

`:'') + +(rows||`

${tr('satellites.no_bird_sees_both',{a:CITY[a].name,b:CITY[b].name})}

`));} +// A circuit's panel: what it carries, its latency and rent, a size up or down, standby and the metric, cancel. +function satPanel(l){const B=SATS[l.bird],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],load=R.load[l.id]||0,cap=capOf(l),u=cap?load/cap:0,ms=satLat(l); + let h=`
🛰️ ${esc(B.n)} · ${O.n} · ${esc(P.n)}

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; + if(l.ready>S.day){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); + h+=`

${tr('satellites.being_commissioned')}

${tr('satellites.pointing_dishes_and_testing')}${tr('common.n_days_left',{n:l.ready-S.day})}
`;} + h+=`

${tr('common.capacity')}

${capName(l)}${l.standby?' · '+tr('common.standby'):''}${fmtG(load)} / ${fmtG(cap)}
+
${tr('common.latency')}${tr('satellites.ms_one_way_rtt',{ms:Math.round(ms),rtt:Math.round(2*ms)})}
+
${tr('satellites.radio_path')}${l.km.toLocaleString()} km
+
${tr('satellites.rent')}${tr('common.price_mo',{price:fmt$(l.mo)})}
+

${B.orb==='geo'?tr('satellites.geo_users_notice',{p:pct(O.loss)}):tr('satellites.meo_users_notice',{p:pct(O.loss)})} ${esc(P.blurb)}

+
${O.g.filter(g=>g!==l.g).map(g=>btn(`${g>l.g?tr('satellites.grow_to',{cap:fmtCap(g)}):tr('satellites.shrink_to',{cap:fmtCap(g)})} ${tr('common.price_mo',{price:fmt$(satMo(l.bird,g))})}`,'satSize',{id:l.id,g},'sm',g>l.g&&S.cash
+ ${trafficSection(l)}${metricSection(l)} +
${btn(UI.confirm===l.id?tr('common.really_cancel'):tr('common.cancel_circuit'),'rmLink',{id:l.id},'ghost sm')}
`; + return h;} diff --git a/src/game/94-dashboard/50-lease-swaps.js b/src/game/94-dashboard/50-lease-swaps.js index c5e56ab..c16c81f 100644 --- a/src/game/94-dashboard/50-lease-swaps.js +++ b/src/game/94-dashboard/50-lease-swaps.js @@ -10,7 +10,7 @@ function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L)-xpSlots for(const o in OPT){const O=OPT[o];if(O.lvl>glassLvl()||(O.sys==='roadm'&&!isRdm(L.sys))||[L.a,L.b].some(c=>S.pops[c]&&RG[S.pops[c].rgen||0].cls{const [a,b]=k.split('|'),sub=isSub(a,b),mo=ls.reduce((s,l)=>s+(l.mo||0),0),cap=leaseCap(ls); const x={a,b,sub,ls,mo,cap,opts:[],own:pairLinks(a,b).find(l=>l.kind==='df'&&l.own&&l.ready<=S.day)};if(x.own){x.fit=litOn(x.own,cap);if(x.fit.fits)x.best=mo;return x;} // Waves and fabric circuits can also move onto a leased fiber pair: cheaper glass, but you buy the gear. diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index b1ede29..1802e8f 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -9,7 +9,7 @@ function renderDash(){checkLayer();
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')} -

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; +

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row'),sat:tr('satellites.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0; // The legend above the table picks which ways in count; "lost" still looks at everything the network gets. diff --git a/src/game/94-dashboard/70-bank.js b/src/game/94-dashboard/70-bank.js index 72566a4..ee218dd 100644 --- a/src/game/94-dashboard/70-bank.js +++ b/src/game/94-dashboard/70-bank.js @@ -21,7 +21,7 @@ function renderBank(){ h+=CT?`
${tr('bank.bank_picks_up_apr_apr_over',{bank:esc(BANKS[CT.bank].name),apr:(CT.apr*100).toFixed(1),n:CALL_MONTHS,limit:fmt$(lim)})}
${CALL_AMTS.map(a=>btn(fmt$(a),'callBank',{amount:a},'sm',a>lim)).join('')}
`:`

${tr('bank.get_to_an_aa_rating_and')}

`;} h+=`

${tr('common.offers')}

`; if(!S.loanOffers.length)h+=`

${tr('bank.no_offers_right_now_banks_get')}

`; - for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`
${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}
${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}
${terms(o)}
${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(x=>x.sub).length}})}
${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}
`;} + for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`
${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}
${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}
${terms(o)}
${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(seaLink).length}})}
${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}
`;} h+=`

${tr('common.your_loans')}

`; if(!S.loans.length)h+=`

${tr('bank.debt_free_your_accountant_is')}

`; for(const l of S.loans){const B=BANKS[l.bank];const cost=repayCost(l,B); diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js index daf9830..ba12d8f 100644 --- a/src/game/95-modals/70-link-modal.js +++ b/src/game/95-modals/70-link-modal.js @@ -1,7 +1,7 @@ function openLinkModal(a,b){ {const nt=noTalk(a,b);if(nt){openModal(`

${tr('common.not_happening')}

${tr(nt)}

`);return;}} if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`

${tr('link_modal.not_without_a_license')}

${tr('link_modal.building_into_mainland_china_needs_a',{city:CITY[cnCity(a)?a:b].name})}

`);return;} - let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'); + let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'); if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),jn=sib.length?routeJoin(a,b):null,ts=landTrenches(a,b),mult=(sib.length&&!(jn&&jn.k===(ts[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(border)route+=`

${tr('link_modal.cross_border_circuits_into_mainland')}

${a==='hkg'||b==='hkg'?`
${btn(tr('common.regular_crossing'),'cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn(tr('link_modal.premium_crossing_60_3_loss'),'cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}
`:`

${tr('link_modal.premium_crossings_are_only_sold_in')}

`}`; if(sib.length&&!(isSub(a,b)&&cablesFor(a,b).length)&&!(UI.via&&UI.via!=='land'&&cablesFor(a,b).some(c=>c.cid===UI.via))){route+=`

${trn('link_modal.you_already_have_n_link_here',sib.length,{list:sib.map(l=>capName(l)).join(', ')})}

diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js index b0d354d..2ec50c9 100644 --- a/src/game/96-map/55-link-look.js +++ b/src/game/96-map/55-link-look.js @@ -5,9 +5,9 @@ const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12],[14,5]]; // A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; - const 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',xp=l.kind==='xp',bld=df&&l.ready>day,cut=!bld&&!xp&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length||xp&&linkDown(l),vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); + const 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',xp=l.kind==='xp',st=l.kind==='sat',bld=(df||st)&&l.ready>day,cut=!bld&&!xp&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length||xp&&linkDown(l),vx=l.kind==='vxc'||st,idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx||xp?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), - col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:xp?8:bld?3:idle?4:0, + col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?(st?SAT_PROV[SATS[l.bird].p].col:FAB[l.prov].col):l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:xp?8:bld?3:idle?4:0, pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills // The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the // links and with the day's routing (R), not with the camera, so it is kept until one of those changes. diff --git a/src/i18n/en.js b/src/i18n/en.js index 46cf379..4e8068b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3926,6 +3926,7 @@ "pie_traffic.via_dishes":"up at {up}, down at {down}", "pitcairn.uk_grant_mo":"UK grant {mo}/mo", "pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online", +"pitcairn.uk_grant_needs_a_cable":"UK grant {mo}/mo needs a cable: rented satellite capacity does not count", "pitcairn.uk_sky_grant_mo":"UK satellite grant {mo}/mo (fiber gets {full})", "pni_all.additional_per_month":"Additional monthly cost", "pni_all.all_at_port":"Peer all networks · {port}", @@ -4533,6 +4534,75 @@ "sales.w_last":"Last week {name} {list}.", "sales.w_now":"This week {name} {list}.", "sales.w_signed":{"one":"signed a customer ({rev}/mo)","other":"signed {n} customers ({rev}/mo)"}, +"satellites.a_teleport_is_a_satellite_gateway":"A teleport is a satellite gateway: big dishes at this POP that rent capacity on other people’s satellites, to small islands and remote towns no cable reaches, or that hang on one cable and a prayer.", +"satellites.add_tracking_antennas_cost_mo":"MEO tracking antennas {cost} + {mo}/mo", +"satellites.being_commissioned":"Being commissioned", +"satellites.build_a_teleport_cost_mo":"Build a teleport {cost} + {mo}/mo", +"satellites.by_satellite":"By satellite", +"satellites.cancel_n_circuits_first":{"one":"Cancel its satellite circuit first.","other":"Cancel its {n} satellite circuits first."}, +"satellites.choose":"Choose", +"satellites.circuit_ordered":{"one":"{cap} on {bird} ordered. {a} ⇄ {b} is being pointed and tested: up in {n} day.","other":"{cap} on {bird} ordered. {a} ⇄ {b} is being pointed and tested: up in {n} days."}, +"satellites.close_the_teleport":"Close the teleport", +"satellites.costs_row":"Teleports and satellites", +"satellites.geo_dishes":"GEO dishes", +"satellites.geo_dishes_and_meo_tracking":"GEO dishes and MEO tracking antennas", +"satellites.geo_users_notice":"From 36,000 km up the round trip is about 600 ms: video calls and games stutter, and users count {p} of the service as bad.", +"satellites.grow_to":"Grow to {cap}", +"satellites.in_view_list":"In view: {list}.", +"satellites.it_waits_on_standby":"You already have a link between these two: the satellite waits on standby and carries traffic only when that link is down.", +"satellites.its_blurb":"Old-school C-band and Ku-band beams that cover a whole ocean. Reliable, everywhere, and priced like it.", +"satellites.kac_blurb":"Ka-band spot beams over the western Pacific: the cheapest Gbps in orbit, if your island is under a beam.", +"satellites.meo_comes_at_level":"The MEO ring (about 130 ms round trip) comes at level {lv}.", +"satellites.meo_ring_misses_city":"The MEO ring does not see {city}: it covers {lat}° either side of the equator.", +"satellites.meo_users_notice":"Much closer to the ground, about 130 ms round trip: users barely notice ({p} of the service counts as bad).", +"satellites.more_islands_and_towns":"More islands and towns in view", +"satellites.ms_one_way_rtt":"{ms} ms one way, {rtt} ms round trip", +"satellites.ms_round_trip":"{ms} ms round trip", +"satellites.n_birds_see_both":{"one":"{n} satellite sees both","other":"{n} satellites see both"}, +"satellites.n_circuits_go_on_standby":{"one":"Your satellite circuit between {a} and {b} goes on standby beside the new link: it carries traffic only when that link is down.","other":"Your {n} satellite circuits between {a} and {b} go on standby beside the new link: they carry traffic only when that link is down."}, +"satellites.n_places_in_reach":{"one":"{n} island or remote town in reach at your level.","other":"{n} islands and remote towns in reach at your level."}, +"satellites.needs_tracking_antennas":"The MEO ring needs tracking antennas at your teleport in {city}.", +"satellites.new_pop_cost":"new POP {cost}", +"satellites.no_bird_sees_both":"No satellite on sale sees both {a} and {b}.", +"satellites.no_bird_sees_this_city":"No satellite on sale sees this city.", +"satellites.no_cable_needed_a_pop_here":"No cable needed: a satellite circuit from one of your teleports brings a POP in {city} online.", +"satellites.no_pop_in_city":"You have no POP in {city}.", +"satellites.no_pop_there_yet":"No POP in {city} yet: this builds one too ({cost}).", +"satellites.no_such_circuit":"No such satellite circuit.", +"satellites.no_teleport_in_city":"You have no teleport in {city}.", +"satellites.no_teleport_reaches_city":"None of your teleports can reach {city}. Build one at a POP whose satellites see it.", +"satellites.not_remote":"{city} is too big a market for satellite capacity: it serves small islands and remote towns.", +"satellites.nothing_in_view_from_here":"No island or remote town is in view from here.", +"satellites.on_standby_beside_your_link":"It waits on standby beside your link between the two and carries traffic only when that link is down.", +"satellites.orbit_unlocks_at_level":"{orb} satellites unlock at level {lv}.", +"satellites.out_of_footprint":"{bird} does not see both {a} and {b}.", +"satellites.pointing_dishes_and_testing":"Pointing dishes and testing", +"satellites.radio_path":"Radio path, up and down", +"satellites.reachable_from_your_teleports":"Your teleports can reach {city} by satellite:", +"satellites.really_close_it":"Really close it?", +"satellites.rent":"Rent", +"satellites.rent_satellite_capacity":"Rent satellite capacity", +"satellites.satellite_capacity":"Satellite capacity", +"satellites.satellites":"Satellites", +"satellites.sea_americas":"Americas", +"satellites.sea_atlantic":"Atlantic", +"satellites.sea_indian":"Indian Ocean", +"satellites.sea_pacific":"Pacific", +"satellites.sea_tropics":"within 50° of the equator", +"satellites.sea_west_pacific":"Western Pacific", +"satellites.sesa_blurb":"A ring of satellites 8,000 km up over the equator, for the other three billion. Open sesame: about 130 ms round trip.", +"satellites.shrink_to":"Shrink to {cap}", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"The teleport in {city} is closed.", +"satellites.teleport_up_in_city":"Teleport up in {city}. Big dishes on the roof, pointed at the sky: rent capacity from it to the islands in view.", +"satellites.teleports_unlock_at_level":"Teleports unlock at level {lv}.", +"satellites.tracking_antennas_up":"Tracking antennas up in {city}. They follow the MEO ring across the sky.", +"satellites.up_in_n_days":{"one":"up in {n} day","other":"up in {n} days"}, +"satellites.users_notice_geo_meo":"Users notice the lag: broadband over GEO counts as half the service, over MEO almost all of it. A cable always beats it, so your routers only send traffic up when there is no other way.", +"satellites.users_ride_a_satellite":"users ride a satellite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"Satellites serve small islands and remote towns that the same satellite sees as your teleport. Pick where to.", +"satellites.your_pops_in_view":"Your POPs in view", "save.cash_in_the_bank":"{cash} in the bank", "save.import_failed_err":"Import failed.
{err}", "save.load_name":"Load {name}?", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 7d1f3e3..c0bb94c 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -32,7 +32,7 @@ const EXCEPTIONS = { W3: { ivc: 'Invercargill waits for its AI campus; nobody sells transit there yet', jub: 'Nobody sells transit in Juba: MTN and Zain haul it in from abroad', - pcn: 'Pitcairn: no cable, no network, land your own (#124), or reach it with a pie dish (backhaul through orbit)', + pcn: 'Pitcairn: no cable, no network, land your own (#124), reach it with a pie dish (backhaul through orbit), or rent a satellite circuit from a teleport (#83)', prr: 'Prince Rupert is a remote town with no carrier in it', smr: 'San Marino buys its transit from Italian carriers in Bologna and Rimini; nobody sells it in the town', sre: "Sucre has no exchange or carrier facility: Bolivia's transit is bought in La Paz", @@ -118,6 +118,8 @@ const REAL_NAMES = [ 'ACMA', 'ASEAN Explorer', 'ASEAN Protector', 'ASEAN Restorer', 'Cable Innovator', 'Cable Retriever', 'Global Marine', 'Léon Thévenin', 'MECMA', 'Orange Marine', 'Pierre de Fermat', 'René Descartes', 'SEAIOCMA', 'Sophie Germain', 'Sovereign', 'Wave Sentinel', 'Yokohama Zone', // rockets and satellite networks (Pie in the Sky) 'Blue Origin', 'Falcon 9', 'Falcon Heavy', 'Iridium', 'Kuiper', 'OneWeb', 'Project Kuiper', 'SpaceX', 'Starship', 'Starlink', + // satellite operators and their birds (teleports, #83) + 'Galaxy 19', 'Intelsat', 'Intelsat 18', 'Intelsat 20', 'Intelsat 37e', 'Intelsat Galaxy 19', 'Kacific', 'Kacific-1', 'O3b', 'O3b mPOWER', 'SES', // vendors 'Arista', 'Brocade', 'Ciena', 'Cisco', 'Extreme Networks', 'Huawei', 'Infinera', 'Juniper', 'MikroTik', 'Nokia', ]; @@ -182,7 +184,7 @@ test('N2: names are puns: no network, cable, exchange, data center, router, opti const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim(); const real = new Set(REAL_NAMES.map(norm)); const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]), - ...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]]),...SHIPS.map(x=>['cable ship',x.n]),...LAY_SHIPS.map(n=>['cable ship',n]),...Object.values(SHIP_CLUBS).map(c=>['maintenance club',c.n]),...PIE_NAMES.map(n=>['rocket company',tr(n)]),...Object.values(ROCKETS).map(r=>['rocket',tr(r.n)]),...Object.values(CRUSTS).map(c=>['constellation',tr(c.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]]),...SHIPS.map(x=>['cable ship',x.n]),...LAY_SHIPS.map(n=>['cable ship',n]),...Object.values(SHIP_CLUBS).map(c=>['maintenance club',c.n]),...PIE_NAMES.map(n=>['rocket company',tr(n)]),...Object.values(ROCKETS).map(r=>['rocket',tr(r.n)]),...Object.values(CRUSTS).map(c=>['constellation',tr(c.n)]),...Object.values(SAT_PROV).map(p=>['satellite operator',p.n]),...Object.values(SATS).map(b=>['satellite',b.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'); }); diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 50bf647..ea139e8 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -228,6 +228,7 @@ test('a dry run prices every command that has a price, and changes nothing', () opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, ip4Buy: { len: 24 }, ip4Lease: { len: 22 }, + teleBuild: { city: 'fra' }, teleTrk: { city: 'fra' }, buySat: { a: 'fra', b: 'rek', bird: 'is37', g: 1 }, satSize: { id: wave, g: 2 }, }; const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required)); assert.deepEqual(missing, [], 'every priced command with arguments has a sample here'); diff --git a/tests/satellites.test.js b/tests/satellites.test.js new file mode 100644 index 0000000..01e26cb --- /dev/null +++ b/tests/satellites.test.js @@ -0,0 +1,445 @@ +// Teleports and rented satellite capacity (#83): a teleport at a POP rents GEO or MEO circuits to small islands and +// remote towns its birds see. A circuit is a link (kind 'sat'): its radio path is its km, so routers take a cable +// whenever there is one; its orbit's latency is what users notice; next to the island's only cable it waits on standby. +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 { createSession, TOOLS } = require('../scripts/lib/mcp-game'); + +const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); +// Level 3, Change Freeze (nothing breaks, lead times quick), plenty of cash. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();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');"; +// Sydney (transit, broadband) and Nuku'alofa (broadband, no transit of its own). +const ISLE = "ACT.buildPop({city:'syd'});ACT.launchBB({city:'syd'});ACT.buyTransit({city:'syd',net:'cog',tier:1});ACT.buildPop({city:'tbu'});ACT.launchBB({city:'tbu'});"; +function game(t, setup = '') { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev(BASE + setup); + return h; +} +const J = (ev, s) => JSON.parse(ev(`JSON.stringify(${s})`)); +const sat = "S.links.find(l=>l.kind==='sat')"; +// Past the day a circuit is commissioned. +const ready = `S.day=${sat}.ready;compute()`; + +test('the footprint: which birds see where, who a satellite serves, and how long the trip is', (t) => { + const { ev, errors } = game(t); + const sees = J(ev, "[['is18','syd'],['is18','tbu'],['is18','mia'],['is37','mia'],['is37','sju'],['kac1','tbu'],['kac1','hnl'],['is20','mru'],['o3b','tbu'],['o3b','yfb']].map(([b,c])=>CITY[c]?satSees(b,c):null)"); + assert.deepEqual(sees, [true, true, false, true, true, true, false, true, true, false], 'the Pacific bird does not see Miami, Kacophony’s spot beams miss Hawaii, the MEO ring misses Iqaluit'); + // Both ends of a MEO circuit must see one satellite at a time. + assert.ok(ev("kmBetween('sju','hnl')") > ev('SAT_ORB.meo.km') && !ev("satPairOk('o3b','sju','hnl')"), 'San Juan to Honolulu is too far apart for one MEO satellite'); + assert.equal(ev("satPairOk('is18','syd','tbu')"), true); + assert.deepEqual(J(ev, "['tbu','pcn','asp','sju','lon','syd','mel'].map(satRemote)"), [true, true, true, true, false, false, false], 'small islands and remote towns, never a big city'); + const geo = ev("satRtt('is18','syd','tbu')"), meo = ev("satRtt('o3b','syd','tbu')"); + assert.ok(geo > 520 && geo < 650, 'GEO: about 600 ms round trip, got ' + geo); + assert.ok(meo > 110 && meo < 160, 'MEO: about 130 ms round trip, got ' + meo); + assert.ok(ev("satKm('is18','syd','tbu')") > 2 * 35786, 'the radio path goes up to the GEO belt and back down'); + // A MEO satellite halfway between Winnipeg and Vaduz is below both horizons: within 7,500 km and 50 degrees is not enough. + assert.ok(ev("kmBetween('ywg','vdz')") <= ev('SAT_ORB.meo.km') && ev("satSees('o3b','ywg')&&satSees('o3b','vdz')")); + assert.equal(ev("satPairOk('o3b','ywg','vdz')"), false, 'Winnipeg to Vaduz: no MEO satellite sees both'); + assert.ok(ev("satElev(satArc(0,satLon('o3b','ywg','vdz'),CITY.ywg.lat,CITY.ywg.lon),SAT_ORB.meo.h)") < ev('SAT_ORB.meo.el')); + assert.ok(ev("satPairOk('o3b','syd','tbu')") && ev("satElev(0,SAT_ORB.meo.h)") === 90, 'straight overhead is 90 degrees'); + // Every MEO pair on sale clears the horizon at both ends, so its radio path never runs through the Earth. + const low = J(ev, "(()=>{const O=SAT_ORB.meo,out=[];for(const A of CITIES)for(const B of CITIES){if(A.id>=B.id||!satRemote(B.id)||!satPairOk('o3b',A.id,B.id))continue;const lon=satLon('o3b',A.id,B.id);for(const C of [A,B])if(satElev(satArc(0,lon,C.lat,C.lon),O.h)Object.keys(SATS).some(id=>SATS[id].orb==='geo'&&satSees(id,c)))"), [true, true, true, true, true, true]); + assert.deepEqual(errors, []); +}); + +test('a teleport and a GEO circuit: level, price, lead time, capacity, latency, the bill, resizing and cancelling', (t) => { + const { ev, errors } = game(t, ISLE); + ev("S.lvl=1;ACT.teleBuild({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 0, 'teleports unlock at level 2'); + ev('S.lvl=3'); + let c0 = ev('S.cash'); + ev("ACT.teleBuild({city:'syd'})"); + assert.equal(ev("S.pops.syd.tele"), 1); + assert.equal(c0 - ev('S.cash'), ev('TPORT_COST')); + c0 = ev('S.cash'); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:2})"); + const l = J(ev, sat); + assert.equal(l.bird, 'kac1'); + assert.equal(l.g, 2); + assert.equal(l.sub, true, 'never a land route'); + assert.equal(!!l.standby, false, 'alone between the two cities, it carries'); + assert.equal(c0 - ev('S.cash'), ev("satMo('kac1',2)"), 'no build: the first month up front'); + assert.equal(l.ready, ev('S.day+leadDays(SAT_ORB.geo.days)')); + ev('compute()'); + assert.equal(ev(`linkDown(${sat})`), true, 'down while it is pointed and tested'); + assert.equal(ev(`R.load[${sat}.id]||0`), 0); + ev(ready); + assert.equal(ev(`capOf(${sat})`), 2); + const ld = ev(`R.load[${sat}.id]`); + assert.ok(ld > 1 && ld <= 2 + 1e-9, 'the island’s traffic fills the circuit: ' + ld); + const ms = ev(`linkLat(${sat})`); + assert.ok(ms > 255 && ms < 310, 'one way over GEO: ' + ms); + assert.equal(ev('R.latF.tbu'), 0.5, 'broadband over GEO counts as half the service'); + assert.ok(ev("sfOf(R,'tbu')") <= 0.5); + ev("UI.sel={type:'city',id:'tbu'};UI.tab='cust';renderAll()"); + assert.match(ev("document.querySelector('#panel').textContent"), /users ride a satellite/, 'the island’s panel says why'); + assert.equal(ev('R.cost.sat'), ev(`TPORT_MO+${sat}.mo`), 'the teleport and the rent have a row of their own'); + assert.equal(ev("S.links.filter(l=>l.kind!=='sat').reduce((a,l)=>a+l.mo,0)"), ev('R.cost.links'), 'and are not in waves and fiber'); + // Bigger pays its month up front; smaller just costs less from now on. + c0 = ev('S.cash'); + ev(`ACT.satSize({id:${sat}.id,g:5})`); + assert.equal(c0 - ev('S.cash'), ev("satMo('kac1',5)")); + assert.equal(ev(`${sat}.mo`), ev("satMo('kac1',5)")); + c0 = ev('S.cash'); + ev(`ACT.satSize({id:${sat}.id,g:1})`); + assert.equal(ev('S.cash'), c0); + assert.equal(ev(`${sat}.g`), 1); + ev(`ACT.satSize({id:${sat}.id,g:3})`); + assert.equal(ev(`${sat}.g`), 1, 'only the sizes on sale'); + // Satellite capacity costs several times a subsea wave per Gbps, so a cable wins once there is one; the cheapest + // backup still fits inside what a small island's homes pay. + const wave = ev("waveMo(kmBetween('suv','tbu'),true,1)/LT[1].g"); + for (const id of ['is18', 'kac1']) assert.ok(ev(`satMo('${id}',10)/10`) > 3 * wave, id + ' per Gbps against a wave'); + assert.ok(ev("satMo('o3b',20)/20") > 3 * wave, 'MEO per Gbps against a wave'); + assert.ok(ev("satMo('kac1',1)") <= ev("CITY.suv.P*EYE_RATE"), 'a 1G backup costs less than Suva’s homes pay'); + // Cancelling asks twice. + ev(`ACT.rmLink({id:${sat}.id})`); + assert.ok(ev(`!!${sat}`), 'armed, not gone'); + ev(`ACT.rmLink({id:${sat}.id})`); + assert.equal(ev(`!!${sat}`), false); + assert.deepEqual(errors, []); +}); + +test('MEO needs tracking antennas and a higher level, and users barely notice it', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'o3b',g:5})"); + assert.equal(ev(`!!${sat}`), false, 'no tracking antennas yet'); + assert.match(ev("satWhy('syd','tbu','o3b',5)"), /tracking antennas/); + ev("S.lvl=2;ACT.teleTrk({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 1, 'MEO comes at level 3'); + ev('S.lvl=3'); + const c0 = ev('S.cash'); + ev("ACT.teleTrk({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 2); + assert.equal(c0 - ev('S.cash'), ev('TRK_COST')); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'o3b',g:5})"); + assert.equal(ev(`${sat}.bird`), 'o3b'); + assert.equal(ev(`${sat}.ready`), ev('S.day+leadDays(SAT_ORB.meo.days)')); + ev(ready); + const ms = ev(`linkLat(${sat})`); + assert.ok(ms > 55 && ms < 80, 'one way over MEO: ' + ms); + assert.ok(Math.abs(ev('R.latF.tbu') - 0.92) < 1e-9, 'MEO costs users 8% of the service, GEO half'); + assert.ok(ev("sfOf(R,'tbu')") >= 0.9, 'enough for broadband to keep growing'); + assert.equal(ev('R.cost.sat'), ev(`TPORT_MO+TRK_MO+${sat}.mo`)); + assert.deepEqual(errors, []); +}); + +test('orders outside a footprint, to a big city or without a teleport are refused, in words', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});ACT.buildPop({city:'mel'});ACT.buildPop({city:'sju'});"); + const tries = [ + ["{a:'syd',b:'tbu',bird:'is37',g:1}", /does not see both/], + ["{a:'syd',b:'sju',bird:'is18',g:1}", /does not see both/], + ["{a:'syd',b:'mel',bird:'is18',g:1}", /too big a market/], + ["{a:'tbu',b:'syd',bird:'is18',g:1}", /no teleport in Nuku/], + ["{a:'syd',b:'tbu',bird:'is18',g:3}", /No such satellite circuit/], + ["{a:'syd',b:'tbu',bird:'nope',g:1}", /No such satellite circuit/], + ]; + const c0 = ev('S.cash'); + for (const [a, why] of tries) { + const o = JSON.parse(ev(`JSON.stringify(${a})`)); + assert.match(ev(`satWhy(${JSON.stringify(o.a)},${JSON.stringify(o.b)},${JSON.stringify(o.bird)},${o.g})`), why, a); + ev(`ACT.buySat(${a})`); + } + assert.equal(ev("S.links.filter(l=>l.kind==='sat').length"), 0); + assert.equal(ev('S.cash'), c0, 'nothing charged'); + assert.deepEqual(errors, []); +}); + +test('beside the island’s only cable, a satellite waits on standby and takes over when the cable is cut', (t) => { + const { ev, errors } = game(t, "ACT.buildPop({city:'suv'});ACT.launchBB({city:'suv'});ACT.buyTransit({city:'suv',net:" + + "NETS.find(n=>sellsAt(n,'suv')).id,tier:1});ACT.buildPop({city:'tbu'});ACT.launchBB({city:'tbu'});UI.pending={a:'suv',b:'tbu'};ACT.buildLink({tier:1});ACT.teleBuild({city:'suv'});"); + const wave = "S.links.find(l=>l.kind==='wave')"; + assert.equal(ev(`${wave}.cable`), 'tonga', 'the wave rides the only cable'); + ev("ACT.buySat({a:'suv',b:'tbu',bird:'kac1',g:5})"); + assert.equal(ev(`${sat}.standby`), true, 'next to the cable it goes on standby by itself'); + ev(ready); + assert.equal(ev(`R.load[${sat}.id]`), 0, 'idle while the cable is up'); + assert.ok(ev(`R.load[${wave}.id]`) > 1); + assert.equal(ev('R.latF.tbu'), undefined, 'nobody notices a satellite that carries nothing'); + // The anchor drags across the cable: the satellite carries the island. + ev(`${wave}.cut=S.day+30;compute()`); + assert.ok(ev(`R.load[${sat}.id]`) > 1, 'the satellite takes over'); + assert.ok(ev('R.citySrv.tbu') > 1); + assert.equal(ev('R.latF.tbu'), 0.5, 'at GEO’s latency'); + // Without it, the island is dark. + ev(`S.links=S.links.filter(l=>l.kind!=='sat');compute()`); + assert.ok((ev('R.citySrv.tbu') || 0) < 1e-6, 'no satellite, no internet in Tonga'); + assert.deepEqual(errors, []); +}); + +test('a cable laid beside a circuit puts it on standby; overflow and a shared load cost users their share', (t) => { + // The issue's own order: the satellite first, a cable later. + const { ev, errors } = game(t, "ACT.buildPop({city:'suv'});ACT.launchBB({city:'suv'});ACT.buyTransit({city:'suv',net:" + + "NETS.find(n=>sellsAt(n,'suv')).id,tier:1});ACT.buildPop({city:'tbu'});ACT.launchBB({city:'tbu'});ACT.teleBuild({city:'suv'});"); + const wave = "S.links.find(l=>l.kind==='wave')"; + ev("ACT.buySat({a:'suv',b:'tbu',bird:'kac1',g:10});" + ready); + assert.equal(!!ev(`${sat}.standby`), false, 'alone, it carries the island'); + assert.equal(ev('R.latF.tbu'), 0.5); + ev("UI.pending={a:'suv',b:'tbu'};ACT.buildLink({tier:0})"); + assert.equal(ev(`${sat}.standby`), true, 'the cable puts it on standby'); + assert.match(ev("document.querySelector('#toasts').textContent"), /goes on standby beside the new link/); + ev('compute()'); + assert.equal(ev(`R.load[${sat}.id]`), 0, 'idle while the cable has room'); + assert.ok(ev(`R.load[${wave}.id]`) > 1); + assert.equal(ev('R.latF.tbu'), undefined, 'nobody notices'); + assert.equal(ev("R.satU.tbu||0"), 0); + assert.doesNotMatch(ev("traceroute('tbu',{city:'suv'}).text"), /Kacophony/, 'the trace takes the cable'); + // The cable loses three quarters of its light: the satellite takes the overflow, and users notice that share. + ev(`${wave}.loss={until:S.day+60,f:0.25};compute()`); + const cab = ev(`capOf(${wave})`), dem = ev('R.cityDem.tbu'); + assert.ok(dem > cab, 'more than the cable carries'); + const sl = ev(`R.load[${sat}.id]`), wl = ev(`R.load[${wave}.id]`), share = sl / (sl + wl); + assert.ok(Math.abs(wl - cab) < 1e-6 && sl > 0.5, 'the cable fills, the satellite takes the rest'); + assert.ok(Math.abs(ev('R.latF.tbu') - (1 - 0.5 * share)) < 1e-6, 'GEO costs half the service of the share it carries: ' + ev('R.latF.tbu')); + assert.ok(Math.abs(ev('R.satU.tbu') / ev('R.citySrv.tbu') - share) < 1e-6); + ev("UI.sel={type:'city',id:'tbu'};UI.tab='cust';renderAll()"); + assert.match(ev("document.querySelector('#panel').textContent"), /users ride a satellite/); + ev("UI.sel={type:'city',id:'suv'};renderAll()"); + assert.doesNotMatch(ev("document.querySelector('#panel .facts').textContent"), /users ride a satellite/, 'not on the teleport’s own city'); + // Taken off standby by hand, it shares the load by capacity, and users notice that share too. + ev(`ACT.setStandby({id:${sat}.id,on:false})`); + const s2 = ev(`R.load[${sat}.id]`) / (ev(`R.load[${sat}.id]`) + ev(`R.load[${wave}.id]`)); + assert.ok(Math.abs(s2 - 10 / (10 + cab)) < 1e-6, 'split by capacity'); + assert.ok(Math.abs(ev('R.latF.tbu') - (1 - 0.5 * s2)) < 1e-6); + assert.deepEqual(errors, []); +}); + +test('the teleport city’s own users get the satellite tag only when they ride it', (t) => { + // Honolulu: transit only in Los Angeles (a haul users notice), and a teleport carrying Papeete. + const { ev, errors } = game(t, "ACT.buildPop({city:'lax'});ACT.buyTransit({city:'lax',net:NETS.find(n=>sellsAt(n,'lax')).id,tier:1});ACT.buildPop({city:'hnl'});ACT.launchBB({city:'hnl'});" + + "UI.pending={a:'hnl',b:'lax'};ACT.buildLink({tier:1});ACT.teleBuild({city:'hnl'});ACT.buildPop({city:'ppt'});ACT.launchBB({city:'ppt'});ACT.buySat({a:'hnl',b:'ppt',bird:'is18',g:1});"); + ev('S.day=Math.max(...S.links.map(l=>l.ready||0))+1;compute()'); + assert.ok(ev(`R.load[${sat}.id]`) > 0.5, 'Papeete rides the satellite'); + assert.ok(ev('R.latF.hnl') < 1, 'Honolulu’s users notice the haul to Los Angeles'); + assert.equal(ev("R.satU.hnl||0"), 0, 'but none of their traffic goes up'); + assert.equal(ev("satFact('hnl')"), ''); + assert.match(ev("satFact('ppt')"), /users ride a satellite/); + assert.deepEqual(errors, []); +}); + +test('subsea counts leave satellites out: a no-subsea covenant and the cables overseas of Fibre to the Basement', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + ev("S.loanOffers.push({id:'wf1',bank:'wf',amount:200000,exp:S.day+25,covs:['nosub','logo','reach99'],apr:0.15,term:12,pay:Math.round(annuity(200000,0.15,12))});ACT.takeLoan({id:'wf1'})"); + const L = "S.loans.find(l=>l.id==='wf1')"; + assert.equal(ev(`COVS.nosub.ok(${L})`), true); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:1})"); + assert.equal(ev(`COVS.nosub.ok(${L})`), true, 'a satellite circuit is no subsea link'); + const bal = ev(`${L}.bal`); + ev('for(let i=0;i<40;i++){S.day++;loanTick(S.day);}'); + assert.ok(!(ev(`${L}.breach`) > 0), 'no breach'); + assert.ok(ev(`${L}.bal`) <= bal, 'no penalty'); + // A real subsea wave still breaks it. + ev("ACT.buildPop({city:'akl'});UI.pending={a:'syd',b:'akl'};ACT.buildLink({tier:1})"); + assert.equal(ev(`COVS.nosub.ok(${L})`), false); + assert.deepEqual(errors, []); +}); + +test('two satellite circuits are not two cables overseas in Fibre to the Basement', (t) => { + const { ev, errors } = game(t); + ev("ACT.startScn({id:'fttb'});S.cash=1e8;S.lvl=2;S.nextFail=S.nextEvent=1e9;ACT.teleBuild({city:'syd'});ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:1});ACT.buySat({a:'syd',b:'nou',bird:'kac1',g:1});"); + assert.equal(ev("S.links.filter(l=>l.kind==='sat').length"), 2); + ev('S.day=Math.max(...S.links.map(l=>l.ready||0))+1;compute()'); + assert.equal(ev('auExits()'), 0, 'no cable leaves Australia'); + assert.equal(J(ev, 'SCN_PROG.fttb()').find((r) => r.max === 2).v, 0, 'the progress row says so'); + assert.deepEqual(errors, []); +}); + +test('a teleport is offered only where a satellite on sale sees the POP, and tracking antennas only under the MEO ring', (t) => { + const { ev, errors } = game(t, "S.lvl=2;ACT.buildPop({city:'hpa'});ACT.buildPop({city:'chi'});ACT.buildPop({city:'lon'});"); + const panel = (c) => { ev(`UI.sel={type:'city',id:'${c}'};UI.tab='links';renderAll()`); return ev("document.querySelector('#panel').textContent"); }; + const disabled = (c) => ev(`(b=>!!b&&b.disabled)(document.querySelector('#panel [data-act="teleBuild"]'))`); + // Haparanda, by the Arctic Circle: nothing on sale sees it, and the panel says so before any money moves. + assert.match(panel('hpa'), /No satellite on sale sees this city/); + assert.equal(disabled('hpa'), true); + const c0 = ev('S.cash'); + ev("ACT.teleBuild({city:'hpa'})"); + assert.equal(ev("teleOf('hpa')"), 0); + assert.equal(ev('S.cash'), c0, 'nothing charged'); + assert.match(ev("teleWhy('hpa')"), /No satellite/); + // Chicago sees the bird over the Americas, and the panel says what is in reach before the build. + assert.match(panel('chi'), /In view: Intelsplat 19/); + assert.match(ev("document.querySelector('#panel').textContent"), /in reach at your level/); + assert.equal(disabled('chi'), false); + ev("ACT.teleBuild({city:'chi'})"); + assert.equal(ev("teleOf('chi')"), 1); + // London is north of the MEO ring: no tracking antennas there, at any level. + ev("S.lvl=3;ACT.teleBuild({city:'lon'})"); + assert.equal(ev("teleOf('lon')"), 1); + assert.ok(!J(ev, "(()=>{UI.sel={type:'city',id:'lon'};UI.tab='links';renderAll();return [...document.querySelectorAll('#panel [data-act]')].map(b=>b.dataset.act);})()").includes('teleTrk')); + const c1 = ev('S.cash'); + ev("ACT.teleTrk({city:'lon'})"); + assert.equal(ev("teleOf('lon')"), 1); + assert.equal(ev('S.cash'), c1); + assert.match(ev("trkWhy('lon')"), /does not see London/); + assert.equal(ev("trkWhy('chi')"), '', 'Chicago is under the ring'); + assert.deepEqual(errors, []); +}); + +test('the order sheet prices a new POP with your POP standard, as the list before it does', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});S.pops.syd.rgen=2;ACT.popStdSet({city:'syd'});"); + const std = ev('newPopCost("pcn")'); + assert.ok(std > ev('popCost("pcn")'), 'the standard adds routers'); + ev("ACT.satOpen({a:'syd'})"); + assert.ok(ev("document.querySelector('#modalCard').textContent").includes(ev(`fmt$(${std})`))); + ev("ACT.satOpen({a:'syd',b:'pcn'})"); + assert.ok(ev("document.querySelector('#modalCard').textContent").includes(ev(`fmt$(${std})`)), 'the same price one tap later'); + assert.deepEqual(errors, []); +}); + +test('MCP: dry runs for satellites quote what the game then does', () => { + const s = createSession(), T = (n, a = {}) => TOOLS.find((x) => x.name === n).run(s, a), ev = (x) => s.game.ev(x); + T('new_game', { city: 'syd', preset: 'sandbox', seed: 7, name: 'Probe' }); + ev('S.lvl=Math.max(S.lvl,3);S.cash=1e9'); + assert.deepEqual(T('act', { action: 'teleBuild', args: { city: 'syd' }, dryRun: true }).quote.blocked, []); + T('act', { action: 'teleBuild', args: { city: 'syd' } }); + assert.deepEqual(T('act', { action: 'teleTrk', args: { city: 'syd' }, dryRun: true }).quote.blocked, [], 'Sydney is under the MEO ring'); + assert.match(T('act', { action: 'teleTrk', args: { city: 'mel' }, dryRun: true }).quote.blocked.join(' '), /no teleport in Melbourne/); + T('act', { action: 'buySat', args: { a: 'syd', b: 'asp', bird: 'is18', g: 1 } }); + const id = ev("S.links.find(l=>l.kind==='sat').id"); + // A wave beside the circuit: no diversity premium, in the quote as in the bill. + const q = T('act', { action: 'buildLink', args: { a: 'syd', b: 'asp', tier: 1 }, dryRun: true }).quote; + const c0 = ev('S.cash'); + T('act', { action: 'buildLink', args: { a: 'syd', b: 'asp', tier: 1 } }); + assert.equal(q.setup, c0 - ev('S.cash'), 'quote equals charge'); + assert.equal(ev(`S.links.find(l=>l.id==='${id}').standby`), true); + // Resizing: only sizes the bird sells, and not the one it has. + for (const g of [20, 1]) { + const r = T('act', { action: 'satSize', args: { id, g }, dryRun: true }).quote; + assert.match(r.blocked.join(' '), /No such satellite circuit/, 'g ' + g); + } + const up = T('act', { action: 'satSize', args: { id, g: 5 }, dryRun: true }).quote; + assert.deepEqual(up.blocked, []); + const c1 = ev('S.cash'); + T('act', { action: 'satSize', args: { id, g: 5 } }); + assert.equal(up.setup, c1 - ev('S.cash')); + assert.deepEqual(s.errors(), []); +}); + +test('a satellite elsewhere is the long way round: routers use the cables and fall back to it only when cut', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.buildPop({city:'suv'});UI.pending={a:'syd',b:'suv'};ACT.buildLink({tier:1});UI.pending={a:'suv',b:'tbu'};ACT.buildLink({tier:1});ACT.teleBuild({city:'syd'});"); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'is18',g:5})"); + assert.equal(!!ev(`${sat}.standby`), false, 'no link between Sydney and Tonga: not on standby'); + ev(ready); + assert.ok(ev(`${sat}.km`) > 10 * ev("kmBetween('syd','tbu')"), 'its metric is the radio path'); + assert.equal(ev(`R.load[${sat}.id]||0`), 0, 'Tonga goes to Sydney over the cables, not the satellite'); + ev("S.links.find(l=>l.kind==='wave'&&(l.a==='tbu'||l.b==='tbu')).cut=S.day+30;compute()"); + assert.ok(ev(`R.load[${sat}.id]`) > 1, 'with the Tonga cable cut, the satellite carries it'); + // Nobody digs up a satellite: cuts land on the cables only. + ev("S.links.forEach(l=>l.cut=0);S.inc=[];for(let i=0;i<12;i++){fireFailure('cut');for(const l of S.links)if(l.kind!=='sat')l.cut=0;S.inc=[];}"); + assert.equal(ev(`${sat}.cut`), 0); + // The traceroute names the bird. + ev("S.links.find(l=>l.kind==='wave'&&(l.a==='tbu'||l.b==='tbu')).cut=S.day+30;compute()"); + assert.match(ev("traceroute('tbu',{city:'syd'}).text"), /via Intelsplat 18/); + assert.deepEqual(errors, []); +}); + +test('Pitcairn by satellite: a POP comes with the circuit, but GEO is not good enough for the UK grant', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + assert.equal(ev("!!S.pops.pcn"), false); + const c0 = ev('S.cash'); + ev("ACT.buySat({a:'syd',b:'pcn',bird:'is18',g:1})"); + assert.ok(ev('!!S.pops.pcn'), 'the order builds the POP'); + assert.equal(c0 - ev('S.cash'), ev("satMo('is18',1)+popCost('pcn')")); + ev("ACT.launchBB({city:'pcn'});" + ready); + assert.ok(ev('R.citySrv.pcn') > 0, 'the islanders are online'); + assert.ok(ev("sfOf(R,'pcn')") <= 0.5 + 1e-9); + assert.equal(ev('grantOn(R)'), false); + assert.equal(ev('R.rev.grant'), 0); + assert.deepEqual(errors, []); +}); + +test('Pitcairn over MEO serves the islanders well, but the UK pays its fiber grant only for a cable', (t) => { + const { ev, errors } = game(t, "ACT.buildPop({city:'akl'});ACT.launchBB({city:'akl'});ACT.buyTransit({city:'akl',net:NETS.find(n=>sellsAt(n,'akl')).id,tier:1});ACT.teleBuild({city:'akl'});ACT.teleTrk({city:'akl'});"); + assert.equal(ev("teleOf('akl')"), 2); + ev("ACT.buySat({a:'akl',b:'pcn',bird:'o3b',g:2});ACT.launchBB({city:'pcn'});" + ready); + assert.ok(ev('R.citySrv.pcn') > 0, 'the islanders are online'); + assert.ok(ev("sfOf(R,'pcn')") >= 0.9, 'MEO serves them nearly as well as fiber'); + assert.ok(Math.abs(ev("satShare(R,'pcn')") - 1) < 1e-9, 'all of it over the satellite'); + assert.equal(ev('grantOn(R)'), false, 'no fiber grant for a satellite'); + assert.equal(ev('R.rev.grant'), 0); + assert.match(ev("grantFact('pcn')"), /needs a cable/); + assert.deepEqual(errors, []); +}); + +test('saves: circuits survive a round trip, broken ones are dropped, and old saves load as they were', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});S.pops.syd.tele=2;ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:2});ACT.buySat({a:'syd',b:'tbu',bird:'o3b',g:5});"); + const before = J(ev, "S.links.filter(l=>l.kind==='sat')"); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.deepEqual(J(ev, "S.links.filter(l=>l.kind==='sat')"), before, 'kind, bird, size and dates kept'); + // Garbage in: an unknown bird, an odd size, a MEO circuit on a GEO-only teleport, a teleport that is not 1 or 2. + ev("S.links.push({id:'x1',a:'syd',b:'tbu',kind:'sat',bird:'nope',g:1,km:1,mo:1,cut:0});S.links.find(l=>l.bird==='kac1').g=7;S.links.find(l=>l.bird==='kac1').km=3;S.pops.tbu.tele='big'"); + ev('S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev("S.links.some(l=>l.id==='x1')"), false, 'an unknown bird is dropped'); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').g"), 5, 'an odd size becomes the largest size on sale under it'); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').km"), ev("satKm('kac1','syd','tbu')"), 'the radio path is the physics, not the save'); + assert.equal(ev("'tele' in S.pops.tbu"), false); + // A circuit's order day from a save: a number no later than today, so its commissioning bar is a real width. + ev("(k=>{k.day='junk';k.ready=S.day+5;})(S.links.find(l=>l.bird==='kac1'));S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').day"), ev('S.day')); + ev("S.links.find(l=>l.bird==='kac1').day=S.day+40;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').day"), ev('S.day'), 'not in the future'); + ev("delete S.links.find(l=>l.bird==='kac1').day;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + assert.doesNotMatch(ev("satPanel(S.links.find(l=>l.bird==='kac1'))"), /NaN/); + ev("S.pops.syd.tele=1;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.some(l=>l.bird==='o3b')"), false, 'a MEO circuit needs tracking antennas at its teleport'); + ev("delete S.pops.syd.tele;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.filter(l=>l.kind==='sat').length"), 0, 'no teleport, no circuits'); + // A save from before satellites: nothing about it changes, not even a row in the bill. + ev("S=migrate(JSON.parse(" + JSON.stringify(SAVE) + "));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()"); + assert.equal(ev("S.links.some(l=>l.kind==='sat')||Object.values(S.pops).some(p=>'tele' in p)"), false); + assert.equal(ev("'sat' in R.cost"), false); + assert.ok(ev('R.served') > 0); + assert.deepEqual(errors, []); +}); + +test('closing: a teleport with circuits stays open; closing the island or the teleport’s POP takes the circuit along', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:1});"); + ev("ACT.teleRm({city:'syd'});ACT.teleRm({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 1, 'not while a circuit starts there'); + ev("decommission(['tbu'])"); + assert.equal(ev(`!!${sat}`), false, 'the island’s POP takes its circuit along'); + ev("ACT.teleRm({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 1, 'the first tap only arms it'); + ev("ACT.teleRm({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 0); + ev("ACT.teleBuild({city:'syd'});ACT.buySat({a:'syd',b:'pcn',bird:'is18',g:1});decommission(['syd'])"); + assert.equal(ev("S.links.some(l=>l.kind==='sat')"), false, 'so does the teleport’s'); + assert.deepEqual(errors, []); +}); + +test('on a phone: the teleport section, the order sheet, a circuit’s panel and the map, at 360 px', (t) => { + const { ev, dom, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + ev('window.innerWidth=360;window.innerHeight=740;window.dispatchEvent(new window.Event("resize"))'); + assert.equal(ev('isPhone()'), true); + const text = (sel) => ev(`(document.querySelector('${sel}')||{}).textContent||''`); + const acts = (sel) => J(ev, `[...document.querySelectorAll('${sel} [data-act]')].map(b=>b.dataset.act)`); + ev("UI.sel={type:'city',id:'syd'};UI.tab='links';renderAll()"); + assert.match(text('#panel'), /Satellites/); + assert.ok(acts('#panel').includes('satOpen')); + // A city without a POP that the teleport reaches. + ev("UI.sel={type:'city',id:'apw'};renderAll()"); + assert.match(text('#panel'), /By satellite/); + ev("ACT.satOpen({a:'syd'})"); + assert.ok(acts('#modalCard').filter((a) => a === 'satOpen').length >= 2, 'a choice of destinations'); + ev("ACT.satOpen({a:'syd',b:'tbu'})"); + assert.ok(acts('#modalCard').filter((a) => a === 'buySat').length >= 8, 'every bird that sees both, every size'); + assert.equal(ev('document.getElementById("modal").hidden'), false); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:2});" + ready + ';renderAll()'); + assert.match(text('#panel'), /round trip/); + assert.ok(acts('#panel').includes('satSize') && acts('#panel').includes('rmLink')); + for (const s of ['#panel', '#modalCard', '#toasts']) assert.doesNotMatch(text(s), /satellites\.|undefined|NaN/, s); + // How the tube looks on the map: dashed like a virtual circuit, in the operator's colour; then a frame is drawn. + const look = J(ev, `(()=>{const L=linkLook([${sat}],S.day);return {dash:L.dash,col:L.col,w:L.w0};})()`); + assert.equal(look.dash, 2); + assert.equal(look.col, ev("SAT_PROV.kac.col")); + ev('draw(performance.now())'); + assert.deepEqual(errors, []); + assert.equal(dom.window.document.querySelectorAll('#panel').length, 1); +}); From b533f3baa8304269dde5749e63ed19355456f2d8 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:12:23 +0100 Subject: [PATCH 417/491] Plans: multiplayer phase 2 design, and what is left after this round --- docs/plans/multiplayer-phase2.md | 404 +++++++++++++++++++++++++++++++ docs/plans/next-session.md | 55 +++++ 2 files changed, 459 insertions(+) create mode 100644 docs/plans/multiplayer-phase2.md create mode 100644 docs/plans/next-session.md diff --git a/docs/plans/multiplayer-phase2.md b/docs/plans/multiplayer-phase2.md new file mode 100644 index 0000000..346e1c7 --- /dev/null +++ b/docs/plans/multiplayer-phase2.md @@ -0,0 +1,404 @@ +# Multiplayer phase 2: players inside each other's simulations + +Status: design only, not built. Phase 1 (sessions, server-side saves, leaderboard) is in `docs/MULTIPLAYER.md`. + +**Conventions:** +- Line numbers are `main` at `1e7638c`. +- Phase 1 (multiplayer sessions, merged on `main`) provides `S.mp`, `MP`, `mpCard`/`mpCardOk`, and `cleanCard` in `scripts/lib/mp.js`. +- Everything runs only when `MP_API` is stamped and `S.mpx` is not null. The plain GitHub Pages build is unchanged (`pages.test.js`, `build.test.js`). + +## 1. Starting point and grafts + +**Base: "contracts".** It had the best totals in two of the three scorings, and the best feasibility and risk. +- Players are pseudo carriers `mp:`, registered only in `NET` with single-entry `CONE`/`CONE_S`/`DOWN`/`ANC`. +- `NETS`, `NET_IDS`, `NSH`, `t1Need()`, seen/grace and the gameplay-rules tests never see a player. +- No catalog id contains `:`, and nothing iterates `NET`. + +**I checked this on big-network** (a throwaway probe, not committed): a buyer row on `mp:p1` in `S.transit` plus a player PNI, through `compute`, 5 day ticks, the intern, every panel and tab, traceroute, `t1Why`/`isTier1` and a `migrate` round trip. + +Results: +- No errors anywhere. +- The rows were kept while registered and dropped once unregistered. +- Warm compute went from 32.3 to 33.2 ms (median of 25 alternating runs). +- `R.sessions` rose by 1. That confirms the exploit fixed below. + +**How each fatal flaw the judges found is removed:** + +| Judged flaw | Fix | +|---|---| +| The seller's `S.biz` row is exposed to dropBiz, decommission, ddosTargets, Pie moods and the mood loop | The seller side is a deal entry read in exactly two places, demand and money (nets) | +| Peering is cosmetic, yet player PNIs count toward `isTier2`/`t1Club` | Player traffic ships with peering (§2.3). Player sessions never enter `R.sessions` | +| Health is all or nothing, and bought transit reaches every network | A capacity factor (`t.mpf`) and a `miss` id list, from day one | +| A↔B transit loops | The server refuses with 409; clients drop loop links in a fixed pid order (nets) | +| A stale or alt buyer keeps paying the commit forever | The seller earns, and carries load, only while the buyer's clock runs. Prices are capped against the catalog | +| A bought wave can be upgraded past its agreed price | `upLink`/`rmLink`/`setStandby` refuse it (gameplay) | +| "An active deal with no row" is ambiguous | A per-deal `made` flag (§5) | +| `NKN` flips inside `compute()` | It is always `NN+4` | + +**Grafted from the other designs:** +- From nets: the two-sided route-server rule; cones through players; PNI lead from `hstr`, with capacity set by the smaller side; the Tier 1 clique star. +- From gameplay: waves, tenders, poaching, consortium seats, notice on each player's own clock, and the LOA handshake. + +**Rejected:** players as `NETS` entries (a mutable catalog, a rescaled `NSH`), reach bitmaps (they break between builds), a Tier 1 that depends on other players, automatic ratio strikes, and own-day timers that end a deal (they fire within seconds at 8×; own-day notice only paces each side's own teardown). + +## 2. Mechanics + +### 2.1 Pseudo carriers (`src/game/30-networks/45-player-carriers.js`, new) + +`mpBind(s)` does three things: +1. deletes every `mp:*` key; +2. registers `{id:'mp:'+pid, name, asn, type:'t2', pol:'open', share:0, price:1, pops:[], up:[], ix:[], cc:'', col, blurb:tr('mp.another_player'), mp:1}` for each `s.mpx.who` entry; +3. sets `MPB.k`. + +It runs at the start of every `sanitize` and every `compute()` (`if(MPB.k!==(S.mpx?S.mpx.k:''))mpBind(S)`). That covers the route worker, slot switches, imports, the failed-load rollback (`91-slots.js:105`) and puzzles. `nocWinState` (`94-dashboard/90-noc-window.js:45`) calls it too. + +Because the carrier has `pops:[]` and is not in `NETS`, no catalog list ever offers a player: +- `sellsAt` and `buyTransit`; +- the intern's providers, `peerAll` and `pniAll`; +- the peering desk and own-exchange joins. + +The `peer` action returns at `ixMembers(city).includes(net)` (`40-sites-peering-caches.js:14`). + +### 2.2 Transit between players (the Tier 1 endgame) + +**Who can sell:** a player publishes `tp` ($/Gbps/month) while `R.reach >= 0.99` and they have at least one POP. + +**Buying:** "Buy transit from X here" posts a `t` deal (city, tier, LAG). The server makes it `live` at once (a price list is a standing offer) when all of these hold: +- the seller's card has `tp`; +- both cards list the city; +- there is no cycle; +- the limits hold. + +**Price:** `min(tp, mpCap(city))`, where `mpCap = 2 × the cheapest catalog transitPerG(n,city,false)` there, or the catalog median if nobody sells there. +- Both sides compute it from the static catalog, ignoring each save's own `priceMul`. +- Both clamp again when they receive the deal. + +**Buyer side: an ordinary `S.transit` row** `{id:'mt-'+deal, net:'mp:'+seller, city, tier, n, mp:deal, mpp:price}`. +- **Comes free:** the router port (`40-ports.js:20`), p95 history (`10-day-tick.js:37`), hot ports, traceroute, incidents, the panels, and `isTier1()===false`. +- **Billing:** `transitMo` (`40-billing.js:9`) uses `t.mpp` instead of `transitPerG(...)*S.priceMul`. The commit floor, `PORT.tmo` and `krFee` still apply. +- **Capacity:** `30-compute.js:53` multiplies by `t.mpf` = min(1, the seller's `sv[city]`/0.95), in 0.05 steps. +- **Reach:** `:54`'s `ok` also needs `!mm.has(n)` (the seller's `miss`). +- **Route cache:** the hash of every miss set joins the flags at `:70` (`+(S.mpx?S.mpx.xk:'')`), so `rcExitKey` rebuilds when a seller's reach changes. +- **Outage:** `t.down=S.day+1` when the seller's POP is down or the seller has left. + +**Seller side: a `sell` entry in `S.mpx.deals`, never in `S.biz`.** +- **Load:** `mpDem(bizBw)` after the biz loop (`:95`) adds `u`, the buyer's reported use. It leaves by catalog share over the seller's own backbone, peering and upstreams; a Tier 1 carries it settlement-free. +- **Money:** `V.mp = Σ price × max(q, 20% of port) × min(1, sfOf(R2,city)/0.95)`. `q` is the buyer's p95; the last factor is the business customers' SLA credit. `V.mp` is added to `revMo` (`:382`) and to the revshare base (`:380`). +- **Port:** the seller's port counts in `portsUsed` (`10-catalog/40-ports.js`, after `:21`). +- **Idle buyer:** if the buyer's roster `idle` is ≥ 300 s (no newer game day reached the server), load and revenue are 0. + - A paused or closed buyer has no traffic to bill, and a fast seller cannot bill a frozen buyer. + - An alt account has to keep playing, and still pays at most the capped price. + +**Loops:** +- The server returns 409 `loop` if the seller already buys from the buyer, directly or through others (a search over at most 12 players). +- Clients build the player-transit graph from `who[].pt` and add edges sorted by (buyer pid, seller pid), dropping any that closes a cycle, so every client drops the same edge. +- So reach passes down a reseller chain one push per hop, never settling at a false 1. + +**Tier 1 stays defined by the built-in networks.** +- `R.reach` only sums `NSH`, so neither `isTier1` (`80-hot-ports-and-rank.js:20`) nor the mood check `R.reach>0.99` (`10-day-tick.js:51`) can depend on players. +- Buying player transit costs Tier 1, and `t1Why` already says so. Selling never does. +- Refusing to peer blocks nobody's win. + +### 2.3 Peering between players, carrying traffic + +**PNI (`pni` deal, always accepted by hand).** Each side adds `S.pni` `{id:'mn-'+deal, net:'mp:'+other, city, tier, n, mp:deal, ready:S.day+lead}`. +- **Lead time:** `lead = pniNow() ? 0 : leadDays(14 + hstr(deal+myPid) % 29)`, with no random numbers. +- **Cost:** each side pays its own `pniMo`. +- **Capacity:** the smaller of the two sides (theirs comes from `dl[].g`). It is 0 until both cards report `ok`: the LOA and cross-connect handshake. + +**IX (`ix` deal).** The server makes it `live` if the responder's policy is open, `no` if closed, and `offer` if selective. Once live, both sides set `S.peers['mp:P@x']`. + +**Route server:** no deal. P peers with me at `x` when both `S.rs[x]` and `P.rs ∋ x` hold and both policies are open. That is the same rule on both clients. + +**Sessions:** +- `mpIx(x)` lists the player peers at an exchange. `ixSessions` (`20-exchanges.js:29`) stays catalog-only. +- At `30-compute.js:61`, player PNIs skip `R2.sessions++` (`if(!p.mp)`) and count in `R.mpSess` instead. +- So friends can never inflate `isTier2`/`t1Club`. + +**Player traffic** (new `src/game/80-simulation/36-mp-traffic.js`). `compute.js:343` calls `mpTraffic({E,SPP,NRES,HAS,R2,carry,NN})` once, after `citySrv` (`:341-342`). The parts are handed in the way `ddosLoad` gets them (`:188`). +- **Demand:** each POP sends `cityEye[c]·w_P` to each active player P. + - `w_P = min(0.02, (biz_P + 0.3·eye_P)/75000)`, and `Σw ≤ 0.1`. +- **Exits that reach P:** + - rank 2: a ready PNI with P, or an IX exit with `mpIx(x) ∋ P`; + - rank 2.5: the same exits toward Q when P buys from Q, which gives cones through players; + - rank 3: player transit from Q when `P===Q` or `Q.mr ∋ P`, and catalog transit when `P.on`; + - `pref:'low'` moves an exit to rank 4. +- **Pushing:** exits are sorted by distance once per POP. Traffic goes along `walkI(SPP[c],ci,e.ci)` and is limited by `l.res`, `NRES` and `e.cap-e.used`. +- **Recording:** each push calls `carry(l,e.ek,NN+3,…)`. `NKN` is always `NN+4` (`:130`), and that column is named `'players'` at `:16`. +- **Effects:** + - Transit p95, hot ports and link loads include player traffic, so peering saves transit money. + - `R2.mp={dem,srv,peer,lost,full,by}` records the totals. + - The pass runs after every catalog flow, so `R.served`, `R.demand`, moods, levels, `peerShare` and Tier 1 never change. + +**Cost of a de-peering war:** +- `computeMoney` applies `V.eyeballs *= 1 - mp.lost/(demand+mp.dem)`, where `lost` is traffic with no route at all. +- Two transit-free Tier 1 players who won't peer cannot reach each other: catalog Tier 1s don't pass on routes they learn from peers. Each loses up to 2% of eyeball revenue, which is real Level 3 vs Cogent drama at a bounded cost. Neither loses Tier 1. +- Two eyeball players who don't peer pay transit p95 for each other's traffic. + +**Clique star (cosmetic):** card `cq=1` when you are Tier 1 and reach every player whose card says `t1` by your own PNI or IX session. The leaderboard sorts the star first. + +**De-peering:** `end` the deal. Each side removes its rows 7 own days after it first sees the end. + +### 2.4 Competition + +**Overlap:** `clComp` (`75-customer-lifecycle.js:30`) also counts rival players whose card POPs cover the customer's cities. The rolls stay hash-stable (`clR`). + +**Poaching:** +- `clLeave` (`:64`), for "cheap" or "multi" with a rival POP in the city, posts the customer to `/lost`. +- The server gives it to one rival, chosen by `hstr`, as a gift. +- The rival checks it with `okBiz`, `BIZ_T` and `rate ≤ catalog×mkt()×1.2`, then puts it in `S.offers` with `ref` set to the loser's name. + +**Tenders:** +- **Issue:** while at least two players are active (`idle` < 300 s), the server issues `{n, city}` every 5 real minutes. The city is seeded from the active players' POPs. +- **Content:** derived from `hstr(seed|n)` and the `BIZ_T` lists, so every client sees the same tender. +- **Bids:** a ratio r from 0.6 to 1.0. You can bid while paused, and an optional standing auto-bid covers your cities. +- **Closing:** after 10 real minutes, or once every active player has bid. Wall-clock time, because no game clock is shared. +- **Winner:** the best `(1.2-r)·sq`, where `sq` is served share. The tender goes into `S.offers` with `mp:1`, expiring in 10 own days, and is signed with the normal `accept`. + +### 2.5 Shared fiber + +**Waves and IRUs (`wave`/`iru` deals):** +- **Seller side:** books spectrum or pairs via `+mpSold(l.id)` in the three counters (`60-requirements.js:72,75`, `37-fiber-broker.js:16`). It earns `V.mp += rate×(fiberOk?1:0)`. +- **Buyer side:** an `S.links` row `{kind:'wave'|'df', own:false, mo:price, mp:deal}`, which copies cut/eqDown/ready from `dl`. + +**Consortium seats:** built like `seatBuy` (`86-specialist.js:4`), at `ownCabCost(km)×myPairs/totalPairs` (`36-specialist.js:54`). + +**Deferred:** +- Joint exchanges, which need an id namespace (`isIx`, `50-sanitize.js:2`). +- An opt-in "Tier 1 must reach every Tier 1 player" rule. + +## 3. Server (`scripts/lib/mp-deals.js`, pure logic, with routes in phase 1's `scripts/lib/mp.js`) + +**The deal record** is public to the session, like PeeringDB. The session keeps a counter `dv`, bumped on every change. + +``` +{id:'d'+base36, k:'t'|'pni'|'ix'|'wave'|'iru', a, b, s (seller), at (city|ix|'a|b'), tier, n, price, slots, st, rev, t0, tl, te, by, why} +``` + +| from | event | to | allowed for | +|---|---|---|---| +| – | create `t` | `live`, or 409 `not_selling`/`no_pop`/`loop`/`dup`/`limit` | the buyer | +| – | create `ix` | `live` (b open and present) / `no` (b closed) / `offer` | a | +| – | create `pni`/`wave`/`iru` | `offer` | a | +| `offer` | accept / decline / withdraw / 7 days pass | `live` / `no` / `gone` / `gone` | b / b / a / server | +| `live` | end | `end` (`quit`) | a or b | +| `live` | a side's card never reports `ok` within 7 days | `end` (`unbuilt`) | server | +| `live` | no card from a party for 14 days | `end` (`idle`) | server | +| any open deal | a party leaves or is pruned | `end` (`left`) | server | +| `no`/`gone`/`end` | 7 days pass | deleted | server | + +**Errors:** every write sends `rev`. A stale `rev` or an illegal transition gets 409, and the wrong party gets 403. + +**Limits:** +- one open deal per (pair, kind, place); +- 10 open offers and 24 live deals per player; +- 300 deals per session; +- price 0.05–50, tier 0–15, n 1–8; +- 30 writes per minute per player. + +**Feed:** the server writes a line for each transition ("X sells transit to Y in Frankfurt", "X de-peered Y"). + +**Endpoints:** +- `POST /api/mp/sessions/:code/deals {k,to,at,tier,n,price?,slots?}` returns 201 `{deal,dv}`. +- `POST …/deals/:id {op,rev}` with `op` one of accept, decline, withdraw or end. +- `POST …/lost` reports a lost customer; `POST …/tenders/:n/bid {r}`; `PUT …/autobid`. +- The roster responses (`GET` the session, and `PUT` the card or save) add: + - `deals[]` (my deals, any state) and `dv`. Other players' links come from their cards' `pt`; + - `tenders[]` and my `gifts[]`; + - each player's `idle`: seconds since their card last carried a newer day. + +So nothing needs extra polling. + +## 4. Card fields beyond phase 1 + +Every field below is added to both `cleanCard` and `mpCardOk`. Phase 1's `transit` field stays catalog-only, because `NET_RE` would silently drop `mp:` ids. + +| field | content | +|---|---| +| `nv` | build version | +| `pt` | pids I buy transit from | +| `rs` | exchanges with my route server on | +| `tp` | my transit price, or null | +| `miss` | catalog ids I can't reach, biggest share first, ≤160 (a reach of 0.99 can still miss 72) | +| `on` | 1 if the internet of built-in networks can reach me: catalog transit, PNIs with every `t1Need()` network, or a seller with `on` | +| `mr` | pids I reach | +| `eye`, `biz` | Gbps, 2 significant digits | +| `sq` | served share | +| `sv` | `{city: delivered share}` where I sell, ≤64, in 0.05 steps | +| `dl` | `[{id,u,q,g,ok,up,cut,eq,rdy}]`, one per live deal, ≤64 | +| `cq` | clique star | + +The card grows by about 4 KB at most. ASNs need nothing new: phase 1 already sends the catalog ASNs to avoid (`mpAvoid`, `mp.js:238`). + +## 5. Client day flow (`src/game/60-features/89-player-deals.js`, new) + +Phase 1's `mpRosterOk` is extended to whitelist `deals`, `dv`, `tenders`, `gifts` and `idle` (plus new `MP_FEED` kinds). The validated roster stays in `MP.roster`, never in S. `mpDay(d)` runs first in `dayPre`, right after `S.day++` (`10-day-tick.js:10`): + +1. **Copy changes in.** If `dv`, `idle` or any card changed, rebuild `S.mpx.who` and `S.mpx.deals` from the validated data, with values in steps. Then recompute `k`/`xk` and call `mpBind(S)`. +2. **Reconcile each deal:** + - **live, not `made`:** create my row (`S.pops[at]`, `portOk`, `portGate`, `spend(setup)`) and set `made`. If that fails, the deal waits under a "waiting on you" badge, with no client timer; the server ends it as `unbuilt`. + - **live, `made`, but the row is gone** (for example after a decommission, which `decomImpact` warns about): post `end` with `why:'gone'`. Decommissioning a city where I sell also ends those sell deals. + - **ended** (or missing from the server's list): set `until=d+notice` (14 own days for transit, 7 for the rest) and remove the rows when it passes. +3. **Copy the coupling values onto the rows:** + - on transit rows: `t.mpf` and `t.down`; + - on PNI rows: their side's capacity and whether it is ready; + - on link rows: cut, eqDown and ready; + - on my seller entries: `u`, `q` and whether the buyer is active. +4. `compute()` runs (worker or not), then `dayPost`, then phase 1's push carries the new fields. `dl` comes from yesterday's R. + +**My own clicks** (`mpOffer`, `mpAnswer`, `mpEnd`, `mpSell`, `mpBid`) apply as soon as the server answers, with `mpApply();after()`. If `RW.job` is set, they apply at the next `dayPre` instead. + +Multiplayer code never calls `Math.random`. + +## 6. Saves and sanitize + +**New field:** `S.mpx = null | {k, xk, dv, who:[≤11], deals:[≤64]}`. `deals` holds only my own deals. Cones, `on` and who-buys-from-whom come from `who[].pt`. +- `mpx:null` is the default in `newGame` (`80-new-game.js:4`), so old saves get null. + +**Order in `sanitize`:** move phase 1's `mpSanitize(s)` from `50-sanitize.js:113` up to `:21`, then call `mpxSanitize(s)`. Both now run before `opsSanitize` (`:22`) and every `isNet` filter (`:34-35, :54-55`). + +**`mpxSanitize`:** +- **When it is null:** unless `MP_API` is stamped and `s.mp` is valid in normal mode. An imported multiplayer save then just loses its player rows. +- **Players (`who`):** pids checked against the regex, unique, never my own. +- **Names:** stripped like the phase 1 server does (control characters and `<>&"'\``, at most 32). They are not escaped, because `labOf`/`hotPorts` print catalog names unescaped too. +- **Ids:** pass `isCity`/`isIx`. `miss` must be catalog ids, and `pt`/`mr` must be pids in `who`. +- **Numbers:** clamped and stepped. +- **Deals:** kinds from a whitelist, the other party present, `at` checked, `tier` within `PORT`, the price at most `mpCap`. +- **Loops:** `pt` edges are dropped in (buyer, seller) pid order. +- **Keys:** `k`/`xk` are recomputed, never trusted. +- **Last step:** it ends with `mpBind(s)`. + +**`mpOrphans(s)`** runs right after `:113`: +- it drops tagged `transit`/`pni`/`links`/`peers` entries that have no deal; +- it drops untagged rows on `mp:` networks; +- it strips `mp`/`mpp`/`mpf` from untagged rows, so a forged `mpp:0` gives no free transit. + +**`RK_SKIP`:** `mpx` stays off it, because `compute` reads it. Phase 1's `mp` stays on, because `compute` must never read it; the `route-skip.test.js` proxy enforces both. + +**Size:** at most +15 KB per save. + +## 7. Ordered steps + +Each step ends with `npm test` green, the i18n check clean, MCP classification, a CHANGELOG bullet and perf numbers. + +**1. Dormant core (no server, no UI).** +- `45-player-carriers.js`. +- `80-new-game.js:4`; `50-sanitize.js:21`/`:113`. +- `30-compute.js`: + - `:28` bind check; + - `:53-54` `mpf` and `miss`; + - `:61` `if(!p.mp)`; + - `:62` `*(p.mp?mpPniF(p):1)`; + - `:70` `xk`; + - `:95` `mpDem`; + - `:130`/`:16` the players column; + - `:375-382` `V.mp`. +- `40-billing.js:9`; `40-ports.js:21`. +- **Guards:** + - `lagT`/`lagP`/`cancelTransit` (`20-pops-transit-ix.js:6,7,11`), `unpeer`/`cancelPni` (`40-sites-peering-caches.js:16,30`) and `downT` (`21-ix-downgrade.js:6`) route to `mpEnd` or a renegotiation offer; + - `cleanPipe` (`80-security-and-china.js:8`) refuses `mp` rows; + - `trExits` (`50-traceroute.js:20`) applies `miss`, and `hotPorts` (`80-hot-ports-and-rank.js:4`) applies `mpf`; + - `connUp` (`40-connections.js:18`) shows no upgrade for these rows; + - the intern (`95-standing-orders.js:155,180,250`) skips `mp` rows; + - `upLink`/`rmLink`/`setStandby` (`60-links.js:2,6`). +- `src/agent/30-docs.js`. +- **Tests:** `mp-sanitize`, and `mp-transit` with `S.mpx` injected. + +**2. Deals and transit, end to end.** +- `scripts/lib/mp-deals.js` and the `mp.js` routes and timers. +- The card fields. +- `89-player-deals.js`, called from `10-day-tick.js:10`. +- `90-actions/92-player-deals.js`, classified in `src/agent/20-commands.js`. +- `95-modals/49-player-deals.js`: a Deals tab in the session sheet, a bottom sheet at 360 px. +- `90-noc-window.js:45`; `decomImpact`; all six languages. +- **Tests:** `mp-deals-server`, and `mp-transit` with `fetch` mocked. + +**3. Peering and player traffic.** +- `pni`/`ix` deals, `mpIx`, and `36-mp-traffic.js` with its hook at `:343`. +- The `V.eyeballs` factor, `R.mpSess` and the star. +- Player Gbps in the PNI list and the connections list. +- **Test:** `mp-peering`. + +**4. Competition:** `clComp`, poaching, tenders. + +**5. Shared fiber:** waves, IRUs, seats. + +**6. `scripts/mp-soak.js`:** opt-in, never part of `npm test`. + +## 8. Performance budget + +**Single-player.** Each `compute()` costs one string comparison, one property read per transit and PNI row, and one more `ACN` column per edge. +- `npm run perf -- --base-ref origin/main` must stay within noise (≤1%). +- `emptyR()` gains no keys; `R.mp`, `R.mpSess` and `V.mp` exist only when `S.mpx` is set. + +**Multiplayer.** The carrier mechanics are measured above: 32.3 → 33.2 ms. A new `big-network-mp` workload (the fixture plus 11 players and 20 deals, built by `scripts/perf-mp-fixture.js`) must meet: +- `mpTraffic` ≤ 1.5 ms (one exit sort per POP, then O(players×exits), with paths cached for each pair of cities); +- `mpBind` ≤ 0.1 ms; +- warm `compute` ≤ +5% compared with the same fixture without players. + +A cold route happens only when `xk` changes, at most once a game day. Report jsdom and `--browser` numbers. + +## 9. Test plan + +**`mp-deals-server`** (spawned server, temporary directory): +- every transition and who may make it (403/409); +- the policy outcomes for `ix` (live, no, offer); +- 409 `loop` on A→B→C→A; +- the limits; +- the `unbuilt`, `idle` and `left` ends, and expiry, with an injected clock; +- card validation; +- restart persistence. + +**`mp-transit`:** +- the buyer's exit and label, `transitMo` using `mpp`, `isTier1` false; +- `mpf` scales capacity, and `miss` blocks reach and changes `xk`; +- the seller's demand rises by `u`, `V.mp` follows the formula, and the seller keeps Tier 1; +- an idle buyer gives zero load and revenue; +- a forged `mpp` is stripped; +- worker parity (the `route-worker.test.js` pattern); +- no `Math.random` calls; +- the inbox is never applied mid-day. + +**`mp-peering`:** +- a PNI carries traffic only once both ends are ready; +- de-peering raises transit p95; +- two unpeered Tier 1 players lose revenue, and both stay Tier 1; +- 24 player PNIs leave `R.sessions` unchanged; +- C reaches B through A's cone; +- the route-server rule is two-sided; +- the PNI lead time is stable. + +**`mp-sanitize`:** +- fuzzing does not throw and stays bounded: 1,000 entries, HTML in names, loops, unknown ids, `mp:` rows in a single-player save; +- old saves load; +- a multiplayer-to-single-player slot switch clears every `mp:*`; +- `` stays text in the panels and the Deals sheet at 360 px. + +**`mp-competition` and `mp-fiber`:** +- rival players raise `clComp`; +- gifts are validated; +- every client derives the same tender; +- cuts are copied; +- a bought wave can't be upgraded. + +**Existing gates:** +- `route-skip` (same digest with `S.mpx` null or empty), `compute-idempotent`, `routing-reference`, `route-cache`; +- `gameplay-rules`, plus a check that no `mp:` id is in `NETS`/`NSH`; +- `persist`, `save-size`, `save-text`, `mcp-commands`, `i18n`, `pages`, `build`, `multiplayer`, `mp-server`. + +**Soak test (the "hardcore" local run):** +- The server plus 12 seeded jsdom players in `worker_threads` (about 0.5 GB each, with `--jobs` capped). +- Each plays about 2,000 days at its own speed, with a random agent making, answering and ending deals. +- During the run: server restarts, reloads through `migrate`, a player leaving, tampered cards and a burst of 409s. +- It checks: no errors or NaN, an acyclic deal graph, each seller's `V.mp` matching the buyer's bill, every save reloading, and a single-player control game keeping `main`'s digest. + +## 10. Failure modes + +| Case | Handling | +|---|---| +| The other player is paused or offline | Their last card stands: an idle buyer brings no load or money, and a buyer keeps the seller's last values. After 14 days the server ends the deal (`idle`) | +| A player leaves | The deal ends (`left`) and each side tears down after notice. `mpBind` drops the carrier on the next sanitize | +| Server down | Play goes on with the frozen `S.mpx`. New deals fail with one toast | +| Two devices | Phase 1's seq/409 picks the save; `made` settles the rows | +| Version skew | Unknown `miss` ids are dropped; networks the seller's build lacks count as reachable | +| Tampered card or save | Whitelists, clamps, steps, local price caps, orphan stripping. Money comes only from local formulas | diff --git a/docs/plans/next-session.md b/docs/plans/next-session.md new file mode 100644 index 0000000..deaef46 --- /dev/null +++ b/docs/plans/next-session.md @@ -0,0 +1,55 @@ +# What is left (as of 2026-11-07) + +Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Built so far: the build standard, multiplayer +phase 1, dark mode (#80), IPv4 address space (#150), express fiber (#58) and satellite teleports (#83). Everything below is +planned or known, not built. + +## Promised and not done yet + +1. **Router model and line system set in one place only.** The build standard (`S.popStd.g`, `S.popStd.sys`) and two + standing-order settings say the same thing: the `routers` order's `model` (upstream 1e7638c) and the `optup` order's + `sys` (upstream 647e302). Neither ever steps down, so they do not fight, but a player can pick two different targets. + Plan: the Build standard sheet becomes the only place to pick them. The `routers` order reads its model from the + standard, and `optup` its line system (their lists turn into a line "from the build standard: X, change"); sanitize + moves an old `model`/`sys` setting into `S.popStd` when the standard has none. +2. **One owner per fiber for line systems and optics.** `std` (sys/opt targets: a quiet fiber, or a parallel link with + room) and `optup` (one full routing without the fiber, one a night) can each darken a fiber in the same shift. Let `std` + use `optup`'s check (`opsDarkOk`) for line-system swaps, or skip fibers `optup` is working on. Today `std` also holds + any fiber that carries an express with traffic; `opsDarkOk` would handle that case by itself. + +## Next features + +3. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative + over the multiplayer server, and **multiplayer phase 2** (players as carriers in each other's simulations: transit, + peering, PNIs, shared fiber): design in `docs/plans/multiplayer-phase2.md`. +4. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is + the busier direction. It comes after #58 because both touch link capacity (express channels now count too). + +## Known limitations of what shipped + +- **Multiplayer:** other players' POPs are not drawn on the map (no clean hook yet); cards are what each browser reports, + the server does not verify them; a save over ~60 KB sends only the card when the tab closes; the HUD chip in phone + landscape wider than 760 px was not measured. Behind a reverse proxy, run the server with `--trust-proxy`, or every + player shares one address for the rate limits. +- **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full; a wave + the standard just upgraded can still be handed back the same day by `decom` if a bigger parallel link carries it. +- **Dark mode (#80):** red error text on dark tinted cards is about 3.8–4.3:1 (bold, but below AA 4.5); the share card PNG + and the web manifest stay light; the WebGL map was checked by tests only, not by eye in a real GPU browser. +- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income + is not in the investor revenue share; blocks granted to old saves can be sold after two years (a one-off windfall); + CGNAT annoyance costs refunds but does not slow broadband growth; the NOC window's address-space button does nothing. +- **Express fiber (#58):** splicing a whole fiber pair through a city was left out on purpose (every fiber end is a POP; + expresses cover the need); loss and MTU incidents on a fiber do not reduce the expresses on it; the fiber panel's + "n of max channels" line does not count express slots (the Express section does); regen sites added later do not charge + regen cards for express channels. +- **Satellites (#83):** no WISP zones, no satellite incidents (rain fade, sun outage), no footprints on the map, no + satellite tab in the drag-to-link window (ordering is from the city panel); GEO/MEO losses and prices are design + numbers; well-cabled islands (Wellington, Hobart) also count as "can be served"; MEO needs 5° elevation (10° would drop + 416 pairs); Pitcairn's $120k satellite grant stays Pie-only. + +## Housekeeping + +- `npm run perf -- --browser` needs Chromium (`sudo pacman -S chromium`, then `PERF_CHROME=/usr/bin/chromium`); only the + jsdom benchmark has been run. +- Upstream release tags are not on `vanvik` yet: `git push vanvik --tags` if wanted. +- The merged worktrees under `.claude/worktrees/` and their `worktree-wf_*` branches can be removed. From 040e25faab8ac818caaa5e3b7ee303b3612686f3 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 05:06:17 +0100 Subject: [PATCH 418/491] Plans: propose a shared session clock for multiplayer --- docs/plans/multiplayer-phase2.md | 4 ++++ docs/plans/next-session.md | 31 +++++++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/docs/plans/multiplayer-phase2.md b/docs/plans/multiplayer-phase2.md index 346e1c7..ab739aa 100644 --- a/docs/plans/multiplayer-phase2.md +++ b/docs/plans/multiplayer-phase2.md @@ -2,6 +2,10 @@ Status: design only, not built. Phase 1 (sessions, server-side saves, leaderboard) is in `docs/MULTIPLAYER.md`. +Clock: this design assumes each player's game keeps its own time. A shared session clock is proposed in +`docs/plans/next-session.md` (item 3). If it is adopted, the parts timed in real minutes or on each player's own clock +(tenders, `idle`, notice, the soak test) move to game days. + **Conventions:** - Line numbers are `main` at `1e7638c`. - Phase 1 (multiplayer sessions, merged on `main`) provides `S.mp`, `MP`, `mpCard`/`mpCardOk`, and `cleanCard` in `scripts/lib/mp.js`. diff --git a/docs/plans/next-session.md b/docs/plans/next-session.md index deaef46..b46aeb6 100644 --- a/docs/plans/next-session.md +++ b/docs/plans/next-session.md @@ -19,10 +19,37 @@ planned or known, not built. ## Next features -3. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative +3. **Wave B starts with a shared session clock.** Proposed on 2026-11-07, not decided yet: it changes how every + multiplayer game plays. Today each player's game runs in their own browser at their own speed (pause, 0.5× to 8×), so + players in one session are on different days. The proposal: the server keeps the time and every game in the session + follows it. The simulation stays in the browser. + - **Server:** a session gets a pace when it is created: one game day every 30 s to 5 min (agent mode's list). Never the + normal 2.5 s, which is 1,440 game days an hour. The day only moves while at least one player was seen recently (the + roster already keeps `seen`), so nobody comes back to years of unattended play. Every roster answer carries the + server's time and the session day. + - **Browser:** the clock is locked to the session. `UI.clockLocked` and `HOOKS.speed()` (`50-state.js`) already hide + the speed buttons and refuse pause, and `save()` already leaves `uiSpeed` alone while locked. The code goes in + `src/game/`, because `src/agent/` does not ship (ADR 0004), so it needs its own copy of agent mode's worker ticker + (`src/agent/85-ticker.js`) to keep time in hidden tabs. Agent mode also sets `HOOKS.speed`: the session wins, and + agent mode is off in a multiplayer game. + - **Catching up:** a game behind the session day runs days until it matches, a few per frame, with its progress + shown. It needs its own loop: with the route worker, `runClock` holds one day at a time. A day takes about 30 ms on + the big test network, so 400 missed days take about 12 s on a desktop and longer on phones. Late joiners start on + the session's current day (to check: what in the world depends on the day a game started). + - **Nobody can pause or speed up.** That is what "the same day" means. + - **Later, optional: the server plays absent players.** It opens an offline player's save in a headless game (jsdom, + as `scripts/lib/mcp-game.js` already does with its realtime clock) and runs their days with the intern. The + browser takes the save back on return through phase 1's save numbers, so the server is just one more device. Up to + about 0.5 GB of RAM per absent player. Without it, other players see an absent network stand still. + - **Not proposed: a server that runs every game** with the browser only showing it. Every click would be a round + trip, and the page reads `S` and `R` directly everywhere, so it would be a rewrite. Its one gain over the above is + verified cards (today the server trusts them). + - **Phase 2 gets simpler:** its wall-clock timing (tenders that close after 10 real minutes, `idle` ≥ 300 s, notice on + each player's own clock, the soak test's "own speed") can move to game days. +4. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative over the multiplayer server, and **multiplayer phase 2** (players as carriers in each other's simulations: transit, peering, PNIs, shared fiber): design in `docs/plans/multiplayer-phase2.md`. -4. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is +5. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is the busier direction. It comes after #58 because both touch link capacity (express channels now count too). ## Known limitations of what shipped From 7a6eb29013bd02a13db402dace1549fd8792be6e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 06:36:19 +0100 Subject: [PATCH 419/491] Interns with specialities, optical upgrades, renewal haggles, seven French cities and smoother big networks (3.1.0) --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fa9e28..2380feb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +## [3.1.0] — 2026-11-07 + - Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. - The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary. - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. diff --git a/package-lock.json b/package-lock.json index a5c7090..28dc651 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "3.0.0", + "version": "3.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "3.0.0", + "version": "3.1.0", "license": "MIT", "devDependencies": { "@modelcontextprotocol/node": "2.1.2", diff --git a/package.json b/package.json index 4e6ade7..097e4de 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "3.0.0", + "version": "3.1.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From fbae6fc3edc2c8b456e251b18b261c40e84b556e Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 06:55:01 +0100 Subject: [PATCH 420/491] The build standard owns the router model and the line system; one owner per fiber The routers order reads its model from the build standard (bstd().g, 'keep' is the old next-model-up rule) and the optical upgrade order its line system (bstd().sys). The Ops sheet shows "From the build standard: X" with a button to the sheet. Old saves move a model or line system from an order that was running into the standard when it has none of its own; a paused order's or an unhired intern's setting is dropped. opsParam refuses model/sys and points at bstdSet. The build standard's order is a generator now: every first job that takes a fiber dark goes through the optical order's routing test (opsDark, in the route worker in play), under one shared budget of dark swaps a night (two for Kevin) and the week-long memory for a failed fiber. A fiber one order worked on is the other's no more that shift, and decom keeps waves the standard just upgraded. The plan is checked at every job, since the shift rests between them: a POP gone or changed by hand meanwhile is skipped. The button still runs the whole plan at once on the page. --- CHANGELOG.md | 2 + docs/plans/next-session.md | 23 +- site/i18n/de.js | 9 +- site/i18n/es.js | 9 +- site/i18n/fr.js | 9 +- site/i18n/it.js | 9 +- site/i18n/pt.js | 9 +- src/agent/20-commands.js | 7 +- src/agent/30-docs.js | 2 +- src/game/60-features/95-standing-orders.js | 85 ++++--- src/game/60-features/96-pop-standard.js | 59 +++-- src/game/90-actions/88-build-standard.js | 2 +- src/game/93-ui/57-ops-panel.js | 6 +- src/game/93-ui/59-build-standard.js | 4 +- src/i18n/en.js | 9 +- src/styles/36-ops.css | 5 + tests/bstd-owner.test.js | 276 +++++++++++++++++++++ tests/build-standard.test.js | 9 +- tests/intern-optical-upgrade.test.js | 34 ++- tests/intern-personas.test.js | 2 +- tests/intern-router-model.test.js | 114 ++++++--- tests/mcp-commands.test.js | 27 ++ 22 files changed, 573 insertions(+), 138 deletions(-) create mode 100644 tests/bstd-owner.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e2a378..6ed9b59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too. +- Your intern no longer takes a fiber dark for the build standard just because it looks quiet: like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day. - Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. - The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary. - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. diff --git a/docs/plans/next-session.md b/docs/plans/next-session.md index b46aeb6..be20f7b 100644 --- a/docs/plans/next-session.md +++ b/docs/plans/next-session.md @@ -6,16 +6,9 @@ planned or known, not built. ## Promised and not done yet -1. **Router model and line system set in one place only.** The build standard (`S.popStd.g`, `S.popStd.sys`) and two - standing-order settings say the same thing: the `routers` order's `model` (upstream 1e7638c) and the `optup` order's - `sys` (upstream 647e302). Neither ever steps down, so they do not fight, but a player can pick two different targets. - Plan: the Build standard sheet becomes the only place to pick them. The `routers` order reads its model from the - standard, and `optup` its line system (their lists turn into a line "from the build standard: X, change"); sanitize - moves an old `model`/`sys` setting into `S.popStd` when the standard has none. -2. **One owner per fiber for line systems and optics.** `std` (sys/opt targets: a quiet fiber, or a parallel link with - room) and `optup` (one full routing without the fiber, one a night) can each darken a fiber in the same shift. Let `std` - use `optup`'s check (`opsDarkOk`) for line-system swaps, or skip fibers `optup` is working on. Today `std` also holds - any fiber that carries an express with traffic; `opsDarkOk` would handle that case by itself. +1. and 2. are built: the router model and the line system are picked in the Build standard sheet only (the `routers` and + `optup` orders read `bstd().g` / `bstd().sys`; sanitize moves an old setting into `S.popStd`), and `std` takes a fiber + dark on `optup`'s routing test (`opsDark()`), sharing its budget a night, with one owner per fiber a shift (`X.fib`). ## Next features @@ -58,8 +51,14 @@ planned or known, not built. the server does not verify them; a save over ~60 KB sends only the card when the tab closes; the HUD chip in phone landscape wider than 760 px was not measured. Behind a reverse proxy, run the server with `--trust-proxy`, or every player shares one address for the rate limits. -- **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full; a wave - the standard just upgraded can still be handed back the same day by `decom` if a bigger parallel link carries it. +- **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full. The + sheet's quote and "Bring everything up now" still judge a line-system swap without routing (`bstdDarkOk()`: a quiet + fiber, under 10% of its capacity, or a parallel link with room; any express with traffic holds its fibers, + `bstdXpBusy()`), so the quote is the bill; only the intern routes to test. A quiet fiber with no way around can still + go dark from the button. An old save's `routers.model` moved into the standard (only from a running order with an + intern hired; a paused one's is dropped) also becomes what new POPs get. A model or line system in the standard is a + ceiling for the `routers` and `optup` orders (their next-one-up rule only applies with "keep"), as an order's own + model was before; `optup` has no per-POP exceptions, so it moves fiber at POPs excepted from `std` too. - **Dark mode (#80):** red error text on dark tinted cards is about 3.8–4.3:1 (bold, but below AA 4.5); the share card PNG and the web manifest stay light; the WebGL map was checked by tests only, not by eye in a real GPU browser. - **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income diff --git a/site/i18n/de.js b/site/i18n/de.js index 0b4dacd..92d66ae 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -413,7 +413,7 @@ "bstd.edit":"Build-Standard bearbeiten", "bstd.every_exchange":"Wo es einen IX gibt", "bstd.fastest":"Die schnellste, die reicht", -"bstd.fiber_note":"Ein Line-System-Tausch legt die Glasfaser einen Tag dunkel: nur wenn sie ruhig ist oder ein paralleler Link ihre Last trägt.", +"bstd.fiber_note_two":"Ein Line-System-Tausch legt die Glasfaser einen Tag dunkel. Der Button macht das nur bei ruhiger Faser oder wenn ein paralleler Link ihre Last trägt; dein Praktikant nur, wenn der ganze Verkehr um die Faser herumkommt.", "bstd.from_level":"(Level {lv})", "bstd.g_fiber":"Glasfaser und Waves", "bstd.g_port":"Ports und Peering", @@ -3402,6 +3402,7 @@ "ops.fire":"Entlassen", "ops.fired":"{name} hat den Ausweis abgegeben und den guten Tacker mitgenommen. Deine Daueraufträge ruhen.", "ops.floor":"Mindestens behalten", +"ops.from_bstd":"Aus dem Build-Standard: {x}", "ops.good_annie":"Am besten beim Peering: geht die Exchanges jeden Tag durch statt wöchentlich und bestellt zweimal pro Woche PNIs.", "ops.good_kevin":"Am besten bei Wartung: zwei Line-System-Tausche pro Nacht statt einem, und nie ein dicker Finger.", "ops.good_tracy":"Am besten im Vorausplanen: kauft Transit, Ports, Router und Optiken, als wäre der Traffic schon 10 % höher.", @@ -3458,7 +3459,7 @@ "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_optup":"Optischen Transport ausbauen", -"ops.o_optup_d":"Auf Glasfaser, die voll ist und heiß läuft, das Line System eine Größe hochziehen oder die kleinsten Kanäle gegen größere Optiken tauschen (die alten kommen ins Ersatzteillager). Wähl ein Line System, und jede Faser mit einem kleineren wird darauf hochgezogen. Ein Tausch des Line Systems legt die Faser für einen Tag lahm, also nur, wo der Traffic einen Weg drumherum hat und kein Kunde darauf fährt, einer pro Nacht.", +"ops.o_optup_std_d":"Auf Glasfaser, die voll ist und heiß läuft, das Line System eine Größe hochziehen oder die kleinsten Kanäle gegen größere Optiken tauschen (die alten kommen ins Ersatzteillager). Steht ein Line System im Build-Standard, wird jede Faser mit einem kleineren darauf hochgezogen. Ein Tausch des Line Systems legt die Faser für einen Tag lahm, also nur, wo der Traffic einen Weg drumherum hat und kein Kunde darauf fährt, einer pro Nacht zusammen mit „Build-Standard einhalten“.", "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_ports":"Peering-Reserve halten", @@ -3466,9 +3467,9 @@ "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_desc":"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. Wähl ein Modell, und jeder POP mit einem kleineren wird darauf getauscht, der am meisten ausgelastete zuerst, im Rahmen des Budgets.", +"ops.o_routers_std_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. Steht ein Router-Modell im Build-Standard, wird stattdessen jeder POP mit einem kleineren darauf getauscht, der am meisten ausgelastete zuerst, im Rahmen des Budgets.", "ops.o_std":"Build-Standard einhalten", -"ops.o_std_d":"POPs, Ports und Glasfaser auf deinen Build-Standard bringen, die meistbelasteten zuerst, ein paar Jobs pro Schicht. Vor einem Tausch kommt ein zweiter Router rein, und ein Line System wechselt nur auf einer ruhigen Glasfaser.", +"ops.o_std_around_d":"POPs, Ports und Glasfaser auf deinen Build-Standard bringen, die meistbelasteten zuerst, ein paar Jobs pro Schicht. Vor einem Tausch kommt ein zweiter Router rein, und ein Line System wechselt nur, wo der Traffic für den dunklen Tag einen Weg um die Faser hat und kein Kunde darauf fährt, einer pro Nacht zusammen mit „Optischen Transport ausbauen“.", "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", diff --git a/site/i18n/es.js b/site/i18n/es.js index 54e4971..b9e5de1 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -411,7 +411,7 @@ "bstd.edit":"Editar el estándar de red", "bstd.every_exchange":"Donde haya un IX", "bstd.fastest":"La más rápida que llegue", -"bstd.fiber_note":"Cambiar el sistema de línea deja la fibra apagada un día: solo si va tranquila o un enlace paralelo lleva su carga.", +"bstd.fiber_note_two":"Cambiar el sistema de línea deja la fibra apagada un día. El botón solo lo hace si va tranquila o un enlace paralelo lleva su carga; tu becario, solo si todo el tráfico puede rodear la fibra.", "bstd.from_level":"(nivel {lv})", "bstd.g_fiber":"Fibra y ondas", "bstd.g_port":"Puertos y peering", @@ -3400,6 +3400,7 @@ "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.from_bstd":"Del estándar de red: {x}", "ops.good_annie":"La mejor en peering: repasa los exchanges cada día, no cada semana, y pide PNI dos veces por semana.", "ops.good_kevin":"El mejor en mantenimiento: dos cambios de sistema de línea por noche en vez de uno, y nunca un dedazo.", "ops.good_tracy":"La mejor planificando: compra tránsito, puertos, routers y ópticas como si el tráfico ya fuera un 10 % mayor.", @@ -3456,7 +3457,7 @@ "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_optup":"Mejorar el transporte óptico", -"ops.o_optup_d":"En la fibra que está llena y va caliente, sube el sistema de línea un tamaño o cambia los canales más pequeños por ópticas más grandes (las viejas van a la estantería). Elige un sistema de línea y cada fibra con uno más pequeño sube a ese. Cambiar el sistema de línea deja la fibra sin servicio un día, así que solo donde el tráfico puede rodearla y ningún cliente va por ella, uno por noche.", +"ops.o_optup_std_d":"En la fibra que está llena y va caliente, sube el sistema de línea un tamaño o cambia los canales más pequeños por ópticas más grandes (las viejas van a la estantería). Con un sistema de línea en el estándar de red, cada fibra con uno más pequeño sube a ese. Cambiar el sistema de línea deja la fibra sin servicio un día, así que solo donde el tráfico puede rodearla y ningún cliente va por ella, uno por noche junto con «Mantener el estándar de red».", "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_ports":"Margen en puertos de peering", @@ -3464,9 +3465,9 @@ "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_desc":"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. Elige un modelo y cada POP con uno más pequeño se cambia a ese, primero el más cargado, dentro del presupuesto.", +"ops.o_routers_std_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. Con un modelo de router en el estándar de red, cada POP con uno más pequeño se cambia a ese, primero el más cargado, dentro del presupuesto.", "ops.o_std":"Mantener el estándar de red", -"ops.o_std_d":"Poner los POP, los puertos y la fibra al nivel de tu estándar de red, los más cargados primero, unos pocos trabajos por turno. Antes de un cambio entra un segundo router, y el sistema de línea solo cambia en una fibra tranquila.", +"ops.o_std_around_d":"Poner los POP, los puertos y la fibra al nivel de tu estándar de red, los más cargados primero, unos pocos trabajos por turno. Antes de un cambio entra un segundo router, y el sistema de línea solo cambia donde el tráfico puede rodear la fibra el día que queda a oscuras y ningún cliente va por ella, uno por noche junto con «Mejorar el transporte óptico».", "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", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index d3d4cd4..dbc21c6 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -411,7 +411,7 @@ "bstd.edit":"Modifier le standard réseau", "bstd.every_exchange":"Partout où il y a un IX", "bstd.fastest":"La plus rapide qui porte", -"bstd.fiber_note":"Changer le système de ligne éteint la fibre pendant un jour : seulement si elle est calme ou qu’un lien parallèle porte sa charge.", +"bstd.fiber_note_two":"Changer le système de ligne éteint la fibre pendant un jour. Le bouton ne le fait que si elle est calme ou qu’un lien parallèle porte sa charge ; ton stagiaire, seulement si tout le trafic peut contourner la fibre.", "bstd.from_level":"(niveau {lv})", "bstd.g_fiber":"Fibre et longueurs d’onde", "bstd.g_port":"Ports et peering", @@ -3400,6 +3400,7 @@ "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.from_bstd":"Selon le standard réseau : {x}", "ops.good_annie":"La meilleure en peering : passe les exchanges en revue chaque jour, pas chaque semaine, et commande des PNI deux fois par semaine.", "ops.good_kevin":"Le meilleur en maintenance : deux changements de système de ligne par nuit au lieu d’un, et jamais une faute de frappe.", "ops.good_tracy":"La meilleure pour anticiper : achète transit, ports, routeurs et optiques comme si le trafic était déjà 10 % plus haut.", @@ -3456,7 +3457,7 @@ "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_optup":"Améliorer le transport optique", -"ops.o_optup_d":"Sur une fibre pleine qui chauffe, passer le système de ligne à la taille au-dessus, ou échanger les plus petits canaux contre des optiques plus grandes (les anciennes partent sur l’étagère). Choisissez un système de ligne, et chaque fibre équipée d’un plus petit y passe. Un changement de système de ligne coupe la fibre pour une journée : seulement là où le trafic peut la contourner et où aucun client ne passe, un par nuit.", +"ops.o_optup_std_d":"Sur une fibre pleine qui chauffe, passer le système de ligne à la taille au-dessus, ou échanger les plus petits canaux contre des optiques plus grandes (les anciennes partent sur l’étagère). Avec un système de ligne dans le standard réseau, chaque fibre équipée d’un plus petit y passe. Un changement de système de ligne coupe la fibre pour une journée : seulement là où le trafic peut la contourner et où aucun client ne passe, un par nuit avec « Tenir le standard réseau ».", "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_ports":"Garder de la marge sur les ports de peering", @@ -3464,9 +3465,9 @@ "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_desc":"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. Choisissez un modèle, et chaque POP équipé d’un plus petit passe à celui-ci, le plus chargé d’abord, dans la limite du budget.", +"ops.o_routers_std_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. Avec un modèle de routeur dans le standard réseau, chaque POP équipé d’un plus petit passe à celui-ci, le plus chargé d’abord, dans la limite du budget.", "ops.o_std":"Tenir le standard réseau", -"ops.o_std_d":"Mettre POP, ports et fibre au niveau de ton standard réseau, les plus chargés d’abord, quelques chantiers par service. Un second routeur arrive avant un échange, et le système de ligne ne change que sur une fibre calme.", +"ops.o_std_around_d":"Mettre POP, ports et fibre au niveau de ton standard réseau, les plus chargés d’abord, quelques chantiers par service. Un second routeur arrive avant un échange, et le système de ligne ne change que là où le trafic peut contourner la fibre le jour où elle est coupée et où aucun client ne passe, un par nuit avec « Améliorer le transport optique ».", "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", diff --git a/site/i18n/it.js b/site/i18n/it.js index 618b5ba..34f9e6a 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -411,7 +411,7 @@ "bstd.edit":"Modifica lo standard di rete", "bstd.every_exchange":"Ovunque ci sia un IX", "bstd.fastest":"La più veloce che arriva", -"bstd.fiber_note":"Cambiare il sistema di linea spegne la fibra per un giorno: solo se è tranquilla o se un link parallelo ne regge il carico.", +"bstd.fiber_note_two":"Cambiare il sistema di linea spegne la fibra per un giorno. Il pulsante lo fa solo se è tranquilla o se un link parallelo ne regge il carico; il tuo stagista solo se tutto il traffico può aggirare la fibra.", "bstd.from_level":"(livello {lv})", "bstd.g_fiber":"Fibra e wave", "bstd.g_port":"Porte e peering", @@ -3400,6 +3400,7 @@ "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.from_bstd":"Dallo standard di rete: {x}", "ops.good_annie":"La migliore nel peering: passa gli exchange ogni giorno, non ogni settimana, e ordina PNI due volte a settimana.", "ops.good_kevin":"Il migliore nella manutenzione: due cambi di line system per notte invece di uno, e mai un errore di battitura.", "ops.good_tracy":"La migliore a pianificare: compra transito, porte, router e ottiche come se il traffico fosse già più alto del 10%.", @@ -3456,7 +3457,7 @@ "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_optup":"Potenzia il trasporto ottico", -"ops.o_optup_d":"Sulla fibra piena che va calda, porta il line system alla taglia successiva, o scambia i canali più piccoli con ottiche più grandi (le vecchie finiscono a scaffale). Scegli un line system e ogni fibra con uno più piccolo passa a quello. Cambiare line system spegne la fibra per un giorno, quindi solo dove il traffico può girarle intorno e nessun cliente ci passa, uno per notte.", +"ops.o_optup_std_d":"Sulla fibra piena che va calda, porta il line system alla taglia successiva, o scambia i canali più piccoli con ottiche più grandi (le vecchie finiscono a scaffale). Con un line system nello standard di rete, ogni fibra con uno più piccolo passa a quello. Cambiare line system spegne la fibra per un giorno, quindi solo dove il traffico può girarle intorno e nessun cliente ci passa, uno per notte insieme a “Tieni lo standard di rete”.", "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_ports":"Margine sulle porte di peering", @@ -3464,9 +3465,9 @@ "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_desc":"Aggiungi un router, o passa alla generazione successiva dove un secondo router regge il traffico, quando carico o porte superano una soglia. Scegli un modello e ogni POP con uno più piccolo passa a quello, prima il più carico, nei limiti del budget.", +"ops.o_routers_std_d":"Aggiungi un router, o passa alla generazione successiva dove un secondo router regge il traffico, quando carico o porte superano una soglia. Con un modello di router nello standard di rete, ogni POP con uno più piccolo passa a quello, prima il più carico, nei limiti del budget.", "ops.o_std":"Tieni lo standard di rete", -"ops.o_std_d":"Porta POP, porte e fibra al tuo standard di rete, i più carichi prima, qualche lavoro a turno. Prima di uno scambio arriva un secondo router, e il sistema di linea cambia solo su una fibra tranquilla.", +"ops.o_std_around_d":"Porta POP, porte e fibra al tuo standard di rete, i più carichi prima, qualche lavoro a turno. Prima di uno scambio arriva un secondo router, e il sistema di linea cambia solo dove il traffico può girare intorno alla fibra nel giorno in cui è spenta e nessun cliente ci passa, uno per notte insieme a “Potenzia il trasporto ottico”.", "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", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index b301858..71d1198 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -411,7 +411,7 @@ "bstd.edit":"Editar o padrão de rede", "bstd.every_exchange":"Onde houver um IX", "bstd.fastest":"A mais rápida que alcança", -"bstd.fiber_note":"Trocar o sistema de linha apaga a fibra por um dia: só quando ela está tranquila ou um link paralelo leva a carga.", +"bstd.fiber_note_two":"Trocar o sistema de linha apaga a fibra por um dia. O botão só faz isso quando ela está tranquila ou um link paralelo leva a carga; seu estagiário só quando todo o tráfego consegue contornar a fibra.", "bstd.from_level":"(nível {lv})", "bstd.g_fiber":"Fibra e waves", "bstd.g_port":"Portas e peering", @@ -3400,6 +3400,7 @@ "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.from_bstd":"Do padrão de rede: {x}", "ops.good_annie":"A melhor em peering: passa pelos exchanges todo dia, não toda semana, e pede PNIs duas vezes por semana.", "ops.good_kevin":"O melhor em manutenção: duas trocas de sistema de linha por noite em vez de uma, e nunca um dedo gordo.", "ops.good_tracy":"A melhor em planejar: compra trânsito, portas, roteadores e ópticas como se o tráfego já estivesse 10% maior.", @@ -3456,7 +3457,7 @@ "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_optup":"Melhorar o transporte óptico", -"ops.o_optup_d":"Na fibra que está cheia e esquentando, sobe o sistema de linha um tamanho ou troca os canais menores por ópticas maiores (as antigas vão para a prateleira). Escolha um sistema de linha e cada fibra com um menor sobe para ele. Trocar o sistema de linha derruba a fibra por um dia, então só onde o tráfego consegue contorná-la e nenhum cliente passa por ela, uma por noite.", +"ops.o_optup_std_d":"Na fibra que está cheia e esquentando, sobe o sistema de linha um tamanho ou troca os canais menores por ópticas maiores (as antigas vão para a prateleira). Com um sistema de linha no padrão de rede, cada fibra com um menor sobe para ele. Trocar o sistema de linha derruba a fibra por um dia, então só onde o tráfego consegue contorná-la e nenhum cliente passa por ela, uma por noite junto com “Manter o padrão de rede”.", "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_ports":"Folga nas portas de peering", @@ -3464,9 +3465,9 @@ "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_desc":"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. Escolha um modelo e cada POP com um menor é trocado para ele, o mais carregado primeiro, dentro do orçamento.", +"ops.o_routers_std_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. Com um modelo de roteador no padrão de rede, cada POP com um menor é trocado para ele, o mais carregado primeiro, dentro do orçamento.", "ops.o_std":"Manter o padrão de rede", -"ops.o_std_d":"Colocar POPs, portas e fibra no seu padrão de rede, os mais carregados primeiro, alguns trabalhos por turno. Antes de uma troca entra um segundo roteador, e o sistema de linha só muda numa fibra tranquila.", +"ops.o_std_around_d":"Colocar POPs, portas e fibra no seu padrão de rede, os mais carregados primeiro, alguns trabalhos por turno. Antes de uma troca entra um segundo roteador, e o sistema de linha só muda onde o tráfego consegue contornar a fibra no dia em que ela fica apagada e nenhum cliente passa por ela, uma por noite junto com “Melhorar o transporte óptico”.", "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", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 20b1366..e9a2a7c 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -367,7 +367,10 @@ const API_CMD={ opsToggle:{args:[['k','opsKey']],watch:['ops'], doc:'Pause or resume one standing order. Keys come from catalog(\'OPSK\'); the sheet in the game shows what each one does.'}, opsParam:{args:[['k','opsKey'],['p','string'],['v','string',false]],watch:['ops'], - doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead, such as the model to standardize routers on.'}, + // The routers order's model and the optup order's line system were settings once: they are the build standard's now. + pass:a=>{const b={routers:{model:'g'},optup:{sys:'sys'}}[a.k],t=b&&b[a.p]; + if(t)throw new Error(`the ${a.k} order takes its ${t==='g'?'router model':'line system'} from the build standard: set it with bstdSet (k "${t}")`);return a;}, + doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead. The routers order\'s model and the optup order\'s line system are not settings: both orders take them from the build standard (bstdSet k "g" and k "sys"; "keep" leaves them to the next model or line system up, when needed).'}, opsCap:{args:[['k','opsKey'],['v','string',false]],watch:['ops'], doc:'Step the monthly budget of an order that has one: 10k, 50k, 250k, 1M, 5M, no limit (for caches, a cap on the rent it adds: 1k, 2.5k, 5k, 10k, 25k, no limit). With v (a position in that list, 0 first) it picks that one.'}, opsFloor:{args:[['v','string',false]],watch:['ops'], @@ -424,7 +427,7 @@ const API_CMD={ popStdClear:{args:[],watch:['popStd'], doc:'Clear the whole build standard; new POPs go back to one basic router.'}, bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'], - doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'}, + doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. g and sys are also what the intern\'s routers and optup orders standardize on. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'}, bstdApply:{args:[],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'], quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};}, doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill.'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 3fe830f..edbe60c 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -62,7 +62,7 @@ const API_STATE_DOC={ core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, w: which warnings were shown. What customers use is derived from their kind and size.'}, - popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, + popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up. g and sys are also the model the routers order and the line system the optup order standardize on.'}, mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 4484fb2..ac49827 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -18,20 +18,19 @@ const OPS_AHEAD=1.1,opsIs=id=>!!S&&!!S.ops&&S.ops.intern===id,opsAhead=()=>opsIs 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'||v==='have'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}}, {k:'ports',i:'🔌',pop:1,cap:50000,t:N_('ops.o_ports'),d:N_('ops.o_ports_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'}}}, - {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_desc'),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])}, - // A model to standardize on: every POP on a smaller one is swapped to it, busiest first, within the budget. - model:{d:'next',ok:v=>v==='next'||(Number.isInteger(v)&&!!RG[v]),l:N_('ops.p_model'),f:v=>v==='next'?tr('ops.model_next'):RG[v].n}}}, + // The model to standardize on is the build standard's, set in its sheet (96-pop-standard.js): none of its own here. + {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_std_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])}}}, // The build standard (96-pop-standard.js): its targets are set in their own sheet, so here it has only the budget. - {k:'std',i:'📐',pop:1,cap:250000,t:N_('ops.o_std'),d:N_('ops.o_std_d'),p:{}}, + {k:'std',i:'📐',pop:1,cap:250000,t:N_('ops.o_std'),d:N_('ops.o_std_around_d'),p:{}}, {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=>v?tr('common.on'):tr('common.off')}}}, {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+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}}}, // Line systems up to a bigger one, and optics swapped for bigger ones, on fiber that is full and runs hot, or every fiber up to - // a chosen line system. A line system swap is a day without that fiber: only where the traffic gets around it. - {k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'}, - sys:{d:'next',v:['next','roadm','cl'],l:N_('ops.p_sys'),f:v=>v==='next'?tr('ops.sys_next'):DF_SYS[v].n},swap:{d:true,v:[true,false],l:N_('ops.p_swap'),f:v=>v?tr('common.on'):tr('common.off')}}}, + // the build standard's line system. A line system swap is a day without that fiber: only where the traffic gets around it. + {k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_std_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'}, + swap:{d:true,v:[true,false],l:N_('ops.p_swap'),f:v=>v?tr('common.on'):tr('common.off')}}}, {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=>v?tr('common.on'):tr('common.off')}}}, ]; const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); @@ -47,10 +46,9 @@ 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;} -// Every value a setting can take, in the order its list shows them: providers that sell where you have POPs, and router -// models you can buy, smallest first. The current value is always on the list, so the list can show it. -function opsOpts(k,p){const cur=opsP(k,p),L=p==='prov'?['cheap','have',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)] - :p==='model'?['next',...RG.map((r,i)=>i).filter(i=>rgOpen(i)).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cap-RG[b].cap||a-b)]:OPSK[k].p[p].v.slice(); +// Every value a setting can take, in the order its list shows them, providers that sell where you have POPs as well. +// The current value is always on the list, so the list can show it. +function opsOpts(k,p){const cur=opsP(k,p),L=p==='prov'?['cheap','have',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)]:OPSK[k].p[p].v.slice(); if(!L.includes(cur))L.push(cur);return L;} 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;} @@ -64,6 +62,10 @@ function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s 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); + // The routers order's model and the optical order's line system moved to the build standard (bstdAdopt()), each only + // from an order that ran: one paused, or with nobody hired, did nothing, and a standard's model costs every new POP. + const ran=k=>!!n.intern&&on[k]===true; + bstdAdopt(s,ran('routers')?ob(p.routers).model:undefined,ran('optup')?ob(p.optup).sys:undefined); 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&&opsCaps(k).includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0)); @@ -122,8 +124,10 @@ 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. // dirty: a job changed the network, so R (loads, routing) is out of date until the next compute(). // up/mo: what this shift paid up front and added to the monthly bill. +// dk: the night's fibers taken dark (n) and routings to test one (t), shared by the orders that do it (opsDarkRoom()). +// fib: the fibers and waves an order worked on this shift, by order: one owner per fiber a shift. function opsShift(){const r=new Map(),broke=new Set(); - return {r,broke,dirty:false,up:0,mo:0,did(k,w){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);}, + return {r,broke,dirty:false,up:0,mo:0,dk:{n:0,t:0},fib:new Map(),did(k,w){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. // quiet: only asking, so a no is not logged as the budget running out. can(k,cost,mo=0,quiet){const O=S.ops,cap=opsCap(k);if(cost<=0&&!(mo>0))return true; @@ -145,14 +149,15 @@ const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;retur // after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there. const OPS_RUN={ // Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js). - std(X){bstdShift(X);}, + *std(X){yield* bstdShift(X);}, *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');yield;}}, - *routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next', + *routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),G=bstd().g,fix=G!=='keep', load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c))); - // A chosen model: swap every POP still on a smaller one to it, the busiest first, while the budget lasts. Never a - // step down, never a model that is not unlocked or does not fit, and only with a second router or no traffic there. - if(fix&&rgOpen(m))for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c],g=p.rgen||0; - if(p.rupDay===S.day||g===m||RG[m].cap<=RG[g].cap||modelFits(c,m)||!((p.routers||1)>1||popIdle(c)))continue; + // The build standard's model: swap every POP still on a smaller one to the model the standard gives it (bstdModel(): + // the best unlocked one no bigger, never a step down, never one that does not fit or cannot run the core), the + // busiest first, while the budget lasts, and only with a second router or no traffic there. + if(fix)for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c]; + if(p.rupDay===S.day||!((p.routers||1)>1||popIdle(c)))continue;const m=bstdModel(G,c);if(m<0)continue; const cost=swapCost(c,m);if(!X.can('routers',cost))continue; if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}} for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; @@ -222,19 +227,20 @@ const OPS_RUN={ 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);yield;}}}, - *optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0; + *optup(X){const at=opsP('optup','at')/100,sys=bstd().sys,goal=sys==='keep'?'next':sys,swap=opsP('optup','swap'); const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)*opsAhead()>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l)); - const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)).sort((a,b)=>u(b)-u(a)); + // A fiber the build standard's order worked on this shift is that order's until tomorrow. + const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)&&(X.fib.get(l.id)||'optup')==='optup').sort((a,b)=>u(b)-u(a)); for(const l of ls){ - // The line system: one step at a time up to the chosen one, or the next one where the fiber is full and hot. + // The line system: one step at a time up to the build standard's, or the next one where the fiber is full and hot. const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]S.day)&&X.can('optup',cost)){tries++;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT); + if(want&&opsDarkRoom(X)){const to=sysNext(l),cost=sysUpCost(l); + if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT); if(ok){const s0=l.sys,top=goal==='next'?to:goal; for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;} // The fiber is dark until tomorrow: its optics wait. - if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}} + if(l.sys!==s0){X.dk.n++;X.fib.set(l.id,'optup');X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}} // Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and // the old optics go on the shelf as spares. if(!swap)continue; @@ -248,7 +254,7 @@ const OPS_RUN={ const was=dfCap(l); X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2}); if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;}); - if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}}, + if(!(dfCap(l)>was))break;X.fib.set(l.id,'optup');X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}}, *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=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9; @@ -269,23 +275,34 @@ const OPS_RUN={ const q=pniRequote(q0);if(!q)continue;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);yield;}}, // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). // Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a - // job changed the network and anything could go (opsDecomWaits()). - *decom(X){for(const ls of opsPairs().values())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}}, + // job changed the network and anything could go (opsDecomWaits()). A wave another order worked on today stays. + // (Left out of what the pick hands back, not out of the pick: it may still be the spare the pick keeps.) + *decom(X){for(const ls of opsPairs().values())for(const l of opsDecomPick(ls).filter(l=>!X.fib.has(l.id))){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}}, }; -// Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once, -// so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week +// Line system swaps per shift, and how many fibers a shift may test for one with a routing: each test routes the whole +// network once, so a shift costs at most one routing more, and only on a night with a fiber to try. The build standard's +// order and this one share them (X.dk). A fiber that failed the test is not tested again for a week // (not saved: after a reload it is simply tested again). const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,roadm:1,cl:2},SYS_TAG={roadm:'ROADM',cl:'C+L'}; +// Room tonight for one more fiber going dark. Kevin does maintenance: twice the swaps, and twice the tests. +const opsDarkRoom=X=>{const k=opsIs('kevin')?2:1;return X.dk.n{const L=(R&&R.load)||{};return !(L[l.id]>1e-6)&&!xpOver(l.id).some(x=>L[x.id]>1e-6);}; +// What a day dark comes to, said without routing: false (a customer rides it, or it carries traffic with no other way +// between its cities), true (nothing rides it, so nothing is lost), null (a routing decides: opsDarkTrial()). +function opsDarkPre(l){if(S.biz.some(b=>b.link===l.id))return false;return opsUnused(l)?true:opsAround(l)?null:false;} const OPS_ROUTE={route:true}; -function* opsDark(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;} - return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});} -// The test itself, on the game it is given: R is put back after. +// X.dk.t counts the tests that route. +function* opsDark(l,X){let k=opsDarkPre(l);if(k===false)return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;k=opsDarkPre(l);} + if(k!==null)return k;X.dk.t++;return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});} +// The test itself, on the game it is given: R is put back after. The fiber's line system is down for the day (eqDown), +// and every express riding it with it (xpDown()): their traffic has to get around too. function opsDarkTrial(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const R0=R,e0=l.eqDown,s0=y.s0,L0=y.L0; try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);} finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}} @@ -300,8 +317,8 @@ function opsDecomPick(ls,cf=capOf){if(!ls||ls.length<2)return [];const live=ls.f for(const l of small.reverse()){if(cap-cf(l)x.id===y.dark);if(!l||S.biz.some(b=>b.link===l.id)||!opsAround(l))return false; - return opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});} +function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const k=opsDarkPre(l); + return k!==null?k:opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});} // A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it (and gone) first. function opsDecomSafe(l,gone=[]){const bz=S.biz.filter(b=>(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); diff --git a/src/game/60-features/96-pop-standard.js b/src/game/60-features/96-pop-standard.js index 752d2d0..6359e40 100644 --- a/src/game/60-features/96-pop-standard.js +++ b/src/game/60-features/96-pop-standard.js @@ -26,6 +26,13 @@ function bstd(d=S&&S.popStd){const o={},ob=d&&typeof d==='object'&&!Array.isArra // Back to the saved form: the model and router count, and any other target that is not "keep". Nothing set: null. function bstdPut(o){const d={};for(const x of BSTD)if(x.k==='rt'||o[x.k]!==x.d)d[x.k]=o[x.k];return Object.keys(d).length>1||d.rt>1?d:null;} function popStdSanitize(s){s.popStd=s.popStd&&typeof s.popStd==='object'&&!Array.isArray(s.popStd)?bstdPut(bstd(s.popStd)):null;} +// Saves from when the intern's orders had their own router model (routers) and line system (optup): the standard takes +// them where it has none of its own; one that names its own keeps it. 'next' was no choice at all: nothing moves. +// opsSanitize() passes only what an order that was running used (undefined otherwise): the rest is dropped. +function bstdAdopt(s,g,sys){const D=bstd(s.popStd);let n=0; + if(D.g==='keep'&&Number.isInteger(g)&&bstdOk(BSTDK.g,g)){D.g=g;n++;} + if(D.sys==='keep'&&sys!=='keep'&&bstdOk(BSTDK.sys,sys)){D.sys=sys;n++;} + if(n)s.popStd=bstdPut(D);} // A bank that forbids generators (Stormy Weather's covenant): the standard never installs one while that loan runs. const bstdNoGen=()=>(S.loans||[]).some(l=>(l.covs||[]).includes('nogen')); // The model a POP should get: the standard's if you can buy it, else the best main-line model that is unlocked and no @@ -80,12 +87,14 @@ function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J const take=(c,n,dry)=>{if(n<=0)return true;if(room(c){const j={grp,k,ch,w,cost,mo,go,...x};J.push(j);return j;}; for(const c of cs){const p=S.pops[c],ch='p:'+c;let g=p.rgen||0,rt=p.routers||1,sw=null,s2=null; - const add=()=>{const g0=g,r0=rt;job('pop','rt',ch,c+' +1',routerCost(g0,r0),routerMo(g0)+cageMo(r0+1)-cageMo(r0),()=>{const n=S.pops[c].routers||1;ACT.addRouter({city:c});return (S.pops[c].routers||1)>n;},{c});rt++;}; + // A router job checks the POP still has what the plan counted on: the intern's shift rests between jobs, and the player + // may click meanwhile (the button, a router by hand). So does a PNI job: one ordered meanwhile is not upgraded. + const add=()=>{const g0=g,r0=rt;job('pop','rt',ch,c+' +1',routerCost(g0,r0),routerMo(g0)+cageMo(r0+1)-cageMo(r0),()=>{const n=S.pops[c].routers||1;if(n!==r0)return false;ACT.addRouter({city:c});return (S.pops[c].routers||1)>n;},{c});rt++;}; const m=p.rupDay===S.day?-1:bstdModel(D.g,c); if(m>=0){ // One router carrying traffic: a second goes in first, so the swap rolls through with no maintenance window. if(rt===1&&!popIdle(c))add(); - const old=g,r=rt;sw=job('pop','g',ch,c+' ⇧'+RG[m].pn,swapCostOf(m,old,r),r*(RG[m].mo-RG[old].mo),()=>{ACT.upRouter({city:c,g:m});return (S.pops[c].rgen||0)===m;},{c});g=m;} + const old=g,r=rt;sw=job('pop','g',ch,c+' ⇧'+RG[m].pn,swapCostOf(m,old,r),r*(RG[m].mo-RG[old].mo),()=>{if((S.pops[c].rgen||0)!==old)return false;ACT.upRouter({city:c,g:m});return (S.pops[c].rgen||0)===m;},{c});g=m;} while(rt{ACT.addSite({city:c});return !!S.pops[c].site2;},{c}); @@ -108,7 +117,7 @@ function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J const opts=NET[net].pops.filter(c=>S.pops[c]&&here(c)&&!by[net].has(c)).map(c=>({c,v:pniVal(net,c)})).filter(o=>o.v.worth).sort((a,b)=>b.v.want-a.v.want||(a.c=pniMin(net)&&!q;t--){const x=pniQuote(c,net,t,resv(c));if(x&&!x.why)q=x;} if(!q||!take(c,q.slots))continue;const tier=q.tier;k--; - job('port','pni','n:'+net+'@'+c,c+' '+net,q.cost,pniMo({net,tier,n:1},0),()=>{const x=pniQuote(c,net,tier,resv(c));if(!x||x.why||!spend(x.cost))return false;pniPlace(x);return true;},{c});}}} + job('port','pni','n:'+net+'@'+c,c+' '+net,q.cost,pniMo({net,tier,n:1},0),()=>{const x=pniQuote(c,net,tier,resv(c));if(!x||x.why||x.ex||!spend(x.cost))return false;pniPlace(x);return true;},{c});}}} // Fiber and waves, hottest first. A POP excepted from the order keeps its links as they are too. if(D.sys!=='keep'||D.opt!=='keep'||D.wv!=='keep'){const sp={...(S.spares||{})},dk=new Map(),wv=new Map(); const ls=S.links.filter(l=>(l.kind==='df'||l.kind==='wave')&&here(l.a)&&here(l.b)&&S.pops[l.a]&&S.pops[l.b]).map(l=>({l,u:(R.load[l.id]||0)/Math.max(1e-9,capOf(l))})).sort((a,b)=>b.u-a.u||(a.l.idS.day)&&opsDarkPre(l)!==false:bstdDarkOk(l)))J.held.push(l); + else if(lit&&(intern?pairLinks(l.a,l.b).some(x=>x!==l&&dk.get(x.id)):!bstdDarkOk(l,dk))){J.held.push(l);continue;} + else{const busy=lit&&(intern?!opsUnused(l):bstdBusy(l)); while(BSTD_SYS[sys]{if(l.sys!==s0)return false;ACT.upSys({id:l.id});return l.sys===to;},{l,dark:lit,busy});sys=to;} if(lit)dk.set(l.id,busy);}} @@ -178,25 +189,32 @@ function bstdOptJobs(l,sys,sp,V,take,ch){const rg=c=>V[c]?V[c].g:(S.pops[c].rgen // The new ones could not go in (ports, cash): the old optics go back in from the shelf. (l.ch=l.ch||[]).push(...Array(k).fill(o0));S.spares[o0]-=k;return false;}});} return out;} -// A line-system swap darkens the fiber for a day: only while it carries little, or its parallel links can take its load. +// The button's test of a line-system swap, which darkens the fiber for a day: only while it carries little, or its +// parallel links can take its load. No routing, so the quote is what the click does. (The intern routes: opsDark().) // ex: fibers already going dark today (id → whether they carry traffic): they carry nothing for this one, and one whose // traffic leans on its parallel links keeps them lit. const bstdBusy=l=>((R.load&&R.load[l.id])||0)>Math.max(1,capOf(l)*0.1); // Express lightpaths (#58) ride the fiber's glass: its own load says nothing about them, and its parallel links do not // carry them, so an express with any traffic at all keeps the fiber lit (the line system waits, as for a busy fiber). +// The intern's routing test needs no such rule: an express goes dark with its fiber there (opsDarkTrial()). const bstdXpBusy=l=>xpSlots(l)>0&&xpOver(l.id).some(x=>((R.load&&R.load[x.id])||0)>1e-6); function bstdDarkOk(l,ex){if(bstdXpBusy(l))return false;const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; return P.filter(x=>!linkDown(x)&&!x.standby&&!(ex&&ex.has(x.id))).reduce((a,x)=>a+Math.max(0,capOf(x)-((R.load&&R.load[x.id])||0)),0)>=((R.load&&R.load[l.id])||0);} -// Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took. -// one: at most one fiber goes dark (the intern's shift); max: at most that many jobs tried, done or failed, so a shift's -// work stays bounded whatever goes wrong. Returns what was done. -function bstdDo(J,can,pay,one,max=1e9){const stop=new Set(),done=new Set(),dark=new Map();let n=0; +/* Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took. + dark(j, ex): may the first job that darkens a fiber go ahead (ex: fibers gone dark so far, as bstdDarkOk() takes them), + a generator, so a test can route (yields included); done1(j, first): after each job done (first: it took a fiber dark). + max: at most that many jobs tried, done or failed, so a shift's work stays bounded whatever goes wrong. A bare yield + after each job is a place to let a frame through. Returns what was done. */ +function* bstdRun(J,can,pay,dark,done1,max=1e9){const stop=new Set(),done=new Set(),dk=new Map();let n=0; for(const j of J){if(n>=max)break;if(stop.has(j.ch))continue;if(j.dep&&!j.dep.every(d=>done.has(d))){stop.add(j.ch);continue;} - if(j.dark&&!dark.has(j.l.id)&&((one&&dark.size)||!bstdDarkOk(j.l,dark))){stop.add(j.ch);continue;} - if(!can(j)){stop.add(j.ch);continue;}n++; + // The money first: no fiber is tested for a job the budget cannot pay, and asked again after a test that routed. + const first=!!j.dark&&!dk.has(j.l.id); + if(!can(j)||first&&(!(yield* dark(j,dk))||!can(j))){stop.add(j.ch);continue;}n++; if(!pay(j)){stop.add(j.ch);continue;} - if(j.dark)dark.set(j.l.id,!!j.busy);done.add(j);} + if(j.dark)dk.set(j.l.id,!!j.busy);done.add(j);if(done1)done1(j,first);yield;} return [...done];} +// The button: the whole plan at once, on the page, every fiber judged as the plan judged it. +function bstdDo(J,can,pay){const g=bstdRun(J,can,pay,function*(j,ex){return bstdDarkOk(j.l,ex);});for(;;){const s=g.next();if(s.done)return s.value;}} // What a job costs as it runs (an optics swap is priced again then: see bstdOptJobs). const bstdPrice=j=>j.price?j.price():j.cost; // The sheet's summary and the MCP quote: how much is below the standard, and what bringing it all up costs. The plan is @@ -206,5 +224,14 @@ function bstdQuote(intern){const J=bstdPlan(intern),P=new Set(),Q=new Set(),L=ne return {cost:Math.round(cost),mo:Math.round(mo),pops:P.size,ports:Q.size,links:L.size,n:J.length,held:J.held.map(l=>l.a+'|'+l.b)};} // The optics order lights the standard's fastest optics while this order keeps to a standard that wants them. const bstdFast=()=>!!(S.popStd&&opsHired()&&S.ops.on.std&&bstd().opt==='fast'); -// The intern's shift: the same plan, every job through the budget and the cash floor at what it costs then, a few at a time. -function bstdShift(X){bstdDo(bstdPlan(true),j=>X.can('std',bstdPrice(j),j.mo),j=>X.pay('std',()=>j.go())&&(X.did('std',j.w),true),true,BSTD_MAX);} +/* The intern's shift: the same plan, every job through the budget and the cash floor at what it costs then, a few at a + time. A fiber goes dark only on the optical order's test (opsDark(): a routing without it, in play in the route + worker), within the night's dark swaps that order shares (opsDarkRoom()), and a fiber that fails waits a week. One + owner per fiber: a fiber or wave the optical order worked on this shift is left alone, and what this order works on + is its own until tomorrow (X.fib: that order and decom leave it alone). The plan is made once a shift, and the shift + rests between jobs: a POP decommissioned or a link given up meanwhile is not worked on (the links last: a walk of them, + only for a job the budget lets through). */ +function* bstdShift(X){const mine=j=>(!j.c||!!S.pops[j.c])&&(!j.l||(X.fib.get(j.l.id)||'std')==='std'); + yield* bstdRun(bstdPlan(true),j=>mine(j)&&X.can('std',bstdPrice(j),j.mo)&&(!j.l||S.links.includes(j.l)),j=>X.pay('std',()=>j.go())&&(X.did('std',j.w),true), + function*(j){const l=j.l;if(OPTUP_NO.get(l.id)>S.day||!opsDarkRoom(X))return false;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);return ok;}, + (j,first)=>{if(j.l)X.fib.set(j.l.id,'std');if(first)X.dk.n++;},BSTD_MAX);} diff --git a/src/game/90-actions/88-build-standard.js b/src/game/90-actions/88-build-standard.js index f832604..f51a55f 100644 --- a/src/game/90-actions/88-build-standard.js +++ b/src/game/90-actions/88-build-standard.js @@ -7,7 +7,7 @@ Object.assign(ACT,{ // The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One // recompute at the end, and one toast: what got done, and what still waits. bstdApply:()=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);if(!J.length)return;const c0=S.cash;let n=0; - opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go(),false).length;}); + opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go()).length;}); after();const q=bstdQuote(false),left=q.pops+q.ports+q.links; toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err'); if(bstdShown())bstdModal();}, diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js index 6d67cb1..240ff20 100644 --- a/src/game/93-ui/57-ops-panel.js +++ b/src/game/93-ui/57-ops-panel.js @@ -9,11 +9,15 @@ function opsVal(k,p,v=opsP(k,p)){const P=OPSK[k].p[p];return p==='prov'?(v==='ch // A setting as a list to pick from: the option values are positions in the list the action reads again. const opsSel=(lab,act,args,vals,cur,name)=>``; const opsCapName=(k,v)=>v?tr('common.price_mo',{price:(OPSK[k].mo?'+':'')+fmt$(v)}):tr('ops.no_cap'); +// The router model and the line system are the build standard's, chosen in its sheet only: in their place, what it says +// and the way there. "Keep as is" leaves each order to its own rule: the next model or line system up, when needed. +const OPS_BSTD={routers:{k:'g',l:N_('ops.p_model'),f:v=>v==='keep'?tr('ops.model_next'):RG[v].n},optup:{k:'sys',l:N_('ops.p_sys'),f:v=>v==='keep'?tr('ops.sys_next'):DF_SYS[v].n}}; +function opsFromStd(k){const x=OPS_BSTD[k];return x?`
${tr(x.l)}${esc(tr('ops.from_bstd',{x:x.f(bstd()[x.k])}))}${pzOn()?'':btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}
`:'';} 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),big:fmt$(CACHE_BIG_MO)}):''}
${k==='std'?`
${tr('bstd.now_line',{list:S.popStd?esc(bstdLine(bstd())):tr('pop_std.none')})}
${btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}
`:''} - ${on?`
${Object.keys(d.p).map(p=>opsSel(tr(d.p[p].l),'opsParam',{k,p},opsOpts(k,p),opsP(k,p),v=>opsVal(k,p,v))).join('')} + ${on?`
${opsFromStd(k)}${Object.keys(d.p).map(p=>opsSel(tr(d.p[p].l),'opsParam',{k,p},opsOpts(k,p),opsP(k,p),v=>opsVal(k,p,v))).join('')} ${d.cap?opsSel(d.mo?tr('ops.budget_running'):tr('ops.budget'),'opsCap',{k},opsCaps(k),cap,v=>opsCapName(k,v)):''}
${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()])})}

`:''}`:''}
`;} diff --git a/src/game/93-ui/59-build-standard.js b/src/game/93-ui/59-build-standard.js index c6437b2..858a39c 100644 --- a/src/game/93-ui/59-build-standard.js +++ b/src/game/93-ui/59-build-standard.js @@ -21,7 +21,7 @@ function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hire let h=`
${tr('ops.ops')}

${tr('bstd.title')}

${tr('bstd.tagline')}

`; for(const [g,lab] of BSTD_GRP)h+=`

${tr(lab)}

${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}
-

${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note')}

`; +

${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note_two')}

`; // What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose // line system has to wait is below it too, but not on the bill. const n={pop:q.pops,port:q.ports,fiber:q.links},w=q.held.length; @@ -30,7 +30,7 @@ function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hire +(w?`

${trn('bstd.held',w)}

`:'') :`

${S.popStd?tr('bstd.all_up'):tr('bstd.none_set')}

`}`; // The intern keeps it there: the order's switch and budget, or a word on hiring one. - h+=`

${tr('ops.o_std')}

${hired?`
${esc(tr('bstd.intern_keeps',{name:opsName()}))}
${tr('ops.o_std_d')}
+ h+=`

${tr('ops.o_std')}

${hired?`
${esc(tr('bstd.intern_keeps',{name:opsName()}))}
${tr('ops.o_std_around_d')}
${on?`
${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}
`:''}
` :`

${tr('bstd.hire_note')}

${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}
`}
`; diff --git a/src/i18n/en.js b/src/i18n/en.js index 7568d89..4ce1e9d 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -412,7 +412,7 @@ "bstd.edit":"Edit the build standard", "bstd.every_exchange":"Wherever there is an IX", "bstd.fastest":"Fastest that reaches", -"bstd.fiber_note":"A line system swap takes the fiber dark for a day: only on a quiet fiber, or where a parallel link carries its load.", +"bstd.fiber_note_two":"A line system swap takes the fiber dark for a day. The button does it only on a quiet fiber or where a parallel link carries its load; your intern only where all the traffic gets around the fiber.", "bstd.from_level":"(level {lv})", "bstd.g_fiber":"Fiber and waves", "bstd.g_port":"Ports and peering", @@ -3401,6 +3401,7 @@ "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.from_bstd":"From the build standard: {x}", "ops.good_annie":"Best at peering: works through the exchanges every day, not weekly, and orders PNIs twice a week.", "ops.good_kevin":"Best at maintenance: two line system swaps a night instead of one, and never a fat finger.", "ops.good_tracy":"Best at planning ahead: buys transit, ports, routers and optics as if traffic were already 10% higher.", @@ -3457,7 +3458,7 @@ "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_optup":"Upgrade optical transport", -"ops.o_optup_d":"On fiber that is full and runs hot, move the line system up a size, or trade the smallest channels for bigger optics (the old ones go on the shelf). Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so only where the traffic gets around it and no customer rides it, one a night.", +"ops.o_optup_std_d":"On fiber that is full and runs hot, move the line system up a size, or trade the smallest channels for bigger optics (the old ones go on the shelf). With a line system in the build standard, every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so only where the traffic gets around it and no customer rides it, one a night together with Keep to the build standard.", "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_ports":"Keep peering headroom", @@ -3465,9 +3466,9 @@ "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_desc":"Add a router, or swap to the next generation where a second router carries the traffic, when load or ports pass a level. Pick a model, and every POP on a smaller one is swapped to it, the busiest first, within the budget.", +"ops.o_routers_std_d":"Add a router, or swap to the next generation where a second router carries the traffic, when load or ports pass a level. With a router model in the build standard, every POP on a smaller one is swapped to it instead, the busiest first, within the budget.", "ops.o_std":"Keep to the build standard", -"ops.o_std_d":"Bring POPs, ports and fiber up to your build standard, the busiest first, a few jobs a shift. A second router goes in before a swap, and a line system only changes on a quiet fiber.", +"ops.o_std_around_d":"Bring POPs, ports and fiber up to your build standard, the busiest first, a few jobs a shift. A second router goes in before a swap, and a line system only changes where the traffic gets around the fiber for its day dark and no customer rides it, one a night together with Upgrade optical transport.", "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", diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css index 68fc552..e0efcd3 100644 --- a/src/styles/36-ops.css +++ b/src/styles/36-ops.css @@ -13,6 +13,11 @@ /* A setting is a list to pick from: two to a row on a phone, the list as wide as its column. */ .ops-sel{display:flex;flex-direction:column;gap:2px;flex:1 1 140px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)} .ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--text);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px} +/* A setting the build standard owns: a whole row, what it says, and the way to its sheet (under it on a narrow phone). */ +.ops-from{flex:1 1 100%;display:flex;flex-wrap:wrap;align-items:center;gap:2px 8px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)} +.ops-from>span{flex:1 1 100%} +.ops-from b{flex:1 1 160px;min-width:0;font:700 14px Nunito,sans-serif;color:var(--text);overflow-wrap:anywhere} +.ops-from .b{flex:none;min-height:36px} .ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto} .ops-good{font-size:12.5px;font-weight:800;color:#6B3FD4;margin-top:2px;line-height:1.3} .ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)} diff --git a/tests/bstd-owner.test.js b/tests/bstd-owner.test.js new file mode 100644 index 0000000..e4612ba --- /dev/null +++ b/tests/bstd-owner.test.js @@ -0,0 +1,276 @@ +// One owner per fiber: the build standard's order (std) and the optical order (optup) take fibers dark with the same +// test (a routing without the fiber, in the route worker in play), share one budget of dark swaps a night, and never both +// work on one fiber in a shift; the decom order leaves a wave the standard just upgraded. Change Freeze, no failures. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt (broadband, 100G Cogentle transit), Amsterdam and Paris with broadband, everyone on four Chonk 800s, level 7. +const BASE = "Date.now=()=>1.7e12;ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" + + "ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(const c of ['ams','par','lon'])ACT.buildPop({city:c});" + + "for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=RG.findIndex(r=>r.n==='Chonk 800');S.pops[c].routers=4;}ACT.launchBB({city:'ams'});ACT.launchBB({city:'par'});compute()"; +function game(t, extra = '', opts = {}) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE); + if (extra) h.ev(extra); + return h; +} +const hire = (ev, id) => ev(`ACT.opsHire({id:'${id}'});S.ops.floor=0;S.ops.cap={std:0,optup:0};S.ops.on.std=true;closeModal()`); +const std = (ev, d) => ev(`S.popStd=bstdPut({...bstd(),...${lit(d)}})`); +// A leased dark fiber, built and lit with these optics; a wave. +const fiber = (ev, a, b, ch, sys = 'lite') => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'df',own:false,sys:'${sys}',ch:${lit(ch)},km:Math.round(kmBetween('${a}','${b}')),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});return id;})()`); +const wave = (ev, a, b, tier) => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'wave',tier:${tier},km:Math.round(kmBetween('${a}','${b}')),cut:0,mo:1,trench:id,day:S.day});return id;})()`); +const L = (ev, id) => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)})||null)`)); +const said = ev => JSON.parse(ev('JSON.stringify((S.ops.log[0]&&S.ops.log[0].d===S.day?S.ops.log[0].r:[]).map(x=>[x[0],x[1]]))')); +// Count the fiber tests that route (opsDarkTrial()), on the page here: tests never use the worker. +const COUNT = "window.__tr=0;const _t=opsDarkTrial;opsDarkTrial=function(){__tr++;return _t.apply(this,arguments);};"; + +test('both orders share one budget of dark swaps a night: one for Annie, two for Kevin, whoever does them', t => { + for (const [id, want] of [['annie', 1], ['kevin', 2]]) { + // Nobody on the far ends: the fibers really are quiet, whenever the shift routes again. + const { ev, errors } = game(t, 'S.pops.ams.bb=null;S.pops.par.bb=null'); + const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4'])); + ev('compute();for(const l of S.links)R.load[l.id]=0'); + hire(ev, id); + std(ev, { sys: 'roadm' }); + ev('S.ops.on.optup=true;opsDay(S.day)'); + assert.equal(ids.filter(x => L(ev, x).sys === 'roadm').length, want, id + ': fibers swapped tonight'); + assert.deepEqual(said(ev), [['std', want]], id + ': the build standard went first, the optical order found no room left'); + // Alone, the optical order has the same budget (the line system from the standard). + ev('S.ops.on.std=false;S.day+=2;compute();for(const l of S.links)R.load[l.id]=0;opsDay(S.day)'); + assert.equal(ids.filter(x => L(ev, x).sys === 'roadm').length, Math.min(3, 2 * want), id); + assert.deepEqual(said(ev), [['optup', Math.min(want, 3 - want)]]); + assert.deepEqual(errors, []); + } +}); + +test('a fiber the build standard worked on tonight is its own: the optical order takes it the next night', t => { + // A full Rainbow-in-a-Box fiber to Amsterdam, running hot, and a big wave beside it for the day it goes dark. + const { ev, errors } = game(t); + const f = fiber(ev, 'fra', 'ams', Array(16).fill('zr4')); + wave(ev, 'fra', 'ams', 3); + const hot = `compute();R.load[${lit(f)}]=1e5;`; + hire(ev, 'annie'); + std(ev, { opt: 'fast' }); + ev(`S.ops.on.optup=true;${hot}opsDay(S.day)`); + assert.deepEqual([L(ev, f).sys, [...new Set(L(ev, f).ch)]], ['lite', ['zr8']], 'the standard swapped its optics; its line system stays tonight'); + assert.deepEqual(said(ev), [['std', 1]], 'the optical order left it alone'); + ev(`S.day++;${hot}opsDay(S.day)`); + assert.equal(L(ev, f).sys, 'roadm', 'the next night, with nothing left for the standard there, the optical order moves it up'); + assert.deepEqual(said(ev), [['optup', 1]]); + assert.deepEqual(errors, []); +}); + +test("the standard's order takes a fiber dark on the optical order's test: a way around, not just a parallel link, and never a little traffic with none", t => { + // Amsterdam's broadband rides Frankfurt–Amsterdam; Paris closes a ring of fibers with room. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'ams', 'par', ['zr4', 'zr4']), c = fiber(ev, 'par', 'fra', ['zr4', 'zr4']); + ev(COUNT); + hire(ev, 'annie'); + std(ev, { sys: 'roadm' }); + // Busy by the plan's own measure, and nothing parallel: the button waits for it, the intern routes and finds the ring. + const busy = `compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`; + ev(busy); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false).held)')), ['fra|ams'], 'the button: busy, nothing parallel'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(true).held)')), [], 'the intern: a routing decides'); + const served = ev('R.served'); + ev('opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'one routing without the fiber'); + assert.deepEqual([L(ev, a).sys, L(ev, b).sys, L(ev, c).sys], ['roadm', 'lite', 'lite'], 'the busy one first, one a night'); + ev('compute()'); + assert.ok(ev('R.served') >= served - 1e-6, 'and every gigabit still gets through, round the ring'); + // A little traffic (well under the plan's "quiet") and no way around: the old test let it go dark; this one never. + const g = game(t); + const x = fiber(g.ev, 'fra', 'ams', ['zr4', 'zr4']); + g.ev('compute()'); + assert.ok(g.ev(`R.load[${lit(x)}]`) > 1 && !g.ev(`bstdBusy(S.links.find(l=>l.id===${lit(x)}))`), 'Amsterdam\'s broadband, under 10% of the fiber'); + hire(g.ev, 'kevin'); + std(g.ev, { sys: 'roadm', opt: 'fast' }); + g.ev(COUNT + 'opsDay(S.day)'); + assert.deepEqual([L(g.ev, x).sys, L(g.ev, x).eqDown], ['lite', undefined], 'Amsterdam is never cut off for a day'); + assert.deepEqual(L(g.ev, x).ch, ['zr8', 'zr8'], 'it gets the fastest optics its line system takes'); + assert.equal(g.ev('__tr'), 0, 'known without routing'); + assert.deepEqual(errors, []); + assert.deepEqual(g.errors, []); +}); + +test('with two swaps a night, the second fiber is judged on the routing with the first one dark, not on the loads from before', t => { + // The ring again, Kevin on shift. Once Frankfurt–Amsterdam is dark, Amsterdam's traffic rides Amsterdam–Paris, which + // carried nothing before: its "nothing rides it" is asked again after the shift routes, and is no longer true. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'ams', 'par', ['zr4', 'zr4']), c = fiber(ev, 'par', 'fra', ['zr4', 'zr4']); + hire(ev, 'kevin'); + std(ev, { sys: 'roadm' }); + ev(`compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`); + assert.equal(ev(`R.load[${lit(b)}]||0`), 0, 'Amsterdam–Paris is idle today'); + const served = ev('R.served'); + ev('opsDay(S.day)'); + assert.deepEqual([L(ev, a).sys, L(ev, b).sys, L(ev, c).sys], ['roadm', 'lite', 'lite'], 'Amsterdam keeps one way in'); + ev('compute()'); + assert.ok(ev('R.served') >= served - 1e-6, 'and every gigabit still gets through'); + assert.deepEqual(errors, []); +}); + +test('two busy fibers side by side: one goes dark tonight, its twin carries it, and the twin goes the next night', t => { + // Amsterdam's broadband split over two Frankfurt–Amsterdam fibers, a few gigabits each: busy, though under the + // button's "quiet". Kevin has room for two swaps, but the twin waits rather than fail the test and wait a week. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + hire(ev, 'kevin'); + std(ev, { sys: 'roadm' }); + ev('compute()'); + assert.ok(ev(`R.load[${lit(a)}]`) > 1 && ev(`R.load[${lit(b)}]`) > 1, 'both carry Amsterdam'); + ev('opsDay(S.day)'); + assert.deepEqual([[L(ev, a).sys, L(ev, b).sys].sort(), ev('OPTUP_NO.size')], [['lite', 'roadm'], 0], 'one tonight, and no fiber failed'); + ev('S.day++;compute();opsDay(S.day)'); + assert.deepEqual([L(ev, a).sys, L(ev, b).sys], ['roadm', 'roadm'], 'the twin the next night'); + assert.deepEqual(errors, []); +}); + +test('a fiber that fails the test waits a week, for both orders, and gets the optics its line system takes meanwhile', t => { + // The ring back from Amsterdam is two 10G waves: too thin for Amsterdam's broadband. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + wave(ev, 'ams', 'par', 0); wave(ev, 'par', 'fra', 0); + ev('compute()'); + assert.ok(ev(`R.load[${lit(a)}]`) > 10, 'more than the ring carries'); + ev(COUNT); + hire(ev, 'annie'); + std(ev, { sys: 'roadm', opt: 'fast' }); + ev('S.ops.on.optup=true;opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'tested once'); + assert.deepEqual([L(ev, a).sys, L(ev, a).ch], ['lite', ['zr4', 'zr4']], 'no swap, and no optics for a line system it did not get'); + assert.equal(ev(`OPTUP_NO.get(${lit(a)})`), ev('S.day+OPTUP_WAIT')); + for (let d = 1; d < 7; d++) ev('S.day++;compute();opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'not tested again that week, by either order'); + assert.deepEqual([L(ev, a).sys, L(ev, a).ch], ['lite', ['zr8', 'zr8']], 'the fastest optics the old line system takes'); + assert.deepEqual(errors, []); +}); + +test('an express riding the fiber goes dark with it in the test: its traffic has to get around too', t => { + // Frankfurt–Brussels–Paris as an express over two bare ROADM fibers; Paris reaches its transit over it. + const { ev, errors } = game(t, "ACT.buildPop({city:'bru'});S.pops.bru.rgen=S.pops.fra.rgen;S.lvl=8;" + + "window.df=(a,b)=>{const id=uid();S.links.push({id,a,b,kind:'df',own:true,sys:'roadm',ch:[],km:kmBetween(a,b),sub:false,cable:null,mo:100,trench:id,cut:0,day:S.day,ready:S.day,spares:false,pairs:1});return id;};" + + "window.s1=df('fra','bru');window.s2=df('bru','par');compute();ACT.xpBuild({a:'fra',b:'par',via:s1+','+s2,o:'zr4'});window.x=S.links.find(l=>l.kind==='xp').id;compute()"); + const [s1, s2, x] = ['s1', 's2', 'x'].map(k => ev(k)); + assert.ok(ev('R.load[x]') > 1 && !ev('(R.load[s1]||0)+(R.load[s2]||0)'), 'the express carries Paris; the fibers carry nothing of their own'); + ev(COUNT + "window.__xd=[];const _c=compute;compute=function(){if(S.links.find(l=>l.id===s1).eqDown>S.day||S.links.find(l=>l.id===s2).eqDown>S.day)__xd.push(xpDown(S.links.find(l=>l.id===x)));return _c.apply(this,arguments);}"); + hire(ev, 'annie'); + std(ev, { sys: 'cl' }); + const sys = () => [L(ev, s1).sys, L(ev, s2).sys]; + // No way around either fiber: known without routing. + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(true).held)')).sort(), ['bru|par', 'fra|bru']); + ev('opsDay(S.day)'); + assert.deepEqual([sys(), ev('__tr')], [['roadm', 'roadm'], 0]); + // A wave beside the first fiber: it has a way around now, but Paris has none without the express. + wave(ev, 'fra', 'bru', 1); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'one routing without the fiber'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__xd)')), [true], 'the express was dark in it'); + assert.deepEqual(sys(), ['roadm', 'roadm'], 'Paris would be cut off: no swap'); + // A wave to Paris carries it round: the swap goes ahead, with the express dark for the day. + wave(ev, 'fra', 'par', 3); + ev('OPTUP_NO.clear();S.day++;compute();opsDay(S.day)'); + assert.deepEqual(sys().sort(), ['cl', 'roadm'], 'one of them, one a night'); + assert.equal(ev('xpDown(S.links.find(l=>l.id===x))'), true); + ev('compute()'); + assert.ok(ev('R.load[x]||0') === 0 && ev('R.served') > 0); + assert.deepEqual(errors, []); +}); + +test('the decom order never hands back a wave the build standard upgraded that same shift', t => { + const { ev, errors } = game(t); + // A 800G wave and two 100G waves between Frankfurt and Amsterdam, in three trenches. + const big = wave(ev, 'fra', 'ams', 3), w1 = wave(ev, 'fra', 'ams', 1), w2 = wave(ev, 'fra', 'ams', 1); + hire(ev, 'annie'); + ev("S.ops.on.decom=true;S.ops.p.decom={keep:false}"); + std(ev, { wv: 2 }); + // The plan sees a pair that needs all three once the small ones are 400G; the routing after the shift's jobs, which + // decom reads, sees almost nothing on them. + ev(`compute();R.load[${lit(big)}]=700;R.load[${lit(w1)}]=150;R.load[${lit(w2)}]=150`); + assert.equal(ev('bstdQuote(true).n'), 2, 'both small waves go up'); + ev('opsDay(S.day)'); + const tiers = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='wave').map(l=>l.tier))")); + assert.deepEqual(tiers(), [3, 2, 2], 'both upgraded, both kept today'); + assert.deepEqual(said(ev), [['std', 2]]); + // Tomorrow they are the decom order's to judge again. + ev('S.day++;compute();opsDay(S.day)'); + assert.deepEqual(tiers(), [3]); + assert.deepEqual(said(ev), [['decom', 2]]); + assert.deepEqual(errors, []); +}); + +// In play the test is routed in the route worker. jsdom has no Worker: a second page plays it (rwServe() there), as in +// tests/day-steps.test.js. The day is the day dayTick() plays, and the page itself never routes. +test("in play, the standard's fiber test is routed by the route worker, and the day is the day dayTick() plays", t => { + // The ring of fibers, Amsterdam's and Paris's broadband on it. + const RING = "for(const [a,b] of [['fra','ams'],['ams','par'],['par','fra']]){const id=uid();S.links.push({id,a,b,kind:'df',own:false,sys:'lite',ch:['zr4','zr4'],km:Math.round(kmBetween(a,b)),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});}compute();" + + "ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap={};S.ops.on.std=true;closeModal();S.popStd=bstdPut({...bstd(),sys:'roadm'});__reseed(4242);"; + const open = seed => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; }; + const ref = open(777), page = open(777), wk = open(1); + for (const h of [ref, page]) { h.ev(BASE); h.ev(RING); } + page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});'); + page.ev('window.__pc=0;const _c=compute;compute=function(){__pc++;return _c.apply(this,arguments);};'); + wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};'); + let trials = 0; + const pump = () => { for (;;) { + if (page.ev('__later.length')) { page.ev('__later.shift()()'); continue; } + if (!page.ev('__q.length')) break; + if (page.ev('!!(__q[0].trial&&__q[0].trial.dark)')) trials++; + wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); } }; + ref.ev('dayTick()'); + page.ev('rwDay()'); pump(); + assert.equal(trials, 1, 'the fiber test went to the worker'); + assert.equal(page.ev('__pc'), 0, 'no routing on the page'); + assert.equal(page.ev("S.links.filter(l=>l.sys==='roadm').length"), 1, 'and it passed: the rest of the ring carries its traffic'); + const STATE = 'JSON.stringify({S,served:R.served,load:R.load})'; + assert.equal(page.ev(STATE), ref.ev(STATE), 'the same day as dayTick()'); + assert.deepEqual([...ref.errors, ...page.errors, ...wk.errors], []); +}); + +// In play the shift rests between the standard's jobs (DAY_REST, rwRest()), and the player can tap meanwhile: every job +// is checked again against the game as it is then, not as the plan found it at the start of the shift. +test('the player acts while the shift rests: nothing past the standard, nothing paid twice, nothing claimed, and no snag for a POP gone', t => { + // Every POP on one router. std: the standard; act: what the player does at the first rest after a job of the shift. + const play = (std, act, setup = '') => { + const { ev, errors } = game(t, "for(const c of ['fra','ams','par','lon'])S.pops[c].routers=1;compute()"); + hire(ev, 'annie'); + ev(`S.popStd=${std};${setup};window.__later=[];RW.budget=0;RW.later=f=>__later.push(f)`); + ev('rwDay()'); + let spent = null; + while (ev('__later.length')) { + if (spent === null && ev('S.ops.spent.std>0')) { spent = ev('S.ops.spent.std'); ev(act); } + ev('__later.shift()()'); + } + assert.ok(spent > 0, 'the shift rested after a job'); + return { ev, errors, spent }; + }; + const routers = ev => JSON.parse(ev('JSON.stringify(Object.fromEntries(Object.entries(S.pops).map(([c,p])=>[c,p.routers])))')); + // The button brings every POP up to the standard while the shift rests after its first job. + let { ev, errors, spent } = play('{rt:3}', 'ACT.bstdApply()'); + assert.deepEqual(routers(ev), { fra: 3, ams: 3, par: 3, lon: 3 }, 'three routers each, as the standard says'); + assert.equal(ev('S.ops.spent.std'), spent, 'the shift paid for nothing after the button'); + assert.deepEqual(said(ev), [['std', 1]]); + assert.deepEqual(errors, []); + // The same with a model: the swaps the button did are not the shift's. + ({ ev, errors, spent } = play("{g:RG.findIndex(r=>r.n==='Absolute Unit 1.6T'),rt:2}", 'ACT.bstdApply()', "for(const c in S.pops)S.pops[c].routers=2")); + assert.deepEqual(JSON.parse(ev('JSON.stringify([...new Set(Object.values(S.pops).map(p=>RG[p.rgen].n))])')), ['Absolute Unit 1.6T']); + assert.equal(ev('S.ops.spent.std'), spent); + assert.deepEqual(said(ev), [['std', 1]], 'one swap, not four'); + assert.deepEqual(errors, []); + // A PNI the player orders by hand meanwhile, smaller than the plan's: the shift does not order it again as an upgrade. + const net = "NETS.find(n=>n.pops.includes('fra')&&n.pops.includes('ams')&&pniMin(n.id)===0&&peerOk(n.id,'pni','ams').ok&&peerOk(n.id,'pni','fra').ok).id"; + ({ ev, errors, spent } = play('{rt:2,pni:2}', `pniPlace(pniQuote('ams',${net},0))`, + `S.rules.pnis='instant';window.__net=${net};S.pni.push({id:'P1',city:'fra',net:__net,tier:1,ready:S.day});compute();const _v=pniVal;pniVal=(id,c)=>id===__net&&c==='ams'?{..._v(id,c),worth:true,want:40,tier:1}:_v(id,c)`)); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(x=>x.city==='ams').map(x=>[x.tier,!!x.up]))")), [[0, false]], 'the player\'s own, as ordered'); + assert.deepEqual(said(ev), [['std', 4]], 'the routers only'); + assert.deepEqual(errors, []); + // Amsterdam decommissioned meanwhile: its jobs are left out, the order runs on, the other POPs get theirs. + ({ ev, errors } = play('{rt:3}', "decommission(['ams'])")); + assert.equal(ev('S.ops.on.std'), true, 'the order is still on'); + assert.deepEqual(said(ev), [['std', 6]], 'no snag'); + assert.deepEqual(routers(ev), { fra: 3, par: 3, lon: 3 }); + assert.deepEqual(errors, []); +}); diff --git a/tests/build-standard.test.js b/tests/build-standard.test.js index faefc4f..d03bedd 100644 --- a/tests/build-standard.test.js +++ b/tests/build-standard.test.js @@ -12,7 +12,8 @@ const { lit } = require('../scripts/lib/js-literal'); const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');S.rules.pnis='instant';" + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});compute()"; const AU = "RG.findIndex(r=>r.n==='Absolute Unit 3.2T')"; -const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;S.ops.cap.std=0;S.ops.on.std=true;closeModal()"); +// Kevin by default; a fiber test that counts swaps a night hires Annie (Kevin does two: tests/bstd-owner.test.js). +const hire = (ev, id = 'kevin') => ev(`ACT.opsHire({id:'${id}'});S.ops.floor=0;S.ops.cap.std=0;S.ops.on.std=true;closeModal()`); const shift = ev => ev('opsDay(S.day)'); function game(t, extra = '') { const h = load(); @@ -144,9 +145,9 @@ test('ports: LAG members up to the standard, split over both buildings; PNIs spr assert.deepEqual(errors, []); }); -test('fiber: the line system only on a quiet fiber or with a parallel link, one a shift; faster optics, old ones on the shelf; bigger waves', t => { +test('fiber: the line system only on a quiet fiber or with a way around, one a shift; faster optics, old ones on the shelf; bigger waves', t => { const { ev, errors } = game(t); - hire(ev); + hire(ev, 'annie'); const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'par', ['zr4']); @@ -189,7 +190,7 @@ test('fiber: the line system only on a quiet fiber or with a parallel link, one test('quiet fibers take their line system one a shift and buy nothing in between: the intern spends what the quote said', t => { const { ev, errors } = game(t); - hire(ev); + hire(ev, 'annie'); const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); ev(`ACT.buildPop({city:'par'});ACT.buildPop({city:'lon'});for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4'])); diff --git a/tests/intern-optical-upgrade.test.js b/tests/intern-optical-upgrade.test.js index f55544f..1166b4e 100644 --- a/tests/intern-optical-upgrade.test.js +++ b/tests/intern-optical-upgrade.test.js @@ -1,5 +1,6 @@ // The intern upgrades optical transport: line systems up a size (only where the traffic gets around the day-long swap and -// no customer rides the fiber), optics traded for bigger ones on full, hot fiber, or every fiber up to a chosen line system. +// no customer rides the fiber), optics traded for bigger ones on full, hot fiber, or every fiber up to the build standard's +// line system. const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); @@ -21,6 +22,8 @@ function game(t, extra) { return h; } const order = (ev, p) => ev(`S.ops.on.optup=true;S.ops.p.optup=${JSON.stringify(p)}`); +// The line system every fiber should have: the build standard's. +const goal = (ev, sys) => ev(`S.popStd=bstdPut({...bstd(),sys:${JSON.stringify(sys)}})`); // The fiber runs at 90% of what it carries. const heat = ev => ev("R.load.f=dfCap(S.links[0])*0.9"); const fiber = ev => JSON.parse(ev("JSON.stringify({sys:S.links[0].sys,ch:S.links[0].ch.join(),down:S.links[0].eqDown>S.day})")); @@ -69,10 +72,11 @@ test('no way around, or a customer on the fiber: no swap; bigger optics instead, assert.deepEqual(errors, []); }); -test('a chosen line system: every fiber below it is moved up, two steps in one night if need be, one fiber a night', t => { +test("the build standard's line system: every fiber below it is moved up, two steps in one night if need be, one fiber a night", t => { const { ev, errors } = game(t, "S.links[0].ch=['zr4'];" + "for(const [i,a,b] of [[2,'fra','par'],[3,'par','ams']])S.links.push({id:'g'+i,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:'t'+i,ready:0,cut:0,mo:1,pairs:1});compute()"); - order(ev, { sys: 'cl', at: 90 }); + order(ev, { at: 90 }); + goal(ev, 'cl'); const want = ev("sysCost('roadm')+sysCost('cl')"); const sys = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='df').map(l=>l.sys))")); const c0 = ev('S.cash'); @@ -82,10 +86,12 @@ test('a chosen line system: every fiber below it is moved up, two steps in one n for (let n = 0; n < 6 && sys().some(s => s !== 'cl'); n++) ev('S.day+=2;compute();opsDay(S.day)'); assert.deepEqual(sys(), ['cl', 'cl', 'cl', 'cl'].slice(0, sys().length), 'the rest on the nights after'); // Nothing is ever moved down. - ev("S.ops.p.optup.sys='roadm';S.day+=2;compute();opsDay(S.day)"); + goal(ev, 'roadm'); + ev('S.day+=2;compute();opsDay(S.day)'); assert.ok(sys().every(s => s === 'cl')); // A fiber with no way around is tested once, then left alone for a week: no routing every night for nothing. - ev("S.links=S.links.filter(l=>l.id==='f');S.links[0].sys='lite';S.ops.p.optup.sys='cl';S.day+=2;compute()"); + goal(ev, 'cl'); + ev("S.links=S.links.filter(l=>l.id==='f');S.links[0].sys='lite';S.day+=2;compute()"); const runs = () => ev('window.__runs||0'); ev("window.__runs=0;const c0=compute;compute=function(){window.__runs++;return c0.apply(this,arguments);};opsDay(S.day)"); assert.equal(sys()[0], 'lite'); @@ -98,7 +104,7 @@ test('a chosen line system: every fiber below it is moved up, two steps in one n assert.deepEqual(errors, []); }); -test('the budget holds, the setting is saved, and the sheet shows it as lists', t => { +test("the budget holds, the settings are saved, and the sheet shows them as lists and the line system as the standard's", t => { const { ev, dom, errors } = game(t); order(ev, { at: 80 }); ev('S.ops.cap.optup=10000'); @@ -107,16 +113,22 @@ test('the budget holds, the setting is saved, and the sheet shows it as lists', assert.equal(fiber(ev).sys, 'lite', 'a $10k budget does not buy a line system'); assert.ok(ev("S.ops.log[0].r.some(x=>x[0]==='broke')")); const back = v => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.optup=${v};sanitize(s);return JSON.stringify(s.ops.p.optup);})()`); - assert.deepEqual(JSON.parse(back("{sys:'cl',swap:false,at:70}")), { at: 70, sys: 'cl', swap: false }); - assert.deepEqual(JSON.parse(back("{sys:'lite',swap:'yes'}")), {}); + assert.deepEqual(JSON.parse(back("{swap:false,at:70}")), { at: 70, swap: false }); + assert.deepEqual(JSON.parse(back("{at:55,swap:'yes'}")), {}); assert.deepEqual(JSON.parse(back('undefined')), {}, 'an old save without the order'); ev("const s=JSON.parse(JSON.stringify(S));delete s.ops.on.optup;sanitize(s);window.__off=s.ops.on.optup"); assert.equal(ev('__off'), false, 'off in an old save'); dom.window.innerWidth = 360; ev("ACT.phoneTab({t:'noc'})"); dom.window.document.querySelector('#leftBody [data-act="opsOpen"]').click(); - const sel = [...dom.window.document.querySelectorAll('#modalCard select[data-chg="opsParam"]')].find(s => s.dataset.args === '{"k":"optup","p":"sys"}'); - assert.deepEqual([...sel.options].map(o => o.textContent), ['Next one, when full', 'ROADMaster 9000', 'ROADMaster 9000 C+L']); - assert.match(dom.window.document.getElementById('modalCard').textContent, /Upgrade optical transport/); + const doc = dom.window.document, card = () => [...doc.querySelectorAll('#modalCard .ops-o.on')].find(o => o.querySelector('.nm').textContent === 'Upgrade optical transport'); + assert.deepEqual([...card().querySelectorAll('select[data-chg="opsParam"]')].map(s => JSON.parse(s.dataset.args).p), ['at', 'swap'], 'no line system list of its own'); + // The line system is the build standard's: what it says, and the way to the sheet. + assert.match(card().querySelector('.ops-from').textContent, /^Line systemFrom the build standard: Next one, when full/); + goal(ev, 'cl'); + ev('ACT.opsOpen()'); + assert.equal(card().querySelector('.ops-from b').textContent, 'From the build standard: ROADMaster 9000 C+L'); + card().querySelector('.ops-from [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), 'the button opens the build standard'); assert.deepEqual(errors, []); }); diff --git a/tests/intern-personas.test.js b/tests/intern-personas.test.js index f663cf1..81800d8 100644 --- a/tests/intern-personas.test.js +++ b/tests/intern-personas.test.js @@ -57,7 +57,7 @@ test('Kevin swaps two line systems a night, the others one', t => { "S.links=[['f1','fra','ams'],['f2','ams','par'],['f3','par','fra'],['f4','fra','ams']].map(([id,a,b])=>({id,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:id,ready:0,cut:0,mo:1,pairs:1}));compute()"; for (const [id, want] of [['kevin', 2], ['annie', 1], ['tracy', 1]]) { const { ev, errors } = game(t, id, fibers); - ev("S.ops.on.optup=true;S.ops.p.optup={sys:'roadm'};opsDay(S.day)"); + ev("S.ops.on.optup=true;S.popStd=bstdPut({...bstd(),sys:'roadm'});opsDay(S.day)"); assert.equal(ev("S.links.filter(l=>l.sys==='roadm').length"), want, id); assert.deepEqual(errors, []); } diff --git a/tests/intern-router-model.test.js b/tests/intern-router-model.test.js index a28ef92..3a1fe7c 100644 --- a/tests/intern-router-model.test.js +++ b/tests/intern-router-model.test.js @@ -1,4 +1,5 @@ -// The intern standardizes routers on a chosen model within the budget, and every setting in the Ops sheet is a list. +// The intern standardizes routers on the build standard's model within the budget; the Ops sheet says where the model +// comes from and leads to the sheet that sets it, and every other setting there is a list. const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); @@ -17,12 +18,15 @@ function game(t) { return h; } const gens = ev => JSON.parse(ev("JSON.stringify(['fra','ams','par'].map(c=>S.pops[c].rgen))")); +// The build standard's router model (the standard's other targets stay as they are). +const model = (ev, g) => ev(`S.popStd=bstdPut({...bstd(),g:${g}})`); -test('a chosen model: every POP on a smaller one is swapped to it, at the price of the swap, never as an outage', t => { +test("the build standard's model: every POP on a smaller one is swapped to it, at the price of the swap, never as an outage", t => { const { ev, errors } = game(t); const m = ev(MODEL); assert.ok(m > 0 && ev(`rgOpen(${m})`), 'the model is unlocked at level 3'); - ev(`S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto',model:${m}};S.ops.cap.routers=0;compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0`); + model(ev, m); + ev("S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto'};S.ops.cap.routers=0;compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0"); const want = ev(`swapCost('ams',${m})+swapCost('par',${m})`), c0 = ev('S.cash'); ev('opsDay(S.day)'); assert.deepEqual(gens(ev), [1, m, m], 'Amsterdam (a second router) and Paris (no traffic yet) are swapped; Frankfurt has one busy router, so no'); @@ -32,18 +36,19 @@ test('a chosen model: every POP on a smaller one is swapped to it, at the price // Frankfurt gets its turn once it has a second router. ev('S.pops.fra.routers=2;S.day++;compute();opsDay(S.day)'); assert.deepEqual(gens(ev), [m, m, m]); - // Busy POPs on the chosen model get more routers, never a swap to another one. + // Busy POPs on the standard's model get more routers, never a swap to another one. ev("S.ops.p.routers.how='swap';S.day++;compute();R.nodeLoad.ams=R.nodeCap.ams*0.95;opsDay(S.day)"); - assert.equal(ev('S.pops.ams.rgen'), m, 'no swap away from the chosen model'); + assert.equal(ev('S.pops.ams.rgen'), m, 'no swap away from the standard\'s model'); ev("S.ops.p.routers.how='add';S.day++;compute();R.nodeLoad.ams=R.nodeCap.ams*0.95;opsDay(S.day)"); assert.equal(ev('S.pops.ams.routers'), 3, 'a busy POP gets a third router'); assert.deepEqual(errors, []); }); -test('the budget decides how far it gets, the busiest POP first; a smaller model is never a downgrade', t => { +test('the budget decides how far it gets, the busiest POP first; a smaller model is never a downgrade; a locked one means the best unlocked below it', t => { const { ev, errors } = game(t); const m = ev(MODEL); - ev(`S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto',model:${m}};compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;R.nodeLoad.par=R.nodeCap.par*0.5`); + model(ev, m); + ev("S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto'};compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;R.nodeLoad.par=R.nodeCap.par*0.5"); // A budget for one swap: Paris is the busier, so it goes first and Amsterdam waits for next month. const one = ev(`swapCost('par',${m})`); ev(`S.ops.cap.routers=OPS_CAPS.filter(c=>c>=${one}).sort((a,b)=>a-b)[0]`); @@ -54,24 +59,70 @@ test('the budget decides how far it gets, the busiest POP first; a smaller model // Next month, a new budget: Amsterdam. ev('{const m0=monthIdx(S.day);while(monthIdx(S.day)===m0)S.day++;}compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;opsDay(S.day)'); assert.deepEqual(gens(ev), [1, m, m]); - // Choosing a smaller model swaps nothing back. - ev("S.ops.cap.routers=0;S.ops.p.routers.model=RG.findIndex(r=>r.n==='Edge Lord 400');S.day++;compute();opsDay(S.day)"); + // A smaller model in the standard swaps nothing back. + ev("S.ops.cap.routers=0;S.day++;compute()"); + model(ev, "RG.findIndex(r=>r.n==='Edge Lord 400')"); + ev('opsDay(S.day)'); assert.deepEqual(gens(ev), [1, m, m]); + // A model above the level: the best main-line model unlocked below it, as the standard means for a new POP. + const big = ev("RG.findIndex(r=>r.n==='Arrrhipster 7800R5')"); + assert.equal(ev(`rgOpen(${big})`), false); + model(ev, big); + ev('S.pops.fra.routers=2'); + const best = ev(`bstdModel(${big},'fra')`); + ev('S.day++;compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;opsDay(S.day)'); + assert.equal(ev('S.pops.fra.rgen'), best); + assert.ok(ev('S.pops.fra.rgen') > 1 && ev(`RG[S.pops.fra.rgen].cap { +test('saves: an old model or line system setting moves into the standard when it names none; its own wins; neither stays neither', t => { const { ev, errors } = game(t); - const back = v => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.routers=${v};sanitize(s);return JSON.stringify(s.ops.p.routers);})()`); - assert.deepEqual(JSON.parse(back(`{model:${ev(MODEL)}}`)), { model: ev(MODEL) }); - assert.deepEqual(JSON.parse(back('{model:999}')), {}); - assert.deepEqual(JSON.parse(back("{model:'7'}")), {}); - assert.deepEqual(JSON.parse(back('undefined')), {}, 'an old save without it'); - assert.equal(ev("opsP('routers','model')"), 'next'); + const m = ev(MODEL), el = ev("RG.findIndex(r=>r.n==='Edge Lord 400')"); + // An old save: the routers order's model and the optical order's line system, with or without a standard. x: what + // else the save says (by default both orders ran, with Kevin hired). + const ON = 's.ops.on.routers=true;s.ops.on.optup=true'; + const back = (p, std, x = ON) => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p=${p};s.popStd=${std};${x};sanitize(s);return JSON.stringify({p:s.ops.p,std:s.popStd});})()`)); + let r = back(`{routers:{model:${m},at:70},optup:{sys:'cl',swap:false}}`, 'null'); + assert.deepEqual(r.std, { g: m, rt: 1, sys: 'cl' }, 'no standard: both move into a new one'); + assert.deepEqual(r.p.routers, { at: 70 }, 'the old setting is gone, the others stay'); + assert.deepEqual(r.p.optup, { swap: false }); + // Only what an order that ran used: a paused order's setting, or one with nobody hired, did nothing, and goes. + r = back(`{routers:{model:${m},at:70},optup:{sys:'cl'}}`, 'null', 's.ops.on.routers=false'); + assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, { at: 70 }, {}], 'both paused: no standard'); + r = back(`{routers:{model:${m}},optup:{sys:'cl'}}`, 'null', 's.ops.on.routers=true'); + assert.deepEqual(r.std, { g: m, rt: 1 }, 'the routers order ran, the optical order was paused'); + r = back(`{routers:{model:${m}},optup:{sys:'cl'}}`, '{rt:2}', ON + ';s.ops.intern=null'); + assert.deepEqual([r.std, r.p.routers, r.p.optup], [{ rt: 2 }, {}, {}], 'nobody hired: the standard stays as it was'); + r = back(`{routers:{model:${m}},optup:{sys:'roadm'}}`, `{g:${el},rt:2,sys:'cl',gen:true}`); + assert.deepEqual(r.std, { g: el, rt: 2, gen: true, sys: 'cl' }, 'a standard that names its own keeps them'); + assert.deepEqual([r.p.routers, r.p.optup], [{}, {}]); + r = back(`{routers:{model:${m}},optup:{sys:'roadm'}}`, '{rt:3,lag:2}'); + assert.deepEqual(r.std, { g: m, rt: 3, lag: 2, sys: 'roadm' }, 'one without them takes them and keeps the rest'); + r = back("{routers:{model:'next'},optup:{sys:'next'}}", 'null'); + assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, {}, {}], "'next' was no choice: nothing moves"); + r = back("{routers:{model:999},optup:{sys:'warp'}}", 'null'); + assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, {}, {}], 'junk moves nowhere'); + r = back("{routers:{model:'7'}}", `{g:${el}}`); + assert.deepEqual(r.std, { g: el, rt: 1 }); + r = back('undefined', 'undefined'); + assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, {}, {}], 'an old save with neither'); + // The order reads the standard: none set, it is the next generation when busy. + assert.equal(ev('bstd().g'), 'keep'); + // A loaded save whose model sat in a paused order, the intern since fired: new POPs cost what they did. + const lon = ev("popCost('lon')"); + ev(`S.ops.p.routers={model:${m}};S.ops.on.routers=false;S.ops.intern=null;S=migrate(JSON.parse(JSON.stringify(S)))`); + assert.deepEqual([ev('S.popStd'), ev("newPopCost('lon')"), ev("JSON.stringify(S.ops.p.routers)")], [null, lon, '{}']); + ev("ACT.buildPop({city:'lon'})"); + assert.equal(ev('S.pops.lon.rgen||0'), 0, 'and get the basic router'); + // A loaded save that had a model in a running order plays with it: the shift swaps to it. + ev(`ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();S.ops.p.routers={model:${m}};S.ops.on.routers=true;S=migrate(JSON.parse(JSON.stringify(S)));compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;opsDay(S.day)`); + assert.equal(ev('S.popStd.g'), m); + assert.equal(ev('S.pops.ams.rgen'), m); assert.deepEqual(errors, []); }); -test('every setting in the Ops sheet is a list to pick from, on a phone too', t => { +test('the Ops sheet: the model comes from the build standard, one line and a way there; every other setting is a list, on a phone too', t => { const { ev, dom, errors } = game(t); dom.window.innerWidth = 360; const doc = dom.window.document; @@ -88,24 +139,29 @@ test('every setting in the Ops sheet is a list to pick from, on a phone too', t // Every setting of every order, every budget and the floor. const n = ev('OPS.reduce((a,d)=>a+Object.keys(d.p).length+(d.cap?1:0),0)+1'); assert.equal(doc.querySelectorAll('#modalCard .ops-p select').length, n); - // The model list: the next generation, then the models you can buy, smallest first. - const model = sel('opsParam', { k: 'routers', p: 'model' }); - assert.ok(model, 'the routers order has a model list'); - assert.equal(model.options[0].textContent, 'Next generation, when busy'); - assert.ok([...model.options].some(o => o.textContent === 'Arrrhipster 7800R')); - assert.ok(![...model.options].some(o => o.textContent === 'Absolute Unit 3.2T'), 'only models unlocked at your level'); - pick(model, 'Arrrhipster 7800R'); - assert.equal(ev("opsP('routers','model')"), ev(MODEL)); - assert.equal(doc.activeElement && doc.activeElement.dataset.args, JSON.stringify({ k: 'routers', p: 'model' }), 'the keyboard stays on the list'); + assert.equal(sel('opsParam', { k: 'routers', p: 'model' }), undefined, 'no model list of its own'); + // The routers order: where its model comes from, and the button to the sheet that sets it. + const routers = [...doc.querySelectorAll('#modalCard .ops-o.on')].find(o => o.querySelector('.nm').textContent === 'Keep routers ahead'); + assert.ok(routers.querySelector('.ops-from'), 'a line in the routers order'); + assert.match(routers.querySelector('.ops-from').textContent, /^ModelFrom the build standard: Next generation, when busy/); + routers.querySelector('.ops-from [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), 'the button opens the build standard'); + // Set there, it is what the line says. + pick([...doc.querySelectorAll('#modalCard select[data-chg="bstdSet"]')].find(s => JSON.parse(s.dataset.args).k === 'g'), 'Arrrhipster 7800R'); + assert.equal(ev('bstd().g'), ev(MODEL)); + ev('ACT.opsOpen()'); + const r2 = [...doc.querySelectorAll('#modalCard .ops-o.on')].find(o => o.querySelector('.nm').textContent === 'Keep routers ahead'); + assert.match(r2.querySelector('.ops-from b').textContent, /^From the build standard: Arrrhipster 7800R$/); + // The rest are still lists. pick(sel('opsParam', { k: 'transit', p: 'prov' }), 'Already connected'); assert.equal(ev("opsP('transit','prov')"), 'have'); pick(sel('opsCap', { k: 'routers' }), 'no limit'); assert.equal(ev("opsCap('routers')"), 0); pick(sel('opsFloor', {}), ev('fmt$(1e6)')); assert.equal(ev('S.ops.floor'), 1e6); - // A value from nowhere changes nothing; the MCP tools still step without a value. - ev("ACT.opsParam({k:'routers',p:'model',v:'99'});ACT.opsCap({k:'routers',v:'-1'});ACT.opsFloor({v:'x'})"); - assert.deepEqual([ev("opsP('routers','model')"), ev("opsCap('routers')"), ev('S.ops.floor')], [ev(MODEL), 0, 1e6]); + // A value from nowhere changes nothing; the retired setting is nothing either; the MCP tools still step without a value. + ev("ACT.opsParam({k:'routers',p:'model',v:'1'});ACT.opsCap({k:'routers',v:'-1'});ACT.opsFloor({v:'x'})"); + assert.deepEqual([ev('bstd().g'), ev("opsCap('routers')"), ev('S.ops.floor'), ev("JSON.stringify(S.ops.p.routers||{})")], [ev(MODEL), 0, 1e6, '{}']); ev("ACT.opsParam({k:'routers',p:'how'})"); assert.equal(ev("opsP('routers','how')"), 'add'); assert.deepEqual(errors, []); diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index ea139e8..beb7695 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -343,6 +343,33 @@ test('a list in a sheet sends its own arguments with the value picked: the build assert.deepEqual(s.errors(), []); }); +test('the router model and the line system are set in the build standard only: the orders\' old settings point there', () => { + const { s, T, ev } = sandbox({ pops: [] }); + act(T, 'opsHire', { id: 'annie' }); + ev('closeModal()'); + for (const k of ['routers', 'optup']) act(T, 'opsToggle', { k }); + ev('closeModal()'); + assert.throws(() => act(T, 'opsParam', { k: 'routers', p: 'model', v: '1' }), /routers order takes its router model from the build standard: set it with bstdSet \(k "g"\)/); + assert.throws(() => act(T, 'opsParam', { k: 'optup', p: 'sys' }), /optup order takes its line system from the build standard: set it with bstdSet \(k "sys"\)/); + assert.equal(ev("JSON.stringify([S.ops.p.routers||{},S.ops.p.optup||{},S.popStd])"), '[{},{},null]', 'nothing changed'); + act(T, 'opsParam', { k: 'routers', p: 'how' }); + assert.equal(ev("opsP('routers','how')"), 'add', 'its other settings still step'); + ev('closeModal()'); + // The catalog of orders has no such settings; the docs say where they went. + const O = T('catalog', { name: 'OPSK' }); + const ps = JSON.stringify(O); + assert.doesNotMatch(ps, /"model"|"sys"/); + assert.match(T('schema', { section: 'commands' }).opsParam.doc, /bstdSet k "g" and k "sys"/); + // Set there, both orders use it; the Ops sheet says so, with the way to the sheet. + act(T, 'bstdSet', { k: 'sys', v: '2' }); + assert.equal(ev('bstd().sys'), 'cl'); + act(T, 'opsOpen'); + const sc = T('screen'); + assert.match(sc.text, /From the build standard: ROADMaster 9000 C\+L/); + assert.ok(sc.buttons.some((b) => b.act === 'bstdOpen'), 'a button to the build standard'); + assert.deepEqual(s.errors(), []); +}); + test('new_game takes your own ASN and the sandbox chaos dial', () => { const s = createSession(), T = tools(s), ev = (x) => s.game.ev(x); assert.equal(T('new_game', { city: 'ams', asn: 213337, seed: 2 }).asn, 213337); From 3bc1641a46cecf1bf27bcef38fa8efb4fb5b83ca Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 06:55:24 +0100 Subject: [PATCH 421/491] Plans: the server runs every multiplayer game, at 1x with a speed vote --- docs/plans/next-session.md | 46 +++++++++++++------------------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/docs/plans/next-session.md b/docs/plans/next-session.md index be20f7b..212fe92 100644 --- a/docs/plans/next-session.md +++ b/docs/plans/next-session.md @@ -12,33 +12,21 @@ planned or known, not built. ## Next features -3. **Wave B starts with a shared session clock.** Proposed on 2026-11-07, not decided yet: it changes how every - multiplayer game plays. Today each player's game runs in their own browser at their own speed (pause, 0.5× to 8×), so - players in one session are on different days. The proposal: the server keeps the time and every game in the session - follows it. The simulation stays in the browser. - - **Server:** a session gets a pace when it is created: one game day every 30 s to 5 min (agent mode's list). Never the - normal 2.5 s, which is 1,440 game days an hour. The day only moves while at least one player was seen recently (the - roster already keeps `seen`), so nobody comes back to years of unattended play. Every roster answer carries the - server's time and the session day. - - **Browser:** the clock is locked to the session. `UI.clockLocked` and `HOOKS.speed()` (`50-state.js`) already hide - the speed buttons and refuse pause, and `save()` already leaves `uiSpeed` alone while locked. The code goes in - `src/game/`, because `src/agent/` does not ship (ADR 0004), so it needs its own copy of agent mode's worker ticker - (`src/agent/85-ticker.js`) to keep time in hidden tabs. Agent mode also sets `HOOKS.speed`: the session wins, and - agent mode is off in a multiplayer game. - - **Catching up:** a game behind the session day runs days until it matches, a few per frame, with its progress - shown. It needs its own loop: with the route worker, `runClock` holds one day at a time. A day takes about 30 ms on - the big test network, so 400 missed days take about 12 s on a desktop and longer on phones. Late joiners start on - the session's current day (to check: what in the world depends on the day a game started). - - **Nobody can pause or speed up.** That is what "the same day" means. - - **Later, optional: the server plays absent players.** It opens an offline player's save in a headless game (jsdom, - as `scripts/lib/mcp-game.js` already does with its realtime clock) and runs their days with the intern. The - browser takes the save back on return through phase 1's save numbers, so the server is just one more device. Up to - about 0.5 GB of RAM per absent player. Without it, other players see an absent network stand still. - - **Not proposed: a server that runs every game** with the browser only showing it. Every click would be a round - trip, and the page reads `S` and `R` directly everywhere, so it would be a rewrite. Its one gain over the above is - verified cards (today the server trusts them). - - **Phase 2 gets simpler:** its wall-clock timing (tenders that close after 10 real minutes, `idle` ≥ 300 s, notice on - each player's own clock, the soak test's "own speed") can move to game days. +3. **The server runs every game of a multiplayer build** (decided 2026-11-07, being designed and built). In a page built + with `MP_API`, each network's days run on the session server, not in the browser, so every player of a session is on + the same day at the same speed. A single-player game in that build is a session of one and runs there too; old local + saves keep working in the browser, and the plain build stays exactly as it is (static, no server, no requests). + - **Speed:** 1× by default (one day per `DAY_MS`, 2.5 s). Players vote for another speed, pause included; alone in a + session your vote decides at once. The world pauses while no player is connected. + - **Absent players:** while anyone plays, the networks of those away keep running on the server (their intern's + standing orders help), so nobody falls behind. + - **Why:** the same day for everyone, which phase 2's trades need, and less work for phones at higher speeds (at 1× the + day is about 10–15% of a phone's CPU on the big test network, at 8× about half; map and panels stay in the browser). + - **What stays in the browser:** map drawing and panels. The flow tables (`R.ef`/`R.fl`, about 3 MB per routing on the + big network) cannot be shipped every day, so what reads them (a selected link on the map, the link panel, PNI value, + puzzles) has to ask for them. + - **Phase 2 gets simpler:** with every world in one server process, its wall-clock timing (tenders that close after 10 + real minutes, `idle` ≥ 300 s, notice on each player's own clock) can move to game days. 4. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative over the multiplayer server, and **multiplayer phase 2** (players as carriers in each other's simulations: transit, peering, PNIs, shared fiber): design in `docs/plans/multiplayer-phase2.md`. @@ -75,7 +63,5 @@ planned or known, not built. ## Housekeeping -- `npm run perf -- --browser` needs Chromium (`sudo pacman -S chromium`, then `PERF_CHROME=/usr/bin/chromium`); only the - jsdom benchmark has been run. -- Upstream release tags are not on `vanvik` yet: `git push vanvik --tags` if wanted. +- `npm run perf -- --browser` runs with `PERF_CHROME=/usr/bin/chromium`. - The merged worktrees under `.claude/worktrees/` and their `worktree-wf_*` branches can be removed. From 69328ce257b64e66a63feb61b4599a9753673fd4 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 07:01:34 +0100 Subject: [PATCH 422/491] IPv6-only broadband: 464XLAT city by city, a NAT64 pool next to CGNAT A broadband city can swap its home routers for ones with a CLAT (ip6Go / ip6Stop, from the city panel's Home broadband). Over 30 to 180 days an even share of the homes moves each day, paid as the routers go in ($4 a home), waiting while cash is short; starting needs only the first day's share. New homes in a swapping or finished city get the new router at the same price. The panel says how many addresses it frees and what it does to the monthly IPv4 bill. ip4Use splits homes into public, behind CGNAT and IPv6-only: the NAT64 pool (ceil(IPv6-only homes / NAT64 ratio), 64/128/256, default 128) comes right after business blocks, before dual-stack homes. NAT64 gateways cost the same per Gbps of IPv4 as CGNAT boxes; NAT64 refunds sit under CGNAT's at the same ratio and never reach zero. The IPv4 share of home traffic is now a curve: 0.55 on day 0, two points less a year, floor 0.2. Out-of-space advice names the sharing left to stretch. Everything is under rule ip4; old saves load unchanged (no field means dual stack). --- .claude/skills/gameplay-rules/SKILL.md | 2 +- CHANGELOG.md | 2 + site/i18n/de.js | 41 ++- site/i18n/es.js | 41 ++- site/i18n/fr.js | 41 ++- site/i18n/it.js | 41 ++- site/i18n/pt.js | 41 ++- src/agent/10-domains.js | 3 +- src/agent/20-commands.js | 11 +- src/agent/30-docs.js | 4 +- src/game/60-features/33-address-space.js | 57 ++- src/game/60-features/34-ipv6-only.js | 58 +++ src/game/80-simulation/50-sanitize.js | 2 +- src/game/88-days/10-day-tick.js | 5 +- src/game/90-actions/50-customers.js | 2 +- src/game/90-actions/54-address-space.js | 11 +- src/game/90-actions/55-ipv6-only.js | 9 + src/game/93-ui/50-city-panel.js | 2 +- src/game/94-dashboard/60-dashboard.js | 2 +- src/game/94-dashboard/72-address-space.js | 24 +- src/i18n/en.js | 41 ++- tests/address-space.test.js | 6 +- tests/gameplay-rules.test.js | 3 +- tests/mcp-commands.test.js | 2 +- tests/nat64.test.js | 415 ++++++++++++++++++++++ 25 files changed, 812 insertions(+), 54 deletions(-) create mode 100644 src/game/60-features/34-ipv6-only.js create mode 100644 src/game/90-actions/55-ipv6-only.js create mode 100644 tests/nat64.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 619584b..4268d96 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -46,7 +46,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: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | 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, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4 and CGNAT (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | +| 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, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4, CGNAT and IPv6-only homes behind NAT64 (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). 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. | | M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). | diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ed9b59..363c7d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Broadband cities can now go IPv6-only with 464XLAT, a second way to save IPv4 next to CGNAT. Start it from a city's Home broadband, which also says what it does to your monthly IPv4 bill: its home routers are swapped over a month or more, paid as each one goes in (new homes there get one too, at the same price), and the homes then need no IPv4 address of their own, only a share of a NAT64 pool at up to 256 homes per address, with fewer refunds than CGNAT at the same ratio. The bank's Address space section shows your homes as public, behind CGNAT and IPv6-only, with the NAT64 ratio next to the CGNAT one, and says which of the two to stretch when space runs out. +- CGNAT gets a little cheaper every year: the world moves to IPv6 about two points a year, so less of your homes' traffic needs IPv4 and the CGNAT and NAT64 boxes carry less of it. - The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too. - Your intern no longer takes a fiber dark for the build standard just because it looks quiet: like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day. - Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. diff --git a/site/i18n/de.js b/site/i18n/de.js index 92d66ae..0fe1bb2 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2693,20 +2693,26 @@ "ip4.cgnat_boxes":"CGNAT-Boxen", "ip4.cgnat_note":"Mehr Haushalte pro Adresse macht Platz für Kunden, aber Spiele und Portweiterleitungen leiden: {p} der Rechnung eines CGNAT-Haushalts gehen als Erstattung zurück.", "ip4.cgnat_ratio":"CGNAT: Haushalte pro Adresse", -"ip4.costs_row":"IPv4-Mieten und CGNAT", "ip4.free":"Frei für neue Kunden (Haushalte kommen zuerst hinter CGNAT)", "ip4.from_rir":"Von der RIR", "ip4.give_back":"Zurückgeben", "ip4.held":"Die RIR überträgt diesen Block erst ab {date} wieder.", "ip4.homes":"Breitband-Haushalte", +"ip4.homes_behind_cgnat":"Haushalte hinter CGNAT", "ip4.homes_cgnat":"{n}, davon {p} hinter CGNAT", +"ip4.homes_public":"Haushalte mit eigener Adresse", +"ip4.homes_v6":"Nur-IPv6-Haushalte (464XLAT)", +"ip4.homes_v6_pool":"{n}, NAT64-Pool {pool}", "ip4.in_use":"Deine Kunden brauchen diese Adressen: steck mehr Haushalte hinter CGNAT oder hol dir erst einen weiteren Block.", +"ip4.in_use_both":"Deine Kunden brauchen diese Adressen: pack mehr Haushalte auf jede CGNAT- oder NAT64-Adresse oder hol dir erst einen weiteren Block.", +"ip4.in_use_v6":"Deine Kunden brauchen diese Adressen: pack mehr Nur-IPv6-Haushalte auf jede NAT64-Adresse oder hol dir erst einen weiteren Block.", "ip4.lease":"Mieten {price}/Monat", "ip4.lease_out":"Vermieten +{price}/Monat", "ip4.leased_in":"Einen {p}-Block ({n} Adressen) für {price}/Monat gemietet.", "ip4.leased_in_mo":"Gemietet · {price}/Monat", "ip4.leased_out":"Dein {p}-Block ist vermietet: +{price}/Monat.", "ip4.leased_out_mo":"Vermietet · +{price}/Monat", +"ip4.leases_cgnat_nat64":"IPv4-Mieten, CGNAT und NAT64", "ip4.leases_in":"Gemietete Blöcke", "ip4.leases_out":"Vermietete Blöcke", "ip4.market":"Transfermarkt", @@ -2714,8 +2720,13 @@ "ip4.movable_from":"wieder übertragbar ab {date}", "ip4.n_addresses":{"one":"{n} Adresse","other":"{n} Adressen"}, "ip4.n_homes_per_address":{"one":"{n} Haushalt pro Adresse","other":"{n} Haushalte pro Adresse"}, +"ip4.nat64_gateways":"NAT64-Gateways", +"ip4.nat64_note":"Nur-IPv6-Haushalte haben kein eigenes IPv4: Was es noch braucht (Konsolen, Nur-IPv4-VPNs), teilt sich deinen NAT64-Pool, und {p} ihrer Rechnung gehen als Erstattung zurück, jedes Jahr weniger, weil die Welt zu IPv6 umzieht. Eine Stadt stellst du unter Heim-Breitband auf Nur-IPv6 um.", +"ip4.nat64_ratio":"NAT64: Nur-IPv6-Haushalte pro Adresse", "ip4.no_grow":"{name} ({city}) wollte auf {bw} wachsen, aber du hattest keine freien IPv4-Adressen dafür.", "ip4.no_space":"{name} braucht einen IPv4-Block {p} ({n} Adressen), und nur {free} sind frei. Kauf oder miete einen Block oder steck mehr Haushalte hinter CGNAT.", +"ip4.no_space_both":"{name} braucht einen IPv4-Block {p} ({n} Adressen), und nur {free} sind frei. Kauf oder miete einen Block oder pack mehr Haushalte auf jede CGNAT- oder NAT64-Adresse.", +"ip4.no_space_v6":"{name} braucht einen IPv4-Block {p} ({n} Adressen), und nur {free} sind frei. Kauf oder miete einen Block oder pack mehr Nur-IPv6-Haushalte auf jede NAT64-Adresse.", "ip4.note":"IPv6 ist kostenlos und unendlich. IPv4 ist seit Jahren aus: Geschäftskunden brauchen öffentliche Blöcke davon, und Haushalte, die nicht mehr reinpassen, teilen sich Adressen hinter CGNAT (IPv6-Traffic läuft an der Box vorbei).", "ip4.off":"Nach den Regeln dieses Spiels gibt es IPv4 reichlich.", "ip4.offer_needs":"Braucht einen IPv4-Block {p} ({n} Adressen); nur {free} frei.", @@ -2727,11 +2738,39 @@ "ip4.sell":"Verkaufen {price}", "ip4.sold":"Dein {p}-Block ist für {price} verkauft.", "ip4.squeezed":"Kein Platz mehr: {p} der Haushalte passen nicht mal bei {r} Haushalten pro Adresse rein. Ihre Verbindungen brechen ab und sie wollen Geld zurück: kauf oder miete einen Block.", +"ip4.squeezed_both":"Kein Platz mehr: {p} der Haushalte passen nicht mal bei {r} Haushalten pro CGNAT-Adresse und {r6} pro NAT64-Adresse rein. Ihre Verbindungen brechen ab und sie wollen Geld zurück: kauf oder miete einen Block.", +"ip4.squeezed_v6":"Kein Platz mehr: {p} der Haushalte passen nicht mal bei {r} Nur-IPv6-Haushalten pro NAT64-Adresse rein. Ihre Verbindungen brechen ab und sie wollen Geld zurück: kauf oder miete einen Block.", "ip4.take_back":"Zurückholen", "ip4.toast_cgnat":"Dein IPv4 ist voll. {p} deiner Haushalte teilen sich jetzt Adressen hinter CGNAT, und ein paar Gamer haben schon geschrieben.", "ip4.toast_out":"IPv4 ist aus. Selbst bei {r} Haushalten pro Adresse passt nicht jeder hinter CGNAT: kauf oder miete einen Block bei der Bank.", +"ip4.toast_out_both":"IPv4 ist aus. Selbst bei {r} Haushalten pro Adresse hinter CGNAT und {r6} bei NAT64 passt nicht jeder Haushalt rein: kauf oder miete einen Block bei der Bank.", +"ip4.toast_out_v6":"IPv4 ist aus. Selbst bei {r} Haushalten pro Adresse passt nicht jeder Nur-IPv6-Haushalt in deinen NAT64-Pool: kauf oder miete einen Block bei der Bank.", "ip4.too_many":"Du hast {n} IPv4-Blöcke, mehr kann ein Netz nicht führen. Verkauf kleine Blöcke oder gib sie zurück, um Platz für einen größeren zu schaffen.", +"ip4.v6_share":"IPv6-Anteil am Traffic der Haushalte dieses Jahr", "ip4.yours":"Deine IPv4-Adressen", +"ip6.already":"Jeder Haushalt hier ist schon Nur-IPv6.", +"ip6.busy":"Der Tausch läuft hier schon.", +"ip6.done":"{city} ist jetzt Nur-IPv6. Jeder Haushalt dort läuft mit 464XLAT, und was noch IPv4 braucht, teilt sich deinen NAT64-Pool.", +"ip6.dual_stack":"Dual Stack", +"ip6.every_home":"Alle Haushalte", +"ip6.go":"Auf Nur-IPv6 umstellen {cost}", +"ip6.homes_that_join_later":"Haushalte, die später dazukommen, bekommen auch einen, für {cost} pro Stück.", +"ip6.n_routers":{"one":"{n} Heimrouter","other":"{n} Heimrouter"}, +"ip6.new_homes_get_a_clat":"Neue Haushalte bekommen gleich einen Router mit CLAT, für {cost} pro Stück, und was noch IPv4 braucht, teilt sich deinen NAT64-Pool, {r} Haushalte pro Adresse.", +"ip6.no_bb":"Starte hier zuerst Breitband.", +"ip6.no_home_is_behind_cgnat":"Noch steckt kein Haushalt hinter CGNAT: Das lohnt sich erst, wenn dein IPv4 knapp wird.", +"ip6.part_note":"Der Tausch wurde bei {p} der Haushalte gestoppt, und neue Haushalte bekommen wieder Dual Stack.", +"ip6.pitch":"Tausch die Heimrouter hier gegen welche mit CLAT: Die Haushalte laufen nur mit IPv6 und haben kein eigenes IPv4, und was noch IPv4 braucht, teilt sich deinen NAT64-Pool, {r} Haushalte pro Adresse.", +"ip6.share_homes":"{p} der Haushalte", +"ip6.started":"{routers} in {city} werden gegen Nur-IPv6-Router getauscht: etwa {days} Tage.", +"ip6.stop":"Tausch stoppen", +"ip6.stopped":"Tausch in {city} bei {p} der Haushalte gestoppt. Die schon getauschten Router bleiben; neue Haushalte bekommen wieder Dual Stack.", +"ip6.swapping_home_routers_paid":"Die Heimrouter werden getauscht und beim Einbau bezahlt; neue Haushalte bekommen gleich den neuen, für {cost} pro Stück. Fertig etwa am {date}.", +"ip6.title":"Nur IPv6 (464XLAT)", +"ip6.waiting":"Warten auf Geld: Die Trupps machen weiter, sobald du die Router des Tages bezahlen kannst.", +"ip6.what":"Tauscht {routers} in etwa {days} Tagen, bezahlt beim Einbau, und macht {addr} für neue Kunden frei.", +"ip6.your_ipv4_bill_goes_down":"Deine IPv4-Rechnung sinkt um {price}/Monat (weniger CGNAT-Boxen und Erstattungen).", +"ip6.your_ipv4_bill_goes_up":"Deine IPv4-Rechnung steigt um {price}/Monat (NAT64-Gateways und Erstattungen).", "ix_downgrade.pni_downgraded":"Das PNI mit {net} in {city} ist jetzt {port}.", "ix_downgrade.port_downgraded_at_ix":"Der Port bei {ix} ist jetzt {port}.", "ix_downgrade.transit_downgraded":"{net}-Transit in {city} ist jetzt {port}.", diff --git a/site/i18n/es.js b/site/i18n/es.js index b9e5de1..354cdf2 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2691,20 +2691,26 @@ "ip4.cgnat_boxes":"Equipos CGNAT", "ip4.cgnat_note":"Más hogares por dirección liberan espacio para clientes, pero los juegos y el port forwarding sufren: el {p} de la factura de un hogar con CGNAT se devuelve en reembolsos.", "ip4.cgnat_ratio":"CGNAT: hogares por dirección", -"ip4.costs_row":"Alquiler de IPv4 y CGNAT", "ip4.free":"Libres para nuevos clientes (los hogares pasan antes a CGNAT)", "ip4.from_rir":"Del RIR", "ip4.give_back":"Devolver", "ip4.held":"El RIR no volverá a transferir ese bloque antes del {date}.", "ip4.homes":"Hogares con banda ancha", +"ip4.homes_behind_cgnat":"Hogares detrás de CGNAT", "ip4.homes_cgnat":"{n}, {p} detrás de CGNAT", +"ip4.homes_public":"Hogares con dirección propia", +"ip4.homes_v6":"Hogares solo IPv6 (464XLAT)", +"ip4.homes_v6_pool":"{n}, pool NAT64 de {pool}", "ip4.in_use":"Tus clientes necesitan esas direcciones: pon más hogares detrás de CGNAT o consigue antes otro bloque.", +"ip4.in_use_both":"Tus clientes necesitan esas direcciones: pon más hogares en cada dirección de CGNAT o NAT64 o consigue antes otro bloque.", +"ip4.in_use_v6":"Tus clientes necesitan esas direcciones: pon más hogares solo IPv6 en cada dirección NAT64 o consigue antes otro bloque.", "ip4.lease":"Alquilar {price}/mes", "ip4.lease_out":"Ceder en alquiler +{price}/mes", "ip4.leased_in":"Has alquilado un {p} ({n} direcciones) por {price}/mes.", "ip4.leased_in_mo":"Alquilado · {price}/mes", "ip4.leased_out":"Tu {p} está cedido en alquiler: +{price}/mes.", "ip4.leased_out_mo":"Cedido en alquiler · +{price}/mes", +"ip4.leases_cgnat_nat64":"Alquiler de IPv4, CGNAT y NAT64", "ip4.leases_in":"Bloques alquilados", "ip4.leases_out":"Bloques cedidos en alquiler", "ip4.market":"Mercado de transferencias", @@ -2712,8 +2718,13 @@ "ip4.movable_from":"transferible desde el {date}", "ip4.n_addresses":{"one":"{n} dirección","other":"{n} direcciones"}, "ip4.n_homes_per_address":{"one":"{n} hogar por dirección","other":"{n} hogares por dirección"}, +"ip4.nat64_gateways":"Pasarelas NAT64", +"ip4.nat64_note":"Los hogares solo IPv6 no tienen IPv4 propio: lo que aún lo necesita (consolas, VPN solo IPv4) comparte tu pool NAT64, y el {p} de su factura se devuelve en reembolsos, menos cada año a medida que el mundo pasa a IPv6. Una ciudad pasa a solo IPv6 desde su banda ancha doméstica.", +"ip4.nat64_ratio":"NAT64: hogares solo IPv6 por dirección", "ip4.no_grow":"{name} ({city}) quería crecer a {bw}, pero no tenías direcciones IPv4 libres para ello.", "ip4.no_space":"{name} necesita un {p} de IPv4 ({n} direcciones) y solo hay {free} libres. Compra o alquila un bloque, o pon más hogares detrás de CGNAT.", +"ip4.no_space_both":"{name} necesita un {p} de IPv4 ({n} direcciones) y solo hay {free} libres. Compra o alquila un bloque, o pon más hogares en cada dirección de CGNAT o NAT64.", +"ip4.no_space_v6":"{name} necesita un {p} de IPv4 ({n} direcciones) y solo hay {free} libres. Compra o alquila un bloque, o pon más hogares solo IPv6 en cada dirección NAT64.", "ip4.note":"IPv6 es gratis e infinito. IPv4 se agotó hace años: los clientes empresariales necesitan bloques públicos, y los hogares que no caben comparten direcciones detrás de CGNAT (el tráfico IPv6 rodea la caja).", "ip4.off":"Con las reglas de esta partida sobra IPv4.", "ip4.offer_needs":"Necesita un {p} de IPv4 ({n} direcciones); solo hay {free} libres.", @@ -2725,11 +2736,39 @@ "ip4.sell":"Vender {price}", "ip4.sold":"Has vendido tu {p} por {price}.", "ip4.squeezed":"Sin espacio: el {p} de los hogares no cabe ni con {r} hogares por dirección. Sus conexiones fallan y piden reembolsos: compra o alquila un bloque.", +"ip4.squeezed_both":"Sin espacio: el {p} de los hogares no cabe ni con {r} hogares por dirección de CGNAT y {r6} por dirección NAT64. Sus conexiones fallan y piden reembolsos: compra o alquila un bloque.", +"ip4.squeezed_v6":"Sin espacio: el {p} de los hogares no cabe ni con {r} hogares solo IPv6 por dirección NAT64. Sus conexiones fallan y piden reembolsos: compra o alquila un bloque.", "ip4.take_back":"Recuperar", "ip4.toast_cgnat":"Tu IPv4 está lleno. El {p} de tus hogares comparte ahora direcciones detrás de CGNAT, y algunos gamers ya han escrito.", "ip4.toast_out":"Sin IPv4. Ni con {r} hogares por dirección cabe todo el mundo en el CGNAT: compra o alquila un bloque en el banco.", +"ip4.toast_out_both":"Sin IPv4. Ni con {r} hogares por dirección detrás de CGNAT y {r6} en NAT64 caben todos los hogares: compra o alquila un bloque en el banco.", +"ip4.toast_out_v6":"Sin IPv4. Ni con {r} hogares por dirección caben en tu pool NAT64 todos los hogares solo IPv6: compra o alquila un bloque en el banco.", "ip4.too_many":"Tienes {n} bloques IPv4, el máximo que puede llevar una red. Vende o devuelve bloques pequeños para hacer sitio a uno más grande.", +"ip4.v6_share":"Cuota de IPv6 en el tráfico de los hogares este año", "ip4.yours":"Tus direcciones IPv4", +"ip6.already":"Todos los hogares de aquí ya son solo IPv6.", +"ip6.busy":"El cambio ya está en marcha aquí.", +"ip6.done":"{city} es solo IPv6. Todos sus hogares usan 464XLAT, y lo que aún necesita IPv4 comparte tu pool NAT64.", +"ip6.dual_stack":"Doble pila", +"ip6.every_home":"Todos los hogares", +"ip6.go":"Pasar a solo IPv6 {cost}", +"ip6.homes_that_join_later":"Los hogares que lleguen después también reciben uno, a {cost} cada uno.", +"ip6.n_routers":{"one":"{n} router doméstico","other":"{n} routers domésticos"}, +"ip6.new_homes_get_a_clat":"Los hogares nuevos reciben un router con CLAT desde el principio, a {cost} cada uno, y lo que aún necesita IPv4 comparte tu pool NAT64, {r} hogares por dirección.", +"ip6.no_bb":"Lanza primero la banda ancha aquí.", +"ip6.no_home_is_behind_cgnat":"Aún no hay ningún hogar detrás de CGNAT: esto compensa cuando empiece a faltarte IPv4.", +"ip6.part_note":"El cambio se detuvo en el {p} de los hogares, y los hogares nuevos vuelven a tener doble pila.", +"ip6.pitch":"Cambia los routers domésticos de aquí por otros con CLAT: los hogares funcionan solo con IPv6 y no tienen IPv4 propio, y lo que aún necesita IPv4 comparte tu pool NAT64, {r} hogares por dirección.", +"ip6.share_homes":"El {p} de los hogares", +"ip6.started":"Cambiando {routers} en {city} por otros solo IPv6: unos {days} días.", +"ip6.stop":"Detener el cambio", +"ip6.stopped":"Cambio detenido en {city} en el {p} de los hogares. Los routers ya cambiados se quedan; los hogares nuevos vuelven a tener doble pila.", +"ip6.swapping_home_routers_paid":"Cambiando routers domésticos, pagados a medida que se instalan; los hogares nuevos reciben el nuevo desde el principio, a {cost} cada uno. Listo hacia el {date}.", +"ip6.title":"Solo IPv6 (464XLAT)", +"ip6.waiting":"Esperando efectivo: los equipos siguen en cuanto puedas pagar los routers del día.", +"ip6.what":"Cambia {routers} en unos {days} días, pagados a medida que se instalan, y libera {addr} para nuevos clientes.", +"ip6.your_ipv4_bill_goes_down":"Tu factura de IPv4 baja {price}/mes (menos equipos CGNAT y reembolsos).", +"ip6.your_ipv4_bill_goes_up":"Tu factura de IPv4 sube {price}/mes (pasarelas NAT64 y reembolsos).", "ix_downgrade.pni_downgraded":"El PNI con {net} en {city} ahora es {port}.", "ix_downgrade.port_downgraded_at_ix":"El puerto en {ix} es ahora de {port}.", "ix_downgrade.transit_downgraded":"El tránsito de {net} en {city} ahora es {port}.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index dbc21c6..c06b195 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2691,20 +2691,26 @@ "ip4.cgnat_boxes":"Boîtiers CGNAT", "ip4.cgnat_note":"Plus de foyers par adresse libère de la place pour les clients, mais les jeux et la redirection de ports en pâtissent : {p} de la facture d’un foyer derrière le CGNAT repart en remboursements.", "ip4.cgnat_ratio":"CGNAT : foyers par adresse", -"ip4.costs_row":"Locations IPv4 et CGNAT", "ip4.free":"Libres pour de nouveaux clients (les foyers passent d’abord derrière le CGNAT)", "ip4.from_rir":"Attribué par le RIR", "ip4.give_back":"Le rendre", "ip4.held":"Le RIR ne transférera pas ce bloc avant le {date}.", "ip4.homes":"Foyers en haut débit", +"ip4.homes_behind_cgnat":"Foyers derrière le CGNAT", "ip4.homes_cgnat":"{n}, dont {p} derrière le CGNAT", +"ip4.homes_public":"Foyers avec leur propre adresse", +"ip4.homes_v6":"Foyers IPv6 uniquement (464XLAT)", +"ip4.homes_v6_pool":"{n}, pool NAT64 de {pool}", "ip4.in_use":"Tes clients ont besoin de ces adresses : mets plus de foyers derrière le CGNAT ou trouve d’abord un autre bloc.", +"ip4.in_use_both":"Tes clients ont besoin de ces adresses : mets plus de foyers sur chaque adresse CGNAT ou NAT64 ou trouve d’abord un autre bloc.", +"ip4.in_use_v6":"Tes clients ont besoin de ces adresses : mets plus de foyers IPv6 uniquement sur chaque adresse NAT64 ou trouve d’abord un autre bloc.", "ip4.lease":"Louer {price}/mois", "ip4.lease_out":"Mettre en location +{price}/mois", "ip4.leased_in":"Tu as loué un {p} ({n} adresses) pour {price}/mois.", "ip4.leased_in_mo":"Loué · {price}/mois", "ip4.leased_out":"Ton {p} est en location : +{price}/mois.", "ip4.leased_out_mo":"Mis en location · +{price}/mois", +"ip4.leases_cgnat_nat64":"Locations IPv4, CGNAT et NAT64", "ip4.leases_in":"Blocs loués", "ip4.leases_out":"Blocs mis en location", "ip4.market":"Marché des transferts", @@ -2712,8 +2718,13 @@ "ip4.movable_from":"transférable à partir du {date}", "ip4.n_addresses":{"one":"{n} adresse","other":"{n} adresses"}, "ip4.n_homes_per_address":{"one":"{n} foyer par adresse","other":"{n} foyers par adresse"}, +"ip4.nat64_gateways":"Passerelles NAT64", +"ip4.nat64_note":"Les foyers IPv6 uniquement n’ont pas d’IPv4 à eux : ce qui en a encore besoin (consoles, VPN IPv4 uniquement) partage ton pool NAT64, et {p} de leur facture repart en remboursements, un peu moins chaque année à mesure que le monde passe à l’IPv6. Une ville passe en IPv6 uniquement depuis son haut débit résidentiel.", +"ip4.nat64_ratio":"NAT64 : foyers IPv6 uniquement par adresse", "ip4.no_grow":"{name} ({city}) voulait passer à {bw}, mais tu n’avais pas d’adresses IPv4 libres pour ça.", "ip4.no_space":"{name} a besoin d’un {p} d’IPv4 ({n} adresses), et seulement {free} sont libres. Achète ou loue un bloc, ou mets plus de foyers derrière le CGNAT.", +"ip4.no_space_both":"{name} a besoin d’un {p} d’IPv4 ({n} adresses), et seulement {free} sont libres. Achète ou loue un bloc, ou mets plus de foyers sur chaque adresse CGNAT ou NAT64.", +"ip4.no_space_v6":"{name} a besoin d’un {p} d’IPv4 ({n} adresses), et seulement {free} sont libres. Achète ou loue un bloc, ou mets plus de foyers IPv6 uniquement sur chaque adresse NAT64.", "ip4.note":"L’IPv6 est gratuit et sans fin. L’IPv4 est épuisé depuis des années : les clients pros ont besoin de blocs publics, et les foyers qui ne rentrent plus partagent des adresses derrière le CGNAT (le trafic IPv6 contourne la boîte).", "ip4.off":"Avec les règles de cette partie, l’IPv4 ne manque pas.", "ip4.offer_needs":"Il lui faut un {p} d’IPv4 ({n} adresses) ; seulement {free} libres.", @@ -2725,11 +2736,39 @@ "ip4.sell":"Vendre {price}", "ip4.sold":"Ton {p} est vendu pour {price}.", "ip4.squeezed":"Plus de place : {p} des foyers ne rentrent pas, même à {r} foyers par adresse. Leurs connexions lâchent et ils veulent être remboursés : achète ou loue un bloc.", +"ip4.squeezed_both":"Plus de place : {p} des foyers ne rentrent pas, même à {r} foyers par adresse CGNAT et {r6} par adresse NAT64. Leurs connexions lâchent et ils veulent être remboursés : achète ou loue un bloc.", +"ip4.squeezed_v6":"Plus de place : {p} des foyers ne rentrent pas, même à {r} foyers IPv6 uniquement par adresse NAT64. Leurs connexions lâchent et ils veulent être remboursés : achète ou loue un bloc.", "ip4.take_back":"Le reprendre", "ip4.toast_cgnat":"Ton IPv4 est plein. {p} de tes foyers partagent maintenant des adresses derrière le CGNAT, et quelques gamers ont déjà écrit.", "ip4.toast_out":"Plus d’IPv4. Même à {r} foyers par adresse, le CGNAT ne suffit pas pour tout le monde : achète ou loue un bloc à la banque.", +"ip4.toast_out_both":"Plus d’IPv4. Même à {r} foyers par adresse derrière le CGNAT et {r6} en NAT64, tous les foyers ne rentrent pas : achète ou loue un bloc à la banque.", +"ip4.toast_out_v6":"Plus d’IPv4. Même à {r} foyers par adresse, ton pool NAT64 ne suffit pas pour tous les foyers IPv6 uniquement : achète ou loue un bloc à la banque.", "ip4.too_many":"Tu as {n} blocs IPv4, le maximum qu’un réseau peut garder. Vends ou rends de petits blocs pour faire de la place à un plus grand.", +"ip4.v6_share":"Part de l’IPv6 dans le trafic des foyers cette année", "ip4.yours":"Tes adresses IPv4", +"ip6.already":"Tous les foyers d’ici sont déjà en IPv6 uniquement.", +"ip6.busy":"Le remplacement est déjà en cours ici.", +"ip6.done":"{city} est en IPv6 uniquement. Tous ses foyers tournent en 464XLAT, et ce qui a encore besoin d’IPv4 partage ton pool NAT64.", +"ip6.dual_stack":"Double pile", +"ip6.every_home":"Tous les foyers", +"ip6.go":"Passer en IPv6 uniquement {cost}", +"ip6.homes_that_join_later":"Les foyers qui arrivent ensuite en ont une aussi, à {cost} pièce.", +"ip6.n_routers":{"one":"{n} box","other":"{n} box"}, +"ip6.new_homes_get_a_clat":"Les nouveaux foyers ont une box avec CLAT dès le départ, à {cost} pièce, et ce qui a encore besoin d’IPv4 partage ton pool NAT64, {r} foyers par adresse.", +"ip6.no_bb":"Lance d’abord le haut débit ici.", +"ip6.no_home_is_behind_cgnat":"Aucun foyer n’est encore derrière le CGNAT : ça ne paie qu’une fois que ton IPv4 vient à manquer.", +"ip6.part_note":"Le remplacement s’est arrêté à {p} des foyers, et les nouveaux foyers repassent en double pile.", +"ip6.pitch":"Remplace les box des foyers d’ici par des modèles avec CLAT : les foyers tournent en IPv6 seul, sans IPv4 à eux, et ce qui a encore besoin d’IPv4 partage ton pool NAT64, {r} foyers par adresse.", +"ip6.share_homes":"{p} des foyers", +"ip6.started":"Remplacement de {routers} à {city} par des modèles IPv6 uniquement : environ {days} jours.", +"ip6.stop":"Arrêter le remplacement", +"ip6.stopped":"Remplacement arrêté à {city} à {p} des foyers. Les box déjà remplacées restent ; les nouveaux foyers repassent en double pile.", +"ip6.swapping_home_routers_paid":"Remplacement des box en cours, payées au fil de la pose ; les nouveaux foyers ont la nouvelle dès le départ, à {cost} pièce. Fini vers le {date}.", +"ip6.title":"IPv6 uniquement (464XLAT)", +"ip6.waiting":"En attente de trésorerie : les équipes reprennent dès que tu peux payer les box du jour.", +"ip6.what":"Remplace {routers} en environ {days} jours, payées au fil de la pose, et libère {addr} pour de nouveaux clients.", +"ip6.your_ipv4_bill_goes_down":"Ta facture IPv4 baisse de {price}/mois (moins de boîtiers CGNAT et de remboursements).", +"ip6.your_ipv4_bill_goes_up":"Ta facture IPv4 augmente de {price}/mois (passerelles NAT64 et remboursements).", "ix_downgrade.pni_downgraded":"Le PNI avec {net} à {city} est maintenant en {port}.", "ix_downgrade.port_downgraded_at_ix":"Le port chez {ix} est maintenant en {port}.", "ix_downgrade.transit_downgraded":"Le transit {net} à {city} est maintenant en {port}.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 34f9e6a..b303833 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2691,20 +2691,26 @@ "ip4.cgnat_boxes":"Apparati CGNAT", "ip4.cgnat_note":"Più case per indirizzo liberano spazio per i clienti, ma giochi e port forwarding ne soffrono: il {p} della bolletta di una casa dietro il CGNAT torna indietro in rimborsi.", "ip4.cgnat_ratio":"CGNAT: case per indirizzo", -"ip4.costs_row":"Affitti IPv4 e CGNAT", "ip4.free":"Liberi per nuovi clienti (prima le case passano dietro il CGNAT)", "ip4.from_rir":"Dal RIR", "ip4.give_back":"Restituiscilo", "ip4.held":"Il RIR non trasferisce di nuovo quel blocco prima del {date}.", "ip4.homes":"Case in banda larga", +"ip4.homes_behind_cgnat":"Case dietro il CGNAT", "ip4.homes_cgnat":"{n}, il {p} dietro il CGNAT", +"ip4.homes_public":"Case con un indirizzo proprio", +"ip4.homes_v6":"Case solo IPv6 (464XLAT)", +"ip4.homes_v6_pool":"{n}, pool NAT64 di {pool}", "ip4.in_use":"I tuoi clienti hanno bisogno di quegli indirizzi: metti più case dietro il CGNAT o prendi prima un altro blocco.", +"ip4.in_use_both":"I tuoi clienti hanno bisogno di quegli indirizzi: metti più case su ogni indirizzo CGNAT o NAT64 o prendi prima un altro blocco.", +"ip4.in_use_v6":"I tuoi clienti hanno bisogno di quegli indirizzi: metti più case solo IPv6 su ogni indirizzo NAT64 o prendi prima un altro blocco.", "ip4.lease":"Affitta {price}/mese", "ip4.lease_out":"Dai in affitto +{price}/mese", "ip4.leased_in":"Preso in affitto un {p} ({n} indirizzi) per {price}/mese.", "ip4.leased_in_mo":"In affitto · {price}/mese", "ip4.leased_out":"Il tuo {p} è dato in affitto: +{price}/mese.", "ip4.leased_out_mo":"Dato in affitto · +{price}/mese", +"ip4.leases_cgnat_nat64":"Affitti IPv4, CGNAT e NAT64", "ip4.leases_in":"Blocchi presi in affitto", "ip4.leases_out":"Blocchi dati in affitto", "ip4.market":"Mercato dei trasferimenti", @@ -2712,8 +2718,13 @@ "ip4.movable_from":"trasferibile dal {date}", "ip4.n_addresses":{"one":"{n} indirizzo","other":"{n} indirizzi"}, "ip4.n_homes_per_address":{"one":"{n} casa per indirizzo","other":"{n} case per indirizzo"}, +"ip4.nat64_gateways":"Gateway NAT64", +"ip4.nat64_note":"Le case solo IPv6 non hanno un IPv4 proprio: quello che ne ha ancora bisogno (console, VPN solo IPv4) condivide il tuo pool NAT64, e il {p} della loro bolletta torna indietro in rimborsi, meno ogni anno man mano che il mondo passa a IPv6. Una città passa a solo IPv6 dalla sua banda larga domestica.", +"ip4.nat64_ratio":"NAT64: case solo IPv6 per indirizzo", "ip4.no_grow":"{name} ({city}) voleva crescere a {bw}, ma non avevi indirizzi IPv4 liberi per farlo.", "ip4.no_space":"{name} ha bisogno di un {p} di IPv4 ({n} indirizzi), e ne restano liberi solo {free}. Compra o affitta un blocco, o metti più case dietro il CGNAT.", +"ip4.no_space_both":"{name} ha bisogno di un {p} di IPv4 ({n} indirizzi), e ne restano liberi solo {free}. Compra o affitta un blocco, o metti più case su ogni indirizzo CGNAT o NAT64.", +"ip4.no_space_v6":"{name} ha bisogno di un {p} di IPv4 ({n} indirizzi), e ne restano liberi solo {free}. Compra o affitta un blocco, o metti più case solo IPv6 su ogni indirizzo NAT64.", "ip4.note":"IPv6 è gratis e infinito. IPv4 è finito anni fa: i clienti business hanno bisogno di blocchi pubblici, e le case che non ci stanno condividono gli indirizzi dietro il CGNAT (il traffico IPv6 gli passa accanto).", "ip4.off":"Con le regole di questa partita l'IPv4 abbonda.", "ip4.offer_needs":"Serve un {p} di IPv4 ({n} indirizzi); solo {free} liberi.", @@ -2725,11 +2736,39 @@ "ip4.sell":"Vendi {price}", "ip4.sold":"Venduto il tuo {p} per {price}.", "ip4.squeezed":"Spazio esaurito: il {p} delle case non ci sta nemmeno con {r} case per indirizzo. Le connessioni saltano e vogliono un rimborso: compra o affitta un blocco.", +"ip4.squeezed_both":"Spazio esaurito: il {p} delle case non ci sta nemmeno con {r} case per indirizzo CGNAT e {r6} per indirizzo NAT64. Le connessioni saltano e vogliono un rimborso: compra o affitta un blocco.", +"ip4.squeezed_v6":"Spazio esaurito: il {p} delle case non ci sta nemmeno con {r} case solo IPv6 per indirizzo NAT64. Le connessioni saltano e vogliono un rimborso: compra o affitta un blocco.", "ip4.take_back":"Riprendilo", "ip4.toast_cgnat":"Il tuo IPv4 è pieno. Il {p} delle tue case ora condivide gli indirizzi dietro il CGNAT, e qualche gamer ha già scritto.", "ip4.toast_out":"IPv4 esaurito. Nemmeno con {r} case per indirizzo il CGNAT basta per tutti: compra o affitta un blocco in banca.", +"ip4.toast_out_both":"IPv4 esaurito. Nemmeno con {r} case per indirizzo dietro il CGNAT e {r6} in NAT64 ci stanno tutte le case: compra o affitta un blocco in banca.", +"ip4.toast_out_v6":"IPv4 esaurito. Nemmeno con {r} case per indirizzo il tuo pool NAT64 basta per tutte le case solo IPv6: compra o affitta un blocco in banca.", "ip4.too_many":"Hai {n} blocchi IPv4, il massimo che una rete può tenere. Vendi o restituisci qualche blocco piccolo per fare posto a uno più grande.", +"ip4.v6_share":"Quota IPv6 del traffico delle case quest’anno", "ip4.yours":"I tuoi indirizzi IPv4", +"ip6.already":"Tutte le case qui sono già solo IPv6.", +"ip6.busy":"La sostituzione qui è già in corso.", +"ip6.done":"{city} è solo IPv6. Tutte le case lì vanno in 464XLAT, e quello che ha ancora bisogno di IPv4 condivide il tuo pool NAT64.", +"ip6.dual_stack":"Dual stack", +"ip6.every_home":"Tutte le case", +"ip6.go":"Passa a solo IPv6 {cost}", +"ip6.homes_that_join_later":"Anche le case che arrivano dopo ne ricevono uno, a {cost} l’uno.", +"ip6.n_routers":{"one":"{n} router di casa","other":"{n} router di casa"}, +"ip6.new_homes_get_a_clat":"Le case nuove hanno subito un router con CLAT, a {cost} l’uno, e quello che ha ancora bisogno di IPv4 condivide il tuo pool NAT64, {r} case per indirizzo.", +"ip6.no_bb":"Prima lancia la banda larga qui.", +"ip6.no_home_is_behind_cgnat":"Nessuna casa è ancora dietro il CGNAT: conviene solo quando l’IPv4 comincia a scarseggiare.", +"ip6.part_note":"La sostituzione si è fermata al {p} delle case, e le case nuove tornano in dual stack.", +"ip6.pitch":"Sostituisci i router di casa qui con modelli con CLAT: le case vanno solo in IPv6 e non hanno un IPv4 proprio, e quello che ha ancora bisogno di IPv4 condivide il tuo pool NAT64, {r} case per indirizzo.", +"ip6.share_homes":"Il {p} delle case", +"ip6.started":"Sostituzione di {routers} a {city} con modelli solo IPv6: circa {days} giorni.", +"ip6.stop":"Ferma la sostituzione", +"ip6.stopped":"Sostituzione fermata a {city} al {p} delle case. I router già sostituiti restano; le case nuove tornano in dual stack.", +"ip6.swapping_home_routers_paid":"Sostituzione dei router di casa in corso, pagati man mano che vengono installati; le case nuove hanno subito quello nuovo, a {cost} l’uno. Finito verso il {date}.", +"ip6.title":"Solo IPv6 (464XLAT)", +"ip6.waiting":"In attesa di cassa: le squadre ripartono appena puoi pagare i router del giorno.", +"ip6.what":"Sostituisce {routers} in circa {days} giorni, pagati man mano che vengono installati, e libera {addr} per nuovi clienti.", +"ip6.your_ipv4_bill_goes_down":"La tua bolletta IPv4 scende di {price}/mese (meno apparati CGNAT e rimborsi).", +"ip6.your_ipv4_bill_goes_up":"La tua bolletta IPv4 sale di {price}/mese (gateway NAT64 e rimborsi).", "ix_downgrade.pni_downgraded":"Il PNI con {net} a {city} ora è {port}.", "ix_downgrade.port_downgraded_at_ix":"La porta su {ix} ora è da {port}.", "ix_downgrade.transit_downgraded":"Il transito {net} a {city} ora è {port}.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 71d1198..d04e619 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2691,20 +2691,26 @@ "ip4.cgnat_boxes":"Caixas de CGNAT", "ip4.cgnat_note":"Mais casas por endereço liberam espaço para clientes, mas jogos e redirecionamento de portas sofrem: {p} da conta de uma casa atrás do CGNAT volta como reembolso.", "ip4.cgnat_ratio":"CGNAT: casas por endereço", -"ip4.costs_row":"Aluguel de IPv4 e CGNAT", "ip4.free":"Livres para novos clientes (as casas vão antes para trás do CGNAT)", "ip4.from_rir":"Do RIR", "ip4.give_back":"Devolver", "ip4.held":"O RIR não transfere esse bloco de novo antes de {date}.", "ip4.homes":"Casas com banda larga", +"ip4.homes_behind_cgnat":"Casas atrás do CGNAT", "ip4.homes_cgnat":"{n}, {p} atrás do CGNAT", +"ip4.homes_public":"Casas com endereço próprio", +"ip4.homes_v6":"Casas só IPv6 (464XLAT)", +"ip4.homes_v6_pool":"{n}, pool NAT64 de {pool}", "ip4.in_use":"Seus clientes precisam desses endereços: coloque mais casas atrás do CGNAT ou arrume outro bloco antes.", +"ip4.in_use_both":"Seus clientes precisam desses endereços: coloque mais casas em cada endereço de CGNAT ou NAT64 ou arrume outro bloco antes.", +"ip4.in_use_v6":"Seus clientes precisam desses endereços: coloque mais casas só IPv6 em cada endereço NAT64 ou arrume outro bloco antes.", "ip4.lease":"Alugar {price}/mês", "ip4.lease_out":"Alugar para terceiros +{price}/mês", "ip4.leased_in":"Você alugou um {p} ({n} endereços) por {price}/mês.", "ip4.leased_in_mo":"Alugado · {price}/mês", "ip4.leased_out":"Seu {p} está alugado: +{price}/mês.", "ip4.leased_out_mo":"Alugado para terceiros · +{price}/mês", +"ip4.leases_cgnat_nat64":"Aluguel de IPv4, CGNAT e NAT64", "ip4.leases_in":"Blocos alugados", "ip4.leases_out":"Blocos alugados para terceiros", "ip4.market":"Mercado de transferências", @@ -2712,8 +2718,13 @@ "ip4.movable_from":"transferível a partir de {date}", "ip4.n_addresses":{"one":"{n} endereço","other":"{n} endereços"}, "ip4.n_homes_per_address":{"one":"{n} casa por endereço","other":"{n} casas por endereço"}, +"ip4.nat64_gateways":"Gateways NAT64", +"ip4.nat64_note":"Casas só IPv6 não têm IPv4 próprio: o que ainda precisa dele (consoles, VPNs só IPv4) compartilha seu pool NAT64, e {p} da conta delas volta como reembolso, menos a cada ano conforme o mundo migra para o IPv6. Uma cidade passa a só IPv6 pela banda larga residencial dela.", +"ip4.nat64_ratio":"NAT64: casas só IPv6 por endereço", "ip4.no_grow":"{name} ({city}) queria crescer para {bw}, mas você não tinha endereços IPv4 livres para isso.", "ip4.no_space":"{name} precisa de um {p} de IPv4 ({n} endereços), e só {free} estão livres. Compre ou alugue um bloco, ou coloque mais casas atrás do CGNAT.", +"ip4.no_space_both":"{name} precisa de um {p} de IPv4 ({n} endereços), e só {free} estão livres. Compre ou alugue um bloco, ou coloque mais casas em cada endereço de CGNAT ou NAT64.", +"ip4.no_space_v6":"{name} precisa de um {p} de IPv4 ({n} endereços), e só {free} estão livres. Compre ou alugue um bloco, ou coloque mais casas só IPv6 em cada endereço NAT64.", "ip4.note":"IPv6 é grátis e infinito. IPv4 acabou há anos: clientes empresariais precisam de blocos públicos, e as casas que não cabem compartilham endereços atrás do CGNAT (o tráfego IPv6 passa por fora da caixa).", "ip4.off":"Nas regras deste jogo, IPv4 não falta.", "ip4.offer_needs":"Precisa de um {p} de IPv4 ({n} endereços); só {free} livres.", @@ -2725,11 +2736,39 @@ "ip4.sell":"Vender {price}", "ip4.sold":"Seu {p} foi vendido por {price}.", "ip4.squeezed":"Sem espaço: {p} das casas não cabem nem com {r} casas por endereço. As conexões caem e elas querem reembolso: compre ou alugue um bloco.", +"ip4.squeezed_both":"Sem espaço: {p} das casas não cabem nem com {r} casas por endereço de CGNAT e {r6} por endereço NAT64. As conexões caem e elas querem reembolso: compre ou alugue um bloco.", +"ip4.squeezed_v6":"Sem espaço: {p} das casas não cabem nem com {r} casas só IPv6 por endereço NAT64. As conexões caem e elas querem reembolso: compre ou alugue um bloco.", "ip4.take_back":"Pegar de volta", "ip4.toast_cgnat":"Seu IPv4 está cheio. {p} das suas casas agora compartilham endereços atrás do CGNAT, e alguns gamers já reclamaram.", "ip4.toast_out":"Acabou o IPv4. Nem com {r} casas por endereço o CGNAT comporta todo mundo: compre ou alugue um bloco no banco.", +"ip4.toast_out_both":"Acabou o IPv4. Nem com {r} casas por endereço atrás do CGNAT e {r6} no NAT64 cabem todas as casas: compre ou alugue um bloco no banco.", +"ip4.toast_out_v6":"Acabou o IPv4. Nem com {r} casas por endereço seu pool NAT64 comporta todas as casas só IPv6: compre ou alugue um bloco no banco.", "ip4.too_many":"Você tem {n} blocos IPv4, o máximo que uma rede pode manter. Venda ou devolva blocos pequenos para abrir espaço para um maior.", +"ip4.v6_share":"Participação do IPv6 no tráfego das casas este ano", "ip4.yours":"Seus endereços IPv4", +"ip6.already":"Todas as casas daqui já são só IPv6.", +"ip6.busy":"A troca já está em andamento aqui.", +"ip6.done":"{city} agora é só IPv6. Todas as casas de lá rodam 464XLAT, e o que ainda precisa de IPv4 compartilha seu pool NAT64.", +"ip6.dual_stack":"Pilha dupla", +"ip6.every_home":"Todas as casas", +"ip6.go":"Passar a só IPv6 {cost}", +"ip6.homes_that_join_later":"As casas que chegarem depois também recebem um, a {cost} cada.", +"ip6.n_routers":{"one":"{n} roteador doméstico","other":"{n} roteadores domésticos"}, +"ip6.new_homes_get_a_clat":"Casas novas já recebem um roteador com CLAT, a {cost} cada, e o que ainda precisa de IPv4 compartilha seu pool NAT64, {r} casas por endereço.", +"ip6.no_bb":"Lance a banda larga aqui primeiro.", +"ip6.no_home_is_behind_cgnat":"Nenhuma casa está atrás do CGNAT ainda: isso só compensa quando seu IPv4 começar a faltar.", +"ip6.part_note":"A troca parou em {p} das casas, e as casas novas voltam a ter pilha dupla.", +"ip6.pitch":"Troque os roteadores das casas daqui por modelos com CLAT: as casas rodam só em IPv6 e não têm IPv4 próprio, e o que ainda precisa de IPv4 compartilha seu pool NAT64, {r} casas por endereço.", +"ip6.share_homes":"{p} das casas", +"ip6.started":"Trocando {routers} em {city} por modelos só IPv6: cerca de {days} dias.", +"ip6.stop":"Parar a troca", +"ip6.stopped":"Troca parada em {city} em {p} das casas. Os roteadores já trocados ficam; casas novas voltam a ter pilha dupla.", +"ip6.swapping_home_routers_paid":"Trocando os roteadores das casas, pagos conforme são instalados; casas novas já recebem o novo, a {cost} cada. Pronto por volta de {date}.", +"ip6.title":"Só IPv6 (464XLAT)", +"ip6.waiting":"Esperando dinheiro: as equipes continuam assim que você puder pagar os roteadores do dia.", +"ip6.what":"Troca {routers} em cerca de {days} dias, pagos conforme são instalados, e libera {addr} para novos clientes.", +"ip6.your_ipv4_bill_goes_down":"Sua conta de IPv4 cai {price}/mês (menos caixas de CGNAT e reembolsos).", +"ip6.your_ipv4_bill_goes_up":"Sua conta de IPv4 sobe {price}/mês (gateways NAT64 e reembolsos).", "ix_downgrade.pni_downgraded":"O PNI com {net} em {city} agora é {port}.", "ix_downgrade.port_downgraded_at_ix":"A porta em {ix} agora é de {port}.", "ix_downgrade.transit_downgraded":"O trânsito de {net} em {city} agora é {port}.", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index 1d3d9a7..3aff76f 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -88,9 +88,10 @@ const API_DOMAINS={ pieSpatId:{table:'PIE_SPAT_DEF',kind:'key'}, pieSpatChoice:{kind:'enum',values:[0,1]}, countryCode:{kind:'enum',values:()=>[...new Set(CITIES.map(c=>c.cc))].sort()}, - // Address space: an IPv4 prefix length the market sells, and the CGNAT ratios. + // Address space: an IPv4 prefix length the market sells, and the CGNAT and NAT64 ratios. ip4Len:{kind:'enum',values:()=>Array.from({length:IP4_MAX-IP4_MIN+1},(_,i)=>IP4_MIN+i)}, ip4Ratio:{kind:'enum',values:()=>IP4_NAT.slice()}, + ip4Ratio64:{kind:'enum',values:()=>IP4_N64.slice()}, scnId:{table:'SCN',kind:'id'}, // A traceroute target in the modal's own terms. }; diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index e9a2a7c..51ab1f1 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -315,7 +315,7 @@ const API_CMD={ quote:a=>({setup:0,monthly:ip4InMo(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}), doc:'Lease an IPv4 block of this prefix length by the month, at today\'s rate (fixed for the lease). Hand it back with ip4Return. Refused at 256 blocks, like ip4Buy.'}, ip4Sell:{args:[['id','entityId']],confirm:'double',watch:['ip4'], - doc:'Sell an owned block (not leased out) for 92% of the market price. Refused within two years of its last transfer, or when the customers signed would no longer fit with every home behind CGNAT.'}, + doc:'Sell an owned block (not leased out) for 92% of the market price. Refused within two years of its last transfer, or when the customers signed would no longer fit with every dual-stack home behind CGNAT and the IPv6-only homes in the NAT64 pool.'}, ip4Out:{args:[['id','entityId']],watch:['ip4'], doc:'Lease an owned block out through a broker for a monthly income, while your own customers still fit without it.'}, ip4Back:{args:[['id','entityId']],watch:['ip4'], @@ -324,6 +324,13 @@ const API_CMD={ doc:'Hand a leased-in block back, ending its monthly fee, when your customers still fit without it.'}, ip4Nat:{args:[['v','ip4Ratio']],watch:['ip4'], doc:'Set how many broadband homes share one IPv4 address behind CGNAT (8, 16, 32 or 64). More frees space for business customers but more gamers ask for refunds; fewer is refused when the customers signed would not fit.'}, + ip4Nat64:{args:[['v','ip4Ratio64']],watch:['ip4'], + doc:'Set how many IPv6-only homes share one IPv4 address in the NAT64 pool (64, 128 or 256). Their refunds are well under CGNAT\'s at the same ratio and shrink as the world moves to IPv6; fewer is refused when the customers signed would not fit.'}, + ip6Go:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:ip6Cost(a.city),days:ip6Days(a.city),monthly:Math.round(ip6Mo(a.city,(R.rev&&R.rev.eyeballs)||0)),blocked:[ip6Why(a.city)].filter(Boolean)}), + doc:'Take a broadband city IPv6-only (464XLAT): swap its dual-stack home routers for ones with a CLAT over the quoted days, paid day by day as they go in (setup is the whole swap; starting needs only the first day\'s share on hand, and it waits while cash is short). Those homes then need no IPv4 of their own, only a share of the NAT64 pool; new homes there get the new router too, at the swap\'s price a router, paid the day they join (even short of cash: a new home needs it). monthly is what it does to the IPv4 bill (NAT64 gateways and refunds against the CGNAT it saves; negative saves). Frees what the city panel says for new customers.'}, + ip6Stop:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Stop a city\'s swap to IPv6-only. The homes already swapped stay IPv6-only (their routers are paid for, nothing comes back); new homes come dual stack again. ip6Go resumes it for the rest.'}, /* ---------- security, China, incidents ---------- */ buildScrub:{args:[['city','cityId'],['tier','scrubTier',false]],watch:['scrubs'], quote:a=>{const T=SCRUB_TIERS[a.tier||0];return {setup:T?T.cost:undefined,monthly:T?T.mo:undefined};}, @@ -498,7 +505,7 @@ const API_CMD={ const API_VIEW={ pieOpen:{args:[],doc:'Open Pie Control, the rocket company\'s panel.'}, - ip4Open:{args:[],doc:'Open the bank at its Address space section: your IPv4 blocks, who uses them, CGNAT and the transfer market.'}, + ip4Open:{args:[],doc:'Open the bank at its Address space section: your IPv4 blocks, who uses them, CGNAT, the NAT64 pool and the transfer market.'}, ip4Pick:{args:[['v','ip4Len']],doc:'Pick the block size the Address space market quotes (a prefix length, 24 to 16).'}, pieGovOpen:{args:[],doc:'Open the bank at its Government money section: the rocket company\'s fund auctions, the Pitcairn grant and the Ex-Im Pie Bank (it used to be Pie Control\'s Gov tab).'}, pieTab:{args:[['t','pieTab']],doc:'Switch the Pie Control tab: traffic, co (the company, its books and the Founder\'s posts), fly (launches) or dish.'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index edbe60c..d84c9bf 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -19,7 +19,7 @@ const API_STATE_DOC={ t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, auV:{type:'integer',doc:'Australia content level gate.'}, seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, - pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site, teleport (tele: 1 GEO dishes, 2 with MEO tracking antennas).'}, + pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb: d, its demand in Gbps; v6, the share of its homes that are IPv6-only behind NAT64, absent for dual stack; v6e, the day a swap to IPv6-only finishes, while it runs), ad boost, downtime, routers, generator, second site, teleport (tele: 1 GEO dishes, 2 with MEO tracking antennas).'}, links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc), express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics) and rented satellite circuits (sat: bird, g Gbps, km of radio path, ready day), each with an entity id.'}, transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, @@ -61,7 +61,7 @@ const API_STATE_DOC={ ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings (network work only: deals belong to the sales desk, slAuto), the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, - ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, w: which warnings were shown. What customers use is derived from their kind and size.'}, + ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, n64: IPv6-only homes per address in the NAT64 pool, w: which warnings were shown. What customers use is derived from their kind and size.'}, popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up. g and sys are also the model the routers order and the line system the optup order standardize on.'}, mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, diff --git a/src/game/60-features/33-address-space.js b/src/game/60-features/33-address-space.js index 8d91812..7897de9 100644 --- a/src/game/60-features/33-address-space.js +++ b/src/game/60-features/33-address-space.js @@ -14,8 +14,13 @@ so the first months fit with room for a few customers (gameplay rule F1). */ // IP4_BLK: the most blocks a network holds; buying and leasing stop there, and a save keeps that many. const IP4_START=21,IP4_MIN=16,IP4_MAX=24,IP4_HOLD=730,IP4_NAT=[8,16,32,64],IP4_NAT0=16,IP4_BLK=256; -// Public addresses per Gbps of busy-hour broadband (a home each), and the part of it CGNAT still carries: the rest is IPv6. -const IP4_BB=10,IP4_V4=0.55,IP4_CGN=2; +// Public addresses per Gbps of busy-hour broadband (a home each), and the part of it CGNAT still carries on day 0: the rest +// is IPv6. The world moves on, two points a year to a floor that never goes (ip4V4). +const IP4_BB=10,IP4_V4=0.55,IP4_V4_YR=0.02,IP4_V4_MIN=0.2,IP4_CGN=2; +// IPv6-only homes (464XLAT, 34-ipv6-only.js) have no address of their own: their IPv4 shares a NAT64 pool, at a wider ratio +// than CGNAT can take. Only what still needs IPv4 notices (consoles, IPv4-only VPNs): a share of the bill comes back, well +// under CGNAT's at the same ratio, and shrinking as the world goes IPv6. +const IP4_N64=[64,128,256],IP4_N640=128,IP4_ANNOY64={64:0.006,128:0.01,256:0.016}; // The market: dollars per address, flat for half a year, then +3% a year on a slow four-year swing. Leases are by the // month (a broker keeps a cut of what yours earn), sales pay 92% of the price after the broker's fee. const IP4_PX=38,IP4_FREE=180,IP4_YR=0.03,IP4_IN=0.5,IP4_OUT=0.4,IP4_SELL=0.92; @@ -30,17 +35,22 @@ const ip4Sz=len=>2**(32-len),ip4LenOk=len=>Number.isInteger(len)&&len>=IP4_MIN&& const ip4Cidr=n=>'/'+(32-Math.ceil(Math.log2(Math.max(1,n)))),ip4N=n=>Math.round(n).toLocaleString(); function ip4On(){return !!S&&!!S.ip4&&rule('ip4')===true&&(S.scn?scnRule('ip4'):S.mode==='normal');} function ip4Need(b){const k=b&&IP4_BIZ[b.type];if(!k||!(b.bw>0))return 0;return Math.min(4096,2**Math.ceil(Math.log2(Math.max(k[1],b.bw*k[0]))));} -/* Who uses what. T: usable addresses (owned and leased in, without what is leased out); B: business customers; H: homes; - cg: homes behind CGNAT; over: the share of homes that do not fit even at the ratio; free: what a new customer can have - with every home behind CGNAT. */ -function ip4Use(s=S){const I=s.ip4,r=I.nat;let own=0,inn=0,out=0,B=0,H=0; +/* Who uses what. T: usable addresses (owned and leased in, without what is leased out); B: business customers; H: homes, + of them H6 IPv6-only (Hd dual stack); p6: the NAT64 pool; cg: dual-stack homes behind CGNAT; over: the share of homes + that do not fit even at the ratios; need: the least the homes can live with; free: what a new customer can have with + every dual-stack home behind CGNAT. The NAT64 pool comes right after business customers: its homes gave their own + addresses up already and cannot fall back on anything, while dual-stack homes still can (behind CGNAT). */ +function ip4Use(s=S){const I=s.ip4,r=I.nat,r6=I.n64||IP4_N640;let own=0,inn=0,out=0,B=0,H=0,H6=0; for(const b of I.b){const n=ip4Sz(b.len);if(b.k==='in')inn+=n;else if(b.out)out+=n;else own+=n;} for(const b of s.biz)B+=ip4Need(b); - for(const c in s.pops){const p=s.pops[c];if(p.bb)H+=p.bb.d*IP4_BB;} - H=Math.ceil(H);const T=own+inn,A=Math.max(0,T-B),min=Math.ceil(H/r);let cg=0,over=0; - if(A=min)cg=Math.min(H,Math.ceil((H-A)*r/(r-1)));else{cg=H;over=min?1-A/min:0;}} - return {T,own,inn,out,B,H,cg,over,free:T-B-min,r};} + for(const c in s.pops){const p=s.pops[c];if(p.bb){const h=p.bb.d*IP4_BB;H+=h;if(p.bb.v6)H6+=h*p.bb.v6;}} + H=Math.ceil(H);H6=Math.min(H,Math.ceil(H6));const Hd=H-H6,T=own+inn,A=Math.max(0,T-B),p6=Math.ceil(H6/r6),min=Math.ceil(Hd/r),need=p6+min,A2=A-p6;let cg=0,over=0; + if(A2=min)cg=Math.min(Hd,Math.ceil((Hd-A2)*r/(r-1)));else{cg=Hd;over=need?1-A/need:0;}} + return {T,own,inn,out,B,H,H6,Hd,p6,cg,over,need,free:T-B-need,r,r6};} const ip4Fits=o=>!ip4On()||ip4Need(o)<=Math.max(0,ip4Use().free); +// Which sharing is left to stretch when space runs out, for the advice: CGNAT (0, no IPv6-only homes), the NAT64 pool alone +// (1, every home IPv6-only) or both (2). +const ip4Pools=u=>!u.H6?0:u.Hd?2:1; // A customer renewing at bw: does the bigger block it needs fit what is free? const ip4GrowOk=(b,bw)=>!ip4On()||ip4Need({type:b.type,bw})-ip4Need(b)<=Math.max(0,ip4Use().free); const ip4Full=()=>S.ip4.b.length>=IP4_BLK; @@ -54,11 +64,17 @@ function ip4Px(d=S.day){if(!rule('market')||d<=IP4_FREE)return IP4_PX;const y=(d const ip4Cost=len=>Math.round(ip4Sz(len)*ip4Px()*(1-0.015*(IP4_MAX-len))/100)*100; const ip4Value=len=>Math.round(ip4Cost(len)*IP4_SELL/100)*100; const ip4InMo=len=>Math.round(ip4Sz(len)*IP4_IN*ip4Px()/IP4_PX),ip4OutMo=len=>Math.round(ip4Sz(len)*IP4_OUT*ip4Px()/IP4_PX); -// The month's IPv4 bill: leases in and out, CGNAT boxes, refunds (eye: what broadband earns a month). -function ip4Bill(eye){const u=ip4Use();let lin=0,lout=0;for(const b of S.ip4.b){if(b.k==='in')lin+=b.mo||0;else if(b.out)lout+=b.mo||0;} - const cgS=u.H?u.cg/u.H:0;return {u,lin,lout,box:u.cg/IP4_BB*IP4_V4*IP4_CGN,refund:eye*(cgS*IP4_ANNOY[u.r]+u.over*IP4_SQZ)};} +// The IPv4 share of home traffic on day d: 55% on day 0 (so nothing changes at the start), two points less a year, never +// under a fifth (old consoles, old VPNs, old everything). +const ip4V4=(d=S.day)=>Math.max(IP4_V4_MIN,IP4_V4-IP4_V4_YR*Math.max(0,d)/365.2425); +/* The month's IPv4 bill: leases in and out, CGNAT boxes and NAT64 gateways (the same price per Gbps of IPv4 they carry), + refunds (eye: what broadband earns a month). NAT64 refunds shrink with the IPv4 share: in an IPv6-only home only what + still needs IPv4 meets the NAT at all. s: the network as ip4Use() takes it (a city panel asks about one that might be). */ +function ip4Bill(eye,s=S){const u=ip4Use(s),v4=ip4V4();let lin=0,lout=0;for(const b of s.ip4.b){if(b.k==='in')lin+=b.mo||0;else if(b.out)lout+=b.mo||0;} + const cgS=u.H?u.cg/u.H:0,v6S=u.H?u.H6/u.H:0; + return {u,lin,lout,v4,box:u.cg/IP4_BB*v4*IP4_CGN,box64:u.H6/IP4_BB*v4*IP4_CGN,refund:eye*(cgS*IP4_ANNOY[u.r]+v6S*IP4_ANNOY64[u.r6]*v4/IP4_V4+u.over*IP4_SQZ)};} // computeMoney: only what is there, so a network with nothing to pay keeps its money rows as they were. -function ip4Money(C,V){if(!ip4On())return;const b=ip4Bill(V.eyeballs||0),c=Math.round(b.lin+b.box+b.refund);if(c>0)C.ip4=c;if(b.lout>0)V.ip4=b.lout;} +function ip4Money(C,V){if(!ip4On())return;const b=ip4Bill(V.eyeballs||0),c=Math.round(b.lin+b.box+b.box64+b.refund);if(c>0)C.ip4=c;if(b.lout>0)V.ip4=b.lout;} /* A new network gets its /21 from the RIR. An older save gets what it already uses registered to it and a quarter more to grow into (about a month for a big, fast-growing network), rounded up to /24s in real CIDR blocks (a /21 at the least), so nothing changes on load; those blocks move like any other two years on. @@ -69,19 +85,22 @@ function ip4Grant(s){const d=s.day||0,b=[],add=len=>b.push({id:'rir'+b.length,le need=Math.max(ip4Sz(IP4_START),Math.ceil(need*1.25/256)*256); while(need>=ip4Sz(IP4_MIN)&&b.length<200){add(IP4_MIN);need-=ip4Sz(IP4_MIN);} for(let len=IP4_MIN+1;len<=IP4_MAX;len++)if(need>=ip4Sz(len)){add(len);need-=ip4Sz(len);} - return {b,nat:IP4_NAT0,w:0};} + return {b,nat:IP4_NAT0,n64:IP4_N640,w:0};} const ip4New=()=>ip4Grant({}); function ip4Fix(s){const I=s.ip4&&typeof s.ip4==='object'&&!Array.isArray(s.ip4)?s.ip4:null;if(!I){s.ip4=ip4Grant(s);return;} const day=Math.max(0,num(s.day,0)),mo=v=>Math.round(Math.min(1e8,Math.max(0,num(v,0)))); const b=(Array.isArray(I.b)?I.b:[]).filter(x=>x&&typeof x==='object'&&ip4LenOk(x.len)&&['rir','buy','in'].includes(x.k)).slice(0,IP4_BLK).map(x=>{ const o={id:typeof x.id==='string'&&x.id&&x.id.length<=40?x.id:uid(),len:x.len,k:x.k,d:int(x.d,0,day,0)}; if(x.k==='in')o.mo=mo(x.mo);else if(x.out===true){o.out=true;o.mo=mo(x.mo);}return o;}); - s.ip4={b,nat:IP4_NAT.includes(I.nat)?I.nat:IP4_NAT0,w:int(I.w,0,3,0)};} + s.ip4={b,nat:IP4_NAT.includes(I.nat)?I.nat:IP4_NAT0,n64:IP4_N64.includes(I.n64)?I.n64:IP4_N640,w:int(I.w,0,3,0)};} /* Once a day: say so when homes go behind CGNAT (a percent of them at least), and when even CGNAT cannot fit them all (w: what was said). Each rearms only with room to spare again, so homes hovering at the limit hear it once. */ -function ip4Day(d){if(!ip4On())return;const I=S.ip4,u=ip4Use(),A=u.T-u.B,go=[{l:tr('ip4.section'),act:'ip4Open'}]; - if(u.cg>=Math.max(1,u.H*0.01)){if(!(I.w&1)){I.w|=1;toast(tr('ip4.toast_cgnat',{p:pct(u.cg/u.H)}),'',go);}}else if(A>=u.H*1.05)I.w&=~1; - if(u.over>0){if(!(I.w&2)){I.w|=2;toast(tr('ip4.toast_out',{r:u.r}),'bad',go);sfx('err');}}else if(A>=Math.ceil(u.H/u.r)*1.1)I.w&=~2;} +function ip4Day(d){if(!ip4On())return;ip6Day(d);const I=S.ip4,u=ip4Use(),A=u.T-u.B,go=[{l:tr('ip4.section'),act:'ip4Open'}]; + if(u.cg>=Math.max(1,u.H*0.01)){if(!(I.w&1)){I.w|=1;toast(tr('ip4.toast_cgnat',{p:pct(u.cg/u.H)}),'',go);}}else if(A-u.p6>=u.Hd*1.05)I.w&=~1; + if(u.over>0){if(!(I.w&2)){I.w|=2;const k=ip4Pools(u);toast(k===1?tr('ip4.toast_out_v6',{r:u.r6}):k?tr('ip4.toast_out_both',{r:u.r,r6:u.r6}):tr('ip4.toast_out',{r:u.r}),'bad',go);sfx('err');}} + else if(A>=u.need*1.1)I.w&=~2;} +// Your customers need the addresses: what to stretch or get instead (ip4Busy, the bank's block rows). +function ip4InUse(u=ip4Use()){const k=ip4Pools(u);return k===1?tr('ip4.in_use_v6'):k?tr('ip4.in_use_both'):tr('ip4.in_use');} // Renewals that wanted a bigger block than is free (clGrow, [customer, bandwidth]): they stay as they are, and hear why. function ip4News(l=[]){for(const [b,bw] of l.slice(0,3))toast(tr('ip4.no_grow',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(bw)}),'',[{l:tr('ip4.section'),act:'ip4Open'}]);} // The line under an offer that cannot be signed for want of addresses. diff --git a/src/game/60-features/34-ipv6-only.js b/src/game/60-features/34-ipv6-only.js new file mode 100644 index 0000000..9c2967e --- /dev/null +++ b/src/game/60-features/34-ipv6-only.js @@ -0,0 +1,58 @@ +/* ---------- IPv6-only broadband (464XLAT), city by city, next to CGNAT (33-address-space.js) ---------- + A broadband city can go IPv6-only: every home router is swapped for one with a CLAT, and the network runs NAT64/DNS64 + for whatever still needs IPv4. Those homes hold no IPv4 address of their own: their IPv4 shares the NAT64 pool at the + player's NAT64 ratio (S.ip4.n64), which ip4Use() sets aside right after business customers. CGNAT costs nothing to + start; this costs a home router per home, paid as each one goes in, and some days per city. + p.bb.v6: the share of the city's homes that are IPv6-only (absent: none, dual stack, as in every older save); + p.bb.v6e: the day the swap finishes, while it runs. Homes that join a city that is swapping or done get the new router + from the start, at the same price (ip6Grow): a city that goes IPv6-only the day it launches pays for every home it grows + into, as one that switches years later does. Stop halfway and the swapped ones stay, the new ones come dual stack + again. A POP closed and rebuilt starts dual stack: its homes, and the routers they had, left with it. Rule ip4, like + the rest of the address space. */ +// Dollars per home router; a swap takes IP6_D0 days plus one for every IP6_PER homes, IP6_DMAX at most. +const IP6_CPE=4,IP6_D0=30,IP6_PER=200,IP6_DMAX=180; +const ip6Pop=c=>own(S.pops,c)?S.pops[c]:null; +// Dual-stack homes still to swap in a city. +const ip6Homes=p=>p&&p.bb?Math.max(0,p.bb.d*IP4_BB*(1-(p.bb.v6||0))):0; +const ip6Cost=c=>{const n=ip6Homes(ip6Pop(c));return n>0?Math.max(100,Math.round(n*IP6_CPE/100)*100):0;}; +const ip6Days=c=>Math.min(IP6_DMAX,IP6_D0+Math.ceil(ip6Homes(ip6Pop(c))/IP6_PER)); +// To start, the first day's routers on hand: the rest is paid as they go in, and the swap waits while cash is short. +const ip6First=c=>ip6Cost(c)/Math.max(1,ip6Days(c)); +// The network as it would be with every home here IPv6-only (p: the city's POP, with broadband). +const ip6If=(c,p)=>({ip4:S.ip4,biz:S.biz,pops:{...S.pops,[c]:{...p,bb:{...p.bb,v6:1}}}}); +// Exactly what going IPv6-only here frees for new customers: the address space counted again with every home here on it. +function ip6Free(c){const p=ip6Pop(c);if(!p||!p.bb)return 0;return ip4Use(ip6If(c,p)).free-ip4Use().free;} +/* And what it does to the month's IPv4 bill, counted the same way (eye: what broadband earns a month): NAT64 gateways and + refunds against the CGNAT boxes and refunds it saves. While no home is behind CGNAT it only adds. */ +function ip6Mo(c,eye){const p=ip6Pop(c);if(!p||!p.bb)return 0;const m=b=>b.box+b.box64+b.refund;return m(ip4Bill(eye,ip6If(c,p)))-m(ip4Bill(eye));} +// Why this city cannot start a swap now ('' when it can). +function ip6Why(c){const p=ip6Pop(c);if(!ip4On())return tr('ip4.off');if(!p||!p.bb)return tr('ip6.no_bb');if(p.bb.v6e)return tr('ip6.busy');if(p.bb.v6>=1)return tr('ip6.already');return '';} +// Today's routers: an even share of what is left, so the swap ends on its day however the city grows meanwhile. +const ip6Left=(b,d)=>Math.max(1,b.v6e-d+1),ip6Slice=(b,d)=>b.d*IP4_BB*(1-(b.v6||0))/ip6Left(b,d)*IP6_CPE; +/* Once a day (from ip4Day): every running swap does its share of the homes and pays for their routers. Short of cash, + the crews wait a day and the end slides with them, so a swap never pushes the network into the red. */ +function ip6Day(d){if(!ip4On())return;for(const c in S.pops){const b=S.pops[c].bb;if(!b||!b.v6e)continue; + const k=ip6Left(b,d),cost=ip6Slice(b,d);if(cost>Math.max(0,S.cash)){b.v6e++;continue;} + S.cash-=cost;const v=b.v6||0;b.v6=k<=1?1:Math.min(1,v+(1-v)/k); + if(k<=1){delete b.v6e;toast(tr('ip6.done',{city:esc(CITY[c].name)}),'good',[{l:tr('ip4.section'),act:'ip4Open'}]);}}} +/* The day's new homes (d0: demand before it grew): while swapping or done each gets the new router, IP6_CPE like a swapped + one, dual stack after a stop. The swap of old routers is a project and waits for cash; a home that signs up today + needs its router today, so that is spent like any running cost (homes only join where the service is good, and they + pay it back within days). */ +function ip6Grow(b,d0){if(!ip4On()||!(b.d>d0))return;const v=b.v6||0; + if(b.v6e||v>=1){S.cash-=(b.d-d0)*IP4_BB*IP6_CPE;if(v<1)b.v6=1-(1-v)*d0/b.d;}else if(v>0)b.v6=v*d0/b.d;} +// Saves: v6 is a share (none at all is no field, so a dual-stack city saves as it always did); v6e a day, gone once done. +function ip6Fix(b,day){if(b.v6!==undefined){const v=num(b.v6,0);if(v>0)b.v6=Math.min(1,v);else delete b.v6;} + if(b.v6e!==undefined){if(b.v6>=1||!Number.isFinite(b.v6e))delete b.v6e;else b.v6e=int(b.v6e,day,day+3650,day);}} +// The city panel's Home broadband: where the city stands, and the swap to start or stop. +function ip6Html(c){if(!ip4On())return '';const p=ip6Pop(c),b=p&&p.bb;if(!b)return '';const v=b.v6||0,r=S.ip4.n64||IP4_N640; + let h=`
${tr('ip6.title')}${v>=1?tr('ip6.every_home'):v>0||b.v6e?tr('ip6.share_homes',{p:pct(v)}):tr('ip6.dual_stack')}
`; + if(b.v6e){const wait=ip6Slice(b,S.day+1)>Math.max(0,S.cash); + h+=`

${tr('ip6.swapping_home_routers_paid',{cost:fmt$(IP6_CPE),date:dateStr(b.v6e)})}

${wait?`

${tr('ip6.waiting')}

`:''}
${btn(tr('ip6.stop'),'ip6Stop',{city:c},'ghost sm')}
`;} + else if(v>=1)h+=`

${tr('ip6.new_homes_get_a_clat',{cost:fmt$(IP6_CPE),r})}

`; + else{const n=Math.ceil(ip6Homes(p)),cost=ip6Cost(c),f=Math.max(0,ip6Free(c)),mo=Math.round(ip6Mo(c,(R.rev&&R.rev.eyeballs)||0)); + // Before the player commits: what the month costs after it too, and that it buys nothing yet while IPv4 still fits. + const bill=mo>0?tr('ip6.your_ipv4_bill_goes_up',{price:fmt$(mo)})+(ip4Use().cg?'':' '+tr('ip6.no_home_is_behind_cgnat')):mo<0?tr('ip6.your_ipv4_bill_goes_down',{price:fmt$(-mo)}):''; + h+=`

${v>0?tr('ip6.part_note',{p:pct(v)}):tr('ip6.pitch',{r})} ${tr('ip6.what',{routers:trn('ip6.n_routers',n,{n:ip4N(n)}),days:ip6Days(c),addr:trn('ip4.n_addresses',f,{n:ip4N(f)})})} ${tr('ip6.homes_that_join_later',{cost:fmt$(IP6_CPE)})}${bill?' '+bill:''}

+
${btn(tr('ip6.go',{cost:fmt$(cost)}),'ip6Go',{city:c},'sm',S.cash`;} + return h+'
';} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 3c25690..80cae7a 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -17,7 +17,7 @@ function sanitize(s){ {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;} + 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);ip6Fix(p.bb,s.day);}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); diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 26d651d..bef2a76 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -49,9 +49,10 @@ function* dayPreRun(){ toast(where?tr('day_tick.resolved_what_where_is_back_to',{what:incTitle(i.type),where:esc(where)}):tr('day_tick.resolved_what',{what:incTitle(i.type)}),'good',[],o);} yield DAY_REST; // eyeball growth / churn uses last computed service - for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c)*((R.bbF&&R.bbF[c])??1),P=eyeP(c); + for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c)*((R.bbF&&R.bbF[c])??1),P=eyeP(c),d0=p.bb.d; 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));} + else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04)); + if(p.bb.v6||p.bb.v6e)ip6Grow(p.bb,d0);} return d;} function* dayPost(d){ yield* ddosNewsRun();ddosTrack(); diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index 19aa159..201eb09 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -4,7 +4,7 @@ Object.assign(ACT,{ if(!w&&!p){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}const L=l.list||(l.list={w:0,p:0});L.w+=w;L.p+=p; toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();}, unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();}, - accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o);toast(tr('ip4.no_space',{name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))}),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');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;} + accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o),u=ip4Use(),k=ip4Pools(u),v={name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,u.free))};toast(k===1?tr('ip4.no_space_v6',v):k?tr('ip4.no_space_both',v):tr('ip4.no_space',v),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');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)-xpSlots(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/54-address-space.js b/src/game/90-actions/54-address-space.js index e2c934f..feb196d 100644 --- a/src/game/90-actions/54-address-space.js +++ b/src/game/90-actions/54-address-space.js @@ -1,9 +1,9 @@ -/* Address space (#150, 33-address-space.js): buy, lease in, lease out, sell, hand back, and the CGNAT ratio. Every block - change keeps room for the customers already signed, with every home behind CGNAT. */ +/* Address space (#150, 33-address-space.js): buy, lease in, lease out, sell, hand back, and the CGNAT and NAT64 ratios. + Every block change keeps room for the customers already signed, with every dual-stack home behind CGNAT. */ const ip4Re=()=>{after();renderBank();}; function ip4Can(){if(ip4On())return true;toast(tr('ip4.off'),'bad');sfx('err');return false;} const ip4Blk=id=>S.ip4.b.find(b=>b.id===id); -function ip4Busy(){toast(tr('ip4.in_use'),'bad');sfx('err');} +function ip4Busy(){toast(ip4InUse(),'bad');sfx('err');} // No more blocks than a save keeps (IP4_BLK): a new one is refused with the way out. function ip4Room(){if(!ip4Full())return true;toast(tr('ip4.too_many',{n:IP4_BLK}),'bad');sfx('err');return false;} Object.assign(ACT,{ @@ -25,5 +25,8 @@ Object.assign(ACT,{ S.ip4.b=S.ip4.b.filter(x=>x!==b);sfx('click');ip4Re();}, // Fewer homes per address needs more addresses: refused when the customers already signed would not fit. ip4Nat:({v})=>{if(!ip4Can())return;const r=Number(v);if(!IP4_NAT.includes(r)||r===S.ip4.nat)return;const u=ip4Use(); - if(r{if(!ip4Can())return;const r=Number(v);if(!IP4_N64.includes(r)||r===S.ip4.n64)return;const u=ip4Use(); + if(r{if(!ip4Can())return;const why=ip6Why(city);if(why){toast(why,'bad');sfx('err');return;}const p=ip6Pop(city); + if(S.cash{if(!ip4Can())return;const p=ip6Pop(city);if(!p||!p.bb||!p.bb.v6e)return;delete p.bb.v6e;sfx('click'); + toast(tr('ip6.stopped',{city:esc(CITY[city].name),p:pct(p.bb.v6||0)}),'');after();}, +}); diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index fd7fbd6..f1cbc88 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -33,7 +33,7 @@ function cityPanel(c){
${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)}
`;} +
${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)}
${ip6Html(c)}`;} h+=`

${tr('common.business_customers')}

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

${tr('city_panel.no_businesses_yet_offers_pop_up')}

`; diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 1802e8f..a0dfe73 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -9,7 +9,7 @@ function renderDash(){checkLayer();
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')} -

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row'),sat:tr('satellites.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; +

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.leases_cgnat_nat64'),sat:tr('satellites.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0; // The legend above the table picks which ways in count; "lost" still looks at everything the network gets. diff --git a/src/game/94-dashboard/72-address-space.js b/src/game/94-dashboard/72-address-space.js index 149689c..d90d78e 100644 --- a/src/game/94-dashboard/72-address-space.js +++ b/src/game/94-dashboard/72-address-space.js @@ -1,21 +1,29 @@ -/* The bank's Address space section (#150, 33-address-space.js): what you hold and who uses it, the CGNAT ratio, your - blocks, and the transfer market. Phones: the boxes are full width, the dropdowns stack and every button row wraps. */ +/* The bank's Address space section (#150, 33-address-space.js): what you hold and who uses it (homes in three groups once + some are IPv6-only), the CGNAT and NAT64 ratios, your blocks, and the transfer market. Phones: the boxes are full + width, the dropdowns stack and every button row wraps. */ const ip4Pc=x=>(x*100).toFixed(1).replace(/\.0$/,'')+'%'; function ip4Bank(){if(!S||!ip4On())return '';const I=S.ip4,B=ip4Bill((R.rev&&R.rev.eyeballs)||0),u=B.u,len=ip4LenOk(UI.ip4Len)?UI.ip4Len:IP4_MAX,px=ip4Px(),full=ip4Full(); const kv=(l,v,bad)=>`
${l}${v}
`,mo=v=>tr('common.price_mo',{price:fmt$(v)}); let h=`

🔢 ${tr('ip4.section')}

${tr('ip4.note')}

`; - h+=`
${kv(tr('ip4.yours'),ip4N(u.T))}${kv(tr('ip4.business'),ip4N(u.B))}${kv(tr('ip4.homes'),u.cg?tr('ip4.homes_cgnat',{n:ip4N(u.H),p:pct(u.cg/u.H)}):ip4N(u.H))}${kv(tr('ip4.free'),ip4N(Math.max(0,u.free)),u.free<=0)}`; - if(u.over>0)h+=`
${tr('ip4.squeezed',{p:pct(u.over),r:u.r})}
`; - if(B.lin>0)h+=kv(tr('ip4.leases_in'),mo(B.lin));if(B.box>=1)h+=kv(tr('ip4.cgnat_boxes'),mo(B.box));if(B.refund>=1)h+=kv(tr('ip4.refunds'),mo(B.refund));if(B.lout>0)h+=kv(tr('ip4.leases_out'),'+'+mo(B.lout)); + h+=`
${kv(tr('ip4.yours'),ip4N(u.T))}${kv(tr('ip4.business'),ip4N(u.B))}`; + // Public, behind CGNAT, IPv6-only: the three groups once there is a third. + h+=u.H6>0?kv(tr('ip4.homes'),ip4N(u.H))+kv(tr('ip4.homes_public'),ip4N(u.H-u.H6-u.cg))+kv(tr('ip4.homes_behind_cgnat'),ip4N(u.cg))+kv(tr('ip4.homes_v6'),tr('ip4.homes_v6_pool',{n:ip4N(u.H6),pool:ip4N(u.p6)})) + :kv(tr('ip4.homes'),u.cg?tr('ip4.homes_cgnat',{n:ip4N(u.H),p:pct(u.cg/u.H)}):ip4N(u.H)); + h+=kv(tr('ip4.free'),ip4N(Math.max(0,u.free)),u.free<=0); + if(u.over>0){const k=ip4Pools(u);h+=`
${k===1?tr('ip4.squeezed_v6',{p:pct(u.over),r:u.r6}):k?tr('ip4.squeezed_both',{p:pct(u.over),r:u.r,r6:u.r6}):tr('ip4.squeezed',{p:pct(u.over),r:u.r})}
`;} + if(B.lin>0)h+=kv(tr('ip4.leases_in'),mo(B.lin));if(B.box>=1)h+=kv(tr('ip4.cgnat_boxes'),mo(B.box));if(B.box64>=1)h+=kv(tr('ip4.nat64_gateways'),mo(B.box64));if(B.refund>=1)h+=kv(tr('ip4.refunds'),mo(B.refund));if(B.lout>0)h+=kv(tr('ip4.leases_out'),'+'+mo(B.lout)); + h+=kv(tr('ip4.v6_share'),pct(1-B.v4)); h+=` -

${tr('ip4.cgnat_note',{p:ip4Pc(IP4_ANNOY[I.nat])})}

`; - h+=`
${tr('ip4.blocks')}
`; +

${tr('ip4.cgnat_note',{p:ip4Pc(IP4_ANNOY[I.nat])})}

+ +

${tr('ip4.nat64_note',{p:ip4Pc(IP4_ANNOY64[u.r6]*B.v4/IP4_V4)})}

`; + h+=`
${tr('ip4.blocks')}
`;const inUse=ip4InUse(u); for(const b of I.b){const n=ip4Sz(b.len),spare=u.free>=n,held=ip4Held(b),sure=UI.confirm===b.id; const what=b.k==='in'?tr('ip4.leased_in_mo',{price:fmt$(b.mo||0)}):b.out?tr('ip4.leased_out_mo',{price:fmt$(b.mo||0)}):b.k==='buy'?tr('ip4.bought_on',{date:dateStr(b.d)}):tr('ip4.from_rir'); const btns=b.k==='in'?btn(tr('ip4.give_back'),'ip4Return',{id:b.id},'ghost sm',!spare):b.out?btn(tr('ip4.take_back'),'ip4Back',{id:b.id},'ghost sm') :btn(tr('ip4.lease_out',{price:fmt$(ip4OutMo(b.len))}),'ip4Out',{id:b.id},'sm',!spare)+btn(sure?tr('ip4.really_sell',{price:fmt$(ip4Value(b.len))}):tr('ip4.sell',{price:fmt$(ip4Value(b.len))}),'ip4Sell',{id:b.id},sure?'red sm':'ghost sm',held||!spare); // Greyed for want of room: say so (a disabled button never gets to show ip4Busy's toast). - h+=`
/${b.len} · ${trn('ip4.n_addresses',n,{n:ip4N(n)})}
${what}${held&&!b.out?' · '+tr('ip4.movable_from',{date:dateStr(b.d+IP4_HOLD)}):''}
${!spare&&!b.out?`
${tr('ip4.in_use')}
`:''}
${btns}
`;} + h+=`
/${b.len} · ${trn('ip4.n_addresses',n,{n:ip4N(n)})}
${what}${held&&!b.out?' · '+tr('ip4.movable_from',{date:dateStr(b.d+IP4_HOLD)}):''}
${!spare&&!b.out?`
${inUse}
`:''}
${btns}
`;} h+=`
${tr('ip4.market')}

${tr('ip4.market_note',{px:fmt$(px),lin:'$'+(IP4_IN*px/IP4_PX).toFixed(2),lout:'$'+(IP4_OUT*px/IP4_PX).toFixed(2),p:pct(IP4_SELL)})}

${full?`
${tr('ip4.too_many',{n:IP4_BLK})}
`:''}
${btn(tr('ip4.buy',{price:fmt$(ip4Cost(len))}),'ip4Buy',{len},'pink sm',full||S.cash
`; diff --git a/src/i18n/en.js b/src/i18n/en.js index 4ce1e9d..05cc3fd 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2692,20 +2692,26 @@ "ip4.cgnat_boxes":"CGNAT boxes", "ip4.cgnat_note":"More homes per address frees space for customers, but games and port forwarding suffer: {p} of a CGNAT home's bill comes back as refunds.", "ip4.cgnat_ratio":"CGNAT: homes sharing one address", -"ip4.costs_row":"IPv4 leases and CGNAT", "ip4.free":"Free for new customers (homes move behind CGNAT first)", "ip4.from_rir":"From the RIR", "ip4.give_back":"Give it back", "ip4.held":"The RIR won't transfer that block again before {date}.", "ip4.homes":"Broadband homes", +"ip4.homes_behind_cgnat":"Homes behind CGNAT", "ip4.homes_cgnat":"{n}, {p} behind CGNAT", +"ip4.homes_public":"Homes with their own address", +"ip4.homes_v6":"IPv6-only homes (464XLAT)", +"ip4.homes_v6_pool":"{n}, NAT64 pool {pool}", "ip4.in_use":"Your customers need those addresses: put more homes behind CGNAT or get another block first.", +"ip4.in_use_both":"Your customers need those addresses: put more homes on each CGNAT or NAT64 address or get another block first.", +"ip4.in_use_v6":"Your customers need those addresses: put more IPv6-only homes on each NAT64 address or get another block first.", "ip4.lease":"Lease {price}/mo", "ip4.lease_out":"Lease out +{price}/mo", "ip4.leased_in":"Leased a {p} ({n} addresses) for {price}/mo.", "ip4.leased_in_mo":"Leased in · {price}/mo", "ip4.leased_out":"Your {p} is leased out: +{price}/mo.", "ip4.leased_out_mo":"Leased out · +{price}/mo", +"ip4.leases_cgnat_nat64":"IPv4 leases, CGNAT and NAT64", "ip4.leases_in":"Blocks leased in", "ip4.leases_out":"Blocks leased out", "ip4.market":"Transfer market", @@ -2713,8 +2719,13 @@ "ip4.movable_from":"can move again from {date}", "ip4.n_addresses":{"one":"{n} address","other":"{n} addresses"}, "ip4.n_homes_per_address":{"one":"{n} home per address","other":"{n} homes per address"}, +"ip4.nat64_gateways":"NAT64 gateways", +"ip4.nat64_note":"IPv6-only homes have no IPv4 of their own: what still needs it (consoles, IPv4-only VPNs) shares your NAT64 pool, and {p} of their bill comes back as refunds, less each year as the world moves to IPv6. A city goes IPv6-only from its Home broadband.", +"ip4.nat64_ratio":"NAT64: IPv6-only homes sharing one address", "ip4.no_grow":"{name} ({city}) wanted to grow to {bw}, but you had no IPv4 addresses free for it.", "ip4.no_space":"{name} needs a {p} of IPv4 ({n} addresses), and only {free} are free. Buy or lease a block, or put more homes behind CGNAT.", +"ip4.no_space_both":"{name} needs a {p} of IPv4 ({n} addresses), and only {free} are free. Buy or lease a block, or put more homes on each CGNAT or NAT64 address.", +"ip4.no_space_v6":"{name} needs a {p} of IPv4 ({n} addresses), and only {free} are free. Buy or lease a block, or put more IPv6-only homes on each NAT64 address.", "ip4.note":"IPv6 is free and endless. IPv4 ran out years ago: business customers need public blocks of it, and homes that don't fit share addresses behind CGNAT (IPv6 traffic goes around the box).", "ip4.off":"IPv4 is plentiful under this game's rules.", "ip4.offer_needs":"Needs a {p} of IPv4 ({n} addresses); only {free} free.", @@ -2726,11 +2737,39 @@ "ip4.sell":"Sell {price}", "ip4.sold":"Sold your {p} for {price}.", "ip4.squeezed":"Out of space: {p} of homes don't fit even at {r} homes per address. Their connections break and they want refunds: buy or lease a block.", +"ip4.squeezed_both":"Out of space: {p} of homes don't fit even at {r} homes per CGNAT address and {r6} per NAT64 address. Their connections break and they want refunds: buy or lease a block.", +"ip4.squeezed_v6":"Out of space: {p} of homes don't fit even at {r} IPv6-only homes per NAT64 address. Their connections break and they want refunds: buy or lease a block.", "ip4.take_back":"Take it back", "ip4.toast_cgnat":"Your IPv4 is full. {p} of your homes now share addresses behind CGNAT, and a few gamers have already written in.", "ip4.toast_out":"Out of IPv4. Even at {r} homes per address, CGNAT can't fit everyone: buy or lease a block at the bank.", +"ip4.toast_out_both":"Out of IPv4. Even at {r} homes per address behind CGNAT and {r6} on NAT64, not every home fits: buy or lease a block at the bank.", +"ip4.toast_out_v6":"Out of IPv4. Even at {r} homes per address, your NAT64 pool can't fit every IPv6-only home: buy or lease a block at the bank.", "ip4.too_many":"You hold {n} IPv4 blocks, the most one network can keep track of. Sell or give back small ones to make room for a bigger block.", +"ip4.v6_share":"IPv6 share of home traffic this year", "ip4.yours":"Your IPv4 addresses", +"ip6.already":"Every home here is IPv6-only already.", +"ip6.busy":"The swap here is already under way.", +"ip6.done":"{city} is IPv6-only. Every home there runs 464XLAT, and what still needs IPv4 shares your NAT64 pool.", +"ip6.dual_stack":"Dual stack", +"ip6.every_home":"Every home", +"ip6.go":"Go IPv6-only {cost}", +"ip6.homes_that_join_later":"Homes that join later get one too, at {cost} each.", +"ip6.n_routers":{"one":"{n} home router","other":"{n} home routers"}, +"ip6.new_homes_get_a_clat":"New homes get a CLAT router from the start, at {cost} each, and what still needs IPv4 shares your NAT64 pool, {r} homes per address.", +"ip6.no_bb":"Launch broadband here first.", +"ip6.no_home_is_behind_cgnat":"No home is behind CGNAT yet: this pays off once your IPv4 runs short.", +"ip6.part_note":"The swap stopped at {p} of homes, and new homes come dual stack again.", +"ip6.pitch":"Swap the home routers here for ones with a CLAT: the homes run on IPv6 alone and hold no IPv4 of their own, and what still needs IPv4 shares your NAT64 pool, {r} homes per address.", +"ip6.share_homes":"{p} of homes", +"ip6.started":"Swapping {routers} in {city} for IPv6-only ones: about {days} days.", +"ip6.stop":"Stop the swap", +"ip6.stopped":"Stopped the swap in {city} at {p} of homes. The routers already swapped stay; new homes come dual stack again.", +"ip6.swapping_home_routers_paid":"Swapping home routers, paid as they go in; new homes get the new one from the start, at {cost} each. Done around {date}.", +"ip6.title":"IPv6-only (464XLAT)", +"ip6.waiting":"Waiting for cash: the crews go on once you can pay for the day's routers.", +"ip6.what":"Swaps {routers} in about {days} days, paid as they go in, and frees {addr} for new customers.", +"ip6.your_ipv4_bill_goes_down":"Your IPv4 bill goes down by {price}/mo (fewer CGNAT boxes and refunds).", +"ip6.your_ipv4_bill_goes_up":"Your IPv4 bill goes up by {price}/mo (NAT64 gateways and refunds).", "ix_downgrade.pni_downgraded":"The PNI with {net} in {city} is now {port}.", "ix_downgrade.port_downgraded_at_ix":"Port at {ix} is now {port}.", "ix_downgrade.transit_downgraded":"{net} transit in {city} is now {port}.", diff --git a/tests/address-space.test.js b/tests/address-space.test.js index 92fafdf..e3017db 100644 --- a/tests/address-space.test.js +++ b/tests/address-space.test.js @@ -269,7 +269,7 @@ test('the address space says what its numbers mean: free counts homes behind CGN test('the AS box on the dashboard lists the blocks you announce, not a made-up count', (t) => { const { ev, dom, errors } = game(t); - const asBox = () => { ev("ACT.dash({});ACT.dashTab({k:'infra'})"); const k = [...dom.window.document.querySelectorAll('.kv')].map(e => e.textContent).find(x => /IPv6/.test(x)); ev('ACT.dashClose()'); return k; }; + const asBox = () => { ev("ACT.dash({});ACT.dashTab({k:'infra'})"); const k = [...dom.window.document.querySelectorAll('#dashCard .kv')].map(e => e.textContent).find(x => /IPv6/.test(x)); ev('ACT.dashClose()'); return k; }; assert.match(asBox(), /1 × \/21 IPv4, 1 × \/32 IPv6/, 'the starting allocation'); ev("ACT.ip4Lease({len:22});ACT.ip4Buy({len:24})"); assert.match(asBox(), /1 × \/21, 1 × \/22, 1 × \/24 IPv4/, 'bought and leased-in blocks are announced too'); @@ -405,7 +405,7 @@ test('saves: garbage is repaired, and the state round-trips', (t) => { ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); assert.equal(ev('JSON.stringify(S.ip4)'), before); ev(`S.ip4={b:[{id:'a',len:12,k:'rir',d:0},{id:'b',len:24,k:'stolen',d:0},{id:'c',len:24,k:'buy',d:-5,out:'yes',mo:5},{id:'d',len:23,k:'in',d:1e9,mo:-3},null,{id:'e',len:24,k:'rir',d:0,out:true,mo:'x'}],nat:7,w:99};S=sanitize(JSON.parse(JSON.stringify(S)))`); - assert.deepEqual(J(ev, 'S.ip4'), { b: [{ id: 'c', len: 24, k: 'buy', d: 0 }, { id: 'd', len: 23, k: 'in', d: ev('S.day'), mo: 0 }, { id: 'e', len: 24, k: 'rir', d: 0, out: true, mo: 0 }], nat: 16, w: 3 }); + assert.deepEqual(J(ev, 'S.ip4'), { b: [{ id: 'c', len: 24, k: 'buy', d: 0 }, { id: 'd', len: 23, k: 'in', d: ev('S.day'), mo: 0 }, { id: 'e', len: 24, k: 'rir', d: 0, out: true, mo: 0 }], nat: 16, n64: 128, w: 3 }); ev("S.ip4='nope';S=sanitize(JSON.parse(JSON.stringify(S)))"); assert.ok(J(ev, 'S.ip4.b.length') >= 1, 'a broken field is granted afresh'); assert.deepEqual(errors, []); @@ -416,7 +416,7 @@ test('the address space works on a phone: one column, wrapping buttons, the drop ev("window.innerWidth=360;window.innerHeight=740;S.pops.fra.bb.d=250;compute();ACT.ip4Lease({len:24});ACT.ip4Open()"); const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); assert.ok(sec, 'the section is in the bank'); - assert.equal(sec.querySelectorAll('select').length, 2, 'the CGNAT ratio and the block size'); + assert.equal(sec.querySelectorAll('select').length, 3, 'the CGNAT ratio, the NAT64 ratio and the block size'); for (const s of sec.querySelectorAll('select')) assert.ok(s.closest('.ops-sel'), 'each dropdown in a stacking label'); for (const b of sec.querySelectorAll('button')) assert.ok(b.closest('.btns'), 'every button in a wrapping row: ' + b.textContent); assert.match(sec.textContent, /2,500, \d+% behind CGNAT/); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 95194de..c907c66 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -259,7 +259,8 @@ test('M3: every subsystem that can annoy the player reads a rule', () => { ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], ['dfBuildDays', 'leadDays'], ['dayPreRun', "rule('clock')"], ['snub', "rule('market')"], ['failureRun', 'shipsOn()'], ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()'], - ['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()']]; + ['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()'], + ['ip6Day', 'ip4On()'], ['ip6Grow', 'ip4On()'], ['ip6Why', 'ip4On()'], ['ip6Html', 'ip4On()'], ['ip4Can', 'ip4On()']]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(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 and no market means a quiet year const g = load(); diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index beb7695..7fa3f79 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -227,7 +227,7 @@ test('a dry run prices every command that has a price, and changes nothing', () fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key }, opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, - pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, ip4Buy: { len: 24 }, ip4Lease: { len: 22 }, + pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, ip4Buy: { len: 24 }, ip4Lease: { len: 22 }, ip6Go: { city: 'fra' }, teleBuild: { city: 'fra' }, teleTrk: { city: 'fra' }, buySat: { a: 'fra', b: 'rek', bird: 'is37', g: 1 }, satSize: { id: wave, g: 2 }, }; const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required)); diff --git a/tests/nat64.test.js b/tests/nat64.test.js new file mode 100644 index 0000000..df961a7 --- /dev/null +++ b/tests/nat64.test.js @@ -0,0 +1,415 @@ +// IPv6-only broadband with 464XLAT and NAT64, next to CGNAT (src/game/60-features/34-ipv6-only.js, the address space in +// 33-address-space.js): a city's home routers are swapped over some days, paid as they go in; its homes then hold no IPv4 +// of their own, only a share of the NAT64 pool at a wider ratio than CGNAT, and grumble less. Rule ip4, like the rest. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt on On-call, plenty of cash, nothing breaking, 1,300 homes on the starting /21. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall');S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=9;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.offers=[];S.biz=[];" + + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:3});S.pops.fra.bb.d=130;compute()"; +function game(t, opts) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE); + return h; +} +const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); +// Days of the swap without the rest of the day (homes stay put): the day's IPv4 step, as dayPost runs it. +const days = (ev, n) => ev(`for(let i=0;i<${n};i++){S.day++;ip4Day(S.day)}compute()`); +const host = (ev, id, bw) => ev(`S.biz.push(${lit({ id, city: 'fra', city2: null, reqs: [], name: 'H ' + id, type: 'host', bw, rate: 60, mood: 100, since: 0 })});compute()`); +const panel = (ev, dom, c = 'fra') => { ev(`selectCity('${c}');UI.tab='cust';renderPanel()`); return dom.window.document.getElementById('panelBody'); }; + +test('going IPv6-only frees exactly what the address math says, the NAT64 pool before dual-stack homes', (t) => { + const { ev, errors } = game(t); + let u = J(ev, 'ip4Use()'); + assert.deepEqual([u.T, u.H, u.H6, u.p6, u.cg, u.free], [2048, 1300, 0, 0, 0, 2048 - 82], '1,300 dual-stack homes, all public; free counts them at 1:16'); + // The city panel promises it: 1,300 homes at 1:128 take 11 addresses instead of 82. + assert.equal(ev("ip6Free('fra')"), 82 - 11); + ev("ACT.ip6Go({city:'fra'})"); + days(ev, 37); + u = J(ev, 'ip4Use()'); + assert.deepEqual([u.H, u.H6, u.Hd, u.p6, u.cg, u.free], [1300, 1300, 0, 11, 0, 2048 - 11], 'every home on the NAT64 pool'); + assert.equal(u.free - (2048 - 82), 71, 'freed exactly what it said'); + // Two cities: Frankfurt IPv6-only, Amsterdam dual stack, a /23 customer. The pool comes off first, then the dual-stack + // homes take what is left and the rest go behind CGNAT. + ev("ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});S.pops.fra.bb.d=100;S.pops.ams.bb.d=160;compute()"); + host(ev, 'h1', 80); + u = J(ev, 'ip4Use()'); + assert.deepEqual([u.B, u.H6, u.p6, u.Hd], [512, 1000, 8, 1600]); + assert.equal(u.cg, Math.ceil((1600 - (1536 - 8)) * 16 / 15), 'dual-stack homes get what the pool leaves'); + assert.equal(u.free, 2048 - 512 - 8 - 100); + assert.ok(u.H - u.H6 - u.cg + Math.ceil(u.cg / 16) + u.p6 <= 1536, 'public homes, the CGNAT pool and the NAT64 pool fit the space'); + // What Amsterdam would free is what the address space then frees. + const f = ev("ip6Free('ams')"), free0 = u.free; + assert.equal(f, 100 - (Math.ceil(2600 / 128) - 8)); + ev("ACT.ip6Go({city:'ams'})"); + days(ev, ev("S.pops.ams.bb.v6e-S.day")); + assert.equal(J(ev, 'ip4Use()').free, free0 + f); + assert.equal(J(ev, 'ip4Use()').cg, 0); + assert.deepEqual(errors, []); +}); + +test('the swap: its cost and days, paid as the routers go in, new homes on the new router, stopped with nothing back', (t) => { + const { ev, dom, errors } = game(t); + // 1,300 homes: $4 a router, 30 days and one more for every 200 homes. + assert.deepEqual([ev("ip6Cost('fra')"), ev("ip6Days('fra')")], [5200, 37]); + const cash0 = ev('S.cash'); + ev("ACT.ip6Go({city:'fra'})"); + assert.equal(ev('S.pops.fra.bb.v6e'), ev('S.day') + 37); + assert.equal(ev('S.cash'), cash0, 'nothing paid up front'); + assert.match(dom.window.document.getElementById('toasts').textContent, /Swapping 1,300 home routers in Frankfurt for IPv6-only ones: about 37 days/); + days(ev, 10); + assert.ok(Math.abs(ev('S.pops.fra.bb.v6') - 10 / 37) < 1e-9, 'an even share a day'); + assert.ok(Math.abs(cash0 - ev('S.cash') - 5200 * 10 / 37) < 1e-4, 'paid for the routers that went in'); + // Homes that join during the swap get the new router from the start, at the same price, paid the day they join. + let c = ev('S.cash'); + ev('ip6Grow(Object.assign(S.pops.fra.bb,{d:260}),130)'); + assert.ok(Math.abs(ev('S.pops.fra.bb.v6') - (1 - (27 / 37) / 2)) < 1e-9); + assert.ok(Math.abs(c - ev('S.cash') - 1300 * 4) < 1e-6, '1,300 new homes, 1,300 routers'); + ev('S.pops.fra.bb.d=130;S.pops.fra.bb.v6=10/37;S.cash=' + c); + // Stopped: the swapped homes stay, nothing comes back, nothing more is paid. + const cash1 = ev('S.cash'); + ev("ACT.ip6Stop({city:'fra'})"); + assert.equal(ev('S.pops.fra.bb.v6e'), undefined); + assert.equal(ev('S.cash'), cash1); + days(ev, 30); + assert.deepEqual([ev('S.cash'), ev('S.pops.fra.bb.v6')], [cash1, 10 / 37]); + assert.match(dom.window.document.getElementById('toasts').textContent, /Stopped the swap in Frankfurt at 27% of homes/); + // After a stop, new homes are dual stack again, and cost nothing. + ev('ip6Grow(Object.assign(S.pops.fra.bb,{d:260}),130)'); + assert.ok(Math.abs(ev('S.pops.fra.bb.v6') - 5 / 37) < 1e-9); + assert.equal(ev('S.cash'), cash1); + // Resumed: the rest, at the same price a router, and it finishes on its day. + const left = ev('2600*(1-S.pops.fra.bb.v6)'); + assert.equal(ev("ip6Cost('fra')"), Math.round(left * 4 / 100) * 100); + assert.equal(ev("ip6Days('fra')"), 30 + Math.ceil(left / 200)); + const cash2 = ev('S.cash'), n = ev("ip6Days('fra')"); + ev("ACT.ip6Go({city:'fra'})"); + days(ev, n - 1); + assert.ok(ev('S.pops.fra.bb.v6') < 1); + days(ev, 1); + assert.deepEqual([ev('S.pops.fra.bb.v6'), ev('S.pops.fra.bb.v6e')], [1, undefined]); + assert.ok(Math.abs(cash2 - ev('S.cash') - left * 4) < 1e-4, 'the whole rest, router by router'); + assert.match(dom.window.document.getElementById('toasts').textContent, /Frankfurt is IPv6-only/); + // Done: new homes come IPv6-only and pay for their router, even short of cash (a new home needs one today), and the + // swap cannot start again. + c = ev('S.cash'); + ev('ip6Grow(Object.assign(S.pops.fra.bb,{d:400}),260)'); + assert.equal(ev('S.pops.fra.bb.v6'), 1); + assert.ok(Math.abs(c - ev('S.cash') - 1400 * 4) < 1e-6); + ev('S.cash=100;ip6Grow(Object.assign(S.pops.fra.bb,{d:410}),400)'); + assert.deepEqual([ev('S.pops.fra.bb.v6'), ev('S.pops.fra.bb.v6e'), Math.round(ev('S.cash'))], [1, undefined, 100 - 400], 'still IPv6-only, not a stopped swap'); + ev('S.cash=1e8'); + ev("document.getElementById('toasts').innerHTML='';ACT.ip6Go({city:'fra'})"); + assert.match(dom.window.document.getElementById('toasts').textContent, /already/); + assert.deepEqual(errors, []); +}); + +test('the swap waits while cash is short, and the real day runs it with the city growing', (t) => { + const { ev, dom, errors } = game(t); + // Starting needs only the first day's routers on hand ($5,200 over 37 days), not the whole swap. + ev('S.cash=Math.ceil(ip6First("fra"))-1'); + assert.equal(panel(ev, dom).querySelector('[data-act="ip6Go"]').disabled, true); + ev("ACT.ip6Go({city:'fra'})"); + assert.equal(ev('S.pops.fra.bb.v6e'), undefined, 'not even a day of routers: no start'); + ev('S.cash=Math.ceil(ip6First("fra"))'); + assert.ok(ev('S.cash') < ev('ip6Cost("fra")') / 10); + assert.equal(panel(ev, dom).querySelector('[data-act="ip6Go"]').disabled, false); + ev("ACT.ip6Go({city:'fra'});S.cash=50"); + const e = ev('S.pops.fra.bb.v6e'); + days(ev, 3); + assert.deepEqual([ev('S.pops.fra.bb.v6') || 0, ev('S.pops.fra.bb.v6e'), ev('S.cash')], [0, e + 3, 50], 'no router it cannot pay for: the end slides'); + assert.match(panel(ev, dom).textContent, /Waiting for cash/); + ev('S.cash=1e8'); + // The whole day, homes and all: the share only rises, and the swap ends on its day. + ev('for(let i=0;i<20;i++)dayTick()'); + const v = ev('S.pops.fra.bb.v6'); + assert.ok(v > 20 / 37 - 0.01 && v < 1, 'about 20 of 37 days done: ' + v); + ev('while(S.pops.fra.bb.v6e)dayTick()'); + assert.equal(ev('S.pops.fra.bb.v6'), 1); + assert.equal(ev('S.day'), e + 3); + const d = ev('S.pops.fra.bb.d'); + ev('for(let i=0;i<30;i++)dayTick()'); + assert.ok(ev('S.pops.fra.bb.d') !== d && ev('S.pops.fra.bb.v6') === 1, 'homes come and go, all IPv6-only'); + assert.deepEqual(errors, []); +}); + +test('a city that goes IPv6-only the day it launches pays a router for every home it grows into', (t) => { + const { ev, errors } = game(t); + // A fresh launch: 180 homes, so the swap itself is cheap. + ev("S.pops.fra.bb.d=bbStart('fra');compute()"); + assert.deepEqual([ev('S.pops.fra.bb.d*10'), ev("ip6Cost('fra')")], [180, 700]); + ev("ACT.ip6Go({city:'fra'})"); + // A year of real days: count every dollar the swap and the new homes' routers take. + ev("window.__paid=0;window.__shrank=false;for(const f of ['ip6Grow','ip6Day']){const g=window[f];window[f]=(...a)=>{const c=S.cash;g(...a);__paid+=c-S.cash;};}"); + ev('for(let i=0;i<365;i++){const d=S.pops.fra.bb.d;dayTick();if(S.pops.fra.bb.d 5000 && ev('__shrank') === false, 'it grew all year: ' + homes); + assert.equal(ev('S.pops.fra.bb.v6'), 1); + assert.ok(Math.abs(ev('__paid') - homes * 4) < 1e-3, `a router for each of its ${homes} homes, as a city switching now would pay: ${ev('__paid')}`); + assert.deepEqual(errors, []); +}); + +test('before the swap, the city panel says what it does to the monthly IPv4 bill', (t) => { + const { ev, dom, errors } = game(t); + // Day 0: every home has a public address and there is no IPv4 bill; going IPv6-only adds NAT64 gateways and refunds. + const eye = 'R.rev.eyeballs'; + const mo = ev(`ip6Mo('fra',${eye})`), before = ev('R.cost.ip4') || 0; + assert.equal(before, 0); + assert.ok(mo > 300 && mo < 400, 'gateways for 130 Gbps and 1% of the bill back: ' + mo); + assert.match(panel(ev, dom).textContent, new RegExp(`Your IPv4 bill goes up by \\$${Math.round(mo)}/mo \\(NAT64 gateways and refunds\\)\\. No home is behind CGNAT yet: this pays off once your IPv4 runs short\\.`)); + assert.match(panel(ev, dom).textContent, /Homes that join later get one too, at \$4 each\./); + // Exactly what the bill does once it is done. + ev('S.pops.fra.bb.v6=1;compute()'); + assert.ok(Math.abs(ev('R.cost.ip4') - mo) <= 0.5, 'the bill moves by what the panel said'); + // Squeezed into a /24 at 1:64, most homes are behind CGNAT: going IPv6-only saves money, and says so. + ev("delete S.pops.fra.bb.v6;S.ip4.b=[{id:'x',len:24,k:'rir',d:0}];S.ip4.nat=64;compute()"); + const save = ev(`ip6Mo('fra',${eye})`), cost = ev('R.cost.ip4'); + assert.ok(save < 0, 'CGNAT boxes and refunds it no longer pays: ' + save); + const txt = panel(ev, dom).textContent; + assert.match(txt, new RegExp(`Your IPv4 bill goes down by \\$${Math.round(-save)}/mo \\(fewer CGNAT boxes and refunds\\)\\.`)); + assert.doesNotMatch(txt, /No home is behind CGNAT yet/); + ev('S.pops.fra.bb.v6=1;compute()'); + assert.ok(Math.abs(ev('R.cost.ip4') - (cost + save)) <= 1, 'the bill moves by what the panel said'); + assert.deepEqual(errors, []); +}); + +test('out of space: the advice names the sharing that is left to stretch, CGNAT, NAT64 or both', (t) => { + const { ev, dom, errors } = game(t); + const toasts = () => dom.window.document.getElementById('toasts').textContent; + const bank = () => { ev('ACT.ip4Open()'); const s = dom.window.document.querySelector('#bankCard .bank-ip4').textContent; ev('ACT.bankClose()'); return s; }; + // 10,000 homes, every one IPv6-only, on a /24 a host customer takes whole: only the NAT64 pool is short. + ev("S.pops.fra.bb.d=1000;S.pops.fra.bb.v6=1;S.ip4.b=[{id:'x',len:24,k:'rir',d:0}];compute()"); + host(ev, 'h', 64); + let u = J(ev, 'ip4Use()'); + assert.deepEqual([u.H6, u.Hd, u.cg, u.p6, u.over], [10000, 0, 0, 79, 1]); + ev('ip4Day(S.day)'); + assert.match(toasts(), /Out of IPv4\.\s*Even at 128 homes per address, your NAT64 pool can't fit every IPv6-only home/); + assert.doesNotMatch(toasts(), /CGNAT/); + assert.match(bank(), /don't fit even at 128 IPv6-only homes per NAT64 address/); + // Raising the CGNAT ratio would free nothing, so the advice does not suggest it. + ev("document.getElementById('toasts').innerHTML='';S.offers=[{id:'o1',city:'fra',city2:null,reqs:[],name:'Offer',type:'dia',bw:10,rate:60}];ACT.accept({id:'o1'})"); + assert.match(toasts(), /put more IPv6-only homes on each NAT64 address\./); + ev("document.getElementById('toasts').innerHTML='';ip4Busy()"); + assert.match(toasts(), /put more IPv6-only homes on each NAT64 address or get another block first/); + // Half the homes dual stack: both ratios help, and both are named. + ev("S.pops.fra.bb.v6=0.5;S.ip4.w=0;compute();document.getElementById('toasts').innerHTML='';ip4Day(S.day)"); + u = J(ev, 'ip4Use()'); + assert.ok(u.H6 > 0 && u.Hd > 0 && u.over > 0); + assert.match(toasts(), /Even at 16 homes per address behind CGNAT and 128 on NAT64, not every home fits/); + assert.match(bank(), /don't fit even at 16 homes per CGNAT address and 128 per NAT64 address/); + ev("document.getElementById('toasts').innerHTML='';ip4Busy()"); + assert.match(toasts(), /put more homes on each CGNAT or NAT64 address or get another block first/); + // No IPv6-only homes: CGNAT, as it always said. + ev("delete S.pops.fra.bb.v6;S.ip4.w=0;compute();document.getElementById('toasts').innerHTML='';ip4Day(S.day);ip4Busy()"); + assert.match(toasts(), /Even at 16 homes per address, CGNAT can't fit everyone/); + assert.match(toasts(), /put more homes behind CGNAT or get another block first/); + assert.match(bank(), /don't fit even at 16 homes per address\./); + assert.deepEqual(errors, []); +}); + +test('the CGNAT ratio and the warnings count only the dual-stack homes, after the NAT64 pool', (t) => { + const { ev, errors } = game(t); + // 1,300 homes, every one IPv6-only, on a /24 with a host customer on a /25: 128 addresses left, the pool takes 11. + ev("S.pops.fra.bb.v6=1;S.ip4.b=[{id:'x',len:24,k:'rir',d:0}];compute()"); + host(ev, 'h', 32); + let u = J(ev, 'ip4Use()'); + assert.deepEqual([u.T - u.B, u.p6, u.Hd], [128, 11, 0]); + // No home is behind CGNAT, so a narrower CGNAT ratio needs no room (counting all 1,300 homes, 1:8 would need 163). + ev("ACT.ip4Nat({v:'8'})"); + assert.equal(ev('S.ip4.nat'), 8); + // Homes behind CGNAT: the warning rearms once the dual-stack homes fit public again next to the pool, though all the + // homes together would not. + ev("S.biz=[];S.ip4.nat=16;S.pops.fra.bb.v6=0;S.ip4.w=0;compute();ip4Day(S.day)"); + assert.equal(ev('S.ip4.w'), 1, 'homes behind CGNAT'); + ev('S.pops.fra.bb.v6=0.85;compute();ip4Day(S.day)'); + u = J(ev, 'ip4Use()'); + assert.ok(u.T - u.B - u.p6 >= u.Hd * 1.05 && u.T - u.B < u.H * 1.05, JSON.stringify(u)); + assert.equal(ev('S.ip4.w'), 0, 'room to spare for the dual-stack homes: it rearms'); + // Out of space (the host back, 1:8): it rearms once the pool and the CGNAT homes fit with room, whatever all the homes + // at 1:8 would take. + host(ev, 'h2', 32); + ev('S.ip4.nat=8;S.pops.fra.bb.v6=0;compute();ip4Day(S.day)'); + assert.ok(J(ev, 'ip4Use()').over > 0 && (ev('S.ip4.w') & 2) === 2, 'out of space at 1:8'); + ev('S.pops.fra.bb.v6=1;compute();ip4Day(S.day)'); + u = J(ev, 'ip4Use()'); + assert.ok(u.T - u.B >= u.need * 1.1 && u.T - u.B < Math.ceil(u.H / u.r) * 1.1, JSON.stringify(u)); + assert.equal(ev('S.ip4.w') & 2, 0, 'the pool fits with room: it rearms'); + assert.deepEqual(errors, []); +}); + +test('NAT64 refunds: well under CGNAT at the same ratio, never zero, smaller as the world goes IPv6', (t) => { + const { ev, errors } = game(t); + assert.deepEqual(J(ev, '[IP4_N64,IP4_N640]'), [[64, 128, 256], 128]); + assert.ok(J(ev, 'IP4_N64.every(r=>IP4_ANNOY64[r]>0&&IP4_ANNOY64[r] 1000 && b.u.H6 === 0); + const cgHome = b.refund / b.u.cg; + assert.ok(Math.abs(cgHome - eye / 1300 * 0.04) < 1e-9); + ev("ACT.ip4Nat64({v:'64'});S.pops.fra.bb.v6=1;compute()"); + b = J(ev, 'ip4Bill(R.rev.eyeballs)'); + assert.deepEqual([b.u.cg, b.u.H6, b.u.p6, b.u.over], [0, 1300, Math.ceil(1300 / 64), 0]); + const v6Home = b.refund / b.u.H6; + assert.ok(v6Home > 0 && v6Home < cgHome / 5, `an IPv6-only home ${v6Home} against one behind CGNAT ${cgHome}`); + assert.ok(Math.abs(b.refund - eye * 0.006) < 1e-9); + assert.equal(ev('R.cost.ip4'), Math.round(b.box + b.box64 + b.refund), 'the gateways and refunds are on the bill'); + assert.ok(Math.abs(b.box64 - 130 * 0.55 * 2) < 1e-9, 'NAT64 costs what CGNAT does per Gbps of IPv4 it carries'); + // Ten years on: less IPv4 to translate, fewer refunds; CGNAT's grumbling per home stays. + ev('S.day=3652;compute()'); + const late = J(ev, 'ip4Bill(R.rev.eyeballs)'); + assert.ok(late.refund / ev('R.rev.eyeballs') < 0.006 && late.refund > 0); + assert.ok(late.box64 < b.box64); + ev("S.pops.fra.bb.v6=0;compute()"); + const lateCg = J(ev, 'ip4Bill(R.rev.eyeballs)'); + assert.ok(Math.abs(lateCg.refund / lateCg.u.cg - ev('R.rev.eyeballs') / 1300 * 0.04) < 1e-9); + // A narrower NAT64 ratio is refused when the signed customers would not fit; a wider one never is. + ev("S.pops.fra.bb.v6=1;S.ip4.b=[{id:'x',len:24,k:'rir',d:0}];S.biz=[];ACT.ip4Nat64({v:'256'});compute()"); + assert.equal(ev('S.ip4.n64'), 256); + host(ev, 'big', 40); // a /24: nothing left + ev("ACT.ip4Nat64({v:'64'})"); + assert.equal(ev('S.ip4.n64'), 256, 'needs 21 addresses it does not have'); + ev('S.biz=[];compute();ACT.ip4Nat64({v:"64"})'); + assert.equal(ev('S.ip4.n64'), 64); + assert.deepEqual(errors, []); +}); + +test('the world goes IPv6: 55% IPv4 on day 0, two points less a year, down to a floor', (t) => { + const { ev, dom, errors } = game(t); + assert.equal(ev('ip4V4(0)'), 0.55); + assert.equal(ev('ip4V4()'), ev('ip4V4(S.day)')); + const ys = [0, 1, 2, 5, 10, 20, 40].map((y) => ev(`ip4V4(${y * 365.2425})`)); + for (let i = 1; i < ys.length; i++) assert.ok(ys[i] <= ys[i - 1], 'never back up: ' + ys); + assert.ok(Math.abs(ys[1] - 0.53) < 1e-9 && Math.abs(ys[4] - 0.35) < 1e-9, 'two points a year: ' + ys); + assert.equal(ys[6], 0.2, 'a floor: some things never leave IPv4'); + assert.ok(Math.abs(ev('ip4V4(181)') - ev('ip4V4(180)')) < 1e-4, 'a gentle slope, no jumps'); + // CGNAT gets cheaper with it: the same homes behind it, ten years apart. + ev("S.ip4.b=[{id:'x',len:24,k:'rir',d:0}];compute()"); + const box0 = J(ev, 'ip4Bill(0)').box; + ev('S.day=3652;compute()'); + assert.ok(Math.abs(J(ev, 'ip4Bill(0)').box - box0 * ev('ip4V4(3652)') / 0.55) < 1e-9); + // The address space says how far the world has come. + ev('ACT.ip4Open()'); + assert.match(dom.window.document.querySelector('#bankCard .bank-ip4').textContent, /IPv6 share of home traffic this year65%/); + assert.deepEqual(errors, []); +}); + +test('rule off means no effect: no button, no swap, no pool, no bill', (t) => { + const { ev, dom, errors } = game(t); + ev("S.rules=makeRules('freeze');compute()"); + assert.equal(ev('ip4On()'), false); + const p = panel(ev, dom); + assert.doesNotMatch(p.textContent, /IPv6-only|464XLAT/); + assert.equal(p.querySelector('[data-act="ip6Go"]'), null); + ev("ACT.ip6Go({city:'fra'})"); + assert.equal(ev('S.pops.fra.bb.v6e'), undefined, 'refused'); + assert.match(dom.window.document.getElementById('toasts').textContent, /IPv4 is plentiful/); + // Even with the fields in place (a scenario that dropped the rule), nothing moves and nothing is billed. + ev('S.pops.fra.bb.v6=0.5;S.pops.fra.bb.v6e=S.day+10;compute()'); + const cash = ev('S.cash'); + ev('for(let i=0;i<5;i++){S.day++;ip4Day(S.day);ip6Day(S.day)}ip6Grow(Object.assign(S.pops.fra.bb,{d:200}),130);compute()'); + assert.deepEqual([ev('S.pops.fra.bb.v6'), ev('S.cash'), ev('R.cost.ip4')], [0.5, cash, undefined]); + ev("ACT.ip6Stop({city:'fra'});ACT.ip4Nat64({v:'64'})"); + assert.deepEqual([ev('!!S.pops.fra.bb.v6e'), ev('S.ip4.n64')], [true, 128]); + assert.deepEqual(errors, []); +}); + +test('saves: an old one loads unchanged, a swap in progress round-trips, garbage is repaired', (t) => { + const { ev, errors } = game(t); + ev("ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});compute()"); + // An old save: no NAT64 ratio, no IPv6-only homes. Its homes and its money are what they were. + ev('delete S.ip4.n64;window.__m=[R.revMo,R.costMo]'); + const bbs = 'JSON.stringify(Object.entries(S.pops).map(([c,p])=>[c,p.bb]))', pops = ev(bbs); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev(bbs), pops, 'no new field in any city'); + assert.equal(ev('S.ip4.n64'), 128); + assert.deepEqual([ev('R.revMo'), ev('R.costMo')], J(ev, '__m')); + // Mid-swap: every field as it was. + ev("ACT.ip6Go({city:'fra'})"); + days(ev, 5); + ev("ACT.ip4Nat64({v:'256'})"); + const before = ev('JSON.stringify([S.pops,S.ip4])'); + ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('JSON.stringify([S.pops,S.ip4])'), before); + // Garbage. + const fix = (bb) => J(ev, `(()=>{S.pops.ams.bb=${lit(bb)};S=sanitize(JSON.parse(JSON.stringify(S)));return S.pops.ams.bb;})()`); + const day = ev('S.day'); + assert.deepEqual(fix({ d: 50, v6: 'x', v6e: 'soon' }), { d: 50 }); + assert.deepEqual(fix({ d: 50, v6: -1 }), { d: 50 }); + assert.deepEqual(fix({ d: 50, v6: 5, v6e: day + 9 }), { d: 50, v6: 1 }, 'done is done'); + assert.deepEqual(fix({ d: 50, v6: 0.25, v6e: -40 }), { d: 50, v6: 0.25, v6e: day }, 'a past end: it finishes on the next day'); + assert.deepEqual(fix({ d: 50, v6e: 1e12 }), { d: 50, v6e: day + 3650 }); + ev("S.ip4.n64=7;S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ip4.n64'), 128); + // A POP closed and built again starts dual stack: its homes and their routers left with it. + ev("S.pops.ams.bb={d:50,v6:1};decommission(['ams']);ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'})"); + assert.equal(ev('S.pops.ams.bb.v6'), undefined); + assert.deepEqual(errors, []); +}); + +test('the agent prices the swap and says why it cannot start', (t) => { + const { ev, errors } = game(t, { agent: true }); + assert.deepEqual(J(ev, "API_CMD.ip6Go.quote({city:'fra'})"), { setup: 5200, days: 37, monthly: Math.round(ev("ip6Mo('fra',R.rev.eyeballs)")), blocked: [] }); + assert.ok(J(ev, "API_CMD.ip6Go.quote({city:'fra'})").monthly > 0, 'nothing behind CGNAT yet: it only adds'); + ev("ACT.ip6Go({city:'fra'})"); + assert.match(J(ev, "API_CMD.ip6Go.quote({city:'fra'})").blocked[0], /already under way/); + assert.match(J(ev, "API_CMD.ip6Go.quote({city:'nyc'})").blocked[0], /Launch broadband here first/); + assert.deepEqual(errors, []); +}); + +test('on a phone: the swap in the city sheet and the NAT64 ratio in the bank, portrait and landscape', (t) => { + const { ev, dom, errors } = game(t); + for (const [w, hgt] of [[360, 740], [740, 360]]) { + ev(`window.innerWidth=${w};window.innerHeight=${hgt};S.pops.fra.bb={d:130};compute()`); + assert.equal(ev('isPhone()'), true); + let p = panel(ev, dom); + const go = p.querySelector('[data-act="ip6Go"]'); + assert.ok(go && go.closest('.btns'), 'the button in a wrapping row'); + assert.match(go.textContent, /Go IPv6-only \$5\.2k/); + assert.match(p.textContent, /Swaps 1,300 home routers in about 37 days, paid as they go in, and frees 71 addresses for new customers\./); + ev("ACT.ip6Go({city:'fra'})"); + days(ev, 3); + p = panel(ev, dom); + assert.ok(p.querySelector('[data-act="ip6Stop"]').closest('.btns')); + assert.match(p.textContent, /IPv6-only \(464XLAT\)8% of homes/); + ev('ACT.ip4Open()'); + const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); + const sel = sec.querySelector('select[data-chg="ip4Nat64"]'); + assert.ok(sel && sel.closest('.ops-sel'), 'the NAT64 ratio stacks like the CGNAT one'); + assert.deepEqual([...sel.options].map((o) => [o.value, o.selected]), [['64', false], ['128', true], ['256', false]]); + for (const b of sec.querySelectorAll('button')) assert.ok(b.closest('.btns'), 'every button in a wrapping row: ' + b.textContent); + // The three groups once some homes are IPv6-only: 1,300 homes, 3/37 of them on NAT64 (a pool of one address). + assert.match(sec.textContent, /Broadband homes1,300Homes with their own address1,194Homes behind CGNAT0IPv6-only homes \(464XLAT\)106, NAT64 pool 1/); + ev('ACT.bankClose()'); + } + assert.deepEqual(errors, []); +}); + +test('no raw labels: the swap, the address space and the news, in every language', (t) => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); + ev(BASE); + const doc = dom.window.document; + let txt = ''; + const look = () => { txt += doc.getElementById('panelBody').textContent + doc.getElementById('toasts').textContent; }; + ev("ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});S.pops.ams.bb.d=1;S.ip4.b=[{id:'x',len:24,k:'rir',d:0}];compute()"); + panel(ev, dom); look(); + ev("ACT.ip6Go({city:'fra'})"); days(ev, 2); ev('S.cash=0'); panel(ev, dom); look(); + ev("S.cash=1e8;ACT.ip6Stop({city:'fra'})"); panel(ev, dom); look(); + ev("ACT.ip6Go({city:'fra'});ACT.ip6Go({city:'fra'})"); days(ev, 40); panel(ev, dom); look(); + ev("ACT.ip6Go({city:'fra'});ACT.ip6Go({city:'bos'})"); look(); + ev("ACT.ip4Open()"); + txt += doc.getElementById('bankCard').textContent; + ev("ACT.bankClose();ACT.dash({});ACT.dashTab({k:'overview'})"); + txt += doc.getElementById('dashCard').textContent; + assert.match(txt, /464XLAT/, lang); + assert.doesNotMatch(txt, /\bip[46]\.[a-z0-9_]+|\{[a-z]+\}|undefined|NaN/, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); From e25f843526d177fd75d761a757c79e1d96282a59 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 07:06:37 +0100 Subject: [PATCH 423/491] Plans: IPv6-only broadband follow-up, and what it left out --- docs/plans/next-session.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/plans/next-session.md b/docs/plans/next-session.md index 212fe92..4f100dc 100644 --- a/docs/plans/next-session.md +++ b/docs/plans/next-session.md @@ -1,8 +1,9 @@ # What is left (as of 2026-11-07) -Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Built so far: the build standard, multiplayer -phase 1, dark mode (#80), IPv4 address space (#150), express fiber (#58) and satellite teleports (#83). Everything below is -planned or known, not built. +Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Built so far: the build standard (the only +place for the router model and line system), multiplayer phase 1, dark mode (#80), IPv4 address space (#150) with +IPv6-only broadband and NAT64, express fiber (#58) and satellite teleports (#83). Everything below is planned or known, +not built. Items 5 and 6 wait for the owner's go. ## Promised and not done yet @@ -27,10 +28,14 @@ planned or known, not built. puzzles) has to ask for them. - **Phase 2 gets simpler:** with every world in one server process, its wall-clock timing (tenders that close after 10 real minutes, `idle` ≥ 300 s, notice on each player's own clock) can move to game days. -4. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative +4. **IPv6-only broadband, the follow-up** (after the server-run game, or alongside it: it touches the build standard and + the intern, not the server). A build-standard row "Broadband: IPv6-only" (cities with broadband start the swap) and the + intern's `std` order rolling it out when there is money, busiest CGNAT cities first. `ip6Go`/`ip6Stop` and the city + panel are in `src/game/60-features/34-ipv6-only.js`; the row goes into `BSTD` and `bstdPlan` (96-pop-standard.js). +5. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative over the multiplayer server, and **multiplayer phase 2** (players as carriers in each other's simulations: transit, peering, PNIs, shared fiber): design in `docs/plans/multiplayer-phase2.md`. -5. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is +6. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is the busier direction. It comes after #58 because both touch link capacity (express channels now count too). ## Known limitations of what shipped @@ -52,6 +57,9 @@ planned or known, not built. - **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income is not in the investor revenue share; blocks granted to old saves can be sold after two years (a one-off windfall); CGNAT annoyance costs refunds but does not slow broadband growth; the NOC window's address-space button does nothing. +- **IPv6-only broadband:** no one-off grumble while a city's home routers are swapped; the swap and the NAT64 ratio are + not in the build standard or the intern's orders yet (item 4); a new home in an IPv6-only city pays its router even + when cash is short (a running cost, so a finished city never looks like a stopped swap). - **Express fiber (#58):** splicing a whole fiber pair through a city was left out on purpose (every fiber end is a POP; expresses cover the need); loss and MTU incidents on a fiber do not reduce the expresses on it; the fiber panel's "n of max channels" line does not count express slots (the Express section does); regen sites added later do not charge From 0342d90657ac8c803826f850a3bd049ddd351edb Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 07:24:09 +0100 Subject: [PATCH 424/491] Faster tests, split everywhere: one sharded CI for pushes and releases - The harness builds the DOM without the page's 2 MB of script text and runs the scripts straight in the window: a page load in tests takes about half the time (jsdom's parser was slow on the script text). - That also took the game's source out of the DOM, which showed three tests that matched a phrase in the page source rather than the screen; they now check the panel, the routing window and the dictionary. - CI plans its split once and runs the tests on 6 runners; every run on main records each file's time and caches it, so the parts stay even without anyone refreshing tests/durations.json. - auto-release.yml and release.yml call the same sharded tests instead of running all 170 files on one runner each (11 and 15 min); a release is tested once, before it is tagged. - Audit: five tests that duplicated a gameplay rule or checked nothing are gone; the two slowest checks sample a third of the cities, and a year of play to reach one due date became a moved due date. --- .github/workflows/auto-release.yml | 49 +++++++------ .github/workflows/ci.yml | 107 ++++++++++++++++++++++++----- .github/workflows/release.yml | 20 ++++-- docs/ARCHITECTURE.md | 7 +- scripts/lib/timings-reporter.js | 18 +++++ scripts/test-timings.js | 19 +++++ scripts/test.js | 24 +++++-- tests/backbone-core.test.js | 7 +- tests/calendar.test.js | 8 --- tests/game.test.js | 6 -- tests/harness.js | 34 ++++++++- tests/load-time.test.js | 8 ++- tests/peering-desk.test.js | 11 --- tests/pie-in-the-sky.test.js | 21 +----- tests/pie-incidents.test.js | 5 -- tests/regions.test.js | 3 +- tests/routers-per-pop.test.js | 6 +- 17 files changed, 244 insertions(+), 109 deletions(-) create mode 100644 scripts/lib/timings-reporter.js diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index ae6a513..bf254e9 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -20,18 +20,19 @@ concurrency: cancel-in-progress: false jobs: - release: + check: runs-on: ubuntu-latest env: GH_TOKEN: ${{ github.token }} + outputs: + skip: ${{ steps.v.outputs.skip }} + ver: ${{ steps.v.outputs.ver }} + tag: ${{ steps.v.outputs.tag }} + pre: ${{ steps.v.outputs.pre }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 24 - cache: npm - name: Work out the version and whether it is new id: v @@ -57,34 +58,40 @@ jobs: case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac echo "skip=false" >> "$GITHUB_OUTPUT" - - name: Test before releasing - if: steps.v.outputs.skip == 'false' - run: npm ci && npm test + # The same tests as every push, split over several runners (ci.yml), before anything is tagged. + tests: + needs: check + if: needs.check.outputs.skip == 'false' + uses: ./.github/workflows/ci.yml + + release: + needs: [check, tests] + if: needs.check.outputs.skip == 'false' + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.check.outputs.tag }} + VER: ${{ needs.check.outputs.ver }} + PRE: ${{ needs.check.outputs.pre }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Publish the release - if: steps.v.outputs.skip == 'false' - env: - TAG: ${{ steps.v.outputs.tag }} - VER: ${{ steps.v.outputs.ver }} - PRE: ${{ steps.v.outputs.pre }} run: | set -euo pipefail + awk -v v="$VER" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md pre=(); [ "$PRE" = "true" ] && pre=(--prerelease) gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \ --target "$GITHUB_SHA" --title "$VER" --notes-file notes.md "${pre[@]}" - name: Deploy it - # Pre-releases are for testing and never go live. - if: steps.v.outputs.skip == 'false' && steps.v.outputs.pre == 'false' - env: - TAG: ${{ steps.v.outputs.tag }} - run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" + # Pre-releases are for testing and never go live. The tag was just tested above, so the deploy does not + # test it again (tested=true). + if: env.PRE == 'false' + run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" -f tested=true - name: Publish the Docker image # Same pattern as the deploy above: the image is built and pushed from the # release tag by docker.yml. Pre-releases get one too: an image tag is # pulled on purpose, so a test image costs nothing. - if: steps.v.outputs.skip == 'false' - env: - TAG: ${{ steps.v.outputs.tag }} run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e135ebb..a70d674 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,44 +1,89 @@ name: CI +# Every push and PR, and the releases too (auto-release.yml and release.yml call this workflow), so the tests run +# one way, split over several runners, everywhere. on: push: branches: [main] pull_request: + workflow_call: + inputs: + ref: + description: The commit or tag to test (a release tag); the caller's commit when empty + type: string + default: '' permissions: contents: read # A newer push to the same pull request makes the older run pointless: cancel it instead of queueing behind it. -# Runs on main always finish. +# Runs on main always finish. A release's call gets a group of its own, so it never waits behind main's push run. concurrency: - group: ci-${{ github.ref }} + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ inputs.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + # Runners for the tests. Standard GitHub-hosted runners (4 cores each) are the only free ones for a public repo, + # and a run may use up to 20 at once, so more parts is how the tests get faster. Each part costs ~30 s of setup. + PARTS: 6 + jobs: - # The tests in four parts of about equal time, each on its own runner, each running as many files at once as - # it has cores (scripts/test.js; the split comes from tests/durations.json). + # Splits the test files into parts of about equal time, once, so every part works from the same plan. The times + # come from the last run on main (the cache, see "timings" below), else from the committed tests/durations.json. + plan: + runs-on: ubuntu-latest + outputs: + parts: ${{ steps.plan.outputs.parts }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} + restore-keys: test-durations- + - id: plan + run: echo "parts=$(node scripts/test.js --plan "$PARTS")" >> "$GITHUB_OUTPUT" + part: - name: test ${{ matrix.part }}/4 + name: part ${{ strategy.job-index }} + needs: plan runs-on: ubuntu-latest timeout-minutes: 20 strategy: fail-fast: false matrix: - part: [1, 2, 3, 4] + files: ${{ fromJSON(needs.plan.outputs.parts) }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm - run: npm ci - - run: npm test -- --shard ${{ matrix.part }}/4 + - name: Tests + env: + FILES: ${{ matrix.files }} + # Word splitting on purpose: FILES is a space-separated list of tests/*.test.js paths. + run: npm test -- --timings "$RUNNER_TEMP/timings.json" $FILES + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: timings-${{ strategy.job-index }} + path: ${{ runner.temp }}/timings.json + retention-days: 1 + if-no-files-found: ignore build: name: build runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 @@ -47,21 +92,12 @@ jobs: - name: Build (not deployed — only releases deploy) run: npm run build - # The one check to look at, named as before: green only when every part and the build are. - test: - needs: [part, build] - if: always() - runs-on: ubuntu-latest - steps: - - name: Every part and the build passed - run: | - echo "parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}" - test "${{ needs.part.result }}" = success && test "${{ needs.build.result }}" = success - translations: runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 @@ -69,3 +105,38 @@ jobs: - run: npm ci - name: Translation coverage run: node scripts/i18n-check.js --summary "$GITHUB_STEP_SUMMARY" + + # The one check to look at: green only when the plan, every part, the build and the translations are. + test: + needs: [plan, part, build, translations] + if: always() + runs-on: ubuntu-latest + steps: + - name: Everything passed + run: | + echo "plan: ${{ needs.plan.result }}, parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}, translations: ${{ needs.translations.result }}" + test "${{ needs.plan.result }}" = success && test "${{ needs.part.result }}" = success + test "${{ needs.build.result }}" = success && test "${{ needs.translations.result }}" = success + + # After a run on main: each file's time from this run goes into the cache, so the next run (main or a PR) splits + # its parts by today's tests. Nobody has to remember to refresh tests/durations.json. + timings: + needs: part + if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.part.result != 'skipped' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} + restore-keys: test-durations- + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: timings-* + path: ${{ runner.temp }}/timings + - run: node scripts/test-timings.js --merge "$RUNNER_TEMP/timings" + - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b77850e..3d2acf5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -23,6 +23,10 @@ on: description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped type: boolean default: false + tested: + description: The tag's tests already passed (auto-release.yml tests it before tagging) + type: boolean + default: false # Least privilege: only the deploy job can write to Pages. permissions: @@ -33,9 +37,18 @@ concurrency: cancel-in-progress: false jobs: + # The release's tests, split over several runners like every push (ci.yml). Skipped when auto-release.yml has just + # run them on this tag, and for a weekly redeploy (the build step below tests the weekly files against the tag). + tests: + if: ${{ (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && !inputs.weekly && !inputs.tested }} + uses: ./.github/workflows/ci.yml + with: + ref: ${{ github.event.release.tag_name || inputs.tag }} + build: + needs: tests # Pre-releases are for testing and never go live. - if: ${{ github.event_name == 'workflow_dispatch' || !github.event.release.prerelease }} + if: ${{ always() && (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && (needs.tests.result == 'success' || needs.tests.result == 'skipped') }} runs-on: ubuntu-latest env: TAG: ${{ github.event.release.tag_name || inputs.tag }} @@ -93,10 +106,9 @@ jobs: 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 }} + # The weekly files come from main, not the tag: whatever tested the tag, they are tested against it here. - name: Test the weekly puzzles against this release - if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} + if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' }} 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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 202c46f..2d10c00 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -80,9 +80,10 @@ Development runs on `npm run dev` (assembles the development page on every reque | `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab | | `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries | | `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over | -| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}` | -| `.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 | +| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}`. The page's scripts run straight in the window (jsdom's parser is slow on 2 MB of script) | +| `scripts/test.js`, `tests/durations.json` | Runs the tests, every file in its own process; splits them into parts of equal time for CI (`--plan`, `--shard`) by each file's seconds, which CI refreshes after every run on `main` | +| `.github/workflows/ci.yml` | Tests (split over 6 runners), build and translations on every push and PR; the releases call it too, so the tests run one way everywhere | +| `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test (ci.yml), tag, GitHub release from the CHANGELOG, start the deploy (already tested, so it does not test again) | | `.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) | diff --git a/scripts/lib/timings-reporter.js b/scripts/lib/timings-reporter.js new file mode 100644 index 0000000..0341ee6 --- /dev/null +++ b/scripts/lib/timings-reporter.js @@ -0,0 +1,18 @@ +// A node:test reporter that writes how long each test file took, as JSON {"tests/x.test.js": seconds}, to its +// destination. scripts/test.js adds it next to the usual output with --timings FILE; CI merges the parts' files +// into tests/durations.json, which the next run splits its parts by. +const path = require('node:path'); + +module.exports = async function* timings(source) { + const sec = {}; + for await (const { type, data } of source) { + // Top-level tests only: their durations include their subtests. + if ((type === 'test:pass' || type === 'test:fail') && data.nesting === 0 && data.file && data.details) { + const f = path.relative(process.cwd(), data.file).split(path.sep).join('/'); + sec[f] = (sec[f] || 0) + (data.details.duration_ms || 0) / 1000; + } + } + const out = {}; + for (const f of Object.keys(sec).sort()) out[f] = Math.round(sec[f] * 10) / 10; + yield JSON.stringify(out, null, 1) + '\n'; +}; diff --git a/scripts/test-timings.js b/scripts/test-timings.js index 1bf7d5e..ed8cf48 100644 --- a/scripts/test-timings.js +++ b/scripts/test-timings.js @@ -5,6 +5,7 @@ // machine has cores, so absolute numbers vary, but their sizes relative to each other are what count. // // npm run test:timings +// node scripts/test-timings.js --merge DIR (CI) fold the parts' --timings files into it const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); @@ -12,6 +13,24 @@ const { spawn } = require('node:child_process'); const root = path.join(__dirname, '..'); const dir = path.join(root, 'tests'); + +// --merge DIR: fold the timings CI's parts wrote (scripts/test.js --timings) into tests/durations.json. Files that are +// gone drop out; files no part ran keep their old time. +const mi = process.argv.indexOf('--merge'); +if (mi >= 0) { + const from = process.argv[mi + 1], dur = path.join(dir, 'durations.json'); + let out = {}; + try { out = JSON.parse(fs.readFileSync(dur, 'utf8')); } catch (e) { /* none yet */ } + let n = 0; + for (const f of fs.readdirSync(from, { recursive: true }).filter((f) => String(f).endsWith('.json'))) { + for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(path.join(from, String(f)), 'utf8')))) if (v > 0) { out[k] = v; n++; } + } + const have = new Set(fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).map((f) => 'tests/' + f)); + const sorted = Object.fromEntries(Object.keys(out).filter((k) => have.has(k)).sort().map((k) => [k, out[k]])); + fs.writeFileSync(dur, JSON.stringify(sorted, null, 1) + '\n'); + console.log(`merged ${n} timings; tests/durations.json has ${Object.keys(sorted).length} of ${have.size} files`); + process.exit(0); +} const files = fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => 'tests/' + f); const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism()); const out = {}; diff --git a/scripts/test.js b/scripts/test.js index e847053..1232bd1 100644 --- a/scripts/test.js +++ b/scripts/test.js @@ -5,14 +5,18 @@ // // npm test everything // npm test -- tests/peering.test.js just these files (other arguments go to node --test) -// npm test -- --shard 2/4 one of four parts of about equal time (CI runs the four at once) +// npm test -- --shard 2/4 one of four parts of about equal time // npm test -- --shard 2/4 --list which files that part holds, without running them +// node scripts/test.js --plan 6 the split into 6 parts as JSON (CI's plan job: one list per runner) +// npm test -- --timings out.json also write each file's seconds to out.json (CI merges these into +// the durations the next run splits by) // TEST_JOBS=1 npm test one file at a time, as it used to be // npm test -- --stress 8 tests/x.test.js hunt a flaky test: 8 copies of these files at once, on a machine kept // busier than CI ever is, and how many runs failed (and why) // -// Parts are balanced by tests/durations.json, each file's typical seconds (refresh: npm run test:timings). -// A file missing from it counts as a typical one, so a stale list only makes the parts a little uneven. +// Parts are balanced by tests/durations.json, each file's typical seconds. CI keeps it fresh in its cache from every +// run on main (.github/workflows/ci.yml); npm run test:timings rewrites the committed copy. A file missing from it +// counts as a typical one, so a stale list only makes the parts a little uneven. const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); @@ -31,6 +35,12 @@ if (ti >= 0) { if (!(stress >= 1)) { console.error('--stress wants a count, like --stress 8'); process.exit(2); } args.splice(ti, 2); } +let timings = null; +const tmi = args.indexOf('--timings'); +if (tmi >= 0) { timings = args[tmi + 1]; args.splice(tmi, 2); if (!timings) { console.error('--timings wants a file'); process.exit(2); } } +let plan = 0; +const pi = args.indexOf('--plan'); +if (pi >= 0) { plan = parseInt(args[pi + 1], 10); args.splice(pi, 2); if (!(plan >= 1)) { console.error('--plan wants a count, like --plan 6'); process.exit(2); } } let shard = null; const si = args.indexOf('--shard'); if (si >= 0) { @@ -58,6 +68,10 @@ function part(list, i, n) { } return out[i - 1].sort(); } +if (plan) { + console.log(JSON.stringify(Array.from({ length: plan }, (_, i) => part(files, i + 1, plan).join(' ')))); + process.exit(0); +} if (shard && files.length) { files = part(files, shard[0], shard[1]); console.log(`# part ${shard[0]}/${shard[1]}: ${files.length} files`); @@ -84,5 +98,7 @@ if (stress) { }); return; } -const r = spawnSync(process.execPath, ['--test', `--test-concurrency=${jobs}`, ...args, ...files], { stdio: 'inherit', cwd: root }); +const rep = timings ? ['--test-reporter=spec', '--test-reporter-destination=stdout', + `--test-reporter=${path.join(__dirname, 'lib', 'timings-reporter.js')}`, `--test-reporter-destination=${timings}`] : []; +const r = spawnSync(process.execPath, ['--test', `--test-concurrency=${jobs}`, ...rep, ...args, ...files], { stdio: 'inherit', cwd: root }); process.exit(r.status ?? 1); diff --git a/tests/backbone-core.test.js b/tests/backbone-core.test.js index 10611a1..f3cea64 100644 --- a/tests/backbone-core.test.js +++ b/tests/backbone-core.test.js @@ -38,9 +38,10 @@ test('a new network runs plain IGP: no Auto-TE until the backbone is upgraded, o assert.deepEqual(JSON.parse(ev('JSON.stringify(S.core)')), { lv: 0, run: 0 }); ev('ACT.buyTE()'); assert.equal(ev('!!S.te'), false, 'no Auto-TE on plain IGP'); - ev("ACT.leftTab({t:'noc'})"); - assert.match(dom.window.document.body.textContent, /Backbone/); - assert.match(dom.window.document.body.textContent, /Auto-TE needs an RSVP-TE/); + // The backbone lives in the NOC's routing window; the refusal is a toast. + ev('ACT.routingOpen()'); + assert.match(dom.window.document.getElementById('modal').textContent, /Backbone/); + assert.match(dom.window.document.getElementById('toasts').textContent, /Auto-TE needs an RSVP-TE/); const cash = ev('S.cash'); ev('ACT.coreUp()'); assert.equal(ev('S.core.lv'), 1); diff --git a/tests/calendar.test.js b/tests/calendar.test.js index 18bea1e..40d8e19 100644 --- a/tests/calendar.test.js +++ b/tests/calendar.test.js @@ -23,14 +23,6 @@ test('#257 the calendar has real months and leap years',()=>{ assert.deepEqual(errors,[]); }finally{dom.window.close();} }); -test('#257 a calendar month costs its monthly price, whatever its length',()=>{ - const {ev,dom}=load();try{ - ev("ACT.start({});S.day=31");// 1 February Y1 - const before=ev('S.cash'),net=ev('R.revMo-R.costMo'); - ev("for(let i=0;i<28;i++)S.cash+=(R.revMo-R.costMo)/monLen(S.day+i)"); - assert.ok(Math.abs(ev('S.cash')-before-net)<1e-6,'28 days of February add up to one month'); - }finally{dom.window.close();} -}); test('#257 loan statements and the intern budget follow calendar months',()=>{ const {ev,dom}=load();try{ ev("ACT.start({})"); diff --git a/tests/game.test.js b/tests/game.test.js index aa21ff1..abf1247 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -15,12 +15,6 @@ test('every city sits on its landmass', () => { assert.equal(off, ''); }); -test('every cable lands at two known cities and has a length', () => { - const { ev } = load(); - const bad = ev("CABLE_PAIRS.filter(c=>!CITY[c.a]||!CITY[c.b]||!(c.km>0)).map(c=>c.cid).join()"); - assert.equal(bad, ''); -}); - test('a year of scripted play stays healthy', () => { const { ev, errors } = load(); seed(ev, 7); diff --git a/tests/harness.js b/tests/harness.js index a9f897a..2e5c0a2 100644 --- a/tests/harness.js +++ b/tests/harness.js @@ -6,12 +6,33 @@ // it fails here rather than in production. const fs = require('node:fs'); const path = require('node:path'); +const vm = require('node:vm'); const { JSDOM, VirtualConsole } = require('jsdom'); const { assemble } = require('../scripts/lib/page'); const PAGE = {}; const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html); +// The page's inline scripts, taken out of the HTML once per process and compiled once. jsdom's HTML parser is slow +// on 2 MB of script text (it was more than half of every load()), so the DOM is built from the rest of the page and +// the scripts then run in its window, in order, the same way jsdom runs them (vm.Script.runInContext). Only plain +// '; + }); + // With scripting on, the parser keeps a
${k==='mix'?l:``}