Scenarios, weekly challenge, sandbox, traceroute and share card

This commit is contained in:
Frederic Jung 2026-10-23 15:54:49 +02:00
parent 0ca92556dc
commit 0ae6f881c1
No known key found for this signature in database
3 changed files with 223 additions and 18 deletions

View file

@ -6,7 +6,7 @@
"homepage": "https://seriesoftub.es/",
"repository": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" },
"scripts": {
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js",
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js",
"build": "bash scripts/build.sh",
"serve": "npm run build && npx --yes serve@14.2.4 _site"
},

View file

@ -235,6 +235,14 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap:
.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}
.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}
.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}
.menu-list{display:flex;flex-direction:column;gap:8px;margin-top:12px}
.menu-list .b{justify-content:space-between;width:100%}
#mega{position:fixed;left:0;right:0;bottom:0;z-index:17;background:#7A86B8;border-top:3px solid var(--ink);overflow:hidden;white-space:nowrap;pointer-events:none;animation:megaflash 1.2s steps(2) infinite}
@ -641,7 +649,7 @@ const CABLE_PAIRS=CABLES.flatMap(c=>c.pairs.map(([a,b,mid])=>{const A=CITY[a],B=
const mp=mid.map(q=>proj(q[0],q[1]));const pts=[[near(A.x,mp[0][0]),A.y]].concat(mp,[[near(B.x,mp[mp.length-1][0]),B.y]]);
const ll=[[A.lon,A.lat]].concat(mid,[[B.lon,B.lat]]);let L=0;for(let i=1;i<ll.length;i++)L+=hav(ll[i-1][0],ll[i-1][1],ll[i][0],ll[i][1]);
return {cid:c.id,a,b,pts,km:Math.round(L)};}));
function cablesOk(a,b){const ban=S&&S.ev&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city);return ban?[]:cablesFor(a,b);}
function cablesOk(a,b){const ban=S&&S.ev&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city);if(ban)return [];const bp=S&&S.scn&&S.scn.rules&&S.scn.rules.banPairs;return bp?cablesFor(a,b).filter(c=>!bp.includes(c.cid+':'+c.a+'-'+c.b)&&!bp.includes(c.cid+':'+c.b+'-'+c.a)):cablesFor(a,b);}
function cablesFor(a,b){return CABLE_PAIRS.filter(c=>(c.a===a&&c.b===b)||(c.a===b&&c.b===a));}
function cablePair(cid,a,b){const c=CABLE_PAIRS.find(x=>x.cid===cid&&((x.a===a&&x.b===b)||(x.a===b&&x.b===a)));if(!c)return null;return c.a===a?c:{...c,pts:c.pts.slice().reverse()};}
const ALLC=CITIES.filter(c=>!c.cn&&!c.ru&&!c.ixOnly).map(c=>c.id);
@ -862,6 +870,112 @@ function loanTick(d){
const broke=S.cash<0;
if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d>20&&Math.random()<1/40)))spawnLoanOffer(broke);
}
/* Seeded games (scenarios, weekly challenge) draw every random number from S.rng, so the same seed
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)};}
function pathExists(a,b){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l))continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
const SCN=[
{id:'stg',n:'Only Spätzle-IX',city:'stg',cash:400000,days:730,rules:{noTransit:true},d:'Start in Stuttgart, where nobody sells transit. Reach the internet through peering, PNIs, caches and your own fiber only. No transit anywhere, ever.',goal:'Serve 200 Gbps',ok:()=>R.served>=200},
{id:'redsea',n:'Red Sea Crisis',city:'mrs',cash:2500000,days:540,rules:{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']},d:'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.',goal:'A path from Marseille to Singapore, and 300 Gbps served',ok:()=>pathExists('mrs','sin')&&R.served>=300},
{id:'spat',n:'The Cogentle Spat',city:'nyc',cash:700000,days:540,rules:{spat:true},d:'Cogentle and Goggle are not speaking, and this time it is permanent. Buy the cheap transit if you dare.',goal:'99% reach and 150 Gbps served',ok:()=>R.reach>=0.99&&R.served>=150},
{id:'carnaval',n:'Carnaval',city:'rio',cash:600000,days:100,rules:{},setup:()=>{S.biz.push({id:uid(),city:'rio',city2:null,reqs:[],name:'Carnaval-ish Parade in Rio de Janeiro',type:'event',bw:400,rate:0,mood:100,since:0,start:90,dur:5,fee:400*5*70});},d:'Rio from scratch. Carnaval-ish starts in 90 days and wants 400 Gbps for five days straight. The whole world is watching.',goal:'Deliver Carnaval in full',ok:()=>(S.stats.evFull||0)>=1},
{id:'darien',n:'Mind the Gap',city:'pan',cash:900000,days:730,rules:{},d:'Start in Panama City. Nothing crosses the Darién Gap by land, and the Andes are in the way of everything else.',goal:'POPs in Bogotá, Lima, Santiago and São Paulo, and 150 Gbps served',ok:()=>['bog','lim','scl','sao'].every(c=>S.pops[c])&&R.served>=150},
{id:'baltic',n:'Anchors Away',city:'tll',cash:500000,days:540,rules:{anchors:3},d:'Tallinn. Ships drag their anchors over Baltic cables three times as often as usual.',goal:'90 days in a row with 99.5% of demand served',ok:()=>(S.stats.clean||0)>=90},
];
const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','mex','hkg'];
const WEEK_MODS=[{id:'pricey',n:'Everything costs 30% more'},{id:'chaos',n:'Twice the failures'},{id:'poor',n:'Start with only $200k'},{id:'boom',n:'Eyeballs grow 50% faster'},{id:'dk',n:'Every IX is run by DE-KICKS'},{id:'sharks',n:'Shark season: subsea cuts twice as likely'}];
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={}){newGame(nm,city);S.mode=o.mode||'normal';
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=4;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||('Weekly challenge '+sc.key),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';
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=200000;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;}}
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?`<b>${esc(S.scn.name)}</b><br>${esc(o.scn.goal||'Serve as much traffic as you can in one year.')} You have ${S.scn.days} days.`:S.mode==='sandbox'?`<b>Sandbox mode</b><br>A billion dollars, every unlock, and nothing ever breaks. Build the internet you always wanted.`:`<b>Welcome, ${esc(nm)}!</b><br>The RIPE-ish NCC assigned you AS${S.asn}. Your first router is humming in ${CITY[city].name}.`,'goal');
renderAll();save();if(!S.scn&&S.mode!=='sandbox')tutorialStart();}
function tutorialStart(){}
/* ---------- traceroute and looking glass ---------- */
const slug=t=>String(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]);}
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]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
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:NET[net].cache.name+' cache',used:R.useCache[x.id]||0,cap:CACHE_CAP});
for(const p of S.pni)if(p.net===net&&popUp(p.city)&&!siteDown(p.city,p.site||'a'))out.push({k:'p',rank:1,city:p.city,pref:p.pref||'normal',lab:'PNI with '+NET[net].name,used:R.usePni[p.id]||0,cap:lagCap(PORT[p.tier].g,p.n)});
for(const c in S.ixp)if(ixSessions(c).has(net)&&(popUp(c)||remoteCities().includes(c))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:2,city:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:ixName(c)+' peering',used:R.useIx[c]||0,cap:ixCap(c)});
for(const t of S.transit)if(popUp(t.city)&&!(t.down>day)&&!siteDown(t.city,t.site||'a')&&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:NET[t.net].name+' transit',tnet:t.net,used:R.useT[t.id]||0,cap:lagCap(PORT[t.tier].g,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:''}`);};
hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,`${CITY[src].name}, your router`);
const walk=path=>{for(const h of path){const l=h.l,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'?'own dark fiber':l.kind==='vxc'?'fabric circuit':l.cable?CAB[l.cable].name:'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 * * * ← no working path between these POPs');return {text:lines.join('\n'),why:'No path: every route between these cities is down or missing.'};}walk(path);return {text:lines.join('\n'),why:`Internal path over ${path.length} link${path.length===1?'':'s'}, chosen by distance and link metrics${S.te&&S.te.on?'. Auto-TE may move overflow elsewhere when this is full':''}.`};}
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 * * * ← !N network unreachable');return {text:lines.join('\n'),why:`Nothing on your network reaches ${N.name}: no transit, IX session, PNI or cache with a working path from ${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]);
const e=ex.find(x=>x.used<x.cap*0.999)||ex[0];walk(P.path(e.city));
let asPath=[S.asn];
if(e.k==='t'){const T=NET[e.tnet];asPath.push(T.asn);hop(`be-${S.asn}.${e.city}.${slug(T.name)}.net`,`203.0.113.${hstr(e.city)%250}`,0.4,`hand-off to ${T.name}`);
if(T.id!==N.id){const far=(N.pops&&N.pops.length?N.pops:[e.city]).reduce((a,c)=>kmBetween(e.city,c)<kmBetween(e.city,a)?c:a,(N.pops||[e.city])[0]);const km=CITY[far]?kmBetween(e.city,far):0;
hop(`ae-2.core.${far}.${slug(T.name)}.net`,`203.0.113.${(hstr(far)+7)%250}`,km*1.3/100+0.3,CITY[far]?`${T.name} carries it to ${CITY[far].name}`:'');
hop(`${slug(N.name)}-peer.${far}.${slug(T.name)}.net`,`198.51.100.${hstr(N.id)%250}`,0.4,`${T.name} hands it 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,`across the ${ixName(e.city)} switch`);}
else if(e.k==='p'){hop(`pni-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,'private cross-connect');}
else{hop(`cache-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),4),0.1,'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:'caches beat PNIs',p:'PNIs beat IX peering',ix:'IX peering beats transit',t:'transit is the last resort'}[e.k];
const cn=cnCity(src)!==!!N.cn?` Crossing the Great Firewall here loses about ${S.ev.gfw>S.day?35:20}% of packets.`:'';
return {text:lines.join('\n'),why:`Exit: ${e.lab} in ${CITY[e.city].name}. ${order[0].toUpperCase()+order.slice(1)}, and closer exits win ties${e.pref!=='normal'?`; this one is set to ${e.pref==='high'?'Prefer':'Backup only'}`:''}.${e.used>=e.cap*0.999?' It is full, so some traffic overflows to the next exit.':''}${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)});
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Looking glass</div><h2 style="font-size:26px">Traceroute</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>
<div class="trsel"><label>From <select id="trFrom">${pops.map(c=>`<option value="${c}"${c===src?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label>
<label>To <select id="trTo"><optgroup label="Networks">${nets.map(n=>`<option value="net:${n.id}"${t==='net:'+n.id?' selected':''}>${esc(n.name)} (AS${n.asn})</option>`).join('')}</optgroup><optgroup label="Your POPs">${pops.filter(c=>c!==src).map(c=>`<option value="city:${c}"${t==='city:'+c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</optgroup></select></label>${btn('Run','traceRun',{},'pink sm')}</div>
<pre class="term">${esc(r.text)}</pre>${r.asPath?`<p class="meta"><b>AS path:</b> ${r.asPath.map(a=>'AS'+a).join(' → ')}</p>`:''}<p class="note">${esc(r.why)}</p>
<div class="btns">${btn('Copy','traceCopy',{},'ghost sm')}</div>`);UI.trText=r.text;}
/* ---------- share card ---------- */
function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas');cv.width=Wc;cv.height=Hc;const g=cv.getContext&&cv.getContext('2d');if(!g)return null;
g.fillStyle='#57C4E5';g.fillRect(0,0,Wc,Hc);
// mini map
const mx=40,my=150,mw=700,mh=350,sx=mw/W,sy=mh/H;g.save();g.beginPath();g.rect(mx,my,mw,mh);g.clip();g.fillStyle='#3AA6CF';g.fillRect(mx,my,mw,mh);
g.fillStyle='#9BDA6C';g.strokeStyle='#1E2640';g.lineWidth=1.5;for(const L of LANDS){if(L.hide)continue;g.beginPath();L.pts.forEach((q,i)=>i?g.lineTo(mx+q[0]*sx,my+q[1]*sy):g.moveTo(mx+q[0]*sx,my+q[1]*sy));g.closePath();g.fill();g.stroke();}
g.strokeStyle='#FF4F9A';g.lineWidth=2.5;for(const l of S.links){const A=CITY[l.a],B=CITY[l.b];let bx=B.x;if(Math.abs(bx-A.x)>W/2)bx+=bx<A.x?W:-W;g.beginPath();g.moveTo(mx+A.x*sx,my+A.y*sy);g.lineTo(mx+bx*sx,my+B.y*sy);g.stroke();}
for(const c in S.pops){const C=CITY[c];g.fillStyle='#FF4F9A';g.strokeStyle='#1E2640';g.lineWidth=2;g.beginPath();g.arc(mx+C.x*sx,my+C.y*sy,5,0,7);g.fill();g.stroke();}
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'?' · 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 rows=[['Peak traffic',fmtG(S.stats.peak||0)],['Peered',pct(R.peerShare||0)],['POPs',`${Object.keys(S.pops).length} in ${regionsCount()} regions`],['Links',String(S.links.length)],['Customers',String(S.biz.length)],['Incidents survived',String(S.stats.survived||0)],['Shark bites',String(S.stats.sharks||0)],['Badges',`${got.length}/${BADGES.length}`]];
if(S.scn)rows.unshift([S.scn.id==='weekly'?'Weekly '+S.scn.key:S.scn.name,S.scn.done?(S.scn.id==='weekly'?'score '+fmtG(S.scn.score||S.stats.peak||0):`done in ${S.scn.done} days`):S.scn.failed?'not this time':'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;}
g.font='34px sans-serif';top.forEach((b,i)=>g.fillText(b.i,40+i*48,520));
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('Build the internet, one tube at a time',300,580);
return cv;}
function shareModal(){const cv=shareCanvas();if(!cv){toast('<b>Your browser cannot draw the card.</b>','bad');return;}let url='';try{url=cv.toDataURL('image/png');}catch(e){}
UI.shareCv=cv;openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Share</div><h2 style="font-size:26px">Your network card</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>${url?`<img src="${url}" alt="Stats card for ${esc(S.name)}" style="width:100%;border:3px solid var(--ink);border-radius:12px;margin-top:8px">`:''}<div class="btns" style="margin-top:10px">${navigator.share?btn('Share…','shareGo',{},'pink'):''}${btn('Download PNG','shareDl',{},navigator.share?'':'pink')}</div><p class="note">Post it wherever your peering friends hang out.</p>`);track('share_open');}
function shareFile(cb){const cv=UI.shareCv;if(!cv||!cv.toBlob){cb(null);return;}cv.toBlob(b=>cb(b?new File([b],`series-of-tubes-${slug(S.name)}.png`,{type:'image/png'}):null),'image/png');}
function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)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(`<div class="eyebrow">Weekly challenge ${esc(sc.key)}</div><h2 style="font-size:30px">Your score: ${fmtG(score)}</h2><p class="tagline">Peak traffic served in one year${best&&best>score?`. Your best this week is ${fmtG(best)}`:best?'. A new personal best for this week!':''}.</p><div class="btns">${btn('Share my result','share',{},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`);track('weekly_done');}return;}
const def=SCN.find(x=>x.id===sc.id);if(!def)return;let ok=false;try{ok=def.ok();}catch(e){}
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(`<div class="eyebrow">Scenario complete</div><h2 style="font-size:30px">${esc(def.n)}: done in ${d} days</h2><p class="tagline">${esc(def.goal)}. ${d<def.days/2?'With time to spare.':'Just in time.'}</p><div class="btns">${btn('Share my result','share',{},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}${btn('More scenarios','scenarios',{},'ghost')}</div>`);sfx('coin');}
else if(d>=def.days){sc.failed=d;openModal(`<div class="eyebrow">Scenario over</div><h2 style="font-size:30px">Time's up</h2><p class="tagline">${esc(def.goal)} was not reached in ${def.days} days. Keep playing this network as free play, or try again.</p><div class="btns">${btn('Try again','startScn',{id:def.id},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`);}}
function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){}
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Scenarios</div><h2 style="font-size:28px">Pick a challenge</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="Close">×</button></div>
<div class="scn wk"><div class="grow"><div class="nm">Weekly challenge ${esc(wk.key)}</div><div class="meta">Start in ${esc(CITY[wk.city].name)} · ${wk.mods.map(m=>esc(m.n)).join(' · ')} · one year, score = peak traffic. The same world for everyone this week.${best?` Your best: ${fmtG(best)}.`:''}</div></div>${btn('Play','startWeekly',{},'pink')}</div>
${SCN.map(x=>`<div class="scn"><div class="grow"><div class="nm">${esc(x.n)} ${h[x.id]?`<span class="tag open">done in ${h[x.id].days} days</span>`:''}</div><div class="meta">${esc(x.d)}</div><div class="meta"><b>Goal:</b> ${esc(x.goal)} · <b>Time:</b> ${x.days} days · start in ${esc(CITY[x.city].name)}</div></div>${btn('Play','startScn',{id:x.id},'')}</div>`).join('')}`);}
function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(Math.random()*15000),home,day:0,cash:START_CASH,
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:{},
@ -930,7 +1044,7 @@ function ixPortMo(c,tier){return Math.round(PORT[tier].ix*(S.pops[c]?1:REMOTE_FE
No price list, personalised quotes, haggling, yearly "harmonisation", auto-enrolled add-ons
you have to opt out of, and a retention offer when you try to leave. */
const DK_CITIES=['fra','mad','mrs','dxb','bom','nyc'];
const isDk=c=>DK_CITIES.includes(c)&&!!CITY[c]&&!!CITY[c].ix&&!S.myIx[c];
const isDk=c=>(DK_CITIES.includes(c)||scnRule('dkAll'))&&!!CITY[c]&&!!CITY[c].ix&&!S.myIx[c];
const DK_ADDONS=[['Blackholing Plus™','Like blackholing, but with a Plus.'],['Route Server Gold','The same route server, in a gold-coloured portal.'],['Premium Port LEDs','Your port light now blinks in brand colours.'],['Strategic Peering Insights','A monthly PDF of your own traffic graphs.'],['GlobePeer Ready™','Makes your port "ready" for a product you did not buy.'],['Cloud Exchange Readiness Fee','A fee for being ready for the cloud.'],['Account Manager Lunch Fund','Your account manager is hungry.']];
const DK_STALL=['Your account manager would love to "align on value" first. Strategic call booked for next week.','Pricing is reviewed by the Global Commercial Council, who meet on the next full moon.','They sent a 14-page NDA before they can even repeat the price. Lawyers estimate a week.','Your account manager is at a conference in Dubai. And then one in Madrid.'];
function dkMult(c){if(!S||!isDk(c)||!S.dk||!S.dk.m[c])return 1;const ret=S.dk.ret[c];return S.dk.m[c]*(ret&&ret>S.day?0.6:1);}
@ -997,7 +1111,7 @@ function compute(){
const prevU=e=>{let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;return e.cap?ld/e.cap:0;};
const dijk=(s0,mode)=>{const dist={[s0]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,e] of adj[u]){const nd=ud+(mode==='fast'?e.lat+0.05:e.w*(1+10*prevU(e)));if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=e;}}}return {dist,prev};};
const E=[], ev=S.ev;
const depeer=ev.depeer>day, leak=ev.leak&&ev.leak.until>day?ev.leak.net:null;
const depeer=ev.depeer>day||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||siteDown(t.city,t.site||'a'))continue;
E.push({k:'t',prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:NET[t.net].name+' transit',id:t.id,city:t.city,cap:lagCap(PORT[t.tier].g,t.n),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak});}
for(const c in S.ixp){if(!(popUp(c)||remote.includes(c))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||siteDown(c,(S.ixSite||{})[c]||'a'))continue;const set=ixSessions(c);R2.sessions+=set.size;
@ -1155,7 +1269,7 @@ function bTerms(o){const T=BIZ_T[o.type];
// Events are paid once at the end, prorated by how much of the crowd you served.
function eventTick(b,d){if(!BIZ_T[b.type].event)return false;if(d<b.start)return true;
if(d<b.start+b.dur){b.srv=(b.srv||0)+sfOf(R,b.city);b.srvDays=(b.srvDays||0)+1;if(d===b.start)toast(`<b>${esc(b.name)} starts today!</b><br>${fmtG(b.bw)} of extra demand in ${CITY[b.city].name} for ${b.dur} days.`,'goal',[{l:'Show me',act:'focusCity',args:{city:b.city}}]);return true;}
const avg=b.srvDays?b.srv/b.srvDays:0,pay=avg>=0.95?b.fee:avg>=0.7?Math.round(b.fee*avg):-Math.round(b.fee*0.2);S.cash+=pay;S.biz=S.biz.filter(x=>x!==b);
const avg=b.srvDays?b.srv/b.srvDays:0;if(avg>=0.95)S.stats.evFull=(S.stats.evFull||0)+1;const pay=avg>=0.95?b.fee:avg>=0.7?Math.round(b.fee*avg):-Math.round(b.fee*0.2);S.cash+=pay;S.biz=S.biz.filter(x=>x!==b);
toast(pay>=0?`<b>${esc(b.name)} is over: +${fmt$(pay)}</b><br>You delivered ${pct(avg)} of what the crowd wanted.${avg>=0.95?' Flawless.':''}`:`<b>${esc(b.name)} was a disaster.</b><br>Only ${pct(avg)} delivered, and it trended on social media. Penalty: ${fmt$(-pay)}.`,pay>=0?'good':'bad');sfx(pay>=0?'coin':'err');return true;}
/* Where the giants actually build: gigawatt AI campuses and cloud regions, mapped to the nearest city on the map. */
const MEGA=[{c:'ash',n:'Data Center Alley-ish'},{c:'ash',n:'Prometheus-ish Ohio'},{c:'dal',n:'Star-Gait Abilene'},{c:'dal',n:'Hyperion-ish Louisiana'},{c:'dal',n:'Colossal Ego Memphis'},{c:'chi',n:'Fairwater-ish Wisconsin'},{c:'chi',n:'Project Rainier-ish Indiana'},{c:'chi',n:'Cornfield Cluster Iowa'},{c:'nyc',n:'Neocloud New Jersey'},{c:'sto',n:'Star-Gait Fjord-way'},{c:'mad',n:'Aragón Mega-shed'},{c:'dub',n:'Bring-Your-Own-Power Dublin'},{c:'auh',n:'Star-Gait UAE'},{c:'dxb',n:'Desert Kingdom AI Campus'},{c:'kul',n:'Johor-ish Overflow'},{c:'hyd',n:'Vizag-ish AI Hub'},{c:'icn',n:'Ulsan-ish AI Campus'},{c:'tok',n:'Hokkaido-ish Snow DC'},{c:'syd',n:'Star-Gait Down Under'},{c:'mex',n:'Querétaro-ish Cluster'},{c:'for',n:'Short-Video Ceará Campus'},{c:'scl',n:'Quilicura-ish Region'}];
@ -1292,7 +1406,7 @@ function fireFailure(){
addInc({type,ref:l.id,until:S.day+dur,msg:pick([`A ${OPT[o].n} on ${A}–${B} overheated and is now a very expensive keychain.`,`The laser in a ${OPT[o].n} on ${A}–${B} died. One channel dark.`,`A ${OPT[o].n} on ${A}–${B} started reporting a temperature of 900°C. It was wrong, but it shut down anyway.`])+(l.spares?' Swapped from your spares kit by tomorrow.':''),cost:l.spares?0:OPT[o].cost,fix:'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'||['clion','balt'].includes(x.cable)),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)*(tw(x)?4:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),tr=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===tr);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));
const l=pick(live.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?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);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),tr=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===tr);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));
const A=CITY[l.a].name,B=CITY[l.b].name;
const msg=vn(l)&&Math.random()<0.8?pick([`Another of Vietnam’s subsea cables is broken: your ${A}–${B} link. The repair ship will come after the holidays. Which holidays is unclear.`,`Your ${A}–${B} cable broke in the same spot as last time. The repair crew recognised it.`]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([`A crocodile took a bite out of your ${A}–${B} fiber. It was not impressed.`,`Termites ate the duct on ${A}–${B}. Then the fiber. Then the replacement duct.`]):tw(l)&&Math.random()<0.8?pick([`A cargo ship “forgot” to raise its anchor and dragged it across your ${A}–${B} cable. The owners are very sorry, and somewhat hard to reach.`,`Another anchor, another cut: your ${A}–${B} cable. The ship’s flag changed twice during the investigation.`,`A fishing boat with an unusually heavy anchor cut ${A}–${B}. It was not fishing.`]):!l.sub&&andesPair(l.a,l.b)?pick([`A landslide in the Andes buried your ${A}–${B} fiber.`,`Snow closed the mountain pass, and the repair crew with it: ${A}–${B} is down.`,`An earthquake shook your ${A}–${B} fiber loose somewhere above 4,000 metres.`,`A llama herd trampled the fiber marker on ${A}–${B}. Then a backhoe found the fiber.`]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([`Road widening near ${A} cut your fiber to ${B}. It is always road widening.`,`The monsoon flooded a manhole on ${A}–${B}. The fiber is now underwater, as is the manhole.`,`A JCB-ish digger found your ${A}–${B} fiber. A different JCB-ish digger is coming to fix it.`]):l.sub?pick([`A curious shark bit your subsea cable ${A}–${B}.`,`A ship dragged its anchor across your ${A}–${B} cable.`,`An undersea landslide snapped ${A}–${B}.`]):pick([`A backhoe found your fiber between ${A} and ${B}.`,`Squirrels chewed through ${A}–${B}. They regret nothing.`,`Road works cut ${A}–${B}. Nobody called before digging.`]);
addInc({type,ref:tr,until:S.day+dur,msg:msg+(hit.length>1?` All ${hit.length} links in that trench went down with it.`:''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))});
@ -1403,7 +1517,7 @@ function dayTick(){
for(const i of S.inc.slice())if(i.until<=d){clearInc(i);toast(`<b>Resolved:</b> ${incTitle(i.type).toLowerCase()} is fixed.`,'good');}
// 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),P=CITY[c].P;
if(sf>=0.9){const g=0.025*(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);}
if(sf>=0.9){const g=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(3,p.bb.d*(1-(0.9-sf)*0.04));}
compute();
for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();}
@ -1428,16 +1542,18 @@ 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(`<b>${esc(n.name)} joined ${esc(m.name)}!</b><br>Another member paying ${fmt$(MYIX_FEE)}/mo for a port.`,'good');sfx('coin');}
m.next=d+8+Math.floor(Math.random()*10);}}
loanTick(d);
if(S.mode==='sandbox'&&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))spawnOffer();
// failures & events
if(d>=S.nextFail){fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.max(22,50-size*1.5)+Math.floor(Math.random()*25);}
if(d>=S.nextFail){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){fireEvent();S.nextEvent=d+45+Math.floor(Math.random()*45);}
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');}
checkGoals();
scnTick(d);
// money trouble
if(S.cash<0){S.neg++;if(S.neg===1)toast('<b>You are in the red.</b><br>Cancel something expensive, wait for revenue, or check the bank for a loan. At −$100k the bank takes your routers.','bad');}
else S.neg=0;
@ -1518,11 +1634,15 @@ const BADGES=[
{id:'blitz',i:'🚀',t:'Blitz',d:'Reach Tier 1 within two years.',r:'l',ok:()=>!!S.won&&S.day<=730},
{id:'peta',i:'🌌',t:'Hundred Terabits',d:'Serve 100 Tbps.',r:'l',ok:()=>R.served>=100000},
{id:'llama',i:'🦙',t:'Llama Drama',d:'Lose fiber to a llama herd.',r:'l',secret:true,ok:()=>!!(st().f||{}).llama},
{id:'scen1',i:'🎯',t:'Scenario Solver',d:'Complete any scenario.',r:'r',ok:()=>Object.keys(scnHof()).some(k=>k!=='weekly')},
{id:'weekly',i:'📅',t:'Weekly Regular',d:'Finish a weekly challenge.',r:'r',ok:()=>!!scnHof().weekly},
{id:'scen3',i:'🏅',t:'Scenario Specialist',d:'Complete three different scenarios.',r:'e',ok:()=>Object.keys(scnHof()).filter(k=>k!=='weekly').length>=3},
{id:'scenall',i:'🏆',t:'Scenario Grandmaster',d:'Complete every scenario.',r:'l',ok:()=>SCN.every(x=>scnHof()[x.id])},
{id:'elephant',i:'🐘',t:'I Survived the Elephant',d:'Live through the day half the internet went down.',r:'l',secret:true,ok:()=>!!S.phpDone&&!(S.ev.php>S.day)},
{id:'zero',i:'🕳️',t:'Zero Peers Given',d:'Reach Tier 2 with every single session over the route server.',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||{};let h=null;
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};
@ -1533,7 +1653,7 @@ function badgeGrid(){const h=hof(),got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==und
return `<div class="bdg ${on?'on':ever?'ever':''}" style="--rc:${R0.col}" title="${esc(hide?'A secret badge':b.t+': '+b.d)}"><span class="bi">${hide?'❔':b.i}</span><span class="bt">${esc(hide?'???':b.t)}</span><span class="br">${R0.n}${ever&&!on?' · earned before':''}</span>${hide?'':`<span class="bd">${esc(b.d)}</span>`}</div>`;}).join('')}</div>`;}
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.cash+=g.r;}
if(ok){S.done[g.id]=S.day;if(g.r&&S.mode!=='sandbox'){S.cash+=g.r;}
toast(`<b>Goal complete: ${esc(g.t)}</b>${g.r?`<br>Reward: +${fmt$(g.r)}`:''}`,'goal');sfx('coin');
track('goal_'+g.id);if(g.win&&!S.won){S.won=true;track('win_tier1');showWin();}}}
}
@ -1568,7 +1688,7 @@ const ACT={
buildPop:({city})=>{if(S.pops[city])return;if(cnCity(city)&&!cnOk()){toast('<b>You need a license first.</b><br>Foreign networks need a joint venture to build in mainland China.','bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};floater(CITY[city].x,CITY[city].y-30,'New POP!','#FF4F9A');UI.tab='cust';after();},
launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:Math.max(8,C.P*0.03)};floater(C.x,C.y-30,'Eyeballs online!','#16A866');after();},
ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,'Ad campaign!','#FF8A3D');after();},
buyTransit:({city,net,tier})=>{tier=+tier;if(!S.pops[city]||!NET[net]||!NET[net].price||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.transit.push({id:uid(),city,net,tier,down:0});toast(`<b>${esc(NET[net].name)} transit is live in ${CITY[city].name}.</b><br>Full table received: ~1,000,000 routes.`,'good');after();},
buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast('<b>No transit in this scenario.</b><br>Peering, PNIs, caches and your own fiber only.','bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!NET[net].price||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.transit.push({id:uid(),city,net,tier,down:0});toast(`<b>${esc(NET[net].name)} transit is live in ${CITY[city].name}.</b><br>Full table received: ~1,000,000 routes.`,'good');after();},
lagT:({id,d})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;const n=(t.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0){if(!portOk(t.city,t.tier))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;toast(+d>0?`<b>LAG member added.</b><br>${esc(NET[t.net].name)} in ${CITY[t.city].name} is now ${lagName(t.tier,n)}.`:`<b>LAG member removed.</b>`,'good');after();},
lagP:({id,d})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0&&!spend(1500+PORT[p.tier].setup/2))return;p.n=n;sfx('build');after();},
lagIx:({city,d})=>{if(S.ixp[city]===undefined||S.myIx[city]||!S.pops[city])return;S.ixn=S.ixn||{};const n=(S.ixn[city]||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0&&!spend(ixPortMo(city,S.ixp[city])))return;S.ixn[city]=n;sfx('build');after();},
@ -1589,6 +1709,12 @@ const ACT={
dkStay:({city})=>{S.stats.retained=1;const dk=dkState();dk.ret[city]=S.day+180;dk.retUsed[city]=true;UI.confirm=null;closeModal();toast(`<b>40% off ${esc(ixName(city))} for 6 months.</b><br>Your account manager is relieved. Read the small print later.`,'good');after();},
buyTE:()=>{if(S.te)return;if(lvl()<3){toast('<b>Auto-TE unlocks at customer level 3.</b>','bad');sfx('err');return;}if(!spend(TE_COST))return;S.te={on:true,day:S.day};toast('<b>Auto-TE is live.</b><br>The controller now pushes overflow onto alternate paths whenever the shortest one is full.','good');after();},
teToggle:()=>{if(!S.te)return;S.te.on=!S.te.on;after();},
trace:({city})=>traceModal(city),
traceRun:()=>{const f=$('trFrom'),t=$('trTo');traceModal(f&&f.value,t&&t.value);},
traceCopy:()=>{try{navigator.clipboard.writeText(UI.trText||'');toast('<b>Copied.</b> Paste it into your favourite NOC chat.','good');}catch(e){}},
share:()=>shareModal(),
shareDl:()=>shareFile(f=>{if(!f)return;const a=document.createElement('a');a.href=URL.createObjectURL(f);a.download=f.name;document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);track('share_download');}),
shareGo:()=>shareFile(f=>{const d={title:'Series of Tubes',text:`${S.name} (AS${S.asn}): ${tierLabel()}, ${fmtG(S.stats.peak||0)} peak. Build your own internet at`,url:'https://seriesoftub.es/'};try{if(f&&navigator.canShare&&navigator.canShare({files:[f]}))d.files=[f];navigator.share(d).then(()=>track('share_done')).catch(()=>{});}catch(e){}}),
addSite:({city})=>{const p=S.pops[city];if(!p||p.site2)return;if(!spend(SITE2_COST))return;p.site2=true;p.site2Day=S.day;toast(`<b>Second site live in ${CITY[city].name}.</b><br>${esc(siteName(city,'b'))} is joined to ${esc(siteName(city,'a'))} by your own metro ring. Move some uplinks there from the Transit and Peering tabs.`,'good');sfx('build');after();},
rmSite:({city})=>{const p=S.pops[city];if(!p||!p.site2)return;if(UI.confirm!=='site'+city){UI.confirm='site'+city;renderPanel();return;}UI.confirm=null;p.site2=0;p.sdown=null;p.ringcut=0;for(const t of S.transit)if(t.city===city)t.site='a';for(const x of S.pni)if(x.city===city)x.site='a';if(S.ixSite)delete S.ixSite[city];after();},
siteSet:({k,id,s})=>{if(s!=='a'&&s!=='b')return;if(k==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.site=s;}else if(k==='p'){const x=S.pni.find(x=>x.id===id);if(x)x.site=s;}else if(k==='ix'&&S.ixp[id]!==undefined){S.ixSite=S.ixSite||{};S.ixSite[id]=s;}after();},
@ -1667,8 +1793,11 @@ const ACT={
spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();},
crews:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.ready<=S.day)return;const c=Math.round(15000+l.km*6);if(!spend(c))return;l.ready=Math.max(S.day+1,l.ready-30);toast('<b>More crews on site.</b><br>Construction is 30 days ahead.','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,'Generator!','#FF8A3D');after();},
start:()=>{const nm=(document.getElementById('nmIn').value||'Packet Pals').slice(0,24);newGame(nm,UI.startCity);track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[UI.startCity].x;cam.y=CITY[UI.startCity].y;cam.z=innerWidth<760?1.1:1.4;selectCity(UI.startCity);
toast(`<b>Welcome, ${esc(nm)}!</b><br>The RIPE-ish NCC assigned you AS${S.asn}. Your first router is humming in ${CITY[UI.startCity].name}.`,'goal');renderAll();save();},
start:()=>{const nm=(($('nmIn')&&$('nmIn').value)||'Packet Pals').slice(0,24);beginGame(nm,UI.startCity,{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));},
scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||'Packet Pals').slice(0,24);scenarioModal();},
startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||'Packet Pals',sc.city,{scn:sc});},
startWeekly:()=>{const wk=weekly();beginGame(UI.nm||(S&&S.name)||'Packet Pals',wk.city,{scn:wk,seed:wk.seed});},
pickStart:({city})=>{UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city));},
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;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();},
@ -1682,6 +1811,8 @@ const ACT={
${btn('Back to the map','closeModal',{},'pink big')}
${btn('Export save <small>download a file</small>','exportSave',{},'')}
${btn('Import a save <small>from a file</small>','importPick',{},'')}
${btn('Share your network <small>image card</small>','share',{},'')}
${btn('Scenarios &amp; weekly challenge','scenarios',{},'ghost')}
${btn('How to play','help',{},'ghost')}
${RELEASE_NOTES.length?btn(`What’s new in ${esc(APP_VERSION)}`,'whatsNewShow',{},'ghost'):''}
${btn('Start a new network','resetAsk',{},'red')}
@ -1748,7 +1879,7 @@ function renderHUD(){
for(const v of [0,1,2,4,8]){const b=$('sp'+v);if(b)b.classList.toggle('on',UI.speed===v);}
$('muteBtn').style.opacity=UI.muted?.4:1;
if(!S)return;
$('hName').textContent=S.name;$('hAsn').textContent='AS'+S.asn;
$('hName').textContent=S.name;$('hAsn').textContent='AS'+S.asn+(S.mode==='sandbox'?' · Sandbox':S.scn?' · '+(S.scn.id==='weekly'?'Weekly '+S.scn.key:S.scn.name)+(S.scn.done||S.scn.failed?'':` · ${Math.max(0,S.scn.days-S.day)}d left`):'');
$('hCash').textContent=fmt$(S.cash);$('hCash').style.color=S.cash<0?'var(--bad)':'';
const net=R.revMo-R.costMo;$('hRate').innerHTML=`<span class="${net>=0?'up':'down'}">${net>=0?'▲':'▼'} ${fmt$(Math.abs(net))}/mo</span>`;
$('hTraffic').textContent=`${fmtG(R.served)}`;
@ -1778,7 +1909,7 @@ function renderLeft(){
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${o.exp-S.day}d left${(o.reqs||[]).length?` · ${o.reqs.length} special requirement${o.reqs.length>1?'s':''}`:''}</div>${reqList(o)}
<div class="btns">${has?btn('Accept','accept',{id:o.id},'green sm'):btn('Go there','focusCity',{city:o.city},'ghost sm')}${btn('Decline','decline',{id:o.id},'ghost sm')}</div>${has?'':`<div class="why">Needs a POP in ${bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')}</div>`}</div></div>`;}
}else if(UI.left==='noc'){
h+=`<div class="btns" style="margin-bottom:8px">${btn('Open NOC dashboard','dash',{},'pink')}</div>`;
h+=`<div class="btns" style="margin-bottom:8px">${btn('Open NOC dashboard','dash',{},'pink')}${btn('Traceroute','trace',{},'')}</div>`;
h+=`<p class="lead">Your Network Operations Center. Every notification also lands here. Things fail all the time on the internet. Redundant links and multiple upstreams let traffic reroute by itself.</p>`;
h+=`<div class="kv"><span>DDoS scrubbing</span><b>${S.scrubAt?'On · '+CITY[S.scrubAt].name:'None (build one from a POP\'s Infra tab)'}</b></div>`;
h+=S.te?`<div class="kv"><span>Auto-TE</span><b>${S.te.on?`On · moving ${fmtG(R.teMoved||0)} onto alternate paths`:'Off'}</b></div><div class="btns">${btn(S.te.on?'Turn Auto-TE off':'Turn Auto-TE on','teToggle',{},'ghost sm')}</div>`
@ -1809,7 +1940,7 @@ function renderPanel(){
function cityPanel(c){
const C=CITY[c],p=S.pops[c],ix=ixName(c),down=p&&p.down>S.day;
let h=`<div class="ph"><div style="min-width:0"><div class="eyebrow">${REG[C.reg]} · ${esc(C.dc)}</div><h2>${C.name}</h2>
<div class="facts"><span class="fact">${fmtG(C.P)} of eyeballs</span>${regionMult(c)>1?`<span class="fact">Transit ${regionMult(c)}× pricier</span>`:''}${C.reg==='AS'&&!C.cn?'<span class="fact ixf">Underserved: users grow 60% faster</span>':''}${ix?`<span class="fact ixf">IX: <b>${esc(ix)}</b></span>`:''}${p?`<span class="fact mine">Your POP</span>`:''}${down?`<span class="fact down">DOWN</span>`:''}</div></div>
<div class="facts"><span class="fact">${fmtG(C.P)} of eyeballs</span>${regionMult(c)>1?`<span class="fact">Transit ${regionMult(c)}× pricier</span>`:''}${C.reg==='AS'&&!C.cn?'<span class="fact ixf">Underserved: users grow 60% faster</span>':''}${ix?`<span class="fact ixf">IX: <b>${esc(ix)}</b></span>`:''}${p?`<span class="fact mine">Your POP</span><button class="fact trb" data-act="trace" data-args='{"city":"${c}"}'>🔍 Traceroute</button>`:''}${down?`<span class="fact down">DOWN</span>`:''}</div></div>
<button class="x" data-act="closePanel" aria-label="Close">×</button></div>`;
if(!p){
h+=`<div class="scroll">${C.note?`<p class="note" style="margin-top:0">${esc(C.note)}</p>`:''}
@ -2081,6 +2212,7 @@ function showTitle(){
${sv?`<div class="btns" style="margin-bottom:6px">${btn(`Continue ${esc(sv.name)} · ${dateStr(sv.day)}`,'cont',{},'pink big')}</div>`:''}
<label class="f" for="nmIn">Name your network</label><input class="t" id="nmIn" maxlength="24" value="Packet Pals" autocomplete="off">
<label class="f">Pick your home city</label><div class="starts">${starts.map(([c,d])=>`<button class="start ${UI.startCity===c?'on':''}" data-city="${c}" data-act="pickStart" data-args='{"city":"${c}"}'><b>${CITY[c].name}</b><span>${d}</span></button>`).join('')}</div>
<label class="f">Mode</label><div class="btns">${[['normal','Normal'],['sandbox','Sandbox']].map(([m,l])=>`<button class="b sm modeb ${(UI.mode||'normal')===m?'pink':'ghost'}" data-m="${m}" data-act="modeSet" data-args='{"m":"${m}"}'>${l}</button>`).join('')}${btn('Scenarios &amp; weekly challenge →','scenarios',{},'sm')}</div>
<div class="btns" style="margin-top:16px;justify-content:space-between;align-items:center">${btn(sv?'Start a new network':'Start building','start',{},'big')}${btn('How to play','help',{},'ghost')}${btn('Import a save','importPick',{},'ghost sm')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">Source on GitHub</a> · Cookieless stats, no tracking</p>`);
if(sv){S=migrate(sv);compute();}
}
@ -2120,7 +2252,7 @@ function showHelp(){
<dt>Badges</dt><dd>Below your goals sits a wall of badges, from common to legendary. Some take luck, some take years, and a couple are secret. Badges you earned in earlier games stay on this device with a dashed outline.</dd><dt>The giants</dt><dd>At customer level 3 and 4, hyperscalers and AI clouds show up with deals only they would ask for: terabit AI WANs between gigawatt campuses, training runs spread over several sites, week-long dataset ingests, and hundreds of fiber pairs in a trench you dug yourself. They pay like nobody else, and they want diverse paths, two sites per metro and zero excuses. Cities near their campuses list them under “Who’s here”.</dd><dt>Auto-TE</dt><dd>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.</dd><dt>Metro diversity</dt><dd>A POP is one building until you add a second site in the Infra tab. Then a power cut, cleaner or A/C failure only takes out half the city, and you choose which site each transit, PNI and IX port plugs into. Spread them out, or both halves of your redundancy will sit in the same dark room. Watch out for metro ring cuts, which cut site B off.</dd><dt>Regional quirks</dt><dd>South America hangs off Miami: transit is pricier, nothing crosses the Darién Gap by land, and fiber over the Andes costs double and breaks often. IX.brrr in Brazil is run by a nonprofit with cheap public prices, and small Brazilian provedores buy transit in bulk. Inside the UAE only the duopoly may run fiber, so no dark fiber and 3× waves. Taiwan’s cables meet a lot of anchors, Indian fiber meets road widening and the monsoon, and South Africa has load shedding: bring a generator.</dd><dt>Boot times</dt><dd>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.</dd><dt>Failures</dt><dd>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.</dd>
</dl><div class="btns" style="margin-top:14px">${btn(UI.started?'Back to the map':'Got it','helpClose',{},'big')}${RELEASE_NOTES.length?btn(`What’s new in ${esc(APP_VERSION)}`,'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn('Start a new network','resetAsk',{},'ghost sm'):''}</div><div class="btns" style="margin-top:6px">${UI.started&&S&&!S.lost?btn('Export save','exportSave',{},'ghost sm'):''}${btn('Import a save','importPick',{},'ghost sm')}</div>`);
}
function showWin(){openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">You're a <span style="color:var(--me)">Tier 1</span>!</h1><p class="tagline">${esc(S.name)} (AS${S.asn}) is transit-free. You peer with every giant on the planet and pay nobody to reach the internet. Took you ${S.day} days and ${S.stats.incidents} incidents.</p>${btn('Keep building','keepPlaying',{},'pink big')}`);sfx('coin');}
function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`<div class="btns" style="margin-top:8px">${btn('Share my network','share',{},'pink')}</div>`);},0);openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">You're a <span style="color:var(--me)">Tier 1</span>!</h1><p class="tagline">${esc(S.name)} (AS${S.asn}) is transit-free. You peer with every giant on the planet and pay nobody to reach the internet. Took you ${S.day} days and ${S.stats.incidents} incidents.</p>${btn('Keep building','keepPlaying',{},'pink big')}`);sfx('coin');}
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">Bankrupt</h1><p class="tagline">The bank repossessed your routers and sold them on eBuy. ${esc(S.name)} lasted ${S.day} days and peaked at ${fmtG(S.stats.peak)}.</p>${btn('Try again','newgame',{},'pink big')}`);try{localStorage.removeItem('sot-save-v1');}catch(e){}}
function openLinkModal(a,b){
if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">Not without a license</h2><button class="x" data-act="closeModal" aria-label="Close">×</button></div><p class="lead" style="margin-top:8px">Building into mainland China needs a joint venture and an operating license. Open ${CITY[cnCity(a)?a:b].name} to apply.</p>`);return;}
@ -2419,7 +2551,7 @@ addEventListener('keydown',e=>{if(e.target.tagName==='INPUT')return;if(e.code===
let pressing=false;
document.addEventListener('pointerdown',e=>{if(e.target.closest('#panel,#left'))pressing=true;});
addEventListener('pointerup',()=>setTimeout(()=>pressing=false,0));
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','pickStart','cont','help','helpClose','newgame','mute','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo'].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;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','pickStart','cont','help','helpClose','newgame','mute','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','scenarios','startScn','startWeekly'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
/* ================= LOOP ================= */
let last=performance.now(),acc=0,hudT=0;

73
tests/modes.test.js Normal file
View file

@ -0,0 +1,73 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('sandbox: endless money, every unlock, nothing breaks, no badges', () => {
const { ev, errors } = load();
ev("ACT.modeSet({m:'sandbox'});ACT.start({})");
assert.equal(ev("S.mode"), 'sandbox');
assert.equal(ev("S.lvl"), 4);
ev("S.cash=5;for(let i=0;i<120;i++)dayTick()");
assert.ok(ev("S.cash") >= 1e8, 'money refills');
assert.equal(ev("S.stats.incidents"), 0, 'no failures');
assert.equal(ev("Object.keys(S.ach||{}).length"), 0, 'no badges in sandbox');
assert.match(ev("document.getElementById('hAsn').textContent"), /Sandbox/);
assert.deepEqual(errors, []);
});
test('scenarios: rules apply, goals complete, deadlines fail, seeds repeat', () => {
const { ev, errors } = load();
ev("ACT.scenarios()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Weekly challenge/);
ev("ACT.startScn({id:'stg'})");
assert.equal(ev("S.home"), 'stg');
ev("ACT.buyTransit({city:'stg',net:'drz',tier:1})");
assert.equal(ev("S.transit.length"), 0, 'no transit in the Spätzle-IX scenario');
ev("ACT.startScn({id:'redsea'})");
assert.equal(ev("cablesOk('mrs','sin').length"), 0, 'Red Sea routes are gone');
assert.ok(ev("cablesFor('mrs','sin').length") > 0);
ev("ACT.startScn({id:'carnaval'})");
assert.ok(ev("S.biz.some(b=>b.type==='event'&&b.start===90)"), 'Carnaval is pre-booked');
ev("S.day=99;S.scn.done=0;dayTick()");
assert.ok(ev("!!S.scn.failed"), 'deadline passes');
assert.match(ev("document.getElementById('modalCard').textContent"), /Time's up/);
// weekly: same seed gives the same first random numbers
ev("ACT.startWeekly()");const a = ev("[Math.random(),Math.random()].join()");
ev("ACT.startWeekly()");const b = ev("[Math.random(),Math.random()].join()");
assert.equal(a, b);
ev("S.stats.peak=1234;S.day=364;dayTick()");
assert.match(ev("document.getElementById('modalCard').textContent"), /score/i);
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-scn')).weekly"));
assert.deepEqual(errors, []);
});
test('completing a scenario records it and unlocks a badge', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-scn');ACT.startScn({id:'spat'});R.reach=1;R.served=200;scnTick(10)");
assert.equal(ev("S.scn.done"), 10);
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-scn')).spat"));
ev("checkBadges()");
assert.ok(ev("S.ach.scen1!==undefined"));
assert.deepEqual(errors, []);
});
test('traceroute shows hops, the exit and the AS path', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'ams',net:'lvl',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute()");
let r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'nfx'}))"));
assert.match(r.text, /traceroute to/);
assert.match(r.text, /ams/, 'goes via Amsterdam to transit');
assert.deepEqual(r.asPath.slice(0, 2), [ev('S.asn'), ev("NET.lvl.asn")]);
r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'akm'}))"));
assert.match(r.why, /peering/i, 'open network over the IX route server');
r = JSON.parse(ev("JSON.stringify(traceroute('ams',{city:'fra'}))"));
assert.match(r.text, /fra/);
ev("S.links[0].cut=S.day+3;compute()");
r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'nfx'}))"));
assert.ok(/unreachable/.test(r.text) || /peering/i.test(r.why));
ev("ACT.trace({city:'fra'})");
assert.match(ev("document.getElementById('modalCard').textContent"), /Traceroute/);
ev("ACT.share()");
assert.deepEqual(errors, []);
});