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
|
|
@ -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;}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue