From 644e6174d9483fdd777980de721db77acea7d5e2 Mon Sep 17 00:00:00 2001 From: tkjaer Date: Fri, 30 Oct 2026 08:01:42 +0100 Subject: [PATCH] Architect runs (prototype): one network, built brief by brief Three runs (Euro Run, Coast to Coast, Pacific Rim) on the puzzle machinery: briefs add sites, raise demand, make sites gold, ask for rings or latency caps, or close a city; earlier builds stay paid for, and the backhoe review cuts every trench and cable in turn. By tkjaer, from seriesoftubes-architect. --- src/game/60-features/92-puzzles.js | 14 +-- src/game/60-features/96-architect.js | 163 +++++++++++++++++++++++++++ src/game/90-actions/95-puzzles.js | 34 +++--- src/game/90-actions/96-architect.js | 8 ++ src/game/94-dashboard/80-hint.js | 2 +- src/game/95-modals/95-puzzles.js | 7 +- src/game/95-modals/96-architect.js | 82 ++++++++++++++ src/game/96-map/50-link-geometry.js | 4 +- src/game/96-map/60-draw.js | 6 +- src/game/96-map/70-world-layer.js | 6 +- src/game/96-map/85-puzzle-cities.js | 10 +- src/game/96-map/95-clicks.js | 2 +- src/i18n/en.js | 113 +++++++++++++++++++ src/styles/71-architect.css | 28 +++++ tests/architect.test.js | 149 ++++++++++++++++++++++++ 15 files changed, 588 insertions(+), 40 deletions(-) create mode 100644 src/game/60-features/96-architect.js create mode 100644 src/game/90-actions/96-architect.js create mode 100644 src/game/95-modals/96-architect.js create mode 100644 src/styles/71-architect.css create mode 100644 tests/architect.test.js diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index c840b9f..201d9bc 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -11,7 +11,7 @@ const pzOn=()=>!!(S&&S.mode==='puzzle'&&S.pz); const pzDef=id=>PZ.find(p=>p.id===id)||null; // goal: a city the traffic starts or ends in; via: a suggested stepping stone; avoid: off limits; off: any other city // (the whole world is open, it just is not part of the plan). -const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)?'off':null; +const pzKind=c=>!pzOn()?null:S.ar?arKind(c):S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)?'off':null; const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key',{key:d.key})):d.n; const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n); // Every city a puzzle's traffic touches, origins first. @@ -64,7 +64,7 @@ const pzFlowName=f=>f.t==='l2'?tr('puzzles.flow_circuit_a_b',{a:CITY[f.a].name,b function pzDemand(){const P=S.pz;S.transit=P.src.map((c,i)=>({id:'pzo'+i,city:c,net:PZ_NET,tier:PZ_ORIG,n:1,pz:1,pref:'normal',hist:[]})); S.biz=P.dem.map((f,i)=>f.t==='l2'?{id:pzFlowId(i),type:'l2vpn',name:pzFlowName(f),city:f.a,city2:f.b,bw:f.g,rate:0,route:'normal',reqs:[],day:0}:null).filter(Boolean);} const pzEye=c=>{const f=pzOn()&&S.pz.dem.find(x=>x.t==='eye'&&x.a===c);return f?f.g:0;}; -const pzNewPop=c=>{const g=pzEye(c);return {day:0,bb:g?{d:g}:null,boost:0,down:0,routers:1,gen:false};}; +const pzNewPop=c=>{const g=pzEye(c);return {day:0,bb:g?{d:g}:null,boost:0,down:0,routers:1,gen:false,br:S.ar?S.ar.bi:0};}; // What each flow gets from the last compute(): Gbps delivered, and a circuit's latency. // Eyeball traffic to networks behind the Great Firewall loses a fifth at the border, as in the main game; that is not // the player's doing, so a puzzle counts what crosses the border as delivered (pzGfw: the share that arrives). @@ -130,7 +130,7 @@ function pzBegin(def){if(!def)return; if(pzOn()){go();return;} const live=!!(S&&UI.started&&!S.lost);UI.pzFrom=live?'game':'title'; if(live)pzFlush();go();} -function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; +function pzLeave(){if(S&&S.ar)arStop(true);const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. @@ -139,17 +139,17 @@ function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList. // The camera frames the puzzle's cities beside the puzzle card: left on wide screens, right on phones on their side, a bottom sheet on phones. function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity; for(const C of cs){const x=x0+wrapDx(x0,C.x);a=Math.min(a,x);b=Math.max(b,x);c=Math.min(c,C.y);d=Math.max(d,C.y);} - const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); + const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:S.ar&&CW>760&&CH>500?410:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} // ---------- building ---------- -function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();} +function pzSnap(){if(S.ar)arStop();const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route),k:S.ar?S.ar.sunk:0}));if(h.length>60)h.shift();} function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null; - compute();renderAll();pzCheck();} + if(S.ar)arRouters();compute();renderAll();pzCheck();} // Stars count the moment they are earned. // Every solved state is recorded, so a cheaper build at the same stars counts too. // A new star below three is a cheer and a nudge, and play goes on; the results card opens at three stars, or when the // player says they are done (the card's Finish button). -function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}return e;} +function pzCheck(){if(arOn())return null;const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}return e;} // The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend. function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null}; if(e.starspzOn()&&!!S.ar; +const arRunDef=id=>AR_RUNS.find(r=>r.id===id)||null; +const arRun=()=>arRunDef(S.ar.id); +const arBrief=()=>arRun().briefs[S.ar.bi]; +const arLast=()=>S.ar.bi>=arRun().briefs.length-1; +// ---------- progress: best stars, spend and briefs cleared per run, under its own key ---------- +function arLoad(){let j=null;try{j=JSON.parse(localStorage.getItem(AR_KEY)||'{}');}catch(e){}const o={runs:{}}; + if(j&&j.runs&&typeof j.runs==='object')for(const k of Object.keys(j.runs)){const r=j.runs[k];if(!arRunDef(k)||!r||typeof r!=='object')continue; + o.runs[k]={st:int(r.st,0,3,0),br:int(r.br,0,99,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)};} + return o;} +function arStore(p){try{localStorage.setItem(AR_KEY,JSON.stringify(p));}catch(e){}} +function arRecord(st,br,sp){const p=arLoad(),r=p.runs[S.ar.id]||{st:0,br:0,sp:null}; + if(st>r.st||(st===r.st&&st>0&&(r.sp==null||sppzPopCost(c)+pzRouterCost(c); +const arLinkCost=l=>l.mo*PZ_YEAR; +const arSpend=()=>pzSpend()+S.ar.sunk; +// Removing what an earlier brief built gives nothing back. +const arAge=l=>l.ub==null?(l.br|0):l.ub; +function arSink(pops,links){const A=S.ar;for(const c of pops)if(S.pops[c]&&(S.pops[c].br|0)pzUnit(l)===u),r=arReach(S.ar.hq,nb);return S.pz.cities.filter(c=>S.pops[c]&&!r.has(c));} +// The fastest path between two sites, by the links' own latency. +function arLat(a,b){if(!S.pops[a]||!S.pops[b])return null;const d={[a]:0},done=new Set(); + for(;;){let u=null;for(const k in d)if(!done.has(k)&&(u===null||d[k]nb[c]&&nb[c].size>=2))return false;const st=cs[0],on=new Set([st]);let ok=false,n=0; + const dfs=(u,d)=>{for(const v of nb[u]){if(ok||++n>50000)return;if(v===st&&d>=3&&cs.every(c=>on.has(c))){ok=true;return;}if(on.has(v))continue;on.add(v);dfs(v,d+1);on.delete(v);}}; + dfs(st,1);return ok;} +// Tubes laid in this brief, against its plan. +const arTubes=()=>{const b=arBrief(),u=S.links.filter(l=>(l.br|0)===S.ar.bi).length;return {u,max:b.tubes==null?null:b.tubes,over:b.tubes==null?0:Math.max(0,u-b.tubes)};}; +// ---------- the brief's checklist ---------- +function arEval(){const A=S.ar,P=S.pz,nb=arAdj(),r=arReach(A.hq,nb); + const got=S.links.some(l=>l.cut)&&UI.arBaseGot?UI.arBaseGot:arGot(); + const sites=P.cities.map(c=>({c,pop:!!S.pops[c],ok:!!S.pops[c]&&r.has(c),gold:A.gold.includes(c),hq:c===A.hq,dem:c===A.hq?0:arDem(c),got:c===A.hq?0:got[c]||0}));for(const s of sites)s.full=s.hq||s.got>=s.dem*0.999-1e-6; + const conn=sites.every(s=>s.ok),lat=A.lat?{a:A.lat[0],b:A.lat[1],cap:A.lat[2],ms:arLat(A.lat[0],A.lat[1])}:null;if(lat)lat.ok=lat.ms!=null&&lat.ms<=lat.cap+1e-9; + const moveOut=P.avoid.filter(c=>S.pops[c]),spend=arSpend(),budget=arRun().budget,cheap=spend<=budget+1e-6,miss=sites.filter(s=>!s.ok).map(s=>CITY[s.c].name),rings=A.rings.map(cs=>({cs,ok:arRingOk(cs)})),tubes=arTubes(); + const why=!conn?tr('architect.not_connected_yet_list',{list:miss.join(', ')}):lat&&!lat.ok?tr('architect.too_slow_for_the_cap'):rings.some(r=>!r.ok)?tr('architect.not_a_ring_yet'):sites.some(s=>!s.full)?tr('architect.too_thin_list',{list:sites.filter(s=>!s.full).map(s=>`${CITY[s.c].name} ${arG(s.got)}/${arG(s.dem)}`).join(', ')}):moveOut.length?tr('architect.move_out_of_city',{city:moveOut.map(c=>CITY[c].name).join(', ')}):''; + return {sites,conn,lat,rings,tubes,moveOut,spend,budget,cheap,ready:!why,why,passed:A.passed===pzSig()};} +// ---------- the shape: the game names what you drew ---------- +const AR_SHAPES={braces:['🦺',N_('architect.shape_braces')],tube:['🧪',N_('architect.shape_tube')],line:['➖',N_('architect.shape_line')],star:['✳️',N_('architect.shape_star')],tree:['🌳',N_('architect.shape_tree')],ring:['💍',N_('architect.shape_ring')],lolli:['🍭',N_('architect.shape_lolli')],ladder:['🪜',N_('architect.shape_ladder')],mesh:['🕸️',N_('architect.shape_mesh')],full:['🧶',N_('architect.shape_full')],islands:['🏝️',N_('architect.shape_islands')],spaghetti:['🍝',N_('architect.shape_spaghetti')]}; +function arShape(){const ns=Object.keys(S.pops),n=ns.length;if(n<2||!S.links.length)return null;const nb=arAdj(),m=new Set(S.links.map(edgeKey)).size,deg=c=>nb[c].size,maxd=Math.max(...ns.map(deg)); + const dbl=[...new Set(S.links.map(edgeKey))].filter(e=>new Set(S.links.filter(l=>edgeKey(l)===e).map(pzUnit)).size>1).length; + let k;if(arReach(ns[0],nb).size=4?'star':maxd<=2?'line':'tree'; + else if(ns.every(c=>deg(c)===2))k='ring';else if(n>=4&&m===n*(n-1)/2)k='full'; + else{const core={};for(const c of ns)core[c]=new Set(nb[c]);let cut=true;while(cut){cut=false;for(const c in core)if(core[c].size<=1){for(const v of core[c])core[v]&&core[v].delete(c);delete core[c];cut=true;}} + const cs=Object.keys(core),cm=cs.reduce((a,c)=>a+core[c].size,0)/2,d2=cs.filter(c=>core[c].size===2).length; + k=cs.lengthcore[c].size===2)?'lolli':cs.length===n&&n>=6&&n%2===0&&cm===3*n/2-2&&d2===4&&cs.every(c=>core[c].size<=3)?'ladder':m>=n*1.8?'spaghetti':'mesh';} + return {k,i:AR_SHAPES[k][0],n:tr(AR_SHAPES[k][1])};} +// What later briefs do to a city, for the map: [{n: brief number, i: icon}], earliest first. +function arTags(c){const A=S.ar,out=[];arRun().briefs.forEach((b,j)=>{if(j<=A.bi)return;const i=(b.gold||[]).includes(c)?'🥇':(b.add||[]).includes(c)?'📍':(b.drop||[]).includes(c)?'🚫':b.dem&&b.dem[c]?'📈':(b.ring||[]).includes(c)?'💍':b.lat&&b.lat.slice(0,2).includes(c)?'⏱':'';if(i)out.push({n:j+1,i});});return out;} +// One line per brief for the plan on the card. +function arSum(b){const nm=c=>CITY[c].name,t=[],d=b.dem||{};if(b.add)t.push(b.add.map(c=>'+'+nm(c)+(d[c]?' '+arG(d[c]):'')).join(' '));for(const c in d)if(!(b.add||[]).includes(c))t.push('📈 '+nm(c)+' '+arG(d[c]));if(b.gold)t.push('🥇 '+b.gold.map(nm).join(', ')); + if(b.ring)t.push('💍 '+b.ring.map(nm).join('–'));if(b.lat)t.push(`⏱ ${nm(b.lat[0])}⇄${nm(b.lat[1])} < ${b.lat[2]} ms`);if(b.drop)t.push('🚫 '+b.drop.map(nm).join(', ')); + if(b.tubes!=null)t.push(trn('architect.n_tubes',b.tubes));return t.join(' · ');} +// ---------- starting, briefs and the end ---------- +const arDem=c=>S.ar.dem[c]||10; +// Short Gbps for chips and tags: 40G, 1.2T. +const arG=g=>g>=1000?+(g/1000).toFixed(1)+'T':Math.round(g)+'G'; +function arDemand(){const P=S.pz,A=S.ar;P.src=[A.hq];P.dem=P.cities.filter(c=>c!==A.hq).map(c=>({t:'eye',a:c,b:null,g:arDem(c),ms:0,be:false}));pzDemand(); + for(const c in S.pops)S.pops[c].bb=P.cities.includes(c)&&c!==A.hq?{d:arDem(c)}:null;} +// What each site gets right now, from the last compute(). +function arGot(){const g=pzGot(),o={};S.pz.dem.forEach((f,i)=>{o[f.a]=g[i].g;});return o;} +// Connected sites that do not get all of their traffic. +function arShort(dark){const got=arGot();return S.pz.cities.filter(c=>c!==S.ar.hq&&S.pops[c]&&!(dark||[]).includes(c)&&(got[c]||0)PZ_RG.slice().sort((a,b)=>pzRtCost(a,1)-pzRtCost(b,1)); +function arRouters(){for(const c in S.pops){const p=S.pops[c];p.routers=1;p.rgen=AR_RG().find(g=>!modelFits(c,g))??(p.rgen||0);}} +// The yearly router cost a tube of this size would add at a city (0 when its router already takes it). +function arRouterDelta(c,tier){const p=S.pops[c],cur=p?pzRtCost(p.rgen||0,1):0,need=Math.max(tier,...S.links.filter(l=>l.a===c||l.b===c).map(l=>l.tier)),g=AR_RG().find(i=>RG[i].maxLT>=need);return g==null?0:Math.max(0,pzRtCost(g,1)-cur);} +const arSnapStr=()=>JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},k:S.ar.sunk}); +function arBegin(run){if(!run)return;const b0=run.briefs[0]; + pzBegin({id:'ar_'+run.id,n:run.n,src:[run.hq],dem:b0.add.map(c=>({t:'eye',a:c,g:1})),via:run.via,budget:0}); + pzToastsClear();S.pz.n=run.n;S.te={on:true,day:0};S.ar={id:run.id,hq:run.hq,bi:-1,sunk:0,over:0,dem:{},rings:[],gold:[],lat:null,passed:null,start:null};UI.arAll=false;arStop(true); + S.pops[run.hq]=pzNewPop(run.hq);arApply(0);} +function arApply(i){const A=S.ar,P=S.pz,b=arRun().briefs[i];A.bi=i; + for(const c of b.drop||[]){P.cities=P.cities.filter(x=>x!==c);A.gold=A.gold.filter(x=>x!==c);if(!P.avoid.includes(c))P.avoid.push(c);if(A.lat&&A.lat.includes(c))A.lat=null;A.rings=A.rings.filter(r=>!r.includes(c));} + for(const c of b.add||[])if(!P.cities.includes(c))P.cities.push(c); + for(const c of b.gold||[])if(!A.gold.includes(c))A.gold.push(c); + if(b.ring)A.rings.push(b.ring.slice());Object.assign(A.dem,b.dem||{}); + if(b.lat)A.lat=b.lat.slice();A.passed=null; + P.via=[...new Set(arRun().briefs.slice(i+1).flatMap(x=>[...(x.add||[]),...(x.gold||[]),...(x.ring||[])]))].filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); + arDemand();A.start=arSnapStr();UI.pzHist=[];UI.sel=null;UI.arFail=null; + compute();pzCam();renderAll(); + toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}${i===0&&arRun().briefs.length>1?'
'+tr('architect.numbers_on_the_map_show')+'':''}`,'goal');sfx('click');} +function arNext(){if(!arOn())return;const e=arEval();if(!e.passed)return;if(arLast()){arResults(true);return;}S.ar.over+=e.tubes.over;arApply(S.ar.bi+1);} +function arReset(){const o=JSON.parse(S.ar.start);S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};S.ar.sunk=o.k||0;arDemand();UI.sel=null;} +// Tubes over plan in the run so far, this brief included. +const arOver=()=>S.ar.over+arTubes().over; +function arStars(sp){return 1+(arOver()?0:1)+(sp<=arRun().budget+1e-6?1:0);} +function arShareText(st,sp){const sh=arShape();return tr('architect.share_line',{what:arRun().n,stars:pzStarStr(st),spend:fmt$(sp),shape:sh?sh.i+' '+sh.n:''});} +// ---------- ▶ the backhoe review ---------- +// Every trench and cable is cut in turn, routed by compute() so the traffic visibly moves; a gold site losing HQ stops +// the review with the cut still on the map, until the next edit. +function arStop(quiet){const sh=UI.arShow;if(sh&&sh.t)clearTimeout(sh.t);UI.arShow=null;if(!S||!S.links)return;let any=false;for(const l of S.links)if(l.cut){l.cut=0;any=true;} + if(UI.arFail){UI.arFail=null;any=true;}if(any&&!quiet)compute();} +function arShowStart(){if(!arOn()||UI.arShow)return;const e=arEval();if(!e.ready){toast(esc(e.why),'bad');sfx('err');return;} + arStop(true);UI.sel=null;closeModal();UI.arBaseGot=arGot();UI.arShow={units:[...new Set(S.links.map(pzUnit))],i:-1,t:0,dark:[],short:[]};arStep();} +// One cut, routed: who goes dark, which gold sites with it, and who is still connected but short of room. +function arCut(u){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1;compute();const dark=arDark(u);return {ls,dark,gold:dark.filter(c=>S.ar.gold.includes(c)),short:arShort(dark)};} +function arStep(){const sh=UI.arShow;if(!sh||!arOn())return;for(const l of S.links)l.cut=0;sh.i++; + if(sh.i>=sh.units.length){UI.arShow=null;compute();S.ar.passed=pzSig();renderAll();sfx('star');haptic(15); + toast(`✅ ${tr('architect.review_passed')}
${arLast()?tr('architect.last_brief_done'):tr('architect.next_brief_waiting')}`,'good');if(arLast())setTimeout(()=>{if(arOn()&&S.ar.passed===pzSig())arResults(true);},900);return;} + const u=sh.units[sh.i],{ls,dark,gold,short}=arCut(u),l0=ls[0],got=arGot();sh.dark=dark;sh.short=short;sh.u=u; + floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,l0.sub?tr('architect.anchor'):tr('architect.backhoe'),'#FF8A3D'); + for(const c of dark)floater(CITY[c].x,CITY[c].y-34,gold.includes(c)?'💥 '+CITY[c].name:tr('architect.city_goes_dark',{city:CITY[c].name}),gold.includes(c)?'#FF4D5E':'#9AA3BE'); + for(const c of short)floater(CITY[c].x,CITY[c].y-34,tr('architect.city_short_g',{city:CITY[c].name,g:arG(arDem(c)-(got[c]||0))}),'#FF4D5E'); + const bad=gold.length||short.length;sfx(bad?'err':'click'); + if(bad){UI.arShow=null;UI.arFail={u,gold,dark,short};renderAll();haptic(30);return;} + renderAll();sh.t=setTimeout(arStep,dark.length?AR_STEP*1.6:AR_STEP);} +// Skip the show: check every cut at once, and stop at the first that breaks a gold site. +function arShowSkip(){const sh=UI.arShow;if(!sh)return;clearTimeout(sh.t);for(const l of S.links)l.cut=0; + for(let i=sh.i+1;i!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9; Object.assign(ACT,{ // The puzzle list. The ruleset's title-screen door calls this. puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();}, pzStart:({id})=>{const d=pzDef(id);if(!d||!pzPackOpen(d.pack))return;pzBegin(d);}, pzWeekly:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());}, - pzFinish:()=>{if(!pzOn())return;const e=pzEval();if(e.stars)pzResults(e,e.stars);}, - pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, + pzFinish:()=>{if(!pzOn())return;if(S.ar){arResults(false);return;}const e=pzEval();if(e.stars)pzResults(e,e.stars);}, + pzRetry:()=>{if(!pzOn())return;if(S.ar){arBegin(arRun());return;}pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, pzLeave:()=>{if(pzOn())pzLeave();}, pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via','off'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop(city);sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();}, - pzRmPop:({city})=>{if(!pzOn()||!S.pops[city])return;pzSnap();delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + pzRmPop:({city})=>{if(!pzOn()||!S.pops[city]||(S.ar&&city===S.ar.hq))return;pzSnap();if(S.ar)arSink([city],S.links.filter(l=>l.a===city||l.b===city));delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, pzLinkTo:({a,b})=>{if(!pzOn()||!S.pops[a]||a===b)return;pzLinkModal(a,b);}, pzVia:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzVia=v;pzLinkModal(p.a,p.b,true);}, pzDiv:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzDiv=!!+v;pzLinkModal(p.a,p.b,true);}, - pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return; + pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!(S.ar?AR_TIERS:PZ_TIERS).includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return; const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub))return; const why=pzWaveWhy(a,b,tier,r);if(why){toast(esc(why),'bad');sfx('err');return;} - if(!portGate(a,1)||(S.pops[b]&&!portGate(b,1)))return; + if(!S.ar&&(!portGate(a,1)||(S.pops[b]&&!portGate(b,1))))return; // Overland: the same trench as a link already on the pair (the one picked from, or the first), or a diverse route // of its own. Every trench but the first runs the long way round and costs 40% more. const lands=pzOn()&&!r.sub?S.links.filter(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):[],t0=lands.length?pzUnit(lands[0]):null; const same=UI.pzDiv===false&&lands.length?(lands.find(l=>pzUnit(l)===UI.pzTrench)||lands[0]):null,trench=same?pzUnit(same):null,div=!!t0&&trench!==t0; pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop(b);const id=uid(),f=r.f*(div?DIVERSE:1); - S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0}); - closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();}, + S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0,br:S.ar?S.ar.bi:0}); + closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,S.ar?tr('architect.tube_laid'):tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();}, // Another link next to this one: the picker opens on the same pair, on the same route, in the same trench or a diverse one. pzAddPar:({id,div})=>{const l=pzOn()&&S.links.find(x=>x.id===id);if(!l)return;UI.pzVia=l.cable||'land';UI.pzDiv=!!+div;UI.pzTrench=l.cable?null:pzUnit(l); if(+div&&l.cable){const o=pzRoutes(l.a,l.b).find(x=>x.via!==l.cable&&!(S.pz.noSub&&x.sub));if(o)UI.pzVia=o.via;} pzLinkModal(l.a,l.b,true);}, - pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;} - pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();}, - pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!(S.ar?AR_TIERS:PZ_TIERS).includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;} + pzSnap();if(S.ar){if(arAge(l){if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();if(S.ar)arSink([],S.links.filter(l=>l.id===id));S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, // Routers: one more of the same model, one fewer, or every router in the POP swapped for another model. - pzRtAdd:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();}, - pzRtRm:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;} + pzRtAdd:({city})=>{const p=pzOn()&&!S.ar&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();}, + pzRtRm:({city})=>{const p=pzOn()&&!S.ar&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;} pzSnap();p.routers--;sfx('click');pzAfter();}, - pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;} + pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&!S.ar&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;} pzSnap();p.rgen=g;sfx('build');floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');pzAfter();}, // A circuit follows the metrics (the IGP's shortest path) or takes the lowest-latency path, as customers can in the main game. pzRoute:({i,m})=>{const b=pzOn()&&S.biz.find(x=>x.id===pzFlowId(+i));if(!b||!['normal','fast'].includes(m)||b.route===m)return;pzSnap();b.route=m;sfx('click');pzAfter();}, - pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();}, - pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();}, - pzShare:()=>{if(!pzOn())return;const t=pzShareText(pzEval()); + pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;if(S.ar)arStop(true);const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};if(S.ar){S.ar.sunk=o.k||0;arDemand();}(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();}, + pzReset:()=>{if(!pzOn())return;pzSnap();if(S.ar){arReset();sfx('click');pzAfter();return;}S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();}, + pzShare:()=>{if(!pzOn())return;const t=S.ar?arShareText(arStars(arSpend()),arSpend()):pzShareText(pzEval()); const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'),copy=()=>{try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}; if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}copy();track('puzzle_share');}, }); diff --git a/src/game/90-actions/96-architect.js b/src/game/90-actions/96-architect.js new file mode 100644 index 0000000..f74e15e --- /dev/null +++ b/src/game/90-actions/96-architect.js @@ -0,0 +1,8 @@ +// Architect runs (prototype). Named pz* like the puzzle actions, so a puzzle lets them through. +Object.assign(ACT,{ + pzArStart:({id})=>{const r=arRunDef(id);if(r)arBegin(r);}, + pzArGo:()=>{if(arOn())arShowStart();}, + pzArSkip:()=>{if(arOn())arShowSkip();}, + pzArNext:()=>{if(arOn())arNext();}, + pzArAll:()=>{if(!arOn())return;UI.arAll=!UI.arAll;if(!UI.arAll&&UI.sel&&UI.sel.type==='city'&&!arKind(UI.sel.id))UI.sel=null;sfx('click');renderAll();}, +}); diff --git a/src/game/94-dashboard/80-hint.js b/src/game/94-dashboard/80-hint.js index 037a7b3..387fb46 100644 --- a/src/game/94-dashboard/80-hint.js +++ b/src/game/94-dashboard/80-hint.js @@ -1,7 +1,7 @@ function renderHint(){ const hn=$('hint');if(!S||UI.hintOff||(S.tut!==undefined&&S.tut!==null)||(innerWidth<760&&(UI.sel||UI.leftOpen)&&!(UI.drag&&UI.drag.mode==='link'))){hn.hidden=true;return;} let t=''; - if(pzOn()){t=UI.drag&&UI.drag.mode==='link'?(UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city')):!Object.keys(S.pops).length?tr('puzzles.tap_a_goal_city_to_open'):!S.links.length?tr('puzzles.drag_from_a_pink_pop_to'):'';hn.textContent=t;hn.hidden=!t;return;} + if(pzOn()){t=UI.drag&&UI.drag.mode==='link'?(UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city')):!Object.keys(S.pops).length?tr('puzzles.tap_a_goal_city_to_open'):!S.links.length?(S.ar?tr('architect.drag_from_your_hq'):tr('puzzles.drag_from_a_pink_pop_to')):'';hn.textContent=t;hn.hidden=!t;return;} if(UI.drag&&UI.drag.mode==='link')t=UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city'); else if(!S.links.length&&S.done.tr)t=tr('hint.tip_drag_from_your_pink_router'); else if(!S.done.bb)t=tr('hint.tap_your_city_then_launch_broadband'); diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index e0311fd..3104a60 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -13,7 +13,7 @@ function pzFlowRow(x){const f=x.f,ok=x.full&&x.fast,u=f.g?Math.min(1,x.g/f.g):0; return `
${f.t==='l2'?'🔗':'👀'} ${esc(pzFlowName(f))}${f.be?` ${tr('puzzles.best_effort')}`:''}${fmtG(x.g)} / ${fmtG(f.g)}
${lat?`
${tr('puzzles.latency')}${lat}
`:''}${f.t==='l2'?pzRouteCtl(x.i):''}
`;} // A circuit's path: the metrics, or the lowest latency. function pzRouteCtl(i){const b=S.biz.find(x=>x.id===pzFlowId(i));if(!b)return '';return `
${['normal','fast'].map(m=>btn(RT[m],'pzRoute',{i,m},b.route===m?'pink sm':'ghost sm')).join('')}
`;} -function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false; +function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false;el.classList.toggle('ar',!!S.ar);if(S.ar){arRender(el);return;} const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); const star=(on,l)=>`⭐${l}`; let h=`
${pk?esc(pk.n):P.theme&&own(PZ_WK_THEMES,P.theme)?`${PZ_WK_THEMES[P.theme].i} ${tr('puzzles.weekly_puzzle')} · ${tr(PZ_WK_THEMES[P.theme].t)}`:tr('puzzles.weekly_puzzle')}

