Puzzles: real traffic routed by the game, routers, link sizes and paths

Every puzzle now carries demand (eyeballs pulling from a content origin, circuits
with latency caps, best-effort flows) routed by compute(). Stars: delivered,
within budget, N-1 under load. Routers, ports, metrics, standby and the
redundancy check work in puzzles; the whole world is open. Weekly schema 2
carries the demand; scripts/lib/puzzle-solver.js sizes and searches builds.
This commit is contained in:
Frederic Jung 2026-10-29 10:35:28 +01:00
parent 9b7b1c150c
commit e90f5f675e
No known key found for this signature in database
18 changed files with 817 additions and 364 deletions

View file

@ -3,7 +3,8 @@
const PORT_SLOT=i=>i===0?0.25:1;
function portsUsed(c){let u=0;
for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;u+=l.kind==='df'?(l.ch||[]).length:1;}
for(const t of S.transit)if(t.city===c)u+=PORT_SLOT(t.tier)*(t.n||1);
// A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours.
for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1);
for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1);
if(S.myIx[c])u+=1;
@ -17,6 +18,6 @@ const popIdle=c=>{const p=S.pops[c];return !!p&&!p.bb&&portsUsed(c)===0&&!S.biz.
const fmtPorts=u=>Number.isInteger(u)?String(u):u.toFixed(2).replace(/0+$/,'');
function modelFits(c,g){const G=RG[g],p=S.pops[c];if(!p)return '';
if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='wave'&&l.tier>G.maxLT))return tr('ports.a_wave_here_is_faster_than',{pn:G.pn});
if([...S.transit,...S.pni].some(t=>t.city===c&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn});
if([...S.transit,...S.pni].some(t=>t.city===c&&!t.pz&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn});
if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='df'&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this');
if(portsUsed(c)>portsMax(c,g))return tr('ports.you_use_u_ports_here_and',{u:fmtPorts(portsUsed(c)),r:p.routers||1,model:G.n,max:portsMax(c,g)});return '';}

View file

