Merge branch 'main' into own-carrier-egress

This commit is contained in:
thesysadmindev 2026-10-31 22:16:55 +11:00 • committed by GitHub
commit 296de1d946
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
232 changed files with 18447 additions and 2047 deletions

View file

@ -2,41 +2,56 @@
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)<g)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;}
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;}
// Looked up rather than read from the save, so it follows a language switch mid-scenario.
const scnName=()=>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;
// 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
// 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_45_of_the_internet_and'),ok:()=>R.reach>=0.45&&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},
// 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},
{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')}];
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;}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;}
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;}}
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?`<b>${esc(S.scn.name)}</b><br>${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?`<b>${esc(S.scn.name)}</b><br>${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();}

View file

@ -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);

View file

@ -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;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],ms=bestLat(a,b);if(ms<=latMaxOf(a,b))out.push({t:'hft',a,b,k:'lat',n:+ms.toFixed(1)});}}
const dci=['onramp','ai','hyper'].filter(up);
if(dci.length)for(const l of S.links){if(l.kind!=='df'||l.sub||l.ready>S.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<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(diversePaths(cs[i],cs[j]))out.push({t:'sov',a:cs[i],b:cs[j],k:'div',n:0});}
if(up('cgame')&&R)for(const c of bigEye())if(S.pops[c]&&S.pops[c].bb&&sfOf(R,c)>=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 `<div class="meta">🔭 ${tr(SPOT_W[s.k],{ms:s.n,cap:fmtCap(s.n),a:CITY[o.city].name,b:o.city2?CITY[o.city2].name:''})}</div>`;}
/* 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()<SEAT_LV||S.scn)return;S.seatOff=seatOffer(c,S.day);if(S.seatOff)toast(tr('specialist.a_consortium_is_selling_seats_on',{name:esc(S.seatOff.name),a:CITY[S.seatOff.a].name,b:CITY[S.seatOff.b].name}),'goal',[{l:tr('common.show_me'),act:'leftTab',args:{t:'deals'}}]);}
function seatSection(){const o=S.seatOff;if(!o||o.exp<=S.day)return '';const pop=[o.a,o.b].filter(c=>!S.pops[c]).reduce((x,c)=>x+popCost(c),0);
return `<div class="inc" style="background:#E6F4FF"><div class="nm">🚢 ${tr('specialist.consortium_seat_name',{name:esc(o.name)})}</div><div class="meta">${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})}</div>
<div class="meta">${tr('specialist.your_own_fiber_pairs_on_a')}${pop?' '+tr('specialist.includes_pops_at_the_landings_price',{price:fmt$(pop)}):''}</div>
<div class="btns">${SEAT_N.map(n=>{const c=seatCost(o.km,n)+pop;return btn(`${trn('specialist.n_fiber_pairs',n)} <small>${fmt$(c)} · ${tr('common.price_mo',{price:fmt$(seatMo(o.km,n))})}</small>`,'seatBuy',{n},'sm',S.cash<c);}).join('')}${btn(tr('common.decline'),'seatNo',{},'ghost sm')}</div></div>`;}
function seatPanel(l){if(!l.seat)return '';return `<div class="kv"><span>${tr('specialist.consortium_seat')}</span><b>${esc(l.cname||'')} · ${trn('specialist.n_fiber_pairs',Math.max(1,l.pairs|0))}</b></div><p class="note">${tr('specialist.the_consortium_runs_the_cable_your')}</p>`;}
/* 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;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],o=bestLat(a,b,ownGlass),l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}
SOLC={s:S,k,v};return v;}
const solCust=()=>S.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 `<div class="inc" style="background:#EEF0FF"><div class="nm">${tr('specialist.pick_a_charter')}</div><div class="meta">${tr('specialist.what_kind_of_network_are_you',{n:CHARTER_DAYS-S.day})}</div>${Object.entries(CHARTERS).map(([k,C])=>`<div class="row"><div class="grow"><div class="nm">${C.i} ${tr(C.n)}</div><div class="meta">${tr(C.d,{p:Math.round((LAT_PAY-1)*100),r:SOL_ROUTES,c:SOL_CUST})}</div></div>${btn(charter()===k?tr('specialist.keep_it'):tr('specialist.pick'),'charter',{k},k==='global'?'ghost sm':'pink sm')}</div>`).join('')}</div>`;
if(charter()!=='boutique')return '';
if(S.solWon)return `<div class="inc" style="background:#EAF7EE"><div class="nm">⚡ ${tr('specialist.speed_of_light')}</div><div class="meta">${tr('specialist.won_on_date_your_own_glass',{date:dateStr(S.solWon)})}</div></div>`;
const r=solRoutes();return `<div class="inc" style="background:#EEF0FF"><div class="nm">⚡ ${tr('specialist.speed_of_light')}</div><div class="meta">${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})}</div>${r.slice(0,SOL_ROUTES).map(x=>`<div class="meta">✓ ${CITY[x.a].name} ⇄ ${CITY[x.b].name}: ${tr('common.ms_ms_one_way',{ms:x.o.toFixed(1)})} &lt; ${x.l.toFixed(1)}</div>`).join('')}</div>`;}
// 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(`<b>⚡ ${tr('specialist.speed_of_light')}</b><br>${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;}}

View file

@ -0,0 +1,30 @@
/* ---------- the capacity broker: a listing that sells as the market wants (#203) ----------
You list some alien waves (and, on your own build, spare pairs) on a dark fiber; the broker keeps the listing and
sells it off over the months, as carriers between those two cities want capacity. A route's market is how many 400G
waves other carriers want there, sized by the eyeballs at both ends (a landing town counts the big city it serves),
and everything you already rent out between those cities fills it: a busy route sells in days, a road to nowhere
maybe once. The broker keeps 10% of the monthly price, as before. l.list = {w: waves left to sell, p: pairs}. */
const BR_DIV=40,BR_MAX=48,BR_PAIR=8,BR_NEAR=350;
// What a city weighs for the market: its own eyeballs, or half of a big city's within reach of its backhaul.
const BR_W=new Map();
function brWeight(c){let b=BR_W.get(c);if(b===undefined){const C=CITY[c];b=C.P;
for(const D of CITIES)if(D.id!==c&&!D.off&&D.land===C.land&&kmBetween(c,D.id)<=BR_NEAR)b=Math.max(b,D.P*0.5);BR_W.set(c,b);}
return b*eraMul();}
// 400G waves carriers want between two cities, and how many of them you already rent out there (a pair counts as 8).
const brMarket=(a,b)=>clamp(Math.round(Math.sqrt(brWeight(a)*brWeight(b))/BR_DIV),1,BR_MAX);
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));
// Once a day, each listing may find a buyer: the more room the route has left, the sooner.
function brTick(){for(const l of S.links){const L=l.list;if(!L||l.kind!=='df'||!fiberOk({link:l.id,type:'wwave'}))continue;
const free=brFree(l);if(!free)continue;
if(L.w>0&&freeCh(l)>=1&&Math.random()<Math.min(0.3,free/45)){const n=Math.max(1,Math.min(L.w,freeCh(l),free,1+Math.floor(Math.random()*4)));brSell(l,'wwave',n);L.w-=n;}
else if(L.p>0&&pairFree(l)&&free>=BR_PAIR&&Math.random()<1/90){brSell(l,'dfpair',1);L.p--;}
if(!(L.w>0)&&!(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 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');
floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');}

View file

@ -2,16 +2,20 @@
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={};
// Every link between two cities costs what the pair costs, as in compute(); the trace shows an active link over one on standby.
const pw={};for(const l of live){const k=edgeKey(l);pw[k]=Math.min(pw[k]??Infinity,(l.km+60)*MET[pairMet(k)].f);}
const pw={};for(const l of live){const k=edgeKey(l);pw[k]=Math.min(pw[k]??Infinity,pairW(k,l.km));}
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=pw[edgeKey(l)]+(l.standby?1e-6:0);(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: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',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)});
// 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: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}));
@ -32,10 +36,12 @@ 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'));}
// 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<ch.length-1;i++){const V=NET[ch[i]],C=NET[ch[i+1]];asPath.push(V.asn);hop(`${slug(C.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:C.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')}):''}.${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];

View file

@ -13,13 +13,17 @@ 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 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.
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);
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){}

View file

@ -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(`<div class="eyebrow">${tr('features.weekly_challenge_key',{key:esc(sc.key)})}</div><h2 style="font-size:30px">${tr('scenario_progress.your_score_score',{score:fmtG(score)})}</h2><p class="tagline">${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')}</p><div class="btns">${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);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(`<div class="eyebrow">${tr('common.scenario_complete')}</div><h2 style="font-size:30px">${tr('scenario_progress.name_done_in_d_days',{name:esc(def.n),d})}</h2><p class="tagline">${esc(def.goal)}. ${d<def.days/2?tr('scenario_progress.with_time_to_spare'):tr('scenario_progress.just_in_time')}</p><div class="btns">${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')}</div>`);sfx('coin');}
else if(d>=def.days){sc.failed=d;openModal(`<div class="eyebrow">${tr('common.scenario_over')}</div><h2 style="font-size:30px">${tr('common.time_s_up')}</h2><p class="tagline">${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(def.goal),d:def.days})}</p><div class="btns">${btn(tr('common.try_again'),'startScn',{id:def.id},'pink big')}${btn(tr('common.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){}
function scenarioModal(){wsEnsure();const h=scnHof();
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.scenarios')}</div><h2 style="font-size:28px">${tr('scenario_progress.pick_a_challenge')}</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="${tr('common.close')}">×</button></div>
<div class="scn wk"><div class="grow"><div class="nm">${tr('features.weekly_challenge_key',{key:esc(wk.key)})}</div><div class="meta">${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)}):''}</div></div>${btn(tr('common.play'),'startWeekly',{},'pink')}</div>
${wsRow()}
${SCN.map(x=>`<div class="scn"><div class="grow"><div class="nm">${esc(x.n)} ${h[x.id]?`<span class="tag open">${tr('features.done_in_d_days',{d:h[x.id].days})}</span>`:''}</div><div class="meta">${esc(x.d)}</div><div class="meta">${tr('scenario_progress.goal_goal_time_d_days_start',{goal:esc(x.goal),d:x.days,city:esc(CITY[x.city].name)})}</div></div>${btn(tr('common.play'),'startScn',{id:x.id},'')}</div>`).join('')}`);}

View file

@ -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:{}};
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,core:{lv:0,run:0},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}};
}

View file

@ -0,0 +1,24 @@
/* 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;
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)<o.slots))||(o.type==='dfpair'&&!pairFree(l))||
(o.type==='pairs'&&(!l.own||S.biz.some(x=>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);
/* 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;}}

View file

@ -0,0 +1,42 @@
/* Puzzles: one entry per line, in play order. A puzzle is data:
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.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'),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: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=[
['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'],
];

View file

@ -0,0 +1,158 @@
/* ================= PUZZLES (#190) =================
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;
// 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.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.
const pzCities=d=>[...new Set([...(d.src||[]),...d.dem.flatMap(f=>f.t==='l2'?[f.a,f.b]:[f.a])])];
// ---------- progress (localStorage, never trusted) ----------
// `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=>{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;};
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;}
// 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);
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 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);
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*popMo(c);// thin markets cost more every month too (#94)
// 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&&!RG[i].noPz).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<rt;k++)s+=routerCost(g,k);return s+PZ_YEAR*((rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[g].mo);}
const pzRouterCost=c=>{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,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).
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 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;}
// 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||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)});
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 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.length<n&&pool.length)cities.push(pool.splice(Math.floor(nx()*pool.length),1)[0]);
// Content sits in the first city, eyeballs in the others, and all of it fits one 10G wave: so a 10G ring through the
// cities, nearest first, on the cheapest route of each hop, carries everything whichever hop is cut. A ring survives
// any single cut only if no two hops share a cable, so each hop takes the cheapest route on a cable the ring has not
// used yet (overland is always there: a pool is one landmass). The budget is that ring plus 10%.
const ring=[cities[0]],left=cities.slice(1);while(left.length){const u=ring[ring.length-1];left.sort((a,b)=>kmBetween(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<ring.length;i++){const r=pzRoutes(ring[i],ring[(i+1)%ring.length]).filter(x=>!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);}
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 ----------
// 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 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;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};
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(`<b>${esc(pzName(def))}</b><br>${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(){pzMkStop();if(S&&S.ar)arStop(true);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.
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;
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: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(){pzMkStop();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;
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(){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;const show=()=>{if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}};if(pzMkCan())pzMonkey(show);else show();return e;}
// The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend.
function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null};
if(e.stars<r.st||(e.stars===r.st&&r.sp!=null&&r.sp<=e.spend))return;
r.sp=e.spend;r.st=e.stars;if(P.id==='weekly'&&P.rev>1)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;j<PZ.length;j++)if(pzPackOpen(PZ[j].pack,p))return PZ[j];return null;}

View file

@ -0,0 +1,88 @@
/* ================= 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/<key>.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)&&t<pzLastSun(y,9)?2:1;};
// 06:00 Berlin on the Sunday at UTC midnight `sun`; the clocks change at 01:00 UTC, well before.
const pzSunStart=sun=>sun+(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<pzSunStart(sun))sun-=7*864e5;return pzIso(sun+864e5);}
// When a week starts (UTC ms), or null for a key that is not a real week.
function pzWeekStart(key){const m=/^(\d{4})-W(\d{2})$/.exec(String(key));if(!m)return null;const j4=Date.UTC(+m[1],0,4),mon=j4-((new Date(j4).getUTCDay()+6)%7)*864e5+(+m[2]-1)*7*864e5;
const t=pzSunStart(mon-864e5);return pzWeekKey(t)===key?t:null;}
// n weeks on (or back). Weeks are 7 days plus or minus the hour the clocks change, so aim 3 hours into the week.
const pzKeyAdd=(key,n)=>{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};}
// 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','src','dem','via','avoid','budget','twist','name','joke','ref','rev'];
// 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,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>2e7)return null;
const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['ring','noSub'].includes(k)))return 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,src,dem,via,avoid,budget:j.budget,noSub:false,ring:false,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;}
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{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;}}

View file

@ -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/<key>.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.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})}]},
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.length<lo||v.length>hi||!v.every(pzCityOk)||new Set(v).size!==v.length)return null;}
else if(!Number.isInteger(v)||v<lo||v>hi)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(`<div class="eyebrow">${T_WS(w)} ${tr('wkscn.weekly_scenario_key',{key:esc(w.key)})}</div><h2 style="font-size:30px">${tr('wkscn.won_on_day_d',{d})}</h2><p class="tagline">${esc(wsGoalTxt(w))}. ${d<=w.par?tr('wkscn.under_par_par',{par:w.par}):tr('wkscn.par_was_day_par',{par:w.par})}</p><p class="meta">${esc(wsShareText())}</p><div class="btns">${btn(tr('wkscn.copy_my_result'),'wsShare',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);sfx('coin');}
else if(d>=sc.days){sc.failed=d;openModal(`<div class="eyebrow">${tr('common.scenario_over')}</div><h2 style="font-size:30px">${tr('common.time_s_up')}</h2><p class="tagline">${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(wsGoalTxt(w)),d:sc.days})}</p><div class="btns">${btn(tr('common.try_again'),'startWeekly',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);}}
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]?'':` <span class="pznew">${tr('puzzles.new_this_sunday')}</span>`,cd=`<div class="meta pzcd">⏳ ${wsNext(Date.now())}</div>`;
if(!d){const wk=weekly();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){}
return `<div class="scn wk" id="wsRow"><div class="grow"><div class="eyebrow">📅 ${tr('wkscn.weekly_scenario_key',{key:esc(wk.key)})}${badge}</div><div class="nm">${wsLoading()?tr('wkscn.loading_this_week_s_scenario'):tr('features.weekly_challenge_key',{key:esc(wk.key)})}</div><div class="meta">${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)}):''}</div>${cd}</div>${btn(tr('common.play'),'startWeekly',{},'pink',wsLoading())}</div>`;}
const x=wsWin(o,d),mods=d.mods.map(m=>esc(WEEK_MODS.find(y=>y.id===m).n));
return `<div class="scn wk" id="wsRow"><div class="grow"><div class="eyebrow">📅 ${tr('wkscn.weekly_scenario_key',{key:esc(d.key)})}${badge}</div>
<div class="nm">${T_WS(d)} ${esc(wsTxt(d.name))} ${x?`<span class="tag open">${tr('wkscn.won_day_d_par_par',{d:x.d,par:d.par})}</span>`:''}</div><div class="meta">${esc(wsTxt(d.desc))}</div>
<div class="meta">🎯 ${esc(wsGoalTxt(d))}</div><div class="meta">${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})}</div>
<div class="meta">${tr('wkscn.same_scenario_for_everyone_this_week')}${st?' · 🔥 '+trn('puzzles.n_week_streak',st):''}</div>${cd}</div>${btn(tr('common.play'),'startWeekly',{},x?'ghost':'pink')}</div>`;}
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});}

View file

@ -0,0 +1,217 @@
/* ---------- Standing orders (#98) ----------
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_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, 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,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')}}},
{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'),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};
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;
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;}
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,
// 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);
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&&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);
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}.
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,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(w=>opsWhere(w,k)).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).
// Peering is always at an exchange, and a city's first exchange has the city's id ("lon" is LYNX): name the exchange (#228).
function opsWhere(w,k){if(k==='peer'&&isIx(w)&&ixName(w))return ixName(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(x=>opsWhere(x,k)).join(', ')}));
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,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)<O.floor||(cap&&(OPSK[k].mo?(O.addMo[k]||0)+mo:(O.spent[k]||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,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'];
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');},
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&&v<min){S.offers=S.offers.filter(x=>x!==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)&&tries<OPS_TRIALS&&!(UI.opsTried&&UI.opsTried.s===S&&UI.opsTried.m.get(o.id)>S.day-7)){tries++;ACT.accept({id:o.id,auto:true});
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<at)continue;
const rt=p.routers||1,g=p.rgen||0,nx=mainRG(RG[g].cls+1);
// A swap with one router is a maintenance window: the intern only swaps where a second router carries the traffic.
const swap=nx>=0&&RG[nx].lvl<=lvl()&&!modelFits(c,nx)&&(rt>1||popIdle(c)),add=rt<RMAX;
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');
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=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;
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(k<LAG_MAX&&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{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))){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);}},
// 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);}
// 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)<capOf(big)&&!S.biz.some(b=>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)<load*1.25)break;if(!opsDecomSafe(l))continue;cap-=capOf(l);UI.confirm=l.id;X.pay('decom',()=>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;
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;O.addMo={};}
// 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<w){O.rep=O.wk;logNote(`<b>${esc(tr('ops.shift_report',{name:opsName()}))}</b> ${esc(opsWeekLine(O.rep))}`,O.rep.rev>0?'good':'',[],{a:'ops'});}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]]);
// 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()<ff){const c=pick(Object.keys(S.pops));let f=Math.floor(Math.random()*OPS_FF.length);
if(f===3){const t=O.on.transit&&opsHere('transit',c)&&!scnRule('noTransit')&&S.transit.find(t=>t.city===c&&(t.n||1)<LAG_MAX&&portOk(c,t.tier)&&PORT[t.tier].setup<=Math.min(20000,S.cash*0.05));if(!t||!opsQuiet(()=>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);}
// 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'));}
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'));}
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};}

View file

@ -0,0 +1,164 @@
/* ================= 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. ▶ 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_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
// plan: how many new tubes this brief should take; going over is allowed and costs a star), t (the brief).
// budget: one round number for the whole run, a little above the best plan found (tests/architect.test.js), and below
// the obvious one. Money never blocks a brief. ⭐ every brief done, ⭐ never over a brief's tubes, ⭐ within budget.
const AR_RUNS=[
{id:'euro',n:tr('architect.euro_run'),j:tr('architect.euro_run_joke'),hq:'ams',via:[],budget:410000,briefs:[
{add:['fra'],dem:{fra:40},tubes:1,t:tr('architect.euro_1')},
{add:['par','lon'],dem:{par:50,lon:60},tubes:2,t:tr('architect.euro_2b')},
{gold:['fra','par'],tubes:1,t:tr('architect.euro_3b')},
{add:['zrh'],dem:{zrh:40},gold:['zrh'],tubes:2,t:tr('architect.euro_5')},
{ring:['ams','par','lon'],dem:{par:100},tubes:2,t:tr('architect.euro_ring_grow')},
{drop:['fra'],add:['dus'],dem:{dus:60},gold:['dus'],tubes:2,t:tr('architect.euro_6')},
]},
{id:'usa',n:tr('architect.coast_to_coast'),j:tr('architect.coast_to_coast_joke'),hq:'ash',via:[],budget:610000,briefs:[
{add:['nyc'],t:tr('architect.usa_1')},
{add:['chi'],t:tr('architect.usa_2')},
{gold:['nyc'],t:tr('architect.usa_3')},
{lat:['nyc','chi',8],t:tr('architect.usa_4')},
{add:['dal','sjc'],t:tr('architect.usa_5')},
{gold:['sjc'],t:tr('architect.usa_6')},
]},
{id:'pacific',n:tr('architect.pacific_rim'),j:tr('architect.pacific_rim_joke'),hq:'tok',via:[],budget:2350000,briefs:[
{add:['hkg'],t:tr('architect.pac_1')},
{add:['sin'],t:tr('architect.pac_2')},
{gold:['hkg'],t:tr('architect.pac_3')},
{gold:['sin'],t:tr('architect.pac_4')},
{add:['syd'],t:tr('architect.pac_5')},
]},
];
const arOn=()=>pzOn()&&!!S.ar;
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)&&!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(),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<r.sp))){r.st=st;r.sp=st?sp:r.sp;}r.br=Math.max(r.br,br);p.runs[S.ar.id]=r;arStore(p);}
// ---------- money ----------
// What a POP or a link costs for the year, as the puzzles count it.
const arPopCost=c=>pzPopCost(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)<A.bi)A.sunk+=arPopCost(c);for(const l of links)if(arAge(l)<A.bi)A.sunk+=arLinkCost(l);}
// ---------- the graph ----------
function arAdj(skip){const nb={};for(const c in S.pops)nb[c]=new Set();for(const l of S.links){if(skip&&skip(l))continue;if(!nb[l.a]||!nb[l.b])continue;nb[l.a].add(l.b);nb[l.b].add(l.a);}return nb;}
function arReach(from,nb){const seen=new Set();if(!nb[from])return seen;seen.add(from);const q=[from];while(q.length){const u=q.shift();for(const v of nb[u])if(!seen.has(v)){seen.add(v);q.push(v);}}return seen;}
// Sites a cut leaves without a path to HQ.
function arDark(u){const nb=arAdj(l=>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]<d[u]))u=k;if(u===null)return null;if(u===b)return d[u];done.add(u);
for(const l of S.links){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,x=d[u]+linkLat(l);if(d[v]===undefined||x<d[v])d[v]=x;}}}
// A simple cycle through every one of these cities (the networks are small, so a bounded search will do).
function arRingOk(cs){const nb=arAdj();if(!cs.every(c=>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<n)k='islands';else if(m===n-1&&dbl===m)k='braces';else if(n===2)k='tube';else if(m===n-1)k=maxd===n-1&&n>=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.length<n&&cs.every(c=>core[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.
// ---------- 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)<arDem(c)*0.999-1e-6);}
// Routers follow the tubes: the cheapest model that takes every tube and port at the POP.
const AR_RG=()=>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;mkStop();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;
// 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(`<b>${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}</b><br>${esc(b.t)}`,'goal');sfx('click');}
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;
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 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){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:[]};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)};}
// 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(`✅ <b>${tr('architect.review_passed')}</b><br>${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];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)-(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_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.hit?sh.i+1:sh.i;i<sh.units.length;i++){const x=arCut(sh.units[i]);for(const l of x.ls)l.cut=0;if(x.gold.length||x.short.length){sh.i=i-1;arStep(true);return;}}
sh.i=sh.units.length-1;arStep();}
// The kind of a city in a run: its sites, stepping stones and closed cities show; the rest of the world only on request.
function arKind(c){const P=S.pz;return P.cities.includes(c)?'goal':P.avoid.includes(c)?'avoid':P.via.includes(c)?'via':S.pops[c]||(UI.arAll&&pzCityOk(c))?'off':null;}

View file

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

View file

@ -0,0 +1,63 @@
/* ---------- the published weekly Architect run ----------
Every Sunday scripts/weekly-architect.js publishes architect/weekly/<key>.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-<key>'. 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])}));
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(' ');}
// 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&&!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;}
// 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 '<div id="arWk"></div>';
const x=arLoad().runs[r.id],ok=x&&(x.rv||1)===r.rev?x:null;
return `<div class="scn pzwk" id="arWk"><div class="grow"><div class="eyebrow">🗓️ ${tr('architect_weekly.weekly_run')} · ${arWkNext(new Date())}</div><div class="nm">${esc(r.n)} <span class="pzst">${pzStarStr(ok?ok.st:0)}</span></div><div class="meta">${esc(r.j)}</div><div class="meta">${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)}):''}</div></div>${btn(tr('common.play'),'pzArStart',{id:r.id},ok&&ok.st>=3?'ghost':'pink')}</div>`;}
// "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});}