${esc(pzName(d||P))}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; @@ -43,7 +43,7 @@ function pzPopSection(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1,G=RG[g],c

${tr('puzzles.router_model')}

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

${name}

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

${name}

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

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

`; @@ -129,6 +129,7 @@ function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.lengt if(p.old&&!p.noted){h+=`
🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}
`;p.noted=1;pzStore(p);} h+=`
${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}${p.old?`
🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}
`:''}
`; if(pzOn())h+=`
${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; + h+=arMenuRows(); h+=pzWkRow(); for(const pk of PZ_PACKS){const open=tot>=pk.need,got=PZ.filter(x=>x.pack===pk.id).reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0),n=PZ.filter(x=>x.pack===pk.id).length; h+=`

${open?'':'🔒 '}${esc(pk.n)} ⭐ ${got}/${n*3}

${open?esc(pk.d):tr('puzzles.unlocks_at_n_stars',{n:pk.need})}

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

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

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

${esc(b.t)}

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

${name}

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

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

${tr('architect.hq_lead')}

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

${tr('architect.gold_lead')}

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

${tr('puzzles.not_this_one_find_a_way_around')}

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

${tr('architect.or_drag_a_tube_here')}

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

${tr('architect.closed_lead')}

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

${tr('common.links')}

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

${tr('puzzles.drag_from_this_pop_onto_another')}

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

${tr('architect.lay_a_tube_to')}

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

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

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

${tr('architect.size')}

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

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

${tr('puzzles.add_another_link_here')}

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

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

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

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

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

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

`; + h+=`

${tr('common.route')}

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

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

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

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

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

${tr('architect.this_tube_is_over_the_plan')}

`; + h+=`

${tr('architect.size')}

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

${esc(run.n)}

+
${stars}

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

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

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

${tr('architect.runs_lead')}

`; + for(const r of AR_RUNS){const x=p.runs[r.id]; + h+=`
${esc(r.n)} ${pzStarStr(x?x.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)}${' · '+tr('puzzles.budget_x',{x:fmt$(r.budget)})}${x&&x.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(x.sp)}):x&&x.br?' · '+tr('architect.best_n_briefs',{n:x.br}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},x&&x.st>=3?'ghost':'pink')}
`;} + return h;} diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index 422b708..2f6b4ea 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -30,10 +30,10 @@ function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab); if(!selC&&z<1.7&&cached)return; ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle'; - for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;const col=cableCol(C); + const ar=arOn();for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;const col=cableCol(C); for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]mx)mx=q[0];}if(mx<-20||mn>CW+20)continue; if(hot||!cached){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i=1.7){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);} + if(hot||(z>=1.7&&!ar)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);} ctx.globalAlpha=1;}}} function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit; const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index f82dee0..897b7dc 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -50,7 +50,7 @@ function drawFrame(now){ const [mx2,my]=at(.5);const mxx=mx2; if(bld){if(far){ctx.fillStyle='#FF8A3D';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,4,0,7);ctx.fill();ctx.stroke();}else drawCone(mxx,my,now);} else if(cut&&!vx){if(far){ctx.fillStyle='#FF4D5E';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,5,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',mxx,my+0.5);}else drawBackhoe(mxx,my,now,l.sub);} - else if(sel||pz||(z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} + else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} } } // drag preview @@ -69,7 +69,7 @@ function drawFrame(now){ // cities UI.feed=null;if(UI.sel&&UI.sel.type==='link'){const sl=S.links.find(x=>x.id===UI.sel.id);const rec=sl&&R.ef[edgeKey(sl)];if(rec){UI.feed=new Set(Object.keys(rec.eg).map(k=>R.egDesc[k].city));UI.dest=new Set(Object.keys(rec.dst));}} // Place labels: your POPs and the selected city first, then others; a label that would overlap moves above its city or hides. - const vis=[];for(const C of CITIES){if(C.off&&!cityOn(C.id))continue;for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}} + const vis=[];for(const C of CITIES){if(C.off&&!cityOn(C.id))continue;if(arHide(C.id))continue;for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}} const prio=v=>(UI.sel&&UI.sel.type==='city'&&UI.sel.id===v.C.id?0:S.pops[v.C.id]?1:2);vis.sort((a,b)=>prio(a)-prio(b)||b.C.P-a.C.P); const rects=[],labs=[],hit=(r)=>rects.some(q=>r.x=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; - if(pzOn())for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);if(S.ar)for(const v of vis)arDrawTags(v,sc);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}} diff --git a/src/game/96-map/70-world-layer.js b/src/game/96-map/70-world-layer.js index cfe511a..ab36726 100644 --- a/src/game/96-map/70-world-layer.js +++ b/src/game/96-map/70-world-layer.js @@ -7,15 +7,15 @@ function wlCovers(z){if(WL.full)return true;const hw=CW/2/z,hh=CH/2/z,w=WL.cv.wi return cam.x-hw>=WL.ox&&cam.x+hw<=WL.ox+w&&cam.y-hh>=WL.oy&&cam.y+hh<=WL.oy+h;} function worldLayer(z){ const now=performance.now();if(z!==WL.lastZ){WL.lastZ=z;WL.zAt=now;} - const sc=z*DPR,key=sc.toFixed(4),have=!!(WL.cv&&WL.key); + const sc=z*DPR,key=sc.toFixed(4)+(arOn()?'a':''),have=!!(WL.cv&&WL.key); if(have&&WL.key===key&&wlCovers(z))return WL; if(have&&now-WL.zAt<250)return WL; // mid-gesture: scale the last image const full=W*sc+2<=MAXPX;let ox=0,oy=0,w=W,h=H; if(!full){const mx=Math.min(MAXPX/sc,CW/z*2),my=Math.min(MAXPX/sc,CH/z*2);w=mx;h=my;ox=cam.x-w/2;oy=cam.y-h/2;} const cv2=WL.cv||document.createElement('canvas');cv2.width=Math.ceil(w*sc)+2;cv2.height=Math.ceil(h*sc)+2; const c=cv2.getContext('2d',SOFT_CANVAS?{willReadFrequently:true}:undefined);if(!c)return null; - const kk=full?0:Math.floor(cam.x/W)*W;c.setTransform(1,0,0,1,0,0);c.clearRect(0,0,cv2.width,cv2.height);c.setTransform(sc,0,0,sc,-(ox-kk)*sc,-oy*sc);paintWorld(c,z,z<1.7); - Object.assign(WL,{cv:cv2,key,sc,ox,oy,full,cab:z<1.7});return WL; + const kk=full?0:Math.floor(cam.x/W)*W;c.setTransform(1,0,0,1,0,0);c.clearRect(0,0,cv2.width,cv2.height);c.setTransform(sc,0,0,sc,-(ox-kk)*sc,-oy*sc);paintWorld(c,z,z<1.7&&!arOn()); + Object.assign(WL,{cv:cv2,key,sc,ox,oy,full,cab:z<1.7&&!arOn()});return WL; } // Draw the world image for map copy k (full layers repeat per copy; a crop already holds what is visible). function drawWorldLayer(wl,k,z,k0){if(!wl.full&&k!==k0)return;const f=z*DPR/wl.sc,ox=(wl.full?k*W:wl.ox); diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index 954a64a..621b5e7 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -1,16 +1,20 @@ /* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring and a badge for what they send or ask for, stepping stones with a dashed one, cities to avoid crossed out); every other city is on the map as usual, open to build in but not emphasised. */ -function pzBadge(c){const P=S.pz;return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} +function pzBadge(c){const P=S.pz;if(S.ar)return c===S.ar.hq?'🏠':S.ar.gold.includes(c)?'🥇':'';return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); if(!k||k==='off'){drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);return;} const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id]; ctx.save();ctx.lineWidth=3; if(k==='avoid'){ctx.strokeStyle='#FF4D5E';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.moveTo(v.sx-r*.7,y-r*.7);ctx.lineTo(v.sx+r*.7,y+r*.7);ctx.stroke();} - else{const a=animOn()?.55+.35*Math.sin(now/300):.8;ctx.strokeStyle=k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(k==='via')ctx.setLineDash([5,5]); + else{const a=animOn()?.55+.35*Math.sin(now/300):.8,gold=S.ar&&S.ar.gold.includes(v.C.id),dk=S.ar&&arDarkNow(v.C.id);ctx.strokeStyle=dk?`rgba(255,77,94,${a})`:gold?`rgba(224,160,0,${p?1:a})`:k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(gold||dk)ctx.lineWidth=5;if(k==='via')ctx.setLineDash([5,5]); ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);} ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly); const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx+r*.75,y-r*.75);}} // In a puzzle every line says what it is ("2×100G · 70%"), and a selected POP lights up every pair it has links on. -function pzLinkLab(grp,up,load,cap){return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} +function pzLinkLab(grp,up,load,cap){if(S.ar)return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} const pzLinkHot=grp=>!!(UI.sel&&UI.sel.type==='city'&&grp.some(x=>x.a===UI.sel.id||x.b===UI.sel.id)); +// Architect runs: what later briefs do here, as small numbered tags beside the city ("4🥇", "6🚫"). +function arDrawTags(v,sc){const tg=arTags(v.C.id).slice(0,2);if(!tg.length||!pzKind(v.C.id))return;const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc);const t=tg.map(x=>x.n+x.i).join(' '); + ctx.save();ctx.font=`900 ${Math.round((CM.far?10:12)*Math.max(0.9,Math.min(1.3,sc)))}px "Baloo 2", sans-serif`;const w=ctx.measureText(t).width+12,h=18,x=v.sx-r-w*0.35,yy=y-r-4; + ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(x,yy,w,h,9);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,x+w/2,yy+h/2+1);ctx.restore();} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index 204c6f4..605eba6 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/i18n/en.js b/src/i18n/en.js index cf18cc8..78586e6 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -13,6 +13,119 @@ "action_helpers.too_far_even_at_its_slowest":"Too far even at its slowest setting: an optical span here is {span} km and it reaches {max} km. Add a regen site (Line system).", "action_helpers.unlocks_at_customer_level_n":"Unlocks at customer level {n}.", "actions.your_router_can_t_take_a":"Your router can't take a {port} port.
Upgrade it in the Infra tab.", +"architect.anchor":"⚓ Anchor!", +"architect.architect_runs":"Architect runs", +"architect.backhoe":"🚜 Backhoe!", +"architect.best_n_briefs":"best: {n} briefs", +"architect.brief_n_of_m":"Brief {n} of {m}", +"architect.briefs_done":"Briefs done", +"architect.built_in_an_earlier_brief":"Built in an earlier brief: removing it gives nothing back.", +"architect.changing_an_old_tube":"This tube is from an earlier brief: a new size is a new lease, and the old one is paid for.", +"architect.city_goes_dark":"{city} goes dark", +"architect.city_short_g":"{city} short {g}", +"architect.closed":"Closed", +"architect.closed_city":"No POP in {city}", +"architect.closed_lead":"This city is closed now. Move out: remove the POP and find another way.", +"architect.coast_to_coast":"Coast to Coast", +"architect.coast_to_coast_joke":"From data center alley to Silicon Valley, one brief at a time.", +"architect.coming_up":"Coming up", +"architect.cut_n_of_m":"Cut {n} of {m}…", +"architect.cut_on_x_cuts_off_y":"A cut on {x} cuts off {y}.", +"architect.cut_on_x_no_room":"A cut on {x} leaves no room on the detour. Short: {y}.", +"architect.dark_list":"Dark for now: {list}. Not gold, so that's allowed.", +"architect.drag_from_your_hq":"Drag from your HQ to another city to lay a tube", +"architect.euro_1":"Your servers live in Amsterdam. First customer: Frankfurt. Connect it.", +"architect.euro_2b":"Paris and London want in.", +"architect.euro_3b":"Frankfurt and Paris sign banks. Both go gold.", +"architect.euro_5":"Zürich, another bank. Gold from day one.", +"architect.euro_6":"Your Frankfurt landlord sold the building. Move out. The bank moves to Düsseldorf, and it is still gold.", +"architect.euro_ring":"London, Paris and Amsterdam want a ring between them.", +"architect.euro_ring_grow":"Paris doubles to 100G. And London, Paris and Amsterdam want a ring between them.", +"architect.euro_run":"Euro Run", +"architect.euro_run_joke":"Six briefs, one landlord, one very nervous bank.", +"architect.finish_the_run":"Finish the run", +"architect.fix_it_and_send_it_again":"Fix it, then send the backhoe again.", +"architect.from_x":"from {x}", +"architect.gold_lead":"Gold: this site must stay connected to HQ whichever single trench or cable is cut, and the detour needs room for its traffic.", +"architect.gold_must_survive":"Must survive any single cut: {list}", +"architect.gold_site":"Gold site", +"architect.hide_other_cities":"Hide other cities", +"architect.hq":"HQ", +"architect.hq_lead":"Your servers live here. Every site needs a path to HQ.", +"architect.joins_in_brief_n":"Joins in brief {n}", +"architect.keep_going":"Keep building", +"architect.last_brief_done":"That was the last brief.", +"architect.lay_a_tube_to":"Lay a tube to", +"architect.lay_it_x":"Lay it · {x}", +"architect.line_1":"It works. Finance would like a word.", +"architect.line_2":"Solid design, a little gold plated. Finance can live with it.", +"architect.line_3":"At par or better. The backhoe went home bored.", +"architect.move_out_of_city":"Move out of {city} first.", +"architect.n_briefs":"{n} briefs", +"architect.n_over_plan":"{n} over plan", +"architect.n_tubes":{"one":"{n} tube","other":"{n} tubes"}, +"architect.new":"New", +"architect.next_brief":"Next brief", +"architect.next_brief_waiting":"The next brief is waiting.", +"architect.next_run":"Next run", +"architect.not_a_ring_yet":"Not a ring yet.", +"architect.not_connected_yet_list":"Not connected to HQ yet: {list}", +"architect.numbers_on_the_map_show":"Numbers on the map show what later briefs bring. You can build there early.", +"architect.or_drag_a_tube_here":"Or drag a tube here from one of your POPs.", +"architect.pac_1":"Your servers live in Tokyo. Hong Kong first.", +"architect.pac_2":"Singapore wants in.", +"architect.pac_3":"A stock exchange in Hong Kong. Hong Kong is gold.", +"architect.pac_4":"Singapore signs a bank. Gold too.", +"architect.pac_5":"Sydney. Far from everything: that is the point, and the problem.", +"architect.pacific_rim":"Pacific Rim", +"architect.pacific_rim_joke":"Oceans, anchors and very expensive glass.", +"architect.plus_router_x":"+ bigger router {x}", +"architect.ready_no_gold_yet":"Ready. No gold sites yet, so the backhoe can only make a mess.", +"architect.ready_send_the_backhoe":"Ready. Send the backhoe and see what survives.", +"architect.reset_brief":"Reset brief", +"architect.review_passed":"Review passed", +"architect.ring_list":"One ring through {list}", +"architect.router_follows":"Picked for your tubes", +"architect.router_x":"Router: {x}", +"architect.run_complete":"Run complete", +"architect.run_over":"Run over", +"architect.runs_lead":"One network, built brief by brief. Your build carries over, and a backhoe checks every design: cut any one tube, and everything still connected must get all its traffic.", +"architect.send_the_backhoe":"Send the backhoe", +"architect.shape_braces":"Belt and braces", +"architect.shape_full":"Full mesh", +"architect.shape_islands":"Islands", +"architect.shape_ladder":"Ladder", +"architect.shape_line":"Line", +"architect.shape_lolli":"Ring with spurs", +"architect.shape_mesh":"Mesh", +"architect.shape_ring":"Ring", +"architect.shape_spaghetti":"Spaghetti", +"architect.shape_star":"Star", +"architect.shape_tree":"Tree", +"architect.shape_tube":"One tube", +"architect.share_line":"Series of Tubes · {what} {stars} {spend} {shape} · seriesoftub.es", +"architect.show_all_cities":"Show all cities", +"architect.site":"Site", +"architect.size":"Size", +"architect.skip":"Skip", +"architect.spent":"Spent", +"architect.spent_x_of_y":"Spent {x} of {y}", +"architect.the_cfo_pulled_the_plug":"The CFO pulled the plug. Try a cheaper shape?", +"architect.this_tube_is_over_the_plan":"This brief's tubes are used up. You can still lay it, but it costs a star.", +"architect.too_slow_for_the_cap":"Too slow: find a faster path.", +"architect.too_thin_list":"Too thin: {list}", +"architect.try_again":"Try again", +"architect.tube_laid":"Tube laid!", +"architect.tubes_over_plan":"Tubes over plan", +"architect.tubes_this_brief":"Tubes this brief", +"architect.usa_1":"Your servers live in Ashburn. New York first.", +"architect.usa_2":"Chicago wants in.", +"architect.usa_3":"A bank in New York. New York is gold.", +"architect.usa_4":"Traders want New York ⇄ Chicago under 8 ms.", +"architect.usa_5":"Dallas and Silicon Valley want in.", +"architect.usa_6":"A cloud deal in Silicon Valley. It goes gold.", +"architect.x_paid_for_and_gone":"{x} of that paid for things you removed", +"architect.your_shape":"Your shape", "badges.a_petabit_a_second":"A Petabit a Second", "badges.a_secret_badge":"A secret badge", "badges.attend_a_conference":"Attend a conference.", diff --git a/src/styles/71-architect.css b/src/styles/71-architect.css new file mode 100644 index 0000000..a531a7d --- /dev/null +++ b/src/styles/71-architect.css @@ -0,0 +1,28 @@ +/* Architect runs (prototype): the brief, its sites, the review line */ +.arsteps{display:flex;gap:4px;margin:4px 0 6px}.arsteps i{flex:1;height:7px;border:2px solid var(--ink);border-radius:99px;background:#fff} +.arsteps i.done{background:var(--ok)}.arsteps i.on{background:#FFD23F} +.arbrief{margin:2px 0 8px;font-size:14.5px;font-weight:800;line-height:1.35} +.arsites{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0 6px} +.arsite{font-weight:900;font-size:12px;border:2px solid var(--line);border-radius:999px;padding:1px 8px;background:#fff;color:var(--ink2)} +.arsite.ok{border-color:var(--ok);color:var(--ink)}.arsite.gold{border-color:#E0A000;background:#FFF3C4} +.arline{font-size:12.5px;font-weight:800;margin:3px 0;color:var(--ink2)}.arline.ok{color:var(--ink)}.arline.bad{color:var(--bad)} +.arshape{font-size:12.5px;font-weight:900;margin:4px 0} +.arrev{font-size:12.5px;font-weight:800;margin:6px 0;padding:5px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} +.arrev.on{border-color:#FF8A3D;background:#FFF0E3;color:var(--ink)}.arrev.ok{border-color:var(--ok);background:#DFFBEA;color:var(--ink)} +.arrev.bad{border-color:var(--bad);background:#FFE6E9;color:var(--ink)} +#pzBox .arbtns .b.big{flex:1 1 100%} +.artubes{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;font-weight:800;margin:4px 0}.artubes b{font-size:15px;letter-spacing:2px;color:var(--me)} +.artubes em{font-style:normal;font-size:11.5px;letter-spacing:0;color:#B86A00}.artubes.over b{color:#B86A00} +.arplan{margin:6px 0;padding:5px 8px;border:2px dashed var(--line);border-radius:10px;font-size:12px;font-weight:700;color:var(--ink2)}.arplan b{display:inline-block;min-width:14px;color:var(--ink)} +/* Laptops and up: a bigger card, easier to read at a glance */ +@media (min-width:761px) and (min-height:501px){ + #pzBox.ar{width:390px;padding:14px 18px 16px} + #pzBox.ar h3{font-size:23px}#pzBox.ar .eyebrow{font-size:12px} + #pzBox.ar .arsteps i{height:9px} + #pzBox.ar .arbrief{font-size:17.5px;margin:4px 0 10px} + #pzBox.ar .arsite{font-size:14px;padding:2px 10px} + #pzBox.ar .arline,#pzBox.ar .arrev,#pzBox.ar .artubes,#pzBox.ar .pzbud .kv,#pzBox.ar .arplan{font-size:14px} + #pzBox.ar .artubes b{font-size:19px}#pzBox.ar .pzbud .bar{height:12px} + #pzBox.ar .arbtns .b.sm{font-size:13px;padding:5px 11px} +} +.arsite small{font-weight:800;opacity:.75}.arsite.thin{border-color:var(--bad);background:#FFE6E9;color:var(--ink)} diff --git a/tests/architect.test.js b/tests/architect.test.js new file mode 100644 index 0000000..445ec46 --- /dev/null +++ b/tests/architect.test.js @@ -0,0 +1,149 @@ +// Architect runs (prototype): one network built brief by brief, reviewed by a backhoe. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Reference builds, brief by brief: [a, b, route] lays a tube (a diverse trench when the pair has one), ['@rm', city] +// closes a POP. Each must pass every brief within budget and land at par. +const REF = { + euro: [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']], + [['ams', 'zrh', 'land'], ['par', 'zrh', 'land']], [['lon', 'par', 'pasdc'], ['ams', 'lon', 'concerto']], [['@rm', 'fra'], ['ams', 'dus', 'land'], ['ams', 'dus', 'land']]], + usa: [[['ash', 'nyc', 'land']], [['ash', 'chi', 'land']], [['nyc', 'chi', 'land']], [], [['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], [['chi', 'sjc', 'land']]], + pacific: [[['tok', 'hkg', 'adc']], [['hkg', 'sin', 'land']], [['tok', 'hkg', 'apg']], [['hkg', 'sin', 'sjc2']], [['sin', 'syd', 'indigo']]], +}; +const lay = (ev, a, b, via, div = 1) => ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:${div}});ACT.pzLink({tier:AR_TIER});closeModal()`); +const review = (ev) => { ev('arShowStart();arShowSkip()'); return ev('S.ar.passed===pzSig()'); }; + +test('architect runs: every reference passes each brief, on plan and within budget', () => { + const { ev, errors } = load(); + assert.deepEqual(JSON.parse(ev('JSON.stringify(AR_RUNS.map(r=>r.id))')).sort(), Object.keys(REF).sort()); + for (const [id, plan] of Object.entries(REF)) { + ev(`ACT.pzArStart({id:'${id}'})`); + assert.equal(ev('arOn()&&!!S.pops[S.ar.hq]'), true, `${id}: starts with a POP at HQ`); + plan.forEach((steps, i) => { + for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); + assert.equal(review(ev), true, `${id} brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); + if (i < plan.length - 1) ev('ACT.pzArNext()'); + }); + assert.equal(ev('arOver()'), 0, `${id}: never over a brief's tubes`); + assert.equal(ev('arSpend()<=arRun().budget'), true, `${id}: within budget`); + assert.ok(ev('arSpend()>arRun().budget*0.95'), `${id}: the budget sits just above the reference`); + ev('ACT.pzArNext()'); + assert.equal(ev('JSON.parse(localStorage.getItem(AR_KEY)).runs[S.ar.id].st'), 3, `${id}: three stars stored`); + } + assert.deepEqual(errors, []); +}); + +test('architect runs: the backhoe finds a shared trench, edits clear the cut, old builds are paid for', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); + assert.deepEqual(JSON.parse(ev("JSON.stringify([arHide('dus'),arTags('dus'),arTags('fra').map(t=>t.n+t.i)])")), [false, [{ n: 6, i: '🥇' }], ['3🥇', '6🚫']], 'later briefs show on the map, numbered'); + ev('ACT.pzArAll()'); + assert.equal(ev("arHide('lis')"), false, 'and shown on request'); + ev('ACT.pzArAll()'); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'fra', 'land', 0); // the same trench: looks redundant, is not + assert.equal(review(ev), false); + assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), ['fra']); + assert.ok(ev('S.links.some(l=>l.cut)'), 'the failing cut stays on the map'); + ev('ACT.pzUndo()'); + assert.equal(ev('!UI.arFail&&!S.links.some(l=>l.cut)'), true, 'an edit clears it'); + const sunk = ev('S.ar.sunk'); + ev("ACT.pzRmLink({id:S.links.find(l=>l.br===0).id})"); + assert.ok(ev('S.ar.sunk') > sunk, 'removing an earlier brief\'s tube refunds nothing'); + ev('ACT.pzReset()'); + assert.equal(ev('S.ar.sunk'), sunk, 'reset goes back to the start of the brief'); + // Two diverse trenches would make both gold, but the plan has one tube: the ring is the answer. + lay(ev, 'ams', 'fra', 'land'); lay(ev, 'ams', 'par', 'land'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(arTubes())')), { u: 2, max: 1, over: 1 }); + ev('ACT.pzReset()'); + lay(ev, 'par', 'fra', 'land'); + assert.equal(ev('arTubes().over'), 0); + assert.equal(review(ev), true); + assert.deepEqual(errors, []); +}); + +test('architect runs: a latency brief needs the fast path, and normal puzzles are untouched', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'usa'})"); + lay(ev, 'ash', 'nyc', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ash', 'chi', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ash', 'nyc', 'land'); assert.equal(review(ev), true, 'a diverse trench makes New York gold'); ev('ACT.pzArNext()'); + assert.equal(ev('arEval().lat.ok'), false, 'via Ashburn is too slow'); + lay(ev, 'nyc', 'chi', 'land'); + assert.equal(ev('arEval().lat.ok&&arEval().ready'), true); + ev("ACT.pzStart({id:'hello'})"); + assert.equal(ev('!S.ar&&pzKind("lon")==="goal"&&!arHide("par")'), true); + assert.deepEqual(errors, []); +}); + +test('architect runs: Play on the title screen\'s puzzle list starts a run', () => { + const { ev, errors } = load(); + ev('ACT.puzzleMenu()'); + assert.equal(ev('S'), null, 'no game loaded yet'); + ev("document.querySelector('#modal [data-act=pzArStart]').click()"); + assert.equal(ev('arOn()&&S.ar.id'), 'euro'); + assert.deepEqual(errors, []); +}); + +test('architect runs: a ring goal needs one cycle through its cities', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'par', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); review(ev); ev('ACT.pzArNext()'); + assert.equal(ev("arRingOk(['ams','par','lon'])"), false, 'London hangs off Amsterdam: no ring'); + assert.match(ev('arEval().why'), /ring/i); + lay(ev, 'lon', 'par', 'pasdc'); + assert.equal(ev("arRingOk(['ams','par','lon'])&&arEval().ready"), true); + assert.ok(ev("arSum(arRun().briefs[5])").includes('Frankfurt'), 'the plan shows what is coming'); + assert.deepEqual(errors, []); +}); + +test('architect runs: the detour needs room, and a roomy but pricey build misses the budget star', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + const head = [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']]]; + const run = (plan) => plan.forEach((steps, i) => { + for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); + assert.equal(review(ev), true, `brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); + ev('ACT.pzArNext()'); + }); + run(head); + // Zürich hung off Frankfurt: connected both ways, but a cut on Amsterdam-Frankfurt sends Frankfurt and Zürich through + // Paris, and that tube is too thin for all three. + lay(ev, 'fra', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); + assert.equal(review(ev), false); + assert.ok(JSON.parse(ev('JSON.stringify(UI.arFail.short)')).length > 0, 'someone still connected runs short'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), [], 'nobody gold is cut off'); + ev('ACT.pzReset()'); + lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); + assert.equal(review(ev), true, 'Zürich straight to HQ spreads the detours'); + ev('ACT.pzArNext()'); + // Paris doubles: a second Amsterdam-Paris trench gives room, at a price. + lay(ev, 'lon', 'par', 'pasdc'); lay(ev, 'ams', 'par', 'land'); + assert.equal(review(ev), true); ev('ACT.pzArNext()'); + ev("ACT.pzRmPop({city:'fra'})"); lay(ev, 'ams', 'dus', 'land'); lay(ev, 'dus', 'zrh', 'land'); + assert.equal(review(ev), true); + assert.equal(ev('arOver()'), 0); + assert.ok(ev('arSpend()') > ev('arRun().budget')); + assert.equal(ev('arStars(arSpend())'), 2, 'on plan, over budget: two stars'); + assert.deepEqual(errors, []); +}); + +test('architect runs: a bigger tube brings a bigger router, and changing an old tube is a new lease', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + assert.equal(ev("S.pops.ams.rgen||0"), 0, 'the free router takes 100G'); + const sunk = ev('S.ar.sunk'); + ev("ACT.pzTier({id:S.links[0].id,tier:2})"); + assert.ok(ev("RG[S.pops.ams.rgen].maxLT>=2&&RG[S.pops.fra.rgen].maxLT>=2"), '400G needs a bigger router at both ends'); + assert.ok(ev('S.ar.sunk') > sunk, 'the old 100G lease is paid for'); + ev('ACT.pzUndo()'); + assert.equal(ev("(S.pops.ams.rgen||0)===0&&S.ar.sunk===" + sunk), true, 'undo puts it all back'); + assert.deepEqual(errors, []); +});