@ -1,33 +1,36 @@
/* Puzzles: one entry per line, in play order. A puzzle is data:
id, pack, n (name), j (one-line joke), cities (all must end up connected), via (optional stepping stones),
budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist or two:
noSub (no subsea cables), ring (one ring through every POP), lat:[a,b,ms] (best path under ms), minG (every link at
least this many Gbps), avoid (cities shown on the map that you may not build in). */
id, pack, n (name), j (one-line joke), src (the content origins: eyeballs pull from the nearest), dem (the traffic:
{t:'eye',a,g} eyeballs in city a want g Gbps; {t:'l2',a,b,g,ms} a circuit of g Gbps between a and b, under ms
milliseconds one way; be:1 marks a flow best effort, which may drop when something is cut), via (suggested stepping
stones), budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist:
noSub (no subsea cables), ring (one ring through every POP), avoid (cities you may not build in).
Each pack teaches one idea; the budgets sit a little above the cheapest 3-star build found (tests/puzzles.test.js). */
const PZ_PACKS=[
{id:'hello',n:tr('puzzles.hello_world'),d:tr('puzzles.your_first_tubes_roomy_budgets'),need:0},
{id:'fire',n:tr('puzzles.ring_of_fire'),d:tr('puzzles.the_pacific_rim_where_every_hop'),need:6},
{id:'speed',n:tr('puzzles.speed_runs'),d:tr('puzzles.beat_the_clock_light_in_glass'),need:14},
{id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.for_architects_who_sleep_through_backhoes'),need:22},
{id:'hello',n:tr('puzzles.fat_pipes'),d:tr('puzzles.capacity_first_every_link_has_a'),need:0},
{id:'rodeo',n:tr('puzzles.router_rodeo'),d:tr('puzzles.routers_have_ports_and_a_limit'),need:10},
{id:'cops',n:tr('puzzles.traffic_cops'),d:tr('puzzles.your_routers_pick_the_path'),need:18},
{id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.survive_any_single_cut_with_the'),need:26},
{id:'final',n:tr('puzzles.grand_tour'),d:tr('puzzles.everything_at_once_across_oceans'),need:36},
];
const PZ=[
{id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),cities:['lon','nyc'],budget:0},
{id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),cities:['lon','ams','fra'],budget:0},
{id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),cities:['nyc','chi','dal','sjc'],budget:340000},
{id:'smorgas',pack:'hello',n:tr('puzzles.smorgasbord'),j:tr('puzzles.four_capitals_one_very_long_winter'),cities:['osl','sto','cph','hel'],budget:210000},
{id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),cities:['syd','mel','bne','adl'],budget:320000},
{id:'aloha',pack:'fire',n:tr('puzzles.aloha_latency'),j:tr('puzzles.honolulu_the_world_s_most_scenic'),cities:['sjc','hnl','syd'],budget:1830000},
{id:'rimshot',pack:'fire',n:tr('puzzles.pacific_rim_shot'),j:tr('puzzles.seattle_to_singapore_with_a_stop'),cities:['sea','tok','hkg','sin'],budget:1240000},
{id:'fire',pack:'fire',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),cities:['tok','hkg','sin','syd'],ring:true,budget:1610000},
{id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv','lax'],budget:1450000},
{id:'guam',pack:'fire',n:tr('puzzles.guam_slam'),j:tr('puzzles.a_tiny_island_where_half_the'),cities:['tok','mnl','syd'],via:['gum'],budget:1700000},
{id:'flash',pack:'speed',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),cities:['nyc','lon'],lat:['nyc','lon',27],budget:465000},
{id:'pingpong',pack:'speed',n:tr('puzzles.ping_pong_to_tokyo'),j:tr('puzzles.the_pacific_is_big_light_is'),cities:['lax','tok'],via:['sea','sjc'],lat:['lax','tok',47],budget:880000},
{id:'suez',pack:'speed',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),cities:['fra','sin'],via:['mrs','bom'],lat:['fra','sin',68],budget:1010000},
{id:'samba',pack:'speed',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),cities:['sao','mia'],via:['for','rio'],lat:['sao','mia',45],budget:1060000},
{id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),cities:['lis','mad','par','mil'],via:['bcn','mrs'],noSub:true,budget:210000},
{id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),cities:['nyc','lon','dub'],budget:380000},
{id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),cities:['ams','ber','muc','zrh'],via:['ham','dus'],avoid:['fra'],budget:192000},
{id:'fatpipes',pack:'n1',n:tr('puzzles.fat_pipes_only'),j:tr('puzzles.nobody_ever_got_fired_for_buying'),cities:['par','mrs','mil','zrh'],minG:100,budget:235000},
{id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),src:['nyc'],dem:[{t:'eye',a:'lon',g:8}],budget:0},
{id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),src:['ams'],dem:[{t:'eye',a:'lon',g:30},{t:'eye',a:'fra',g:60}],budget:0},
{id:'bigboat',pack:'hello',n:tr('puzzles.a_bigger_boat'),j:tr('puzzles.paris_wants_150g_one_100g_wave'),src:['fra'],dem:[{t:'eye',a:'par',g:150}],budget:1},
{id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),src:['nyc'],dem:[{t:'eye',a:'chi',g:40},{t:'eye',a:'dal',g:30},{t:'eye',a:'sjc',g:60}],budget:1},
{id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),src:['syd'],dem:[{t:'eye',a:'mel',g:50},{t:'eye',a:'bne',g:30},{t:'eye',a:'adl',g:20}],budget:1},
{id:'edgelord',pack:'rodeo',n:tr('puzzles.edge_lord'),j:tr('puzzles.london_wants_half_a_terabit_your'),src:['ams'],dem:[{t:'eye',a:'lon',g:500}],budget:1},
{id:'hubcap',pack:'rodeo',n:tr('puzzles.hub_cap'),j:tr('puzzles.all_of_europe_s_cat_videos'),src:['lon'],dem:[{t:'eye',a:'ams',g:150},{t:'eye',a:'par',g:150},{t:'eye',a:'fra',g:120}],budget:1},
{id:'ports',pack:'rodeo',n:tr('puzzles.port_authority'),j:tr('puzzles.five_small_cities_one_small_router'),src:['zrh'],dem:[{t:'eye',a:'mil',g:8},{t:'eye',a:'muc',g:8},{t:'eye',a:'fra',g:8},{t:'eye',a:'par',g:8},{t:'eye',a:'vie',g:8}],budget:1},
{id:'flash',pack:'cops',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),src:['nyc'],dem:[{t:'l2',a:'nyc',b:'lon',g:10,ms:26},{t:'eye',a:'lon',g:80,be:1}],budget:1},
{id:'baltic',pack:'cops',n:tr('puzzles.baltic_shortcut'),j:tr('puzzles.the_road_to_tallinn_is_short'),src:['fra'],dem:[{t:'eye',a:'tll',g:60},{t:'l2',a:'fra',b:'tll',g:10,ms:8.8}],via:['hel'],budget:1},
{id:'fjord',pack:'cops',n:tr('puzzles.fjord_focus'),j:tr('puzzles.the_oil_rigs_want_their_numbers'),src:['par'],dem:[{t:'eye',a:'svg',g:30},{t:'l2',a:'par',b:'svg',g:10,ms:7.2}],via:['lon'],budget:1},
{id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),src:['nyc'],dem:[{t:'eye',a:'lon',g:60},{t:'eye',a:'dub',g:40}],budget:1},
{id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),src:['lis'],dem:[{t:'eye',a:'mad',g:40},{t:'eye',a:'par',g:60},{t:'eye',a:'mil',g:30}],via:['bcn','mrs'],noSub:true,budget:1},
{id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),src:['ams'],dem:[{t:'eye',a:'ber',g:50},{t:'eye',a:'muc',g:50},{t:'eye',a:'zrh',g:40}],via:['ham','dus'],avoid:['fra'],budget:1},
{id:'fire',pack:'n1',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),src:['tok'],dem:[{t:'eye',a:'hkg',g:20},{t:'eye',a:'sin',g:20},{t:'eye',a:'syd',g:10}],ring:true,budget:1},
{id:'suez',pack:'final',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),src:['fra'],dem:[{t:'l2',a:'fra',b:'sin',g:10,ms:68},{t:'eye',a:'sin',g:30,be:1}],via:['mrs','bom'],budget:1},
{id:'kiwi',pack:'final',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),src:['sea'],dem:[{t:'eye',a:'akl',g:20},{t:'eye',a:'syd',g:40}],via:['hnl','suv','lax'],budget:1},
{id:'samba',pack:'final',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),src:['mia'],dem:[{t:'l2',a:'sao',b:'mia',g:10,ms:45},{t:'eye',a:'sao',g:40},{t:'eye',a:'rio',g:20,be:1}],via:['for'],budget:1},
];
// Weekly puzzle pools: each is one landmass and one region, so every pair has an overland route.
const PZ_WEEK_POOLS=[

View file

@ -1,17 +1,30 @@
/* ================= PUZZLES (#190) =================
Small, calm builds: connect a few cities, earn up to three stars. A puzzle runs as its own S (S.mode='puzzle'):
no clock, no bills, no incidents, links up at once. That S is never saved. Only progress (stars and best spend per
puzzle, weekly results and the weekly streak) is kept, under its own key, so the main save is never touched. */
const PZ_KEY='sot-puzzles',PZ_YEAR=12;
Small, calm builds that carry real traffic: every puzzle has demand (eyeballs pulling from a content origin, circuits
between two cities with a latency cap), and the game's own compute() routes it: metrics, standby, LAGs, router
capacity and ports all behave as in the main game. A puzzle runs as its own S (S.mode='puzzle'): no clock, no bills,
no incidents, links up at once. The demand is ordinary game state, so compute() needs no puzzle cases: an origin is a
transit port (t.pz, which takes no router port), a circuit is an L2VPN customer, eyeballs are broadband with a fixed
demand. That S is never saved. Only progress (stars and best spend per puzzle, weekly results and the weekly streak)
is kept, under its own key, so the main save is never touched. */
const PZ_KEY='sot-puzzles',PZ_YEAR=12,PZ_SET=2;
const pzOn=()=>!!(S&&S.mode==='puzzle'&&S.pz);
const pzDef=id=>PZ.find(p=>p.id===id)||null;
const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':null;
// goal: a city the traffic starts or ends in; via: a suggested stepping stone; avoid: off limits; off: any other city
// (the whole world is open, it just is not part of the plan).
const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)?'off':null;
const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key',{key:d.key})):d.n;
const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n);
// Every city a puzzle's traffic touches, origins first.
const pzCities=d=>[...new Set([...(d.src||[]),...d.dem.flatMap(f=>f.t==='l2'?[f.a,f.b]:[f.a])])];
// ---------- progress (localStorage, never trusted) ----------
function pzClean(j){const o={s:{},wk:{},streak:{last:null,n:0,best:0}};if(!j||typeof j!=='object')return o;
// `set` is the puzzle set the stars belong to: the set with traffic (2) started again, and the stars won before hang
// framed on the wall (`old`), with a note shown once (`noted`). Weekly results and the streak carry on.
function pzClean(j){const o={set:PZ_SET,s:{},wk:{},streak:{last:null,n:0,best:0},old:null,noted:1};if(!j||typeof j!=='object')return o;
const rec=r=>r&&typeof r==='object'?{st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)}:null;
if(j.s&&typeof j.s==='object')for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;}
const cur=j.set===PZ_SET;
if(j.s&&typeof j.s==='object'){if(cur){for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;}}
else{let n=0;for(const k of Object.keys(j.s).slice(0,200)){const r=rec(j.s[k]);if(r&&/^[a-z0-9]{1,20}$/.test(k))n+=r.st;}if(n){o.old=n;o.noted=0;}}}
if(cur){o.old=j.old==null?null:int(j.old,0,9999,0)||null;o.noted=j.noted?1:0;if(o.old==null)o.noted=1;}
if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;}
const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);}
return o;}
@ -19,7 +32,7 @@ function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{
function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}}
const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);
const pzPackOpen=(k,p)=>{const P=PZ_PACKS.find(x=>x.id===k);return !!P&&pzStarsTotal(p||pzLoad())>=P.need;};
// ---------- prices: the real game's waves, on day 0, for a year ----------
// ---------- prices: the real game's waves and routers, on day 0, for a year ----------
const pzMood=(a,b,sub)=>{const k=waveMarket(a,b,sub);return k.m/k.ero;};
// Overland (when the two cities share a landmass) and every cable between them, each with its price factor and latency.
function pzRoutes(a,b){const out=[],sub=isSub(a,b);
@ -29,53 +42,72 @@ function pzRoutes(a,b){const out=[],sub=isSub(a,b);
const pzMo=(r,tier,div)=>Math.round(waveMo(r.km,r.sub,tier)*r.f*(div?DIVERSE:1));
const pzLinkCost=(r,tier,div)=>pzMo(r,tier,div)*PZ_YEAR;// leased waves have no setup fee: a year of rent
const pzPopCost=c=>popCost(c)+PZ_YEAR*popMo(c);// thin markets cost more every month too (#94)
const PZ_TIERS=[0,1,2];
function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c);for(const l of S.links)s+=l.mo*PZ_YEAR;return s;}
// 10G to 800G: an 800G wave needs an 800G router at both ends, as in the main game.
const PZ_TIERS=[0,1,2,3];
// Router models on offer: the main game's catalogue up to its level-3 gear, cheapest class first.
const PZ_RG=RG.map((r,i)=>i).filter(i=>RG[i].lvl<=3).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cost-RG[b].cost);
// A POP's routers for a year: the chassis (the first Rusty Router is free), each extra one as the main game prices it
// (#157 cages included), and their rent.
function pzRtCost(g,rt){let s=Math.round(RG[g].cost*hwMul('rt'));for(let k=1;k<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};};
// What each flow gets from the last compute(): Gbps delivered, and a circuit's latency.
// Eyeball traffic to networks behind the Great Firewall loses a fifth at the border, as in the main game; that is not
// the player's doing, so a puzzle counts what crosses the border as delivered (pzGfw: the share that arrives).
let PZ_GFW=null;const pzGfw=()=>PZ_GFW||(PZ_GFW=1-0.2*NETS.filter(n=>n.cn).reduce((a,n)=>a+(NSH[n.id]||0),0));
function pzGot(){return S.pz.dem.map((f,i)=>f.t==='l2'?{g:R.l2[pzFlowId(i)]||0,ms:isFinite(R.l2lat[pzFlowId(i)])?R.l2lat[pzFlowId(i)]:null}:{g:S.pops[f.a]?(R.citySrv[f.a]||0)/pzGfw():0,ms:null});}
const pzFull=(f,x)=>x.g>=f.g*0.999-1e-6;
const pzFast=(f,x)=>!f.ms||(x.ms!=null&&x.ms<=f.ms+1e-9);
// ---------- checks ----------
function pzComp(ls,skip,from){const adj={};for(const l of ls){if(skip&&pzUnit(l)===skip)continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
const seen=new Set([from]),q=[from];while(q.length){const u=q.pop();for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return seen;}
function pzRingOk(ls){const nb={};for(const l of ls){(nb[l.a]=nb[l.a]||new Set()).add(l.b);(nb[l.b]=nb[l.b]||new Set()).add(l.a);}
const ns=Object.keys(nb);if(ns.length<3||!S.pz.cities.every(c=>nb[c])||!Object.keys(S.pops).every(c=>nb[c])||!ns.every(c=>nb[c].size===2))return false;
let prev=null,cur=ns[0],n=0;do{const nx=[...nb[cur]].find(x=>x!==prev);prev=cur;cur=nx;n++;}while(cur!==ns[0]&&n<=ns.length);return cur===ns[0]&&n===ns.length;}
function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend();
// The checklist ticks the goal cities that are already joined up: the group holding the most of them.
let best=new Set();for(const c of cs){if(!S.pops[c]||best.has(c))continue;const g=pzComp(ls,null,c);if(cs.filter(x=>g.has(x)).length>cs.filter(x=>best.has(x)).length)best=g;}
const joined=cs.filter(c=>best.has(c)).length>=2?best:new Set();
const marks=cs.map(c=>({c,st:joined.has(c)?2:S.pops[c]?1:0}));
const conn=cs.every(c=>joined.has(c));
// The same build always gets the same answer, so pzEval() keeps the last one (it routes once, then once per cut).
const pzSig=()=>JSON.stringify([S.pops,S.links,S.pairMet||null,S.biz.map(b=>b.route),S.pz.budget]);
/* ⭐ every flow delivered in full (circuits within their latency cap), and the twists; ⭐⭐ the year's spend within
budget; ⭐⭐⭐ N-1 under load: whichever single trench or cable is cut, every priority flow still gets all of its traffic
(best-effort flows may drop). The cut is routed by compute() like the real thing. */
function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&c0.sig===sig)return c0.e;
const P=S.pz,hot=UI.hotMap;compute();const R0=R,got=pzGot(),spend=pzSpend(),peak={},pk=()=>{for(const c in R.nodeLoad)peak[c]=Math.max(peak[c]||0,R.nodeLoad[c]);};pk();
const flows=P.dem.map((f,i)=>({f,i,g:got[i].g,ms:got[i].ms,full:pzFull(f,got[i]),fast:pzFast(f,got[i])}));
const tw=[];if(P.noSub)tw.push({k:'sub',ok:!S.links.some(l=>l.sub)});
if(P.ring)tw.push({k:'ring',ok:pzRingOk(ls)});
if(P.lat){const ms=S.pops[P.lat[0]]&&S.pops[P.lat[1]]?bestLat(P.lat[0],P.lat[1]):Infinity;tw.push({k:'lat',ok:ms<=P.lat[2],ms});}
if(P.minG)tw.push({k:'g',ok:ls.every(l=>LT[l.tier].g>=P.minG)});
if(P.ring)tw.push({k:'ring',ok:pzRingOk(S.links)});
if(P.avoid.length)tw.push({k:'avoid',ok:P.avoid.every(c=>!S.pops[c])});
const goal=conn&&tw.every(t=>t.ok),units=[...new Set(ls.map(pzUnit))];
// N-1: the goal cities stay joined whichever single trench or cable is cut.
const weak=conn?units.filter(u=>{const g=pzComp(ls,u,cs[0]);return !cs.every(c=>g.has(c));}):[];
const n1=conn&&units.length>0&&!weak.length,cheap=!P.budget||spend<=P.budget;
return {marks,conn,tw,goal,spend,cheap,n1,weak,stars:goal?1+(cheap?1:0)+(n1?1:0):0};}
// Two stars, and one more link within budget would survive any cut? Then the third star is close. Tries every route
// between the puzzle's cities at the smallest allowed size, so the nudge is true, not a guess.
function pzOneMore(e){const P=S.pz;if(e.stars!==2||!e.cheap||e.n1)return false;const cs=[...P.cities,...P.via],tier=P.minG?1:0,cs0=P.cities[0];
for(const a of cs)for(const b of cs){if(a>=b)continue;for(const r of pzRoutes(a,b)){if((P.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))continue;
const div=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),cost=pzLinkCost(r,tier,div)+(S.pops[a]?0:pzPopCost(a))+(S.pops[b]?0:pzPopCost(b));
if(e.spend+cost>P.budget)continue;const ls=[...S.links,{id:'pz?',a,b,cable:r.cab,trench:r.cab?'cab:'+r.cab:'pz?'}];if(P.ring&&!pzRingOk(ls))continue;
if([...new Set(ls.map(pzUnit))].every(u=>{const g=pzComp(ls,u,cs0);return P.cities.every(c=>g.has(c));}))return true;}}
return false;}
const del=flows.every(x=>x.full&&x.fast),goal=del&&tw.every(t=>t.ok),units=[...new Set(S.links.map(pzUnit))],cuts=[];
if(goal)try{for(const u of units){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1;
try{compute();pk();const g=pzGot(),lost=[];P.dem.forEach((f,i)=>{if(!f.be&&!pzFull(f,g[i]))lost.push({i,g:Math.max(0,f.g-g[i].g)});});if(lost.length)cuts.push({u,lost,g:lost.reduce((a,x)=>a+x.g,0)});}
finally{for(const l of ls)l.cut=0;}}}
finally{R=R0;UI.hotMap=hot;}
cuts.sort((a,b)=>b.g-a.g);
const n1=goal&&units.length>0&&!cuts.length,cheap=!P.budget||spend<=P.budget;
const e={flows,del,tw,goal,spend,cheap,n1,weak:cuts.map(x=>x.u),worst:cuts[0]||null,peak,stars:goal?1+(cheap?1:0)+(n1?1:0):0};
UI.pzEv={sig,e};return e;}
// ---------- the seeded weekly puzzle: the same for everyone, and the stand-in when the published one (93-puzzles-weekly.js) is not there ----------
function pzWeekly(dt){const key=pzWeekKey(dt||new Date());let r=hstr('puzzle|'+key)||1;const nx=()=>{r=(Math.imul(r,1103515245)+12345)>>>0;return r/4294967296;};
const pool=PZ_WEEK_POOLS[Math.floor(nx()*PZ_WEEK_POOLS.length)].slice(),n=4+Math.floor(nx()*2),cities=[];
while(cities.length<n&&pool.length)cities.push(pool.splice(Math.floor(nx()*pool.length),1)[0]);
// The budget is a ring through the cities, nearest first, on the cheapest 10G route of each hop, plus 10%. 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), and three stars are always possible.
// 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);}
return {id:'weekly',key,cities,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring,refVia:via};}
const g=Math.floor(9/(n-1)),dem=cities.slice(1).map(c=>({t:'eye',a:c,g}));
return {id:'weekly',key,cities,src:[cities[0]],dem,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring,refVia:via};}
function pzStreak(p,key){const st=p.streak;if(st.last===key)return;st.n=st.last&&st.last===pzPrevKey(key)?st.n+1:1;st.last=key;st.best=Math.max(st.best,st.n);}
function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==='weekly'?P.key:pzName(pzDef(P.id)),stars:pzStarStr(e.stars),spend:fmt$(e.spend)});}
// ---------- entering and leaving ----------
@ -85,16 +117,18 @@ const pzToastsClear=()=>{$('toasts').textContent='';};
// (leaving the page mid-puzzle), and leaving the puzzle picks it up again.
function pzFlush(){save(true);UI.pzKeep=S;}
function pzBegin(def){if(!def)return;
const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null;
S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null};
UI.pzHist=[];UI.pzTop=0;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null;
const go=()=>{const cs=pzCities(def);newGame(pzName(def),cs[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null;
S.pz={id:def.id,key:def.key||null,cities:cs,src:(def.src||[]).slice(),dem:def.dem.map(f=>({t:f.t,a:f.a,b:f.t==='l2'?f.b:null,g:f.g,ms:f.ms||0,be:!!f.be})),
via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null};
pzDemand();
UI.pzHist=[];UI.pzTop=0;UI.pzEv=null;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null;
$('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz');
compute();pzCam();renderAll();track('puzzle_'+def.id);
toast(`<b>${esc(pzName(def))}</b><br>${tr('puzzles.connect_list',{list:def.cities.map(c=>CITY[c].name).join(', ')})}`,'goal');};
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(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null;
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
// It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told.
@ -106,8 +140,7 @@ function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].
const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150);
cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();}
// ---------- building ----------
function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links}));if(h.length>60)h.shift();}
const pzNewPop=()=>({day:0,bb:null,boost:0,down:0,routers:1,gen:false});
function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();}
function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null;
compute();renderAll();pzCheck();}
// Stars count the moment they are earned: a better result than this attempt has had opens the results card.

