Server-run play, part 1: game prerequisites and shared contracts
Groundwork for running multiplayer games on the session server; nothing
of it is switched on yet, and the plain build is unchanged.
- A new network in two halves (beginState/beginShow), the coach split into
tutAdvance/coachDom, toastPop split out of toast, bootNotes() for the
once-per-load toasts, the five text actions take their text as an
argument, and srvOn() with its two checks in the loop.
- Live state is what a reload makes of it (migrate() is a no-op on it):
new POPs, ports, PNIs, customers, attacks, dark fiber and the intern's
notes are written in their saved shape; a 365-day test proves it.
- pniAll and bstdApply check the quote the sheet showed (bstdApply by its
plan, within 1% for the daily hardware drift; utilityKit too).
- assemble({mp}) leaves src/game/98-server-play/ and its CSS out of every
page but a multiplayer build's, which also gets a SIM_ID build id.
- Contracts for the server, protocol and browser parts: the action tables
and envelope check (scripts/lib/mp-sim-acts.js), event fixtures, a shape
checker, a fake engine, and load({mp:true}) in the test harness.
- route-fuzz judges both pages with one migrate(), so reload repairs of
the base no longer count as divergences.
This commit is contained in:
parent
e25f843526
commit
d1e127da67
60 changed files with 2200 additions and 105 deletions
|
|
@ -56,6 +56,8 @@ const API_DOMAINS={
|
|||
pzRouteMode:{kind:'enum',values:['normal','fast']},
|
||||
// The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll).
|
||||
pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])},
|
||||
// The total a sheet showed (pniAll, bstdApply carry it as q): the game refuses a different one (bstdApply: more than 1% away).
|
||||
shownTotal:{kind:'fn',ok:v=>typeof v==='number'&&Number.isFinite(v)},
|
||||
dashTab:{kind:'enum',values:()=>DTABS.slice()},
|
||||
dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']},
|
||||
leftTab:{kind:'enum',values:['goals','deals','noc','nets']},
|
||||
|
|
|
|||
|
|
@ -390,10 +390,10 @@ const API_CMD={
|
|||
quote:a=>{const q=S&&S.ops?opsTplQuote(a.city):null;return q?{setup:q.cost}:{};},
|
||||
doc:'Open a city from the template in one go: the POP, then broadband, transit, an IX port and the redundancy kit as the template says — all or nothing on the price.'},
|
||||
/* ---------- the bulk PNI order ---------- */
|
||||
pniAll:{args:[['net','pniAllNet'],['tier','pniTier']],
|
||||
pniAll:{args:[['net','pniAllNet'],['tier','pniTier'],['q','shownTotal',false]],
|
||||
quote:a=>{const b=pniBatch(a.net,a.tier);return b?{setup:b.cost,monthly:b.mo,blocked:(b.blocked||[]).map(q=>q.why).filter(Boolean)}:{};},
|
||||
watch:['pni'],
|
||||
doc:'Order PNIs with one network (net) or every network (net:null) at all shared POPs: missing connections are added, smaller ones upgraded, each at its own minimum size. The quote is the batch total, lead times as for one PNI.'},
|
||||
doc:'Order PNIs with one network (net) or every network (net:null) at all shared POPs: missing connections are added, smaller ones upgraded, each at its own minimum size. The quote is the batch total, lead times as for one PNI. q (optional): the total you were shown; a different one now is refused and the sheet shown again.'},
|
||||
/* ---------- backbone technology ---------- */
|
||||
coreUp:{args:[],watch:['core'],
|
||||
quote:a=>{const n=S&&S.core?S.core.lv+1:1;return n<=4?{setup:CORE_COST[n],blocked:[(lvl()||1)<CORE_REQ[n]?tr('core.needs_customer_level_n',{n:CORE_REQ[n]}):''].filter(Boolean)}:{};},
|
||||
|
|
@ -435,16 +435,16 @@ const API_CMD={
|
|||
doc:'Clear the whole build standard; new POPs go back to one basic router.'},
|
||||
bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'],
|
||||
doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. g and sys are also what the intern\'s routers and optup orders standardize on. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'},
|
||||
bstdApply:{args:[],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'],
|
||||
quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};},
|
||||
doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill.'},
|
||||
bstdApply:{args:[['quote','string',false],['q','shownTotal',false]],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'],
|
||||
quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,key:bstdPlanKey(bstdPlan(false)),blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};},
|
||||
doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill. quote and q (optional): the plan\'s key and the total you were shown; another plan, or a total more than 1% away, is refused and the sheet shown again.'},
|
||||
/* ---------- utilities ---------- */
|
||||
utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'],
|
||||
doc:'Join the route server at every IX you have a port at. One call does what the button does.'},
|
||||
utilityKit:{args:[['city','cityId'],['cost','integer',false]],watch:['pops.#city','caches'],
|
||||
quote:a=>{const q=S?utilityKit(a.city):null;return q?{setup:q.cost,monthly:q.mo}:{};},
|
||||
pass:a=>({city:a.city,cost:a.cost??((utilityKit(a.city)||{}).cost)}),
|
||||
doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches. Nothing to do reads as no_effect.'},
|
||||
doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches (within 1%: hardware prices drift by the day). Nothing to do reads as no_effect.'},
|
||||
utilityCaches:{args:[['city','cityId'],['quote','string',false]],watch:['caches'],
|
||||
quote:a=>{const q=S?utilityCaches(a.city):null;return q?{key:q.key}:{};},
|
||||
pass:a=>({city:a.city,quote:a.quote??((utilityCaches(a.city)||{}).key)}),
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ const IS_DEV=APP_VERSION.startsWith('__');
|
|||
// Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build.
|
||||
// Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests.
|
||||
const MP_API=/*__MP_API__*/'';
|
||||
// Server-run play's build id (scripts/lib/page.js simId()), stamped next to MP_API; the session server refuses a page of another build.
|
||||
const SIM_ID=/*__SIM_ID__*/'';
|
||||
// Only report from the real site; previews, localhost and the Claude viewer stay silent.
|
||||
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
|
||||
(function(){
|
||||
|
|
|
|||
|
|
@ -43,7 +43,14 @@ const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chao
|
|||
function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};}
|
||||
const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]);
|
||||
function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}}
|
||||
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal';
|
||||
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();
|
||||
beginState(nm,city,{...o,asn:+(UI.asnTxt||UI.asnSug||0)});UI.asnSug=null;beginShow(city,o);}
|
||||
/* A new network in two halves. beginState() makes S (no screen, no storage, no slot), so a server can build a network
|
||||
the way the page does; o.asn is the AS number the player typed, kept when asnOk(). beginShow() puts it on screen and
|
||||
starts it: speed, camera, welcome, charter, tutorial. o.srv: the server built this network (beginState, compute,
|
||||
beginHello) and set S.tut, so the page neither routes it (its R comes from the server), nor says welcome again, nor
|
||||
starts the tutorial: it only shows the coach where S.tut is. */
|
||||
function beginState(nm,city,o={}){newGame(nm,city);if(asnOk(o.asn))S.asn=o.asn;S.mode=o.mode||'normal';
|
||||
// A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world.
|
||||
if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;}
|
||||
// The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules.
|
||||
|
|
@ -51,11 +58,14 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci
|
|||
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}}
|
||||
if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('features.weekly_challenge_key',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000);
|
||||
if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup();
|
||||
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}
|
||||
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}}
|
||||
// The welcome line: in the log, and on screen.
|
||||
function beginHello(o={}){toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(S.name),asn:S.asn,city:CITY[S.home].name}),'goal');}
|
||||
function beginShow(city,o={}){
|
||||
// Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen.
|
||||
UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null;
|
||||
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
|
||||
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal');
|
||||
track('game_new');UI.started=true;closeModal();if(!o.srv)compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
|
||||
if(!o.srv)beginHello(o);
|
||||
// A Normal game asks for its charter first; the tutorial starts once it is signed.
|
||||
renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}
|
||||
renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(o.srv)renderCoach();else if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}
|
||||
if(S.mp)mpStartTell();}
|
||||
|
|
|
|||
|
|
@ -68,11 +68,11 @@ function salesGolf(d){if(pieGolf(d))return;const mine=Object.keys(S.pops).filter
|
|||
const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a<b?-1:1))[0];
|
||||
const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name);
|
||||
const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40};
|
||||
const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b));
|
||||
const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';if(clOn(b))b.mk=mkt();S.biz.push(clSign(b));
|
||||
toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');}
|
||||
// Declining an offer the CEO likes: about one in three, he already shook hands on it.
|
||||
function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||!ip4Fits(o)||slR('veto|'+slKey(o))>=0.33)return false;
|
||||
const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;}
|
||||
const b=offerCustomer(o);if(o.mk&&clOn(b))b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;}
|
||||
// Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer.
|
||||
function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null;
|
||||
s.sales={p:own(SALES,L.p)?L.p:null,hired:n(L.hired)||0,vp:L.p==='ceo'?n(L.vp):null,golf:n(L.golf),say:n(L.say)};
|
||||
|
|
|
|||
|
|
@ -8,9 +8,13 @@ const TUT=[
|
|||
{t:tr('tutorial.businesses_pop_up_as_bubbles_on'),sel:'[data-act="leftTab"][data-args*=\'"deals"\']',ok:()=>S.biz.length>0},
|
||||
];
|
||||
function tutorialStart(){let done=false;try{done=!!localStorage.getItem('sot-tut');}catch(e){}if(done||window.__TUBES_TEST__&&!window.__TUBES_TUT__)return;S.tut=0;renderCoach();}
|
||||
function renderCoach(){const el=$('coach');if(!el)return;document.querySelectorAll('.coach-glow').forEach(x=>x.classList.remove('coach-glow'));
|
||||
if(!S||S.tut===undefined||S.tut===null||S.lost){el.hidden=true;return;}
|
||||
// The coach: the steps done move S.tut on (tutAdvance, state only: a server runs it after every day and action), then
|
||||
// the box shows the step it is at (coachDom, the screen only).
|
||||
function renderCoach(){if(!$('coach'))return;tutAdvance();coachDom();}
|
||||
function tutAdvance(){if(!S||S.tut===undefined||S.tut===null||S.lost)return;
|
||||
while(S.tut<TUT.length){const st=TUT[S.tut];let ok=false;try{ok=st.ok()||(st.skip&&st.skip());}catch(e){}if(!ok)break;S.tut++;}
|
||||
if(S.tut>=TUT.length){S.tut=null;el.hidden=true;try{localStorage.setItem('sot-tut','1');}catch(e){}toast(tr('tutorial.you_know_the_basics_the_goals'),'goal');return;}
|
||||
if(S.tut>=TUT.length){S.tut=null;try{localStorage.setItem('sot-tut','1');}catch(e){}toast(tr('tutorial.you_know_the_basics_the_goals'),'goal');}}
|
||||
function coachDom(){const el=$('coach');if(!el)return;document.querySelectorAll('.coach-glow').forEach(x=>x.classList.remove('coach-glow'));
|
||||
if(!S||S.tut===undefined||S.tut===null||S.lost){el.hidden=true;return;}
|
||||
const st=TUT[S.tut];el.innerHTML=`<div class="ct"><span class="cs">${tr('tutorial.step_n_of_total',{n:S.tut+1,total:TUT.length})}</span>${esc(st.t)}</div>${btn(tr('common.skip_tutorial'),'tutSkip',{},'ghost sm')}`;el.hidden=false;
|
||||
if(st.sel){const t=document.querySelector(st.sel);if(t)t.classList.add('coach-glow');}}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
// Every field a reload gives a game is here from the start (sanitize() would add the rest), so a new game is what a
|
||||
// reload makes of it: a server checks every action against that (tests/canonical-state.test.js).
|
||||
function newGame(name,home){
|
||||
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
|
||||
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
|
||||
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null};
|
||||
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
|
||||
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null,
|
||||
lvl:1,hist:[],ach:{},ixn:{},ixPref:{},ixSite:{},confReg:{},cl:{odd:-1e9,mo:[]},sales:{p:null,hired:0,vp:null,golf:null,say:null},baronWon:0};
|
||||
for(const o of OPS)S.ops.p[o.k]={};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
runs. Players share a session by a six-character code: each builds their own network in the same world (one seed,
|
||||
one rules preset), each network's save is also kept on the server (so it can move to another device), and a small
|
||||
public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing
|
||||
when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq}; the secret token is never in
|
||||
when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq, sim?}; the secret token is never in
|
||||
S (saves get exported and shared): it lives in this browser's storage, sot-mp:<code>:<pid>. */
|
||||
const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i;
|
||||
// Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive
|
||||
|
|
@ -23,10 +23,13 @@ function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;
|
|||
function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}}
|
||||
// The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses.
|
||||
const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64);
|
||||
// sim:1, a network the session server runs (its days happen there, this page shows them). Only a page built with the
|
||||
// server's client (src/game/98-server-play/, MP builds) says yes here; everywhere else this one stays.
|
||||
function srvOn(){return false;}
|
||||
function mpSanitize(s){const m=s.mp;
|
||||
if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;}
|
||||
s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall',
|
||||
color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0)};}
|
||||
color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0),...(m.sim===1?{sim:1}:{})};}
|
||||
// What the server said when a session started or someone joined: checked before it becomes S.mp.
|
||||
function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null;
|
||||
return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
/* The sales engine of #185: would this offer work if signed now? The sales desk runs it once a day (39-sales-auto.js).
|
||||
It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */
|
||||
function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};}
|
||||
// Every field a reloaded save gives a customer (sanitize, unpackBiz), so live S is what a reload makes of it.
|
||||
function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined,warned:false,warn60:false,pm:100};}
|
||||
// OFFER_TRIED: the answer of a trial the intern's sales order already ran for this offer (the customer, or null).
|
||||
let OFFER_TRIED=null;
|
||||
function autoOffer(o){if(OFFER_TRIED&&OFFER_TRIED.o===o)return OFFER_TRIED.b;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;}
|
||||
|
|
|
|||
|
|
@ -9,9 +9,10 @@ function pniQuote(city,net,tier,reserved=0){tier=+tier;const g1=tier===-1;if(g1)
|
|||
else if(!g1&&tier<pniMin(net))why=tr('sites_peering_caches.net_does_not_do_port_pnis',{net:esc(NET[net].name),port:PORT[tier].n});
|
||||
else if(slots>0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});}
|
||||
return {city,net,tier,g1,ex,cost,slots,why};}
|
||||
// A new PNI has every field sanitize() gives one, so live S is what a reload makes of it.
|
||||
function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
|
||||
if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
|
||||
if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead});
|
||||
if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead,lacp:null,site:'a',n:1,sacrif:false});
|
||||
return lead;}
|
||||
// The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free.
|
||||
const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
|
||||
|
|
|
|||
|
|
@ -26,6 +26,9 @@ function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sit
|
|||
let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb);
|
||||
while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}}
|
||||
return {add,ports:cachePortsAdd(city,add),key:add.map(c=>c.net+'@'+c.site).join(','),mo:add.reduce((a,x)=>a+cacheMo(x),0),free:Math.max(0,portsMax(city)-portsUsed(city))};}
|
||||
// A total a window showed still holds within 1% either way: hardware prices drift a little every day under the market
|
||||
// rule, and on a server-run network days go on while a window is open. A bigger change is a new plan, shown again.
|
||||
const quoteNear=(shown,now)=>Math.abs(now-shown)<=Math.max(0.5,Math.abs(shown)*0.01);
|
||||
function utilityKit(city){const p=S&&S.pops[city];if(!p)return null;
|
||||
const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0;
|
||||
return {gen,site,router,moves:utilityCacheMoves(city),cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0),
|
||||
|
|
|
|||
|
|
@ -88,11 +88,12 @@ function sanitize(s){
|
|||
{const A=s.ddosAuto&&typeof s.ddosAuto==='object'?s.ddosAuto:{};s.ddosAuto={rtbh:A.rtbh===true,scrub:A.scrub!==false};}
|
||||
if(s.stats&&s.stats.ddT&&typeof s.stats.ddT==='object')s.stats.ddT={port:s.stats.ddT.port?1:0,fs:s.stats.ddT.fs?1:0,rtbh:s.stats.ddT.rtbh?1:0};else if(s.stats)delete s.stats.ddT;
|
||||
// Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it.
|
||||
const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!s.pops[a.city]||!own(DDOS_VEC,a.vec))return null;
|
||||
// An attack whose POP or customer went during the day stays as it is: the next morning ends it (ddosExpire), as in play.
|
||||
const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!own(DDOS_VEC,a.vec))return null;
|
||||
a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+Math.ceil(7*SPICY_LONG));
|
||||
// Attacks before 2.2 hit a city and came in on one port: they now hit someone in it, and spread (#242).
|
||||
delete a.entries;delete a.entry;delete a.ixbh;delete a.fresh;
|
||||
if(typeof a.tgt!=='string'||(a.tgt.startsWith('bb:')?a.tgt!=='bb:'+a.city:!s.biz.some(b=>b.id===a.tgt&&b.city===a.city))){
|
||||
if(typeof a.tgt!=='string'||a.tgt.length>40||own(Object.prototype,a.tgt)||(a.tgt.startsWith('bb:')&&a.tgt!=='bb:'+a.city)){
|
||||
const bs=s.biz.filter(b=>b.city===a.city&&BIZ_T[b.type]&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber).sort((x,y)=>(DD_W[y.type]||1)-(DD_W[x.type]||1)||y.bw-x.bw);a.tgt=bs.length?bs[0].id:'bb:'+a.city;}
|
||||
a.carpet=!!a.carpet;a.sac=a.sac?1:0;a.colMax=clamp(num(a.colMax,0),0,1);if(a.worst!==undefined)a.worst=clamp(num(a.worst,1),0,1);
|
||||
if(a.eng!==undefined){a.eng=num(a.eng,a.start);a.eng=Math.max(a.start,Math.min(s.day,a.eng));}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ function lagsN(){const o=[];for(const t of S.transit)if((t.n||1)>=2&&!(t.down>S.
|
|||
// Several attacks can be live at once: the primary slot keeps older saves compatible, the rest overlap it.
|
||||
function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));}
|
||||
const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id);
|
||||
function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);S.ev.ddos=left[0]||null;S.ev.ddosMore=left.slice(1);}
|
||||
// No primary attack is no ddos key at all, as sanitize() leaves it.
|
||||
function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);if(left[0])S.ev.ddos=left[0];else delete S.ev.ddos;S.ev.ddosMore=left.slice(1);}
|
||||
const ddosBb=a=>!a.tgt||a.tgt.startsWith('bb:');
|
||||
const ddosBiz=a=>ddosBb(a)?null:S.biz.find(b=>b.id===a.tgt)||null;
|
||||
// An attack ends on its day, when its city is gone, or when its target is no longer your customer.
|
||||
|
|
@ -77,11 +78,13 @@ function ddosTick(){if(scnRule('ddos')){if(S.mode==='sandbox')return;let next=+S
|
|||
if(!ddosSpicy()&&ddosAll().length)return;
|
||||
while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next<S.day?S.day+floodGap():next;return;}
|
||||
if(ddosOff()||S.day<=40)return;if(ddosAll().length>=(ddosSpicy()?3:2))return;if(Math.random()<ddosRate())ddosAttack(false);}
|
||||
// A start older than a week no longer counts toward the cap: forgotten the morning it ages out, as sanitize() forgets it.
|
||||
function ddosForget(d){const s=S.ddosStarts;if(Array.isArray(s)&&s.length&&s[0]<=d-7)S.ddosStarts=s.filter(x=>x>d-7);}
|
||||
// A new attack. With recompute, its outcome is worked out and announced now; otherwise after the day's routing.
|
||||
function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire();
|
||||
S.ddosStarts=(S.ddosStarts||[]).filter(d=>d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return null;S.ddosStarts.push(S.day);
|
||||
const [tgt,c]=ddosPickTgt(),vec=pick(ddosVectors(ddGame(tgt))),r=Math.random(),dur=r<0.7?1:r<0.95?2:3;
|
||||
const a={id:uid(),city:c,tgt,vec,gbps:0,until:S.day+dur,bh:false,start:S.day,carpet:Math.random()<0.2,fresh:1};a.gbps=ddosSize(a);
|
||||
const a={id:uid(),city:c,tgt,vec,gbps:0,until:S.day+dur,bh:false,start:S.day,carpet:Math.random()<0.2,fresh:1,sac:0,colMax:0,sla:[]};a.gbps=ddosSize(a);
|
||||
if(fl)a.who=pick(FLOOD_WHO);
|
||||
if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a);
|
||||
addInc({type:'ddos',ref:c,atk:a.id,until:a.until,msg:tr('ddos.started',{g:fmtG(a.gbps),vec:DDOS_VEC[vec].n,who:ddosWho(a)}),cost:0});
|
||||
|
|
@ -90,13 +93,15 @@ function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire();
|
|||
/* After the day's routing: announce new attacks with what they are doing, pull the plug when Auto-RTBH says so, and
|
||||
teach each lesson once. */
|
||||
function ddosNews(){runNow(ddosNewsRun());}
|
||||
// The lessons taught once a game, in the shape sanitize() gives them.
|
||||
const ddosTaught=()=>S.stats.ddT||(S.stats.ddT={port:0,fs:0,rtbh:0});
|
||||
// The same as a step of the day: its yield is the routing after Auto-RTBH pulled a plug.
|
||||
function* ddosNewsRun(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh;
|
||||
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
|
||||
if(auto&&!a.bh&&m.full>0&&ddosCol(a)>=0.01){a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);again=true;
|
||||
toast(tr('ddos.auto_rtbh',{who:esc(ddosWho(a))}),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city});}}
|
||||
if(again)yield;
|
||||
const T=S.stats.ddT||(S.stats.ddT={});
|
||||
const T=ddosTaught();
|
||||
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
|
||||
if(a.fresh){delete a.fresh;const fl=scnRule('ddos'),col=ddosCol(a),sf=ddosSf(a),bad=col>=0.01||sf<0.97;
|
||||
const how=a.bh?tr('ddos.news_rtbh'):col>=0.01?tr('ddos.news_ports',{n:m.full,k:m.slowed}):sf<0.97?tr('ddos.news_target',{p:pct(sf)}):tr('ddos.news_held');
|
||||
|
|
|
|||
|
|
@ -26,7 +26,9 @@ function* dayPreRun(){
|
|||
if(!S||S.lost||!rule('clock'))return false; // no clock (puzzles): no days, no bills, nothing fires
|
||||
S.day++;
|
||||
const d=S.day;
|
||||
dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d);
|
||||
// A charter never picked reads as the classic one once its days are over, as a reload reads it (specSanitize).
|
||||
if(S.chartSet===false&&d>CHARTER_DAYS)S.chartSet=true;
|
||||
ddosForget(d);dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d);
|
||||
yield DAY_REST;
|
||||
if(!S.phpDone&&d>45&&Math.random()<1/400)elephant();
|
||||
if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved);
|
||||
|
|
@ -112,7 +114,7 @@ function* dayPost(d){
|
|||
// the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them
|
||||
yield* slAutoRun(d);
|
||||
if(opsHired())yield DAY_REST;
|
||||
yield* opsRun(d);
|
||||
yield* opsRun(d);opsTidy();
|
||||
if(S.pie){pieDay(d);pieTier();}
|
||||
// payday floaters
|
||||
if(cal(d).d===1){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}
|
||||
|
|
@ -128,6 +130,10 @@ function* dayPost(d){
|
|||
{const c=cal(d);if(c.m===0&&c.d===1&&[2,3,5].includes(c.y))track('game_year_'+c.y,true);}
|
||||
if(d%10===0)save();
|
||||
}
|
||||
// The shift's notes as a reload keeps them (opsSanitize): at most three places a job in the day's log (the broken links
|
||||
// were all listed), and no empty list in the week's tally. So live state is what a reload makes of it (server-sim 5.4).
|
||||
function opsTidy(){const O=S.ops;if(!O)return;for(const e of O.log||[])for(const r of e.r||[])if(Array.isArray(r[2])&&r[2].length>3)r[2]=r[2].slice(0,3);
|
||||
for(const w of [O.wk,O.rep])if(w&&w.wh)for(const k of Object.keys(w.wh))if(Array.isArray(w.wh[k])&&!w.wh[k].length)delete w.wh[k];}
|
||||
function spawnOffer(){
|
||||
const mine=spMine(Object.keys(S.pops).filter(bizCity)),lv=lvl();
|
||||
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub');
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
Object.assign(ACT,{
|
||||
buildPop:({city})=>{if(S.pops[city]||!CITY[city])return;if(!cityOn(city)){toast(popOffWhy(city),'bad');sfx('err');return;}const flipNote=CITY[city]&&CITY[city].au;if(cnCity(city)&&!cnOk()){toast(tr('pops_transit_ix.you_need_a_license_first_foreign'),'bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(city);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');if(flipNote)toast(pick([tr('pops_transit_ix.router_installed_in_city_upside_down',{city:CITY[city].name}),tr('pops_transit_ix.router_installed_in_city_the_vendor',{city:CITY[city].name})]),'good',[],{a:'city',v:city});UI.tab='cust';after();},
|
||||
buildPop:({city})=>{if(S.pops[city]||!CITY[city])return;if(!cityOn(city)){toast(popOffWhy(city),'bad');sfx('err');return;}const flipNote=CITY[city]&&CITY[city].au;if(cnCity(city)&&!cnOk()){toast(tr('pops_transit_ix.you_need_a_license_first_foreign'),'bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(city);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');if(flipNote)toast(pick([tr('pops_transit_ix.router_installed_in_city_upside_down',{city:CITY[city].name}),tr('pops_transit_ix.router_installed_in_city_the_vendor',{city:CITY[city].name})]),'good',[],{a:'city',v:city});UI.tab='cust';after();},
|
||||
launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:bbStart(city)};floater(C.x,C.y-30,tr('common.eyeballs_online'),'#16A866');after();},
|
||||
ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,tr('common.ad_campaign'),'#FF8A3D');after();},
|
||||
buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast(tr('pops_transit_ix.no_transit_in_this_scenario_peering'),'bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!sellsAt(NET[net],city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.transit.push({id:uid(),city,net,tier,down:0,...(premOnlyAt(NET[net],city)?{premium:true}:{})});toast(tr('pops_transit_ix.net_transit_is_live_in_city',{net:esc(NET[net].name),city:CITY[city].name}),'good');after();},
|
||||
// A new port has every field sanitize() gives one, so live S is what a reload makes of it.
|
||||
buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast(tr('pops_transit_ix.no_transit_in_this_scenario_peering'),'bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!sellsAt(NET[net],city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else{const pr=premOnlyAt(NET[net],city);S.transit.push({id:uid(),city,net,tier,down:0,...(pr?{premium:true}:{}),lacp:null,site:'a',n:1,clean:false,...(pr?{}:{premium:false})});}toast(tr('pops_transit_ix.net_transit_is_live_in_city',{net:esc(NET[net].name),city:CITY[city].name}),'good');after();},
|
||||
lagT:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const t=S.transit.find(x=>x.id===id);if(!t)return;const n=(t.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0){if(!portOk(t.city,t.tier)||!portGate(t.city,PORT_SLOT(t.tier)))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;if(n<2&&t.site==='ab')t.site='a';toast(+d>0?tr('pops_transit_ix.lag_member_added_net_in_city',{net:esc(NET[t.net].name),city:CITY[t.city].name,lag:lagName(t.tier,n)}):tr('pops_transit_ix.lag_member_removed'),'good');after();},
|
||||
lagP:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(d>0&&(!pniOn(p)||p.up||msfNope(p.net,p.city)))return;if(+d>0&&(!portGate(p.city,PORT_SLOT(p.tier))||!spend(1500+PORT[p.tier].setup/2)))return;
|
||||
// A LAG member is an augment: the big networks take months for that too.
|
||||
|
|
|
|||
|
|
@ -8,8 +8,9 @@ Object.assign(ACT,{
|
|||
teBack:()=>teModal(),
|
||||
teRecipe:({id})=>{const r=TE_RECIPES.find(x=>x.id===id);if(!r)return;UI.teDraft=r.src().join('\n');teModal(`<p class="note">${tr('route_script_and_tools.loaded_name_check_it_then_deploy',{name:tr(r.n)})}</p>`);},
|
||||
teClear:()=>{S.te.script='';UI.teDraft=undefined;TE_CACHE={src:null,p:null};after();teModal(`<p class="note">${tr('route_script_and_tools.script_removed_plain_auto_te_is')}</p>`);},
|
||||
teCheck:()=>{const t=$('teSrc');const src=t?t.value:'';UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(p.errors.join('\n'))}</pre>`);return;}const r=teTrial(src);teModal(`<pre class="term">${esc(trn('route_script_and_tools.n_rule_ok',p.n)+'\n'+tr('route_script_and_tools.served_a_b',{a:fmtG(r.before.served),b:fmtG(r.after.served)})+'\n'+tr('route_script_and_tools.transit_a_mo_b_mo',{a:fmt$(r.before.tc),b:fmt$(r.after.tc)})+'\n'+tr('route_script_and_tools.spilled_g_onto_alternate_paths',{g:fmtG(r.after.moved)})+(r.after.bh?'\n'+tr('route_script_and_tools.blackholed_g',{g:fmtG(r.after.bh)}):''))}</pre>`);},
|
||||
teDeploy:()=>{const t=$('teSrc');const src=(t?t.value:'').slice(0,4000);UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(tr('common.commit_failed')+'\n'+p.errors.join('\n'))}</pre>`);sfx('err');return;}const r=teTrial(src);S.te.script=src;S.te.on=true;TE_CACHE={src:null,p:null};UI.teDraft=undefined;after();
|
||||
// The script as an argument (a server runs these without the editor), else the editor's text.
|
||||
teCheck:({script}={})=>{const t=$('teSrc');const src=typeof script==='string'?script:t?t.value:'';UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(p.errors.join('\n'))}</pre>`);return;}const r=teTrial(src);teModal(`<pre class="term">${esc(trn('route_script_and_tools.n_rule_ok',p.n)+'\n'+tr('route_script_and_tools.served_a_b',{a:fmtG(r.before.served),b:fmtG(r.after.served)})+'\n'+tr('route_script_and_tools.transit_a_mo_b_mo',{a:fmt$(r.before.tc),b:fmt$(r.after.tc)})+'\n'+tr('route_script_and_tools.spilled_g_onto_alternate_paths',{g:fmtG(r.after.moved)})+(r.after.bh?'\n'+tr('route_script_and_tools.blackholed_g',{g:fmtG(r.after.bh)}):''))}</pre>`);},
|
||||
teDeploy:({script}={})=>{const t=$('teSrc');const src=(typeof script==='string'?script:t?t.value:'').slice(0,4000);UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(tr('common.commit_failed')+'\n'+p.errors.join('\n'))}</pre>`);sfx('err');return;}const r=teTrial(src);S.te.script=src;S.te.on=true;TE_CACHE={src:null,p:null};UI.teDraft=undefined;after();
|
||||
const drop=r.before.served>1?1-r.after.served/r.before.served:0,saved=r.before.tc>0?1-r.after.tc/r.before.tc:0;
|
||||
if(drop>0.1&&UI.slop===src){if(drop>0.3)S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_the',{p:pct(drop)}),'bad');sfx('alert');}
|
||||
else if(drop>0.3){S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_you',{p:pct(drop)}),'bad');sfx('alert');}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,9 @@ Object.assign(ACT,{
|
|||
toast(lead?tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}):tr('sites_peering_caches.pni_with_net_is_up_already',{net:esc(NET[net].name),dc:esc(siteName(city,'a'))}),'good');after();},
|
||||
pniAllOpen:({net})=>{pniAllModal(net);},
|
||||
pniAllSize:({v})=>{if(!UI.pniAll)return;pniAllModal(UI.pniAll.net,+v);$('modalCard').querySelector('[data-chg="pniAllSize"]')?.focus();},
|
||||
pniAll:({net,tier})=>{const b=pniBatch(net,tier);if(!b||!b.orders.length)return;if(!spend(b.cost))return;
|
||||
// q: the total the sheet showed. The batch is planned again now; a different total (the prices are fixed, so another
|
||||
// plan), or nothing left to order, is shown again, not bought.
|
||||
pniAll:({net,tier,q})=>{const b=pniBatch(net,tier);if(!b)return;if(q!==undefined&&(+q!==b.cost||!b.orders.length)){pniAllModal(net,tier,tr('utilities.quote_changed'));sfx('err');return;}if(!b.orders.length)return;if(!spend(b.cost))return;
|
||||
for(const q of b.orders)pniPlace(q);UI.pniAll=null;closeModal();
|
||||
toast(trn('pni_all.n_orders_with_net',b.orders.length,{net:esc(net===null?tr('common.all_networks'):NET[net].name),kept:b.kept,blocked:b.blocked.length}),'good');after();},
|
||||
pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random();
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ Object.assign(ACT,{
|
|||
const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name);
|
||||
if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots);
|
||||
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;}
|
||||
S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer));
|
||||
S.offers=S.offers.filter(x=>x!==o);if(o.mk&&clOn(customer))customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer));
|
||||
// The shark's commission: one month of what the deal pays, on signing.
|
||||
if(o.by==='shark'){const c=Math.round(bizMo(customer));if(c>0){S.cash-=c;toast(tr('sales.commission',{name:esc(o.name),cost:fmt$(c)}),'');}}
|
||||
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();},
|
||||
|
|
|
|||
|
|
@ -13,13 +13,13 @@ Object.assign(ACT,{
|
|||
if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();},
|
||||
myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
|
||||
foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name;
|
||||
S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();},
|
||||
S.myIx[city]={name:nm,members:[],next:S.day+4,fab:0};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();},
|
||||
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
|
||||
if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return;
|
||||
if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;}
|
||||
const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;}
|
||||
{const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b));
|
||||
if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);}
|
||||
if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
|
||||
const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);satBeside(a,b);closeModal();
|
||||
if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';}
|
||||
floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');after();},
|
||||
|
|
@ -47,8 +47,9 @@ Object.assign(ACT,{
|
|||
metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l)return;const key=edgeKey(l),c=pairCm(key);if(!c||c.k===k)return;
|
||||
// The cost stays what it was on this link, written the other way.
|
||||
const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};metBlur();sfx('click');after();},
|
||||
metricSet:({id})=>{const l=S.links.find(x=>x.id===id),t=$('metIn');if(!l||!t)return;const key=edgeKey(l),c=pairCm(key);if(!c)return;const v=parseFloat(String(t.value).replace(',','.'));if(!Number.isFinite(v)){sfx('err');return;}
|
||||
t.blur();S.pairMet[key]={k:c.k,v:clampM(c.k,v)};sfx('click');after();},
|
||||
// v: the typed value as an argument (a server runs this without the field), else the field's.
|
||||
metricSet:({id,v})=>{const l=S.links.find(x=>x.id===id),t=$('metIn'),txt=v!==undefined?v:t?t.value:undefined;if(!l||txt===undefined)return;const key=edgeKey(l),c=pairCm(key);if(!c)return;const x=parseFloat(String(txt).replace(',','.'));if(!Number.isFinite(x)){sfx('err');return;}
|
||||
if(t)t.blur();S.pairMet[key]={k:c.k,v:clampM(c.k,x)};sfx('click');after();},
|
||||
setCarry:({id,on})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;if(on)t.carry=true;else delete t.carry;sfx('click');after();},
|
||||
setStandby:({id,on})=>{const l=S.links.find(x=>x.id===id);if(!l)return;if(on)l.standby=true;else delete l.standby;sfx('click');after();},
|
||||
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();},
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ Object.assign(ACT,{
|
|||
sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('security_and_china.net_pni_is_now_a_sacrificial',{net:NET[p.net].name}):tr('security_and_china.net_pni_is_back_to_normal',{net:NET[p.net].name}),p.sacrif?'good':'');after();},
|
||||
// RTBH blackholes the target upstream: your ports and everyone else are saved, the target is dark until you withdraw it.
|
||||
rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}if(a.bh)return;a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);
|
||||
const T=S.stats.ddT||(S.stats.ddT={}),first=!T.rtbh;T.rtbh=1;toast(tr('ddos.rtbh_on',{who:esc(ddosWho(a))})+(first?'<br><i>'+tr('ddos.learn_rtbh')+'</i>':''),'bad');sfx('alert');after();},
|
||||
const T=ddosTaught(),first=!T.rtbh;T.rtbh=1;toast(tr('ddos.rtbh_on',{who:esc(ddosWho(a))})+(first?'<br><i>'+tr('ddos.learn_rtbh')+'</i>':''),'bad');sfx('alert');after();},
|
||||
unrtbh:({id}={})=>{const a=ddosFind(id);if(!a||!a.bh)return;a.bh=false;toast(tr('ddos.rtbh_off',{who:esc(ddosWho(a))}),'');after();},
|
||||
// On-demand scrubbing, when it does not engage by itself: start the diversion now.
|
||||
ddosEngage:({id}={})=>{const a=ddosFind(id);if(!a||!hasScrub()||a.eng!==undefined)return;a.eng=S.day;toast(tr('ddos.engaged'),'good');sfx('click');after();},
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ Object.assign(ACT,{
|
|||
toast(tr('specialist.the_vendor_ships_a_demo_name',{name:esc(it.n),n:at-S.day,p:Math.round((DEMO_MUL-1)*100)}),'good');after();},
|
||||
seatBuy:({n})=>{const o=S.seatOff;n=+n;if(!o||o.exp<=S.day||!SEAT_N.includes(n))return;const miss=[o.a,o.b].filter(c=>!S.pops[c]),cost=seatCost(o.km,n)+miss.reduce((x,c)=>x+popCost(c),0);if(!spend(cost))return;
|
||||
for(const c of miss){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(c);}
|
||||
const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n)});satBeside(o.a,o.b);
|
||||
const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n),regen:0});satBeside(o.a,o.b);
|
||||
S.seatOff=null;S.stats.seats=(S.stats.seats||0)+1;UI.sel={type:'link',id};
|
||||
toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();},
|
||||
seatNo:()=>{S.seatOff=null;after();},
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ Object.assign(ACT,{
|
|||
orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return;
|
||||
if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
|
||||
const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,id=uid(),ship=layName({id}),days=q.days;
|
||||
S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1});satBeside(a,b);
|
||||
S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1,regen:0});satBeside(a,b);
|
||||
const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;
|
||||
S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id};
|
||||
toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();},
|
||||
|
|
@ -19,7 +19,7 @@ Object.assign(ACT,{
|
|||
const up=(own?digCost(km):0)+sysCost(sys)+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return;
|
||||
if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
|
||||
const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),id=uid();
|
||||
const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false};
|
||||
const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false,regen:0};
|
||||
S.links.push(l);satBeside(a,b);closeModal();UI.sel={type:'link',id};
|
||||
toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();},
|
||||
regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||(l.sub&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return;
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ Object.assign(ACT,{
|
|||
// Next to a link you already have between the two, it goes on standby: the backup that carries only when the cable is down.
|
||||
buySat:({a,b,bird,g})=>{g=+g;const why=satWhy(a,b,bird,g);if(why){toast(why,'bad');sfx('err');return;}
|
||||
if(!portGate(a,1)||!portGate(b,1))return;const mo=satMo(bird,g),pop=!S.pops[b];if(!spend(mo+(pop?popCost(b):0)))return;
|
||||
if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);}
|
||||
if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
|
||||
const sb=pairLinks(a,b).some(l=>l.kind!=='sat'),n=leadDays(SAT_ORB[SATS[bird].orb].days),id=uid();
|
||||
S.links.push({id,a,b,kind:'sat',bird,g,km:satKm(bird,a,b),sub:true,mo,cut:0,day:S.day,ready:S.day+n,...(sb?{standby:true}:{})});
|
||||
closeModal();UI.sel={type:'link',id};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
// The build standard sheet (93-ui/59-build-standard.js): pick a target, or bring everything up to the standard in one go.
|
||||
// The plan a sheet showed, as a short key: its jobs, in any order (the plan sorts POPs by today's load).
|
||||
function bstdPlanKey(J){const s=J.map(j=>j.grp+' '+j.k+' '+j.ch+' '+j.w).sort().join('\n');let h=0x811c9dc5;
|
||||
for(let i=0;i<s.length;i++){h^=s.charCodeAt(i);h=Math.imul(h,0x01000193);}return J.length+'.'+(h>>>0).toString(36);}
|
||||
const bstdSum=J=>Math.round(J.reduce((a,j)=>a+j.cost,0));
|
||||
Object.assign(ACT,{
|
||||
bstdOpen:()=>{if(S&&!pzOn())bstdModal();},
|
||||
// v: a position in the list the sheet shows; without v, the next value (the MCP tools step through a list).
|
||||
|
|
@ -6,9 +10,13 @@ Object.assign(ACT,{
|
|||
D[k]=x;S.popStd=bstdPut(D);sfx('click');after();opsRedraw('bstdSet',{k},bstdModal);},
|
||||
// The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One
|
||||
// recompute at the end, and one toast: what got done, and what still waits.
|
||||
bstdApply:()=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);if(!J.length)return;const c0=S.cash;let n=0;
|
||||
// quote: the plan the sheet showed (bstdPlanKey), q: its total. Another plan, a total that moved more than a day's drift
|
||||
// (quoteNear), or nothing left to do is shown again, not built.
|
||||
bstdApply:({quote,q}={})=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);
|
||||
if((quote!==undefined||q!==undefined)&&(!J.length||(quote!==undefined&&String(quote)!==bstdPlanKey(J))||(q!==undefined&&!quoteNear(+q,bstdSum(J))))){bstdModal(tr('utilities.quote_changed'));sfx('err');return;}
|
||||
if(!J.length)return;const c0=S.cash;let n=0;
|
||||
opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go()).length;});
|
||||
after();const q=bstdQuote(false),left=q.pops+q.ports+q.links;
|
||||
after();const z=bstdQuote(false),left=z.pops+z.ports+z.links;
|
||||
toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err');
|
||||
if(bstdShown())bstdModal();},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ Object.assign(ACT,{
|
|||
utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true;
|
||||
if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));},
|
||||
utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||(!q.cost&&!q.moves.length))return;
|
||||
// Prices can change while a modal is open. Refresh the quote before spending more.
|
||||
if(q.cost!==+cost){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;}
|
||||
// Prices can change while a modal is open. Refresh the quote before spending more (a day's drift is fine: quoteNear).
|
||||
if(!quoteNear(+cost,q.cost)){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;}
|
||||
if(q.cost&&!spend(q.cost))return;const p=S.pops[city];
|
||||
if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2;
|
||||
const moves=new Map(q.moves.map(m=>[m.id,m.site]));for(const c of S.caches)if(moves.has(c.id))c.site=moves.get(c.id);
|
||||
|
|
|
|||
|
|
@ -24,7 +24,8 @@ Object.assign(ACT,{
|
|||
slotTake:({id})=>{if(!slotOkId(id))return;const w=SLOT.wait={id,go:()=>{if(SLOT.wait!==w)return;SLOT.wait=null;clearTimeout(w.t);slotOpen(id,true);}};
|
||||
w.t=setTimeout(w.go,BC?1500:0);try{if(BC)BC.postMessage({t:'take',id});}catch(e){w.go();}},
|
||||
rename:()=>{if(!S||!UI.started||pzOn())return;openModal(`<h2 style="font-size:26px">${tr('slots.rename_your_network')}</h2><label class="f" for="rnIn">${tr('title.name_your_network')}</label><div class="network-name"><input class="t" id="rnIn" maxlength="24" value="${esc(S.name)}" autocomplete="off"></div><div class="btns" style="margin-top:12px">${btn(tr('slots.rename'),'renameGo',{},'pink big')}${btn(tr('common.cancel'),'menu',{},'ghost big')}</div>`);},
|
||||
renameGo:()=>{const el=$('rnIn');if(!S||!el||pzOn())return;const v=el.value.replace(/\s+/g,' ').trim().slice(0,24);if(!v)return;S.name=v;closeModal();after();toast(tr('slots.renamed_to_name',{name:esc(v)}),'good');},
|
||||
// name: the new name as an argument (a server runs this without the sheet), else the sheet's field.
|
||||
renameGo:({name}={})=>{const el=$('rnIn'),raw=typeof name==='string'?name:el?el.value:null;if(!S||raw===null||pzOn())return;const v=raw.replace(/\s+/g,' ').trim().slice(0,24);if(!v)return;S.name=v;closeModal();after();toast(tr('slots.renamed_to_name',{name:esc(v)}),'good');},
|
||||
});
|
||||
// No game on screen: the map stays empty behind the title.
|
||||
function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ Object.assign(ACT,{
|
|||
if(!pieSpend(pieLicPrice(cc)))return pieRe();P.lic[cc]={state:'ok',until:Math.max(S.day,l&&l.state==='ok'?l.until:0)+PIE_LIC_DAYS};toast(tr('pie.t_lic',{n:pieLicCountry(cc)}),'good');pieRe();},
|
||||
pieSafe:()=>{const P=pieGet();if(!P||!P.co)return;P.safe=!P.safe;sfx('click');pieRe();},
|
||||
pieName:()=>{const P=pieGet();if(!P||!P.co)return;const i=PIE_NAMES.indexOf(P.co.name);P.co.name=PIE_NAMES[(i+1)%PIE_NAMES.length];pieFounder(N_('pie.fp_rename'));pieRe();},
|
||||
pieRename:()=>{const P=pieGet(),el=$('pieNm');if(!P||!P.co||!el)return;const v=el.value.replace(/\s+/g,' ').trim().slice(0,40);if(!v)return;P.co.name=v;pieFounder(N_('pie.fp_rename'));pieRe();},
|
||||
// name: the new name as an argument (a server runs this without the field), else the field's.
|
||||
pieRename:({name}={})=>{const P=pieGet(),el=$('pieNm'),raw=typeof name==='string'?name:el?el.value:null;if(!P||!P.co||raw===null)return;const v=raw.replace(/\s+/g,' ').trim().slice(0,40);if(!v)return;P.co.name=v;pieFounder(N_('pie.fp_rename'));pieRe();},
|
||||
// Government money (60-features/99-pie-subsidies.js): its section in the bank, a bid, the Ex-Im loan. It was Pie Control's Gov tab; the name stays for old toasts.
|
||||
pieGovOpen:()=>{if(!S||pzOn()||!pieOn())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankGov');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});},
|
||||
pieBid:({id,f})=>{const P=pieGet();f=+f;const a=P&&P.gov.auc.find(x=>x.id===id);if(!a||!PIE_RDF_BIDS.includes(f))return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));
|
||||
|
|
|
|||
|
|
@ -80,3 +80,7 @@ function importFile(file){if(!file)return;if(file.size>64e6){toast(tr('save.that
|
|||
function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null;
|
||||
try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){}
|
||||
UI.loadBad=true;return null;}
|
||||
// What a network says once when it is opened again: new networks on the map (the courtesy route), Australia's prices.
|
||||
// Boot calls it; a server-run network hears it from the server instead (it changes S).
|
||||
function bootNotes(){if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
|
||||
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}}
|
||||
|
|
|
|||
|
|
@ -17,9 +17,10 @@ function bstdVal(k,v){if(v===BSTDK[k].d&&k!=='rt')return tr('bstd.keep');
|
|||
case 'wv':return tr('bstd.or_better',{x:LT[v].n});}
|
||||
return String(v);}
|
||||
const bstdShown=()=>!!$('modal')&&!$('modal').hidden&&!!$('modalCard').querySelector('[data-sheet="bstd"]');
|
||||
function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hired=opsHired(),on=hired&&S.ops.on.std;
|
||||
// msg: why the sheet is shown again (the quote changed).
|
||||
function bstdModal(msg){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hired=opsHired(),on=hired&&S.ops.on.std;
|
||||
let h=`<div data-sheet="bstd" style="display:flex;align-items:center"><div><div class="eyebrow">${tr('ops.ops')}</div><h2 style="font-size:26px">${tr('bstd.title')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
|
||||
<p class="tagline">${tr('bstd.tagline')}</p>`;
|
||||
<p class="tagline">${tr('bstd.tagline')}</p>${typeof msg==='string'&&msg?`<p class="why">${esc(msg)}</p>`:''}`;
|
||||
for(const [g,lab] of BSTD_GRP)h+=`<section><h3>${tr(lab)}</h3><div class="ops-p">${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}</div>
|
||||
<p class="note">${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note_two')}</p></section>`;
|
||||
// What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose
|
||||
|
|
@ -34,5 +35,6 @@ function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hire
|
|||
<button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"std"}' aria-pressed="${on}" aria-label="${esc(tr('ops.o_std'))}">${on?tr('common.on'):tr('ops.paused')}</button></div>
|
||||
${on?`<div class="ops-p">${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}</div>`:''}</div>`
|
||||
:`<p class="meta">${tr('bstd.hire_note')}</p><div class="btns">${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}</div>`}</section>`;
|
||||
h+=`<div class="btns cta">${btn(q.n?tr('bstd.apply_now',{cost:fmt$(q.cost)}):w?tr('bstd.apply_wait'):tr('bstd.apply_nothing'),'bstdApply',{},'pink',!q.n)}</div>`;
|
||||
// The button carries the plan it shows and its total (bstdApply checks both again).
|
||||
h+=`<div class="btns cta">${btn(q.n?tr('bstd.apply_now',{cost:fmt$(q.cost)}):w?tr('bstd.apply_wait'):tr('bstd.apply_nothing'),'bstdApply',{quote:bstdPlanKey(bstdPlan(false)),q:q.cost},'pink',!q.n)}</div>`;
|
||||
openModal(h,'ops');}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
/* ---------- toasts & modals ---------- */
|
||||
function toast(html,kind='',actions=[],open=null){
|
||||
if(S)logNote(html,kind,actions,open);
|
||||
toastPop(html,kind,actions,UI.tick);}
|
||||
// The toast on screen only (the log line is toast()'s). tick: the day announced it (UI.tick when it was said).
|
||||
function toastPop(html,kind='',actions=[],tick=false){
|
||||
// Quiet notifications: what the day announces pops up only for trouble and milestones; the rest stays in the NOC log.
|
||||
if(UI.tick&&kind!=='bad'&&kind!=='goal'&&quietOn())return;
|
||||
if(tick&&kind!=='bad'&&kind!=='goal'&&quietOn())return;
|
||||
const el=document.createElement('div');el.className='toast '+kind;el.dataset.born=performance.now();
|
||||
el.innerHTML=`<div class="tx">${html}</div>${actions.map(a=>btn(a.l,a.act,a.args,'sm')).join('')}`;
|
||||
const box=$('toasts');box.prepend(el);const max=innerWidth<760?2:3;while(box.children.length>max)box.lastChild.remove();
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
function pniAllModal(net,tier=1){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier};
|
||||
// msg: why the sheet is shown again (the quote changed).
|
||||
function pniAllModal(net,tier=1,msg=''){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier};
|
||||
const all=net===null,n=NET[net],port=tier===-1?'1G':PORT[tier].n,up=b.orders.filter(q=>q.ex).length,byNet={};
|
||||
if(all)for(const q of b.orders)(byNet[q.net]||(byNet[q.net]=[])).push(q.city);
|
||||
const controls=`<div class="btns">${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier},'pink',!b.orders.length||S.cash<b.cost)}${btn(tr('common.cancel'),'closeModal',{},'ghost')}</div>`;
|
||||
const controls=`<div class="btns">${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier,q:b.cost},'pink',!b.orders.length||S.cash<b.cost)}${btn(tr('common.cancel'),'closeModal',{},'ghost')}</div>`;
|
||||
const blocked=b.blocked.map(q=>`<p class="why"><b>${all?esc(NET[q.net].name)+' · ':''}${esc(CITY[q.city].name)}:</b> ${q.why}</p>`).join('');
|
||||
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${all?tr('common.all_networks'):`AS${n.asn} · ${esc(n.name)}`}</div><h2>${all?tr('pni_all.peer_all_networks'):tr('pni_all.peer_on_all_pops')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
|
||||
<p class="lead">${tr('pni_all.order_missing_and_upgrade_smaller')}</p>
|
||||
<p class="lead">${tr('pni_all.order_missing_and_upgrade_smaller')}</p>${msg?`<p class="why">${esc(msg)}</p>`:''}
|
||||
<div class="trsel"><label>${tr('pni_all.pni_size')}<select data-chg="pniAllSize">${pniG1(net)?`<option value="-1"${tier===-1?' selected':''}>1G</option>`:''}${PORT.map((p,i)=>portShown(i)&&(all||i>=pniMin(net))?`<option value="${i}"${tier===i?' selected':''}>${p.n}</option>`:'').join('')}</select></label></div>
|
||||
<div class="kv"><span>${tr('pni_all.new_and_upgrades',{fresh:b.orders.length-up,up})}</span><b>${all?tr('pni_all.n_of_total_connections',{n:b.orders.length,total:b.shared.length}):tr('pni_all.n_of_total_pops',{n:b.orders.length,total:b.shared.length})}</b></div>
|
||||
<div class="kv"><span>${tr('pni_all.setup_total')}</span><b>${fmt$(b.cost)}</b></div>
|
||||
|
|
|
|||
6
src/game/98-server-play/00-about.js
Normal file
6
src/game/98-server-play/00-about.js
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
/* ================= SERVER-RUN PLAY (multiplayer builds only) =================
|
||||
This folder is only in a page built with MP_API (scripts/lib/page.js leaves it out of every other page, the one on
|
||||
GitHub Pages included). A network of a server session (S.mp.sim===1) runs its days on the session server; this page
|
||||
shows it and sends the player's clicks. The folder hooks in by rebinding top-level functions of earlier files, like
|
||||
srvOn() (60-features/89-multiplayer.js), bootNotes() (91-save.js) and renderCoach(), and by adding to ACT. It sorts
|
||||
before 99-loop.js, whose two srvOn() checks keep the clock and the boot routing off for such a network. */
|
||||
|
|
@ -14,7 +14,8 @@ function frame(now){
|
|||
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
|
||||
if(UI.panelsDue){NOC.dirty=true;UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
|
||||
if(NOC.peer)nocPump(now);
|
||||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt);
|
||||
// A network the server runs (srvOn) has its days there: this page only shows them.
|
||||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()&&!srvOn())runClock(dt);
|
||||
if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
|
||||
const t=animOn()?animT:0;
|
||||
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;}
|
||||
|
|
@ -51,11 +52,10 @@ function boot(data){
|
|||
applyAnim();
|
||||
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
|
||||
else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv;
|
||||
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
|
||||
let okSave=false;if(sv){try{S=migrate(sv);if(!srvOn())compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
|
||||
if(okSave){slotIn(UI.slot,stamp);if(MP_API)mpResume();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
|
||||
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
|
||||
renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
|
||||
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}
|
||||
renderAll();bootNotes();
|
||||
if(!whatsNew(true))toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}
|
||||
// A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted.
|
||||
else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot);
|
||||
|
|
|
|||
3
src/styles/43-server-play.css
Normal file
3
src/styles/43-server-play.css
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
/* ================= SERVER-RUN PLAY (multiplayer builds only) =================
|
||||
The look of src/game/98-server-play/: only in a page built with MP_API (scripts/lib/page.js leaves it out of every
|
||||
other page). */
|
||||
Loading…
Add table
Add a link
Reference in a new issue