View file

@ -41,18 +41,29 @@ function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l
for(const k of need){const t=PZ_WK_P[k],v=own(p,k)?p[k]:undefined;
if(t==='c'&&pzCityOk(v))out[k]=v;else if(t==='r'&&typeof v==='string'&&own(WAVE_NAME,v))out[k]=v;else if(t==='n'&&Number.isInteger(v)&&v>0&&v<1000)out[k]=v;else return null;}
return {l:o.l,p:out};}
const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref'];
function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==1||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null;
const PZ_WK_FIELDS=['v','key','theme','cities','src','dem','via','avoid','budget','twist','name','joke','ref'];
// Schema 2 (puzzles with traffic): `src` the content origins, `dem` the flows ({t:'eye',a,g} eyeballs in a; {t:'l2',a,b,g,ms}
// a circuit, ms its latency cap; be:true best effort), `cities` exactly the cities they touch. Older files are refused.
const PZ_WK_V=2;
function pzWkDem(a){if(!Array.isArray(a)||a.length<1||a.length>6)return null;const out=[],eye=new Set();
for(const f of a){if(!pzObj(f)||Object.keys(f).some(k=>!['t','a','b','g','ms','be'].includes(k))||!pzCityOk(f.a)||!Number.isInteger(f.g)||f.g<1||f.g>2000)return null;
if(own(f,'be')&&f.be!==true)return null;
if(f.t==='eye'){if(own(f,'b')||own(f,'ms')||eye.has(f.a))return null;eye.add(f.a);out.push({t:'eye',a:f.a,g:f.g,be:!!f.be});}
else if(f.t==='l2'){if(!pzCityOk(f.b)||f.b===f.a||(own(f,'ms')&&!(typeof f.ms==='number'&&isFinite(f.ms)&&f.ms>=1&&f.ms<=500)))return null;out.push({t:'l2',a:f.a,b:f.b,g:f.g,ms:f.ms||0,be:!!f.be});}
else return null;}
return out;}
function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==PZ_WK_V||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null;
const T=PZ_WK_THEMES[j.theme],ids=(a,lo,hi)=>Array.isArray(a)&&a.length>=lo&&a.length<=hi&&a.every(pzCityOk)&&new Set(a).size===a.length?a.slice():null;
const cities=ids(j.cities,3,6),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2);if(!cities||!via||!avoid)return null;
const cities=ids(j.cities,2,6),src=ids(j.src==null?[]:j.src,0,3),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2),dem=pzWkDem(j.dem);if(!cities||!src||!via||!avoid||!dem)return null;
// Eyeballs need somewhere to pull from; an origin is not also a city of eyeballs.
if(dem.some(f=>f.t==='eye')&&!src.length||dem.some(f=>f.t==='eye'&&src.includes(f.a)))return null;
const d0={src,dem},cs=pzCities(d0);if(cs.length!==cities.length||!cs.every(c=>cities.includes(c)))return null;
const all=[...cities,...via,...avoid];if(new Set(all).size!==all.length)return null;
if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>1e7)return null;
const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['lat','ring','noSub','minG'].includes(k)))return null;
const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null};
if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>2e7)return null;
const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['ring','noSub'].includes(k)))return null;
const d={id:'weekly',key,theme:j.theme,cities,src,dem,via,avoid,budget:j.budget,noSub:false,ring:false};
if(own(tw,'ring')){if(tw.ring!==true)return null;d.ring=true;}
if(own(tw,'noSub')){if(tw.noSub!==true)return null;d.noSub=true;}
if(own(tw,'minG')){if(![100,400].includes(tw.minG))return null;d.minG=tw.minG;}
if(own(tw,'lat')){const l=tw.lat;if(!Array.isArray(l)||l.length!==3||!cities.includes(l[0])||!cities.includes(l[1])||l[0]===l[1]||!Number.isInteger(l[2])||l[2]<1||l[2]>500)return null;d.lat=l.slice();}
d.wn=pzWkTxt(j.name,T.names);d.wj=pzWkTxt(j.joke,T.jokes);if(!d.wn||!d.wj)return null;
return d;}
// ---------- fetching it: when Puzzles opens, never on page load ----------

View file

@ -22,7 +22,7 @@ function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return tr('action_helpers.unlo
if((l.ch||[]).length+soldSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)});
for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].cls<O.rg)return tr('action_helpers.needs_routers_with_pn_ports_or',{pn:RG[mainRG(O.rg)].pn,city:CITY[c].name});}return '';}
function bbCost(c){return 15000+CITY[c].P*20;}
function after(){if(S)purgeInc();compute();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}
function after(){if(pzOn()){pzAfter();return;}if(S)purgeInc();compute();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}
const isTablet=()=>innerWidth>760&&innerWidth<=1200;
function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();}
function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;const P=$('panel');if(P)P.classList.remove('full');if(!S.pops[c])UI.tab='cust';renderPanel();}

View file

@ -1,3 +1,7 @@
// Can a wave of this size be lit between a and b here? Router ports and models as in the main game; a city without a
// POP yet will get a Rusty Router.
function pzWaveWhy(a,b,tier,r){if(r&&subWaveWhy(tier,r.km,r.sub))return tr('common.too_far_for_this_cable');if(!waveOk(a,b,tier))return tr('puzzles.needs_what',{what:waveNeed(tier)});return '';}
const pzPortsFree=c=>!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9;
Object.assign(ACT,{
// The puzzle list. The ruleset's title-screen door calls this.
puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();},
@ -5,27 +9,47 @@ Object.assign(ACT,{
pzWeekly:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());},
pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));},
pzLeave:()=>{if(pzOn())pzLeave();},
pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop();sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();},
pzRmPop:({city})=>{if(!pzOn()||!S.pops[city])return;pzSnap();delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);sfx('click');UI.sel=null;pzAfter();},
pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via','off'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop(city);sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();},
pzRmPop:({city})=>{if(!pzOn()||!S.pops[city])return;pzSnap();delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);prunePairMet();sfx('click');UI.sel=null;pzAfter();},
pzLinkTo:({a,b})=>{if(!pzOn()||!S.pops[a]||a===b)return;pzLinkModal(a,b);},
pzVia:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzVia=v;pzLinkModal(p.a,p.b,true);},
pzDiv:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzDiv=!!+v;pzLinkModal(p.a,p.b,true);},
pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p;if(!S.pops[a]||!['goal','via'].includes(pzKind(b)))return;
const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))return;
const same=!r.sub&&UI.pzDiv===false?S.links.find(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):null,div=!r.sub&&!same&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable);
pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop();const id=uid(),f=r.f*(div?DIVERSE:1);
S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:same?(same.trench||same.id):id,cut:0,day:0});
pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return;
const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub))return;
const why=pzWaveWhy(a,b,tier,r);if(why){toast(esc(why),'bad');sfx('err');return;}
if(!portGate(a,1)||(S.pops[b]&&!portGate(b,1)))return;
// Overland: the same trench as a link already on the pair (the one picked from, or the first), or a diverse route
// of its own. Every trench but the first runs the long way round and costs 40% more.
const lands=pzOn()&&!r.sub?S.links.filter(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):[],t0=lands.length?pzUnit(lands[0]):null;
const same=UI.pzDiv===false&&lands.length?(lands.find(l=>pzUnit(l)===UI.pzTrench)||lands[0]):null,trench=same?pzUnit(same):null,div=!!t0&&trench!==t0;
pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop(b);const id=uid(),f=r.f*(div?DIVERSE:1);
S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0});
closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();},
pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier||subWaveWhy(tier,l.km,l.sub))return;pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();},
pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);sfx('click');UI.sel=null;pzAfter();},
pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;sfx('click');pzAfter();},
pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];UI.sel=null;sfx('click');pzAfter();},
// Another link next to this one: the picker opens on the same pair, on the same route, in the same trench or a diverse one.
pzAddPar:({id,div})=>{const l=pzOn()&&S.links.find(x=>x.id===id);if(!l)return;UI.pzVia=l.cable||'land';UI.pzDiv=!!+div;UI.pzTrench=l.cable?null:pzUnit(l);
if(+div&&l.cable){const o=pzRoutes(l.a,l.b).find(x=>x.via!==l.cable&&!(S.pz.noSub&&x.sub));if(o)UI.pzVia=o.via;}
pzLinkModal(l.a,l.b,true);},
pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;}
pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();},
pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();},
// Routers: one more of the same model, one fewer, or every router in the POP swapped for another model.
pzRtAdd:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();},
pzRtRm:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}
pzSnap();p.routers--;sfx('click');pzAfter();},
pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;}
pzSnap();p.rgen=g;sfx('build');floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');pzAfter();},
// A circuit follows the metrics (the IGP's shortest path) or takes the lowest-latency path, as customers can in the main game.
pzRoute:({i,m})=>{const b=pzOn()&&S.biz.find(x=>x.id===pzFlowId(+i));if(!b||!['normal','fast'].includes(m)||b.route===m)return;pzSnap();b.route=m;sfx('click');pzAfter();},
pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();},
pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();},
pzShare:()=>{if(!pzOn())return;const t=pzShareText(pzEval());
const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'),copy=()=>{try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}};
if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}copy();track('puzzle_share');},
});
// A puzzle is its own S: a leftover main-game button (an old toast, a stale panel, a shortcut) must not build, buy or
// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. This file is the
// last of the actions, so every one is here to wrap.
const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','menu','mute','prefSet','puzzleDoor','puzzleMenu','selLink','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']);
for(const k of Object.keys(ACT))if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k)){const f=ACT[k];ACT[k]=a=>pzOn()?undefined:f(a);}
// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's
// routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone.
// This file is the last of the actions, so every one is here to wrap.
const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']);
const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']);
for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);}

View file

@ -1,62 +1,103 @@
/* ---------- puzzles: the card, the panels, the link picker, the results and the list ---------- */
const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫'};
function pzTwistTxt(t){const P=S.pz;
if(t.k==='sub')return tr('puzzles.no_subsea_cables');
if(t.k==='ring')return tr('puzzles.one_ring_through_every_pop');
if(t.k==='g')return tr('puzzles.every_link_n_g_or_more',{n:P.minG});
const [a,b,ms]=P.lat;return isFinite(t.ms)?tr('puzzles.a_to_b_under_ms_now',{a:CITY[a].name,b:CITY[b].name,ms,now:t.ms.toFixed(1)}):tr('puzzles.a_to_b_under_ms',{a:CITY[a].name,b:CITY[b].name,ms});}
// The short version, for the puzzle list.
function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;}
const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫',off:'📍'};
function pzTwistTxt(t){if(t.k==='sub')return tr('puzzles.no_subsea_cables');return tr('puzzles.one_ring_through_every_pop');}
// The short version, for the puzzle list: what has to be carried, and the twists.
function pzDemTag(d){const t=[];const eye=d.dem.filter(f=>f.t==='eye'),l2=d.dem.filter(f=>f.t==='l2');
if(eye.length)t.push(tr('puzzles.n_g_of_eyeballs',{n:fmtG(eye.reduce((a,f)=>a+f.g,0))}));if(l2.length)t.push(trn('puzzles.n_circuits',l2.length));
if(d.dem.some(f=>f.ms))t.push(tr('puzzles.latency_caps'));if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;}
// A cable carrying several of your waves is named on its own: cutting it takes them all.
const pzUnitName=u=>{const ls=S.links.filter(x=>pzUnit(x)===u),l=ls[0];return !l?'':l.cable&&ls.length>1?esc(CAB[l.cable].name):`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`;};
// Each flow on the card: what it is, how much of it arrives, and a circuit's latency against its cap.
function pzFlowRow(x){const f=x.f,ok=x.full&&x.fast,u=f.g?Math.min(1,x.g/f.g):0;
const lat=f.ms?` · <span class="${x.fast?'':'bad'}">${x.ms==null?tr('common.no_path'):x.ms.toFixed(1)+' ms'} / ${f.ms} ms</span>`:'';
return `<div class="pzf${ok?' ok':''}"><div class="kv"><span>${f.t==='l2'?'🔗':'👀'} ${esc(pzFlowName(f))}${f.be?` <span class="tag st">${tr('puzzles.best_effort')}</span>`:''}</span><b>${fmtG(x.g)} / ${fmtG(f.g)}</b></div><div class="bar ${ok?'':u>=0.999?'warn':'bad'}"><i style="width:${(u*100).toFixed(1)}%"></i></div>${lat?`<div class="meta">${tr('puzzles.latency')}${lat}</div>`:''}${f.t==='l2'?pzRouteCtl(x.i):''}</div>`;}
// A circuit's path: the metrics, or the lowest latency.
function pzRouteCtl(i){const b=S.biz.find(x=>x.id===pzFlowId(i));if(!b)return '';return `<div class="seg pzrt">${['normal','fast'].map(m=>btn(RT[m],'pzRoute',{i,m},b.route===m?'pink sm':'ghost sm')).join('')}</div>`;}
function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false;
const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack);
const star=(on,l)=>`<span class="${on?'on':''}">⭐<small>${l}</small></span>`;
let h=`<div class="grab" data-grab="pz" aria-hidden="true"></div><div class="pzh"><div class="grow"><div class="eyebrow">${pk?esc(pk.n):P.theme&&own(PZ_WK_THEMES,P.theme)?`${PZ_WK_THEMES[P.theme].i} ${tr('puzzles.weekly_puzzle')} · ${tr(PZ_WK_THEMES[P.theme].t)}`:tr('puzzles.weekly_puzzle')}</div><h3>${esc(pzName(d||P))}</h3></div>${btn('☰','puzzleMenu',{},'ghost sm')}</div>`;
if(d)h+=`<p class="pzj">${esc(d.j)}</p>`;else if(P.wj)h+=`<p class="pzj">${esc(pzTxt(P.wj))}</p>`;
h+=`<div class="pzs">${star(e.goal,tr('puzzles.goal'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}</div>`;
// ○ still to reach, ◐ has a POP, ✓ joined up. A leading mark, so nothing looks cut off.
h+=`<div class="pzck">${e.marks.map(m=>`<span class="pzc s${m.st}"><i aria-hidden="true">${m.st===2?'✓':m.st===1?'◐':'○'}</i> ${esc(CITY[m.c].name)}</span>`).join('')}</div>`;
h+=`<div class="pzs">${star(e.goal,tr('puzzles.delivered'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}</div>`;
if(P.src.length)h+=`<div class="pzsrc">🗄️ ${tr('puzzles.content_lives_in_list',{list:P.src.map(c=>esc(CITY[c].name)).join(', ')})}</div>`;
h+=`<div class="pzfl">${e.flows.map(pzFlowRow).join('')}</div>`;
// Cities to avoid cannot be built in at all, so they read as a rule, not as a box to tick.
for(const t of e.tw)h+=t.k==='avoid'?`<div class="pztw rule">🚫 ${tr('puzzles.rule_not_via_list',{list:P.avoid.map(c=>esc(CITY[c].name)).join(', ')})}</div>`:`<div class="pztw ${t.ok?'ok':''}">${t.ok?'✓':'✗'} ${pzTwistTxt(t)}</div>`;
const sp=fmt$(e.spend);
h+=P.budget?`<div class="pzbud"><div class="kv"><span>${tr('puzzles.spent_x_of_y',{x:sp,y:fmt$(P.budget)})}</span><b>${e.cheap?'✓':'✗'}</b></div><div class="bar ${e.cheap?(e.spend>P.budget*0.85?'warn':''):'bad'}"><i style="width:${Math.min(100,e.spend/P.budget*100).toFixed(1)}%"></i></div></div>`
:`<div class="pzbud"><div class="kv"><span>${tr('puzzles.spent_x',{x:sp})}</span><b>${tr('puzzles.no_budget_star_on_the_house')}</b></div></div>`;
h+=!e.conn?`<div class="pzn1">🛡 ${tr('puzzles.n_1_connect_everything_first')}</div>`:e.n1?`<div class="pzn1 on">🛡 ${tr('puzzles.survives_any_single_cut')}</div>`:`<div class="pzn1 bad">⚠️ ${tr('puzzles.one_cut_splits_it_where',{where:pzUnitName(e.weak[0])})}${pzOneMore(e)?`<br><small>${tr('puzzles.so_close_one_more_link_and')}</small>`:''}</div>`;
const w=e.worst;
h+=!e.goal?`<div class="pzn1">🛡 ${tr('puzzles.n_1_deliver_everything_first')}</div>`:e.n1?`<div class="pzn1 on">🛡 ${tr('puzzles.survives_any_single_cut_under_load')}</div>`
:`<div class="pzn1 bad">⚠️ ${tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(w.u),g:fmtG(w.g)})}<br><small>${w.lost.map(x=>esc(pzFlowName(P.dem[x.i]))).join(', ')}</small></div>`;
h+=`<div class="btns">${btn('↶ '+tr('puzzles.undo'),'pzUndo',{},'ghost sm',!(UI.pzHist&&UI.pzHist.length))}${btn(tr('puzzles.reset'),'pzReset',{},'ghost sm',!S.links.length&&!Object.keys(S.pops).length)}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}</div>`;
if(h!==UI._pzh){UI._pzh=h;morph(el,h);}}
// Trenches on a pair get numbers, cables their names, so parallel links say where they run.
function pzTrench(l){if(l.cable)return esc(CAB[l.cable].name);const us=[...new Set(pairLinks(l.a,l.b).filter(x=>!x.cable).map(pzUnit))];return tr('puzzles.trench_n',{n:us.indexOf(pzUnit(l))+1});}
const pzLoadTxt=l=>`${fmtG(R.load[l.id]||0)} / ${fmtG(capOf(l))}`;
function pzPopSection(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1,G=RG[g],cap=nodeCap(c),ld=R.nodeLoad[c]||0,u=cap?ld/cap:0,pu=portsUsed(c),pm=portsMax(c),cur=pzRtCost(g,rt);
const dl=v=>(v>=0?'+':'−')+fmt$(Math.abs(v));
let h=`<h3>${tr('puzzles.your_pop')}</h3><div class="kv"><span>${rt>1?rt+' × ':''}${esc(G.n)}</span><b>${tr('puzzles.price_per_year',{price:fmt$(cur)})}</b></div>
<div class="kv"><span>${tr('puzzles.router_load')}</span><b>${fmtG(ld)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100).toFixed(1)}%"></i></div>
<div class="kv"><span>${tr('puzzles.ports')}</span><b>${tr('puzzles.u_of_m_used',{u:fmtPorts(pu),m:pm})}</b></div><div class="kv"><span>${tr('puzzles.biggest_wave')}</span><b>${LT[G.maxLT].n}</b></div>
<div class="btns">${btn(tr('puzzles.add_a_router_cost',{cost:dl(pzRtCost(g,rt+1)-cur)}),'pzRtAdd',{city:c},'sm',rt>=RMAX)}${rt>1?btn(tr('puzzles.remove_a_router'),'pzRtRm',{city:c},'ghost sm'):''}</div>
<h4 class="sub4">${tr('puzzles.router_model')}</h4>`;
h+=PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i);return `<div class="row${i===g?' on':''}"><div class="grow"><div class="nm">${esc(M.n)}${i===g?` <span class="tag st on">${tr('puzzles.installed')}</span>`:''}</div><div class="meta">${tr('puzzles.model_facts',{cap:fmtG(M.cap),ports:M.ports,wave:LT[M.maxLT].n})}</div>${why?`<div class="why">${esc(why)}</div>`:''}</div>${i===g?'':btn(dl(pzRtCost(i,rt)-cur),'pzRtModel',{city:c,g:i},'ghost sm',!!why)}</div>`;}).join('');
return h;}
function pzPanel(sel){const head=(eb,name,facts)=>`<div class="ph"><div style="min-width:0"><div class="eyebrow">${eb}</div><h2>${name}</h2>${facts?`<div class="facts">${facts}</div>`:''}</div><button class="x" data-act="closePanel" aria-label="${tr('common.close')}">×</button></div>`;
if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c];if(!k)return '';
const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):tr('puzzles.off_limits');
if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c],P=S.pz;if(!k)return '';
const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):k==='off'?tr('puzzles.not_in_the_plan'):tr('puzzles.off_limits');
let h=head(`${PZ_ICON[k]} ${eb}`,esc(C.name),p?`<span class="fact mine">${tr('common.your_pop')}</span>`:'')+'<div class="scroll">';
if(k==='avoid')return h+`<p class="lead">${tr('puzzles.not_this_one_find_a_way_around')}</p></div>`;
if(!p)h+=`<p class="lead">${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}</p><div class="btns">${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}</div>`;
else{const others=[...S.pz.cities,...S.pz.via].filter(x=>x!==c);
h+=`<p class="lead">${tr('puzzles.drag_from_this_pop_onto_another')}</p><h3>${tr('puzzles.lease_a_wave_to')}</h3><div class="seg">${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}</div>`;
const ls=S.links.filter(l=>l.a===c||l.b===c);if(ls.length)h+=`<h3 style="margin-top:10px">${tr('common.links')}</h3>`+ls.map(l=>`<div class="row"><div class="grow"><div class="nm">${esc(CITY[l.a===c?l.b:l.a].name)}</div><div class="meta">${capName(l)} · ${linkLat(l).toFixed(1)} ms</div></div>${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}</div>`).join('');
h+=`<div class="btns" style="margin-top:10px">${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}</div>`;}
// What this city sends or asks for.
const fl=P.dem.map((f,i)=>({f,i})).filter(({f})=>f.a===c||f.b===c),ev=pzEval();
if(P.src.includes(c))h+=`<p class="lead">🗄️ ${tr('puzzles.the_content_origin_lives_here')}</p>`;
if(fl.length)h+=`<div class="pzfl">${fl.map(({i})=>pzFlowRow(ev.flows[i])).join('')}</div>`;
if(k==='off'&&!p)h+=`<p class="note">${tr('puzzles.no_traffic_starts_or_ends_here')}</p>`;
if(!p)return h+`<p class="lead">${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}</p><div class="btns">${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}</div></div>`;
h+=pzPopSection(c);
// Every pair this POP has links on, with what each member carries, so a second link is never a guess.
const nb=[...new Set(S.links.filter(l=>l.a===c||l.b===c).map(l=>l.a===c?l.b:l.a))];
h+=`<h3 style="margin-top:10px">${tr('common.links')}</h3>`;
if(!nb.length)h+=`<p class="note">${tr('puzzles.drag_from_this_pop_onto_another')}</p>`;
for(const x of nb){const ls=pairLinks(c,x),ld=ls.reduce((a,l)=>a+(R.load[l.id]||0),0),cp=ls.filter(l=>!linkDown(l)).reduce((a,l)=>a+capOf(l),0);
h+=`<div class="pzpair"><div class="kv"><span><b>${esc(CITY[x].name)}</b> · ${groupLabel(ls,ls)}</span><b>${fmtG(ld)} / ${fmtG(cp)}</b></div>${ls.map(l=>`<div class="row"><div class="grow"><div class="meta">${capName(l)} · ${pzTrench(l)}${l.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(l)} · ${linkLat(l).toFixed(1)} ms</div></div>${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}</div>`).join('')}</div>`;}
const others=[...P.cities,...P.via].filter(x=>x!==c);
h+=`<h3 style="margin-top:10px">${tr('puzzles.lease_a_wave_to')}</h3><div class="seg">${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}</div><p class="note">${tr('puzzles.or_drag_to_any_city_on_the_map')}</p>`;
h+=`<div class="btns" style="margin-top:10px">${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}</div>`;
return h+'</div>';}
const l=S.links.find(x=>x.id===sel.id);if(!l)return '';
const l=S.links.find(x=>x.id===sel.id);if(!l)return '';const pl=pairLinks(l.a,l.b);
let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`<span class="fact">${capName(l)}</span><span class="fact">${l.km.toLocaleString()} km</span><span class="fact">${linkLat(l).toFixed(1)} ms</span><span class="fact">${tr('puzzles.price_per_year',{price:fmt$(l.mo*PZ_YEAR)})}</span>`)+'<div class="scroll">';
h+=`<h3>${tr('puzzles.size')}</h3><div class="seg">${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=subWaveWhy(i,l.km,l.sub);return btn(`${LT[i].n} <small>${tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}</small>`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}</div>`;
// What it carries now: each circuit by name, the eyeball traffic by where it is going.
{const rec=R.ef[edgeKey(l)],u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;h+=`<div class="kv"><span>${tr('puzzles.this_link')}</span><b>${pzLoadTxt(l)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100).toFixed(1)}%"></i></div>`;
if(rec){const rows=[];let l2=0;S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){rows.push([pzFlowName(f),v]);}});
const byc={};for(const k in rec.dst)byc[k]=rec.dst[k];S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){byc[f.b]=(byc[f.b]||0)-v;l2+=v;}});
for(const k in byc)if(byc[k]>0.01)rows.push([tr('puzzles.flow_eyeballs_in_city',{city:CITY[k].name}),byc[k]]);
if(rows.length)h+=`<h4 class="sub4">${pl.length>1?tr('puzzles.carrying_on_this_pair',{n:pl.length}):tr('puzzles.carrying')}</h4>`+rows.map(([n,v])=>`<div class="kv"><span>${esc(n)}</span><b>${fmtG(v)}</b></div>`).join('');void l2;}}
if(pl.length>1)h+=`<h4 class="sub4">${tr('puzzles.n_links_on_this_pair',{n:pl.length,what:groupLabel(pl,pl)})}</h4>`+pl.map(x=>`<div class="row${x===l?' on':''}"><div class="grow"><div class="meta">${capName(x)} · ${pzTrench(x)}${x.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(x)}</div></div>${x===l?'':btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}</div>`).join('');
h+=`<h3>${tr('puzzles.size')}</h3><div class="seg">${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=pzWaveWhy(l.a,l.b,i,r);return btn(`${LT[i].n} <small>${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}</small>`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}</div>`;
h+=`<h4 class="sub4">${tr('puzzles.add_another_link_here')}</h4><div class="btns">${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}</div>`;
h+=metricSection(l)+linkCheckControl(l);
return h+`<div class="btns" style="margin-top:10px">${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}</div></div>`;}
// The link picker: overland or one of the real cables between the two cities, and a size. Prices are for a year.
function pzLinkModal(a,b,keep){const kb=pzKind(b);
if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.that_city_is_not_part_of'),'bad');sfx('err');return;}
if(!keep){UI.pzVia=null;UI.pzDiv=true;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz;
if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;}
if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz;
const head=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${kmBetween(a,b).toLocaleString()} km</div><h2 style="font-size:26px">${esc(CITY[a].name)} → ${esc(CITY[b].name)}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>`;
if(!rs.length){openModal(head+`<p class="lead" style="margin-top:10px">${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}</p>`);return;}
const r=rs.find(x=>x.via===UI.pzVia)||rs.find(x=>!(P.noSub&&x.sub))||rs[0];UI.pzVia=r.via;
const land=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b);
let h=head+`<h4 class="sub4">${tr('common.route')}</h4><div class="seg">${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} <small>${x.ms.toFixed(1)} ms${x.cab&&CAB[x.cab].age==='old'?'':''}</small>`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}</div>`;
const pl=pairLinks(a,b),land=!r.sub&&pl.some(l=>!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b);
let h=head;
if(pl.length)h+=`<p class="pzhave">${tr('puzzles.already_here_list',{list:groupLabel(pl,pl)+' · '+[...new Set(pl.map(pzTrench))].join(', ')})}</p>`;
h+=`<h4 class="sub4">${tr('common.route')}</h4><div class="seg">${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} <small>${x.ms.toFixed(1)} ms${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}</small>`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}</div>`;
if(P.noSub&&r.sub)h+=`<p class="why">${tr('puzzles.the_sharks_say_no')}</p>`;
if(r.cab)h+=`<p class="note">${esc(CAB[r.cab].blurb)}</p>`;
if(r.cab)h+=`<p class="note">${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}</p>`;
if(land)h+=`<div class="seg" style="margin-top:8px">${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}</div>`;
if(pop)h+=`<p class="lead" style="margin-top:8px">${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}</p>`;
h+=`<div class="tiers">${PZ_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),c=pzLinkCost(r,i,div)+pop;return `<button class="tierbtn" data-act="pzLink" data-args='{"tier":${i}}'${why||(P.noSub&&r.sub)?' disabled':''}><span class="sz">${LT[i].n}</span><span class="grow meta">${why?tr('common.too_far_for_this_cable'):pop?tr('puzzles.with_the_pop_price',{price:fmt$(c)}):''}</span><span class="pr num">${tr('puzzles.price_per_year',{price:fmt$(pzLinkCost(r,i,div))})}</span></button>`;}).join('')}</div>`;
const full=[a,b].filter(c=>!pzPortsFree(c));if(full.length)h+=`<p class="why">${tr('puzzles.no_free_ports_in_list',{list:full.map(c=>esc(CITY[c].name)).join(', ')})}</p>`;
h+=`<div class="tiers">${PZ_TIERS.map(i=>{const why=pzWaveWhy(a,b,i,r),c=pzLinkCost(r,i,div)+pop;return `<button class="tierbtn" data-act="pzLink" data-args='{"tier":${i}}'${why||full.length||(P.noSub&&r.sub)?' disabled':''}><span class="sz">${LT[i].n}</span><span class="grow meta">${why?esc(why):pop?tr('puzzles.with_the_pop_price',{price:fmt$(c)}):''}</span><span class="pr num">${tr('puzzles.price_per_year',{price:fmt$(pzLinkCost(r,i,div))})}</span></button>`;}).join('')}</div>`;
openModal(h);}
// ---------- results ----------
function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?(pzOneMore(e)?tr('puzzles.so_close_one_more_link_and'):tr('puzzles.one_backhoe_away_from_a_very')):tr('puzzles.rock_solid_and_gold_plated_the');}
function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?tr('puzzles.one_backhoe_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');}
// Stars still to win in this puzzle's pack, from the progress just saved.
function pzPackLeft(P){const d=pzDef(P.id);if(!d)return null;const p=pzLoad(),xs=PZ.filter(x=>x.pack===d.pack);return xs.length*3-xs.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);}
function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h='';
@ -67,7 +108,7 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left
const stars=[0,1,2].map(i=>`<span class="pzbig${i<e.stars?' on':''}${i>=prev&&i<e.stars?' pop':''}" style="--d:${Math.max(0,i-prev)*0.45}s">⭐</span>`).join('');
openModal(`<div class="pzres">${e.stars>=3?pzConfetti():''}<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">${tr('puzzles.puzzle_solved')}</div><h2 style="font-size:28px">${esc(pzName(pzDef(P.id)||P))}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<div class="pzstars">${stars}</div><p class="tagline" style="text-align:center">${pzLine(e)}</p>${left==null?'':`<p class="pzleft">${left?trn('puzzles.n_stars_left_in_this_pack',left):tr('puzzles.every_star_in_this_pack_is')}</p>`}
${row(true,tr('puzzles.goal'),tr('puzzles.connected'))}${row(e.cheap,tr('puzzles.budget'),P.budget?tr('puzzles.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):tr('puzzles.on_the_house'))}${row(e.n1,'N-1',e.n1?tr('puzzles.survives_any_single_cut'):tr('puzzles.one_cut_splits_it'))}
${row(true,tr('puzzles.delivered'),tr('puzzles.every_bit_arrives'))}${row(e.cheap,tr('puzzles.budget'),P.budget?tr('puzzles.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):tr('puzzles.on_the_house'))}${row(e.n1,'N-1',e.n1?tr('puzzles.survives_any_single_cut_under_load'):tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(e.worst.u),g:fmtG(e.worst.g)}))}
<div class="btns cta${done?' pzdone':''}" style="margin-top:12px">${nx?btn(tr('puzzles.next_puzzle')+(done?' →':''),'pzStart',{id:nx.id},'pink big pznext'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big pznext')}${!done?btn(tr('puzzles.retry_for_3_stars'),'pzRetry',{},''):''}${btn(tr('common.share_2cd9'),'pzShare',{},done?'ghost':'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}</div></div>`);
// Three stars: Next is the one big obvious tap (and the keyboard's default).
if(done){const b=document.querySelector('#modalCard .pznext');if(b)try{b.focus({preventScroll:true});}catch(_){}}
@ -75,19 +116,21 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left
if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);}
// ---------- the list ----------
// The weekly row: the published puzzle once it has come (or the seeded one), its countdown and the streak.
function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzTwistTag(w);
function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzDemTag(w);
return `<div class="scn wk" id="pzWk"><div class="grow"><div class="eyebrow">📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` <span class="pznew">${tr('puzzles.new_this_sunday')}</span>`}</div>
<div class="nm">${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`<span class="pzst">${pzStarStr(wr.st)}</span>`:''}</div>${w.wj?`<div class="meta">${esc(pzTxt(w.wj))}</div>`:''}
<div class="meta">${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · <b>'+tg.join(' · ')+'</b>':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}</div>
<div class="meta">${pzCities(w).map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · <b>'+tg.join(' · ')+'</b>':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}</div>
<div class="meta">${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}</div><div class="meta pzcd">⏳ ${pzWkNext(Date.now())}</div></div>${btn(tr('common.play'),'pzWeekly',{},wr&&wr.st>=3?'ghost':'pink',load)}</div>`;}
function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot);
let h=`<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">${tr('puzzles.puzzles')}</div><h2 style="font-size:28px">${tr('puzzles.small_calm_network_builds')}</h2></div><button class="x" data-act="helpClose" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('puzzles.no_clock_no_bills_nothing_breaks')}</p>
<div class="pzprog"><div class="kv"><span>${tr('puzzles.your_stars')}</span><b>⭐ ${tot} / ${max}</b></div><div class="bar me"><i style="width:${(tot/max*100).toFixed(1)}%"></i></div>${nxP?`<div class="meta">${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}</div>`:''}</div>`;
let h=`<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">${tr('puzzles.puzzles')}</div><h2 style="font-size:28px">${tr('puzzles.small_networks_real_traffic')}</h2></div><button class="x" data-act="helpClose" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('puzzles.no_clock_no_bills_real_traffic')}</p>`;
// Once, after the puzzles got traffic: the old stars are kept on the wall, the new set starts at zero.
if(p.old&&!p.noted){h+=`<div class="pznote">🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}</div>`;p.noted=1;pzStore(p);}
h+=`<div class="pzprog"><div class="kv"><span>${tr('puzzles.your_stars')}</span><b>⭐ ${tot} / ${max}</b></div><div class="bar me"><i style="width:${(tot/max*100).toFixed(1)}%"></i></div>${nxP?`<div class="meta">${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}</div>`:''}${p.old?`<div class="meta">🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}</div>`:''}</div>`;
if(pzOn())h+=`<div class="btns" style="margin:8px 0">${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}</div>`;
h+=pzWkRow();
for(const pk of PZ_PACKS){const open=tot>=pk.need,got=PZ.filter(x=>x.pack===pk.id).reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0),n=PZ.filter(x=>x.pack===pk.id).length;
h+=`<h3 class="pzpack">${open?'':'🔒 '}${esc(pk.n)} <span class="meta">⭐ ${got}/${n*3}</span></h3><p class="meta" style="margin:0 0 2px">${open?esc(pk.d):tr('puzzles.unlocks_at_n_stars',{n:pk.need})}</p>`;
for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzTwistTag(d);
h+=`<div class="scn${open?'':' lock'}"><div class="grow"><div class="nm">${esc(d.n)} <span class="pzst">${pzStarStr(r?r.st:0)}</span></div><div class="meta">${esc(d.j)}</div><div class="meta">${d.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · <b>'+tg.join(' · ')+'</b>':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}</div></div>${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}</div>`;}}
for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzDemTag(d);
h+=`<div class="scn${open?'':' lock'}"><div class="grow"><div class="nm">${esc(d.n)} <span class="pzst">${pzStarStr(r?r.st:0)}</span></div><div class="meta">${esc(d.j)}</div><div class="meta">${pzCities(d).map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · <b>'+tg.join(' · ')+'</b>':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}</div></div>${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}</div>`;}}
openModal(h);}

View file

@ -28,7 +28,7 @@ function drawFrame(now){
const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY;
for(let gi=0;gi<LG.length;gi++){const grp=LG[gi],l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
const gm=GM[gi],cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby);
const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);let lab=null;
const pz=pzOn(),sel=(UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id))||(pz&&pzLinkHot(grp));let lab=null;
const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length;
if(SX.length<np){SX=new Float64Array(np*2);SY=new Float64Array(np*2);}
for(const k of ks){
@ -50,7 +50,7 @@ function drawFrame(now){
const [mx2,my]=at(.5);const mxx=mx2;
if(bld){if(far){ctx.fillStyle='#FF8A3D';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,4,0,7);ctx.fill();ctx.stroke();}else drawCone(mxx,my,now);}
else if(cut&&!vx){if(far){ctx.fillStyle='#FF4D5E';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,5,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',mxx,my+0.5);}else drawBackhoe(mxx,my,now,l.sub);}
else if(sel||(z>0.9&&!busy)){const t=lab||(lab=many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
else if(sel||pz||(z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
}
}
// drag preview

View file

@ -1,10 +1,16 @@
/* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring, stepping stones with a dashed one, cities to
avoid crossed out); every other city stays on the map, faded and untappable. */
/* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring and a badge for what they send or ask for,
stepping stones with a dashed one, cities to avoid crossed out); every other city is on the map as usual, open to
build in but not emphasised. */
function pzBadge(c){const P=S.pz;return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';}
function pzDrawCity(v,sc,now){const k=pzKind(v.C.id);
if(!k){ctx.save();ctx.globalAlpha=0.3;drawCity(v.C,v.sx,v.sy,sc,now,null);ctx.restore();return;}
if(!k||k==='off'){drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);return;}
const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id];
ctx.save();ctx.lineWidth=3;
if(k==='avoid'){ctx.strokeStyle='#FF4D5E';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.moveTo(v.sx-r*.7,y-r*.7);ctx.lineTo(v.sx+r*.7,y+r*.7);ctx.stroke();}
else{const a=animOn()?.55+.35*Math.sin(now/300):.8;ctx.strokeStyle=k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(k==='via')ctx.setLineDash([5,5]);
ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);}
ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);}
ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);
const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx+r*.75,y-r*.75);}}
// In a puzzle every line says what it is ("2×100G · 70%"), and a selected POP lights up every pair it has links on.
function pzLinkLab(grp,up,load,cap){return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');}
const pzLinkHot=grp=>!!(UI.sel&&UI.sel.type==='city'&&grp.some(x=>x.a===UI.sel.id||x.b===UI.sel.id));