Multiplayer for self-hosted copies: sessions, server-side saves, a leaderboard

Off unless the page is built with MP_API set (MP_API=/api/mp npm run
build): a plain build has no door, no chip and makes no requests. The
session server is scripts/mp-server.js (npm run mp), plain node:http,
which can also serve the built site so one process sits behind the
reverse proxy; docs/MULTIPLAYER.md has the nginx and Caddy setups.

A session has a six-character code, one seed and one rules preset, so
every player starts in the same world, and up to twelve players with
their own AS numbers. Saves go to the server on a new game day at most
every 15 s and when the page hides, ordered by a sequence number (409 on
a stale push, and the player picks which one to keep). Tokens live in
localStorage, never in the save; the server keeps only their hash. A
#mp= link moves a network to another device. The session panel shows
the leaderboard, the feed and a short chat; each player's public card
(tier, POPs, links, exchanges, transit, peak, customers, score) carries
what in-game peering between players will need next.

Server limits: body sizes, one upload per player, uploads per address
and in total, sessions per hour, wrong-code lockout; addresses counted
per IPv6 /64, X-Forwarded-For only with --trust-proxy.
This commit is contained in:
jvanvik 2026-11-07 00:42:39 +01:00
parent 2b48a6ad65
commit 95aa9b6532
39 changed files with 2757 additions and 24 deletions

View file

@ -7,6 +7,9 @@ const RELEASE_NOTES=/*__RELEASE_NOTES__*/[];
// A big release's story, shown in full in "What's new" (paragraphs; **bold** allowed). Empty for most releases.
const RELEASE_STORY=/*__RELEASE_STORY__*/[];
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__*/'';
// 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(){

View file

@ -44,6 +44,8 @@ function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let
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';
// 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.
{const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);}
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}}
@ -55,4 +57,5 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci
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');
// A Normal game asks for its charter first; the tutorial starts once it is signed.
renderAll();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(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}
if(S.mp)mpStartTell();}

View file

@ -1,6 +1,6 @@
function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,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}};
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};
}

View file

@ -0,0 +1,180 @@
/* ================= MULTIPLAYER (docs/MULTIPLAYER.md) =================
Only in a self-hosted copy built with MP_API (scripts/mp-server.js on the same origin); with MP_API empty nothing here
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
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
// request (the page is going away) carries at most 64 KiB, so only a small save goes with it (MP_KEEP bytes of request,
// with room to spare), else the card alone.
const MP_GAP=15000,MP_POLL=5000,MP_KEEP=63000,MP_GZ=32768,MP_FEED=['join','leave','t2','t1','t1first','chat'];
/* cur: the push on its way ({cut, ac}); staleSeq: the server's number when it said it has a newer save; sig: what the
last push that landed looked like (mpSig); force: the player chose to keep this save; now: push at the next save. */
const MP={roster:null,day:-1,last:-1e9,busy:false,cur:null,stale:false,staleSeq:0,gone:false,leaving:false,wait:0,fails:0,told:false,poll:null,sig:'',force:false,now:false};
const mpIs=()=>!!(MP_API&&S&&S.mp&&!pzOn());
const mpShow=c=>c.slice(0,3)+'-'+c.slice(3);
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code, or null. I, L and O read as 1, 1 and 0 (Crockford's base32).
function mpNorm(s){if(typeof s!=='string'||s.length>20)return null;const c=s.toUpperCase().replace(/[\s-]/g,'').replace(/[IL]/g,'1').replace(/O/g,'0');return MP_CODE.test(c)?c:null;}
const mpPath=(m,p)=>'/sessions/'+m.code+(p||'');
const mpTokK=(c,p)=>'sot-mp:'+c+':'+p;
function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;const t=lsGet(mpTokK(m.code,m.pid));return typeof t==='string'&&MP_TOK.test(t)?t: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);
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)};}
// 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):''};}
/* One call to the session server. Same origin, never cached; a call that takes over 15 s gives up. Rejects with
{status, j} on an HTTP error, so callers can tell "no such session" from "server away". */
function mpReq(method,p,body,o={}){
if(!MP_API||typeof fetch!=='function')return Promise.reject(Object.assign(new Error('off'),{status:0}));
const h={};if(body!==undefined)h['content-type']='application/json';
// o.tok: a token not stored yet (a #mp= link's, until the server takes it).
if(o.auth){const t=o.tok||mpTok(o.auth);if(!t)return Promise.reject(Object.assign(new Error('no token'),{status:401}));h.authorization='Bearer '+o.auth.pid+'.'+t;}
const ac=o.keep?null:o.ac||(typeof AbortController==='function'?new AbortController():null),tm=ac?setTimeout(()=>ac.abort(),15000):0;
let f;try{f=fetch(MP_API+p,{method,headers:h,body:body===undefined?undefined:typeof body==='string'?body:JSON.stringify(body),cache:'no-store',credentials:'same-origin',...(o.keep?{keepalive:true}:{}),...(ac?{signal:ac.signal}:{})});}
catch(e){clearTimeout(tm);return Promise.reject(Object.assign(e,{status:0}));}
return Promise.resolve(f).then(r=>Promise.resolve(r.json?r.json():null).catch(()=>null).then(j=>{clearTimeout(tm);if(!r.ok)throw Object.assign(new Error(j&&j.error||'HTTP '+r.status),{status:r.status,j});return j;}),
e=>{clearTimeout(tm);throw Object.assign(e||new Error('failed'),{status:e&&e.status||0});});}
/* The public card: what the leaderboard shows (and what peering between players will need later). */
function mpCard(){let t1=false,tl='Tier 3';try{t1=isTier1();tl=tierLabel();}catch(e){}
const tier=tl==='Tier 1'?'t1':tl==='Tier 2'?'t2':'t3',pairs=new Map();
for(const l of S.links){if(l.ready>S.day)continue;const k=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let g=0;try{g=hopG(l)||0;}catch(e){}pairs.set(k,(pairs.get(k)||0)+g);}
const links=[...pairs].sort((a,b)=>b[1]-a[1]).slice(0,300).map(([k,g])=>{const [a,b]=k.split('|');return [a,b,Math.round(g)];});
const served=R.served||0;
return {day:S.day,name:S.name,asn:S.asn,tier,t1,lvl:S.lvl||1,pops:Object.keys(S.pops).slice(0,500),links,ix:Object.keys(S.ixp).slice(0,500),transit:[...new Set(S.transit.map(t=>t.net))].slice(0,64),
ppol:ppol(),reach:Math.round((R.reach||0)*1e4)/1e4,peak:Math.round((S.stats.peak||0)*10)/10,served:Math.round(served*10)/10,cust:S.biz.length,rev:Math.round(R.revMo||0),
cashB:S.cash<0?-1:Math.min(20,Math.floor(Math.log10(Math.max(1,S.cash)))),score:(t1?2e9:tier==='t2'?1e9:0)+Math.round(served)};}
/* Other players' data, as it comes back: the same whitelist the server keeps, and every id checked against our own
catalogs. Names and chat stay text: everything that shows them escapes them. */
function mpCardOk(c){if(!c||typeof c!=='object'||Array.isArray(c))return null;
const n=(v,lo,hi)=>{v=+v;return Number.isFinite(v)?Math.min(hi,Math.max(lo,v)):0;},L=(v,ok,max)=>Array.isArray(v)?[...new Set(v.filter(ok))].slice(0,max):[];
return {day:Math.round(n(c.day,0,1e7)),tier:['t1','t2','t3'].includes(c.tier)?c.tier:'t3',t1:c.t1===true,lvl:Math.round(n(c.lvl,0,99)),pops:L(c.pops,isCity,500),
links:(Array.isArray(c.links)?c.links:[]).filter(l=>Array.isArray(l)&&isCity(l[0])&&isCity(l[1])&&l[0]!==l[1]).slice(0,300).map(l=>[l[0],l[1],n(l[2],0,1e7)]),
ix:L(c.ix,isIx,500),transit:L(c.transit,isNet,64),ppol:PPOL.includes(c.ppol)?c.ppol:'open',reach:n(c.reach,0,1),peak:n(c.peak,0,1e9),served:n(c.served,0,1e9),
cust:Math.round(n(c.cust,0,1e7)),rev:n(c.rev,-1e13,1e13),cashB:Math.round(n(c.cashB,-1,20)),score:n(c.score,0,1e15)};}
function mpRosterOk(j){if(!j||typeof j!=='object'||Array.isArray(j)||!Array.isArray(j.players))return null;
const txt=(v,max)=>typeof v==='string'?v.slice(0,max):'';
const players=j.players.filter(p=>p&&typeof p==='object'&&MP_PID.test(p.pid)).slice(0,12).map(p=>({pid:p.pid,name:txt(p.name,32),asn:int(p.asn,0,4294967294,0),
color:typeof p.color==='string'&&MP_COL.test(p.color)?p.color:'#888888',card:mpCardOk(p.card),seen:num(p.seen,0),joined:num(p.joined,0)}));
const feed=(Array.isArray(j.feed)?j.feed:[]).filter(f=>f&&typeof f==='object'&&MP_FEED.includes(f.k)).slice(-100).map(f=>({k:f.k,pid:MP_PID.test(f.pid)?f.pid:'',name:txt(f.name,32),at:num(f.at,0),text:f.k==='chat'?txt(f.text,200):''}));
return {code:MP_CODE.test(j.code)?j.code:'',title:txt(j.title,40),preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',players,feed};}
// Tier 1 first, then Tier 2, then whoever serves the most traffic; players who never pushed a card last.
const mpTierN=c=>c?(c.t1?3:c.tier==='t2'?2:1):0;
function mpRank(ps){return ps.slice().sort((a,b)=>mpTierN(b.card)-mpTierN(a.card)||(b.card?b.card.served:0)-(a.card?a.card.served:0)||(b.card?b.card.peak:0)-(a.card?a.card.peak:0)||a.joined-b.joined);}
/* ---------- staying in step with the server ---------- */
function mpOk(roster){MP.fails=0;MP.wait=0;if(MP.told)MP.told=false;const r=mpRosterOk(roster);if(r)MP.roster=r;if(MP_API)mpHud();mpPanelUpdate();}
/* The server is away: back off (30 s, 1, 2, 4 min, at most 5), say so once, and keep playing. Too many pushes at once
(429: another one still on its way, or too often; 503 busy: too many uploads on the server right now) is not "away":
wait a little, quietly. The session panel's own refresh (poll) runs every few seconds while it is open: it may say
the server is away, but never stretches the wait. */
function mpFail(e,poll){const st=e&&e.status;
if((st===401||st===404)&&S&&S.mp){MP.gone=true;toast(tr('mp.not_in_session'),'bad',[{l:tr('mp.session'),act:'mpOpen',args:{}}]);return;}
if(st===429||st===503&&e.j&&e.j.busy===true){MP.wait=performance.now()+MP_GAP*2;return;}
if(!poll||!MP.fails){MP.fails++;MP.wait=performance.now()+Math.min(300000,MP_GAP*2**MP.fails);}
if(!MP.told){MP.told=true;toast(tr('mp.server_away'),'bad');}}
const mpHid=()=>MP.leaving||document.visibilityState==='hidden';
// What a save looks like, in a few characters (FNV-1a and the length): a page hidden on the same game day pushes only
// when something changed since the last push.
function mpSig(t){let h=0x811c9dc5;for(let i=0;i<t.length;i++){h^=t.charCodeAt(i);h=Math.imul(h,16777619);}return (h>>>0).toString(36)+'.'+t.length;}
// The request's size in bytes (UTF-8), which is what the keepalive limit counts.
function mpBytes(t){let n=t.length;for(let i=0;i<t.length;i++){const c=t.charCodeAt(i);if(c>127)n+=c>2047&&(c<0xd800||c>0xdfff)?2:1;}return n;}
/* Does this save go to the server too? 1: yes; 2: if it changed since the last push (the page is being hidden, or the
player asked, on the same game day); 0: no. A push goes on a new game day at most every MP_GAP; at once when the page
is hidden or closed, when the player chose to keep this save (MP.force) or asked for it (MP.now). Never mid-day or in
a puzzle: save() returns before then. */
function mpDue(){if(!mpIs()||MP.stale||MP.gone||S.lost)return 0;
const hid=mpHid(),now=performance.now();
// One push at a time, except when the page goes away: that one cuts the one on its way short (mpPush).
if(MP.busy&&!hid)return 0;
const ask=MP.now;MP.now=false;
if(MP.force&&(hid||now>=MP.wait))return 1;
if(S.day===MP.day)return hid||ask?2:0;
return hid||ask||(now-MP.last>=MP_GAP&&now>=MP.wait)?1:0;}
/* save()'s text for a network in a session, and its push when one is due. The number the server will keep it under is
picked before the text is made, so the save here and the one on the server carry the same: reopening this device
then knows the server has nothing newer. A push that fails leaves this one ahead, which the server accepts. */
function mpSave(st){let d=mpDue();if(d===1)S.mp.seq=(S.mp.seq||0)+1;let txt=JSON.stringify(packSave(st));
if(d===2){if(mpSig(txt)===MP.sig)d=0;else{S.mp.seq=(S.mp.seq||0)+1;txt=JSON.stringify(packSave(st));}}
if(d)mpPush(txt);return txt;}
/* Sends that save (it carries S.mp.seq), gzipped when big, with the card. When the page is being hidden or closed it
goes at once, as a keepalive request: the save when the request fits in one, else the card alone. */
function mpPush(txt){if(!mpIs()||MP.stale||MP.gone||S.lost)return;
const m=S.mp,day=S.day,seq=m.seq||0,hid=mpHid(),force=MP.force,me={cut:false,ac:null};let card;try{card=mpCard();}catch(e){card=undefined;}
// A push still on its way while the page goes away with a newer save: that one is cut short, this one goes.
if(MP.cur){MP.cur.cut=true;try{if(MP.cur.ac)MP.cur.ac.abort();}catch(e){}}
MP.cur=me;MP.busy=true;MP.last=performance.now();
const sig=mpSig(txt),body=data=>({seq,at:Date.now(),data,card,...(force?{force:true}:{})});
// Only a save that went counts as this day's push; a card alone does not.
const done=j=>{if(me.cut)return;if(j&&j.seq!==undefined&&S&&S.mp===m){m.seq=Math.max(m.seq||0,int(j.seq,0,1e15,seq));MP.day=day;MP.sig=sig;if(force)MP.force=false;}mpOk(j&&(j.roster||j));};
const bad=e=>{if(me.cut)return;if(e&&e.status===409&&S&&S.mp===m){MP.stale=true;MP.staleSeq=int(e.j&&e.j.seq,0,1e15,seq);mpStaleTell();}else mpFail(e);};
const fin=()=>{if(MP.cur===me){MP.cur=null;MP.busy=false;}};
const send=(p,b,keep)=>{if(me.cut)return;if(!keep&&typeof AbortController==='function')me.ac=new AbortController();
mpReq('PUT',mpPath(m,p),b,{auth:m,keep,ac:me.ac}).then(done,bad).finally(fin);};
if(hid){const b=txt.length<MP_KEEP?JSON.stringify(body(txt)):'';
if(b&&mpBytes(b)<MP_KEEP)send('/save',b,true);
else if(card&&mpBytes(JSON.stringify({card}))<MP_KEEP)send('/card',{card},true);else fin();
return;}
const go=data=>send('/save',body(data),false);
if(txt.length>=MP_GZ&&gzOk())gzip(txt).then(go,()=>go(txt));else go(txt);}
// The page is going away (pagehide comes before save()'s own handler, which then pushes as a keepalive request).
if(MP_API){addEventListener('pagehide',()=>{MP.leaving=true;});addEventListener('pageshow',()=>{MP.leaving=false;});}
function mpStaleTell(){toast(tr('mp.moved_on_elsewhere'),'bad',[{l:tr('mp.load_newer'),act:'mpNewer',args:{}},{l:tr('mp.keep_mine'),act:'mpKeep',args:{}}]);}
// Pushes this network's save now if it changed since the last push (before a link to another device is handed out).
function mpSyncNow(){if(!mpIs())return;MP.now=true;save(true);}
// The server's save text as a game state: unzipped, parsed, and only if it is this very network.
function mpUnpack(data){if(typeof data!=='string')return Promise.reject(new Error('no save'));
return (data.startsWith(GZ)?gunzip(data):Promise.resolve(data)).then(t=>JSON.parse(t));}
function mpSaveOk(s,m){if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links)||s.lost)return false;
if(!Object.keys(s.pops).every(isCity))return false;return !!(s.mp&&s.mp.code===m.code&&s.mp.pid===m.pid);}
/* Opening a network of a session: if another device played on and pushed a newer save, that one is loaded instead.
Nothing is pushed until the answer is in. */
function mpResume(){if(!mpIs())return;const m=S.mp;mpReset({day:S.day,last:performance.now(),busy:true});mpHud();
// A push of the page going away meanwhile is its own: only an answer to this question frees the next one.
const free=()=>{if(!MP.cur)MP.busy=false;};
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{free();if(S&&S.mp===m&&j&&int(j.seq,0,1e15,0)>(m.seq||0))mpAdopt(j,m);else mpRefresh();},
e=>{free();if(e&&e.status===404&&S&&S.mp===m)mpRefresh();else mpFail(e);});}
// A network of a session opened or started: nothing from another one carries over (a push still on its way is forgotten).
function mpReset(o){if(MP.cur)MP.cur.cut=true;Object.assign(MP,{roster:null,cur:null,busy:false,stale:false,staleSeq:0,gone:false,fails:0,wait:0,told:false,sig:'',force:false,now:false},o);}
function mpAdopt(j,m,n=0){if(!S||S.mp!==m)return;
// A day still routing in the worker finishes first.
if(RW.job){if(n<50)setTimeout(()=>mpAdopt(j,m,n+1),100);return;}
mpUnpack(j.data).then(s=>{if(!S||S.mp!==m||!mpSaveOk(s,m))throw new Error('not this network');delete s.sv;const nx=migrate(s);nx.mp.seq=int(j.seq,0,1e15,0);
S=nx;compute();UI.sel=null;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);Object.assign(MP,{stale:false,staleSeq:0,force:false,day:S.day,last:performance.now()});
renderAll();save(true);toast(tr('mp.loaded_newer',{name:esc(S.name),date:dateStr(S.day)}),'good');mpRefresh();})
.catch(e=>{console.error('[tubes] loading the session save failed',e);toast(tr('mp.save_unreadable'),'bad');});}
function mpRefresh(poll){if(!mpIs()||MP.gone)return Promise.resolve();const m=S.mp;return mpReq('GET',mpPath(m),undefined,{auth:m}).then(mpOk,e=>mpFail(e,poll));}
/* ---------- a link to the same network on another device ----------
<origin>/#mp=<CODE>.<pid>.<token>: the fragment never reaches a server. At boot (before the slots are picked) the save
is fetched into a new slot, or the one this browser already has for that network is opened (one open in another tab
too: slotBoot then offers to take it over), and the fragment is cleared. The link's token is stored only once the
server took it: a wrong or old link never replaces nor deletes the one this browser already has. */
const mpLink=m=>{const t=mpTok(m);return t?location.origin+location.pathname+'#mp='+m.code+'.'+m.pid+'.'+t:'';};
function mpBoot(go){const hash=String(location.hash||''),h=MP_API?/^#mp=([0-9A-Za-z-]{6,8})\.([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(hash):null;
if(!h){go();return;}
try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}
const code=mpNorm(h[1]),m={code,pid:h[2]},tok=h[3],fin=b=>{UI.mpBoot=b;go();};
if(!code){fin({bad:1});return;}
const had=mpTok(m),keep=()=>{if(had!==tok)mpTokSet(code,m.pid,tok);};
// The server is away (or busy): the link may be fine, so it stays in the address bar for a reload to try again.
const no=e=>{console.error('[tubes] moving the network here failed',e);const st=e&&e.status,away=st===0||st===429||st>=500;
if(away)try{history.replaceState(null,'',location.pathname+location.search+hash);}catch(x){}fin(away?{away:1}:{bad:1});};
const ex=slotIdx(true).find(e=>e.mp===code+'.'+m.pid&&!e.broken);
if(ex){const open=()=>{ssSet(SLOT_SS,ex.id);fin({code});};
// Opening it fetches the server's save when that one is newer. A link with another token is asked about first.
if(had===tok)open();else mpReq('GET',mpPath(m),undefined,{auth:m,tok}).then(()=>{keep();open();},no);return;}
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m,tok}).then(j=>mpUnpack(j&&j.data).then(s=>{if(!mpSaveOk(s,m))throw new Error('not this network');
delete s.sv;s.mp.seq=int(j.seq,0,1e15,0);const txt=JSON.stringify(s);return (txt.length>=GZ_MIN&&gzOk()?gzip(txt):Promise.resolve(txt)).then(data=>{
const id=slotRid();localStorage.setItem(SLOT_K+id,data);keep();
slotIdxPut(slotIdx(true).filter(x=>x.id!==id).concat([slotClean({id,...slotMeta(s,null),seq:1,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})]));ssSet(SLOT_SS,id);});}))
.then(()=>fin({code}),no);}
// Said once the game is on screen (or the title is).
function mpBootTell(){const b=UI.mpBoot;if(!b)return;UI.mpBoot=null;
if(b.bad)toast(tr('mp.link_bad'),'bad');else if(b.away)toast(tr('mp.err_offline'),'bad');
else if(S&&S.mp&&S.mp.code===b.code)toast(tr('mp.welcome_device',{name:esc(S.name),code:mpShow(b.code)}),'goal');}

View file

@ -110,7 +110,7 @@ function sanitize(s){
three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */
{const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{};
const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);}
specSanitize(s);
specSanitize(s);mpSanitize(s);
pieSanitize(s);pieIncFix(s);
if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}}
return s;}

View file

@ -8,5 +8,7 @@ Object.assign(ACT,{
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();},
charter:({k})=>{if(!own(CHARTERS,k)||S.chartSet||S.scn||S.mode!=='normal')return;S.charter=k;S.chartSet=true;if($('modal').className==='charter')closeModal();
toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}after();},
toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}
// A new multiplayer session's code to share waited for the charter (95-modals/48-multiplayer.js).
if(UI.mpLater)mpStartTell();after();},
});

View file

@ -23,13 +23,13 @@ Object.assign(ACT,{
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S;
// An import is a new network next to the others: the one playing here is saved and kept.
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);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;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);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;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');if(MP_API)mpResume();},
menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}
<div class="menu-list">
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${saveFailing()?btn(tr('common.export_save'),'exportSave',{},'pink'):''}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''}
</div>
<div class="menu-tiles">${[['🗂️',tr('slots.your_networks'),'toTitle'],['🧩',tr('puzzles.puzzles'),'puzzleMenu'],['🏆',tr('common.scenarios'),'scenarios'],['🧑‍💻',tr('ops.standing_orders'),'opsOpen'],['📐',tr('bstd.title'),'bstdOpen'],['📸',tr('common.share'),'share'],['⚙️',tr('common.settings'),'settings']].map(([i,l,a])=>`<button class="mtile" data-act="${a}"><i aria-hidden="true">${i}</i><span>${l}</span></button>`).join('')}</div>
<div class="menu-tiles">${[['🗂️',tr('slots.your_networks'),'toTitle'],['🧩',tr('puzzles.puzzles'),'puzzleMenu'],['🏆',tr('common.scenarios'),'scenarios'],['🧑‍💻',tr('ops.standing_orders'),'opsOpen'],['📐',tr('bstd.title'),'bstdOpen'],...(mpIs()?[['🌐',tr('mp.session'),'mpOpen']]:[]),['📸',tr('common.share'),'share'],['⚙️',tr('common.settings'),'settings']].map(([i,l,a])=>`<button class="mtile" data-act="${a}"><i aria-hidden="true">${i}</i><span>${l}</span></button>`).join('')}</div>
<p class="menu-links">${[saveFailing()?null:[tr('common.export_save'),'exportSave'],[tr('common.import_a_save'),'importPick'],[tr('common.how_to_play'),'help'],RELEASE_NOTES.length?[tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow']:null,[tr('common.start_a_new_network'),'resetAsk']].filter(Boolean).map(([l,a])=>`<button class="lnk" data-act="${a}">${l}</button>`).join(' · ')}</p>
</div><div class="menu-plugs"><a class="mplug" href="${SIGNAL}" target="_blank" rel="noopener">💬 ${tr('modal_and_names.join_the_noc_chat')} →</a><a class="mplug" href="${ISSUES}" target="_blank" rel="noopener">🐛 ${tr('modal_and_names.found_a_bug_or_have_an')} →</a></div>`);},
settings:()=>{UI.setOpen=true;openModal(settingsHtml());},

View file

@ -43,7 +43,7 @@ function bbCost(c){return 15000+CITY[c].P*20;}
/* A click that changes nothing routing reads (the log, offers, cash, names, settings…) keeps the routing it has:
compute() gives the same R again for the same state (tests/compute-idempotent), so it is skipped. The key is the save
without the fields routing never reads (tests/route-skip checks each one); any other change routes again. */
const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd']);
const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd','mp']);
function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);}
function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;}
function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}

View file

@ -31,4 +31,4 @@ function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;U
// Back from the title (or a puzzle) into a loaded network.
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=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;}}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');if(MP_API)mpResume();}

View file

@ -0,0 +1,34 @@
// Multiplayer (60-features/89-multiplayer.js, 95-modals/48-multiplayer.js). Every one does nothing unless the build
// stamped MP_API; the title-screen ones are in the click delegate's no-game list (96-map/95-clicks.js).
Object.assign(ACT,{
mpDoor:()=>{if(!MP_API)return;const i=$('nmIn');UI.nm=((i&&i.value)||UI.nm||randomNetworkName()).slice(0,24);openModal(mpStartHtml());
const n=$('mpName');if(n)n.addEventListener('input',e=>{UI.nm=e.target.value;});
const c=$('mpCode');if(c)c.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpJoin({});}});},
mpBack:()=>{const n=$('mpName');if(n)UI.nm=n.value.slice(0,24);showTitle();},
mpStart:()=>{if(!MP_API||UI.mpBusy)return;const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra',preset=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',t=$('mpTitle');
mpBusy(true);mpReq('POST','/sessions',{net:{name:nm,home},preset,title:(t&&t.value||'').slice(0,40),avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,false);},e=>{mpBusy(false);mpErr(e);});},
mpJoin:()=>{if(!MP_API||UI.mpBusy)return;const i=$('mpCode'),code=mpNorm(i?i.value:'');if(!code){toast(tr('mp.err_code'),'bad');if(i)i.focus();return;}
const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra';
mpBusy(true);mpReq('POST','/sessions/'+code+'/join',{net:{name:nm,home},avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,true);},e=>{mpBusy(false);mpErr(e);});},
mpOpen:()=>{if(!mpIs())return;openModal(mpPanelHtml(),'mp');const s=$('mpSay');if(s)s.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpChat({});}});
// About to move to another device: the server gets what this one has first, so the link opens it as it is now.
const d=document.querySelector('#mpPanel details.mpmove');if(d)d.addEventListener('toggle',()=>{if(d.open)mpSyncNow();});mpPoll();},
mpShare:()=>{if(!mpIs())return;mpSend(tr('mp.share_line',{code:mpShow(S.mp.code),url:location.origin+location.pathname}));},
// The link carries the secret: it goes to the clipboard, or is selected for copying by hand, never into a toast.
mpCopyLink:()=>{if(!mpIs())return;const l=mpLink(S.mp);if(!l)return;mpSyncNow();const sel=()=>{const i=$('mpLink');if(i){i.focus();i.select();}};
try{navigator.clipboard.writeText(l).then(()=>toast(tr('mp.link_copied'),'good'),sel);}catch(e){sel();}},
mpChat:()=>{if(!mpIs()||MP.gone)return;const i=$('mpSay'),t=(i?i.value:'').trim().slice(0,200);if(!t)return;const m=S.mp;
mpReq('POST',mpPath(m,'/feed'),{text:t},{auth:m}).then(j=>{if(i)i.value='';mpOk(j);},e=>{if(e&&e.status===429)toast(tr('mp.slow_down'),'bad');else mpFail(e);});},
mpLeaveAsk:()=>{if(!mpIs())return;openModal(`<h2 style="font-size:26px">${tr('mp.leave_q',{code:mpShow(S.mp.code)})}</h2><p class="tagline">${tr('mp.leave_d',{name:esc(S.name)})}</p><div class="btns">${btn(tr('mp.leave'),'mpLeave',{},'red big')}${btn(tr('common.keep_playing'),'mpOpen',{},'ghost big')}</div>`);},
// Leaving keeps the network, as a game of its own; the session forgets it (and a session that forgot it already too).
mpLeave:()=>{if(!mpIs())return;const m=S.mp,out=()=>{if(!S||S.mp!==m)return;S.mp=null;mpTokSet(m.code,m.pid,null);mpReset();
closeModal();renderAll();save(true);toast(tr('mp.left',{name:esc(S.name)}),'good');};
mpReq('DELETE',mpPath(m,'/me'),undefined,{auth:m}).then(out,e=>{if(e&&(e.status===401||e.status===404))out();else toast(tr('mp.server_away'),'bad');});},
// Only a save at least as new as the one the server said it has (after a conflict), or newer than this one, is loaded:
// "Load the newer save" never takes the player back to an older one.
mpNewer:()=>{if(!mpIs())return;const m=S.mp,min=(m.seq||0)+(MP.stale?0:1);
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{if(!S||S.mp!==m)return;const sq=int(j&&j.seq,0,1e15,0);if(sq>=min){mpAdopt(j,m);return;}
m.seq=Math.max(m.seq||0,sq);MP.stale=false;toast(tr('mp.no_newer',{name:esc(S.name)}),'good');mpPanelUpdate();},mpFail);},
// Overwrite the server's save with this one: with a number past the server's, at the next save (never half a day).
mpKeep:()=>{if(!mpIs())return;S.mp.seq=Math.max(S.mp.seq||0,MP.staleSeq||0);Object.assign(MP,{stale:false,force:true,wait:0});save(true);mpPanelUpdate();},
});

View file

@ -14,7 +14,8 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
UI.lastSave=performance.now();
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.
if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return;
const txt=JSON.stringify(packSave(st));
// A network in a multiplayer session: the server keeps a copy too (60-features/89-multiplayer.js).
const txt=MP_API&&st===S&&S.mp?mpSave(st):JSON.stringify(packSave(st));
let tier=null;if(st===S)try{tier=tierLabel();}catch(e){}
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)};
if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));}

View file

@ -22,8 +22,11 @@ function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null;
tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz,
// A save marked damaged (bv: the game version that could not load it) is tried again by the next version: the fault is
// usually in the game, and the save itself is fine once it is fixed.
...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false})};}
const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier});
...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false}),
// A network in a multiplayer session: <code>.<pid>, so a link from another device finds it again.
...(typeof e.mp==='string'&&/^[0-9A-HJKMNP-TV-Z]{6}\.[a-z0-9]{8}$/.test(e.mp)?{mp:e.mp}:{})};}
// mp is always there (null outside a session), so a network that left its session loses its badge in the list.
const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier,mp:s.mp&&s.mp.code?s.mp.code+'.'+s.mp.pid:null});
function slotKeys(){const out=[];try{for(let i=0;i<localStorage.length;i++){const k=localStorage.key(i);if(k===SLOT_OLD)out.old=true;else if(k&&k.startsWith(SLOT_K)&&slotOkId(k.slice(SLOT_K.length)))out.push(k.slice(SLOT_K.length));}}catch(e){}return out;}
// An index entry rebuilt from the save itself. A compressed one can only be read in the background: slotFix() fills it in.
function slotFromKey(id){const raw=slotRaw(id)||'';if(raw.startsWith(GZ))return slotClean({id,gz:true,size:raw.length});
@ -46,7 +49,7 @@ function slotIdx(scan){const raw=lsGet(SLOT_IX);let list=null;
function slotIdxPut(list){const t=JSON.stringify({v:1,slots:list});try{localStorage.setItem(SLOT_IX,t);SLOT.ixRaw=t;SLOT.ixList=list.map(e=>({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}}
function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id);
gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return;
if(m)Object.assign(x,slotClean({...x,...m}));else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}}
if(m){const c=slotClean({...x,...m});if(!c.mp)delete x.mp;Object.assign(x,c);}else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}}
const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at);
// ---------- one writer per slot ----------
// The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a
@ -88,7 +91,7 @@ function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false;
if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;}
if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed
SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);
const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false}));
const e=ent||{id};if(!ent)list.push(e);const c=slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false});if(!c.mp)delete e.mp;Object.assign(e,c);
slotIdxPut(list);return true;}
function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}}
// ---------- opening, leaving, losing ----------

View file

@ -6,6 +6,7 @@ function renderHUD(){
// A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud).
{const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();}
$('muteBtn').style.opacity=UI.muted?.4:1;
if(MP_API)mpHud();// the session chip: also hidden again on the title screen and in a puzzle
if(!S)return;
if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;}
{const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';}

View file

@ -22,7 +22,7 @@ function showTitle(){
${top?`<div class="btns tcont" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}</div>`:''}
${many?slotsHtml():''}
<label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><div class="nmwrap"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off"><button class="reroll" data-act="randomName" aria-label="${tr('common.another_one')}" title="${tr('common.another_one')}">↻</button></div><div class="asnwrap"><span aria-hidden="true">AS</span><input class="t" id="asnIn" inputmode="numeric" maxlength="10" value="${esc(UI.asnTxt==null?'':UI.asnTxt)}" placeholder="${UI.asnSug}" aria-label="${tr('title.as_number')}" autocomplete="off"></div></div>
${doorsHtml()}
${doorsHtml()}${MP_API?mpDoorHtml():''}
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
<div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
$('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;});
@ -44,8 +44,10 @@ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot
const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'};
// The chosen preset in one line: its joke, then what actually changes.
const presetWhat=k=>`${esc(PRESETS[k].d)} <span class="meta">${esc(PRESETS[k].x)}</span>`;
// The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js).
const presetBtns=pr=>`<label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p>`;
function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none';
return `<label class="f">${tr('title.pick_a_door')}</label><div class="doors">${DOORS.map(([k,i,n,d])=>`<button class="door${k===m?' on':''}" data-door="${k}" data-act="${doorAct[k]}" data-args='${k==='sandbox'||k==='normal'?`{"m":"${k}"}`:'{}'}'><i aria-hidden="true">${i}</i><b>${n}</b><span>${d}</span>${k==='puzzle'&&pzWkNew()||k==='scn'&&wsNew()?`<em class="pznew">${tr('puzzles.new_this_sunday')}</em>`:''}</button>`).join('')}</div>
<div id="doorNormal"${m==='normal'?'':' hidden'}><label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p></div>
<div id="doorNormal"${m==='normal'?'':' hidden'}>${presetBtns(pr)}</div>
<div id="doorSandbox"${m==='sandbox'?'':' hidden'}><label class="f">${tr('title.chaos_in_your_sandbox')}</label><div class="chaos">${Object.entries(CHAOS).map(([k,C])=>`<button class="chs${k===ch?' on':''}" data-chaos="${k}" data-act="chaosSet" data-args='{"c":"${k}"}'><i aria-hidden="true">${C.i}</i><b>${C.n}</b><span>${C.d}</span></button>`).join('')}</div></div>
<p class="note lockn">🔒 ${tr('title.rules_are_picked_once_and_locked')}</p>`;}

View file

@ -5,7 +5,7 @@ const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?
// The network to continue: the most recent one that is not open in another window (or damaged).
function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;}
function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete');
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);if(MP_API&&e.mp)bits.push('🌐 '+mpShow(e.mp.slice(0,6)));
return bits.filter(Boolean).join(' · ');}
function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network'));
const tag=busy?`<span class="tag">${tr('slots.open_in_another_window')}</span>`:top?`<span class="tag">▶ ${tr('slots.continue')}</span>`:'';

View file

@ -0,0 +1,73 @@
/* Multiplayer on screen (89-multiplayer.js has the logic): the title screen's door, the start/join sheet, the session
panel (leaderboard, feed and chat, the code to share, the link to another device) and the HUD chip. Only ever drawn
when the build stamped MP_API. Everything another player wrote is escaped here. */
const MP_FEED_L={join:N_('mp.feed_join'),leave:N_('mp.feed_leave'),t2:N_('mp.feed_t2'),t1:N_('mp.feed_t1'),t1first:N_('mp.feed_t1first')};
const mpDoorHtml=()=>`<div class="mpdoor-row"><button class="door mpdoor" data-act="mpDoor"><i aria-hidden="true">🌐</i><b>${tr('mp.multiplayer')}</b><span>${tr('mp.door_d')}</span></button></div>`;
function mpStartHtml(){const pr=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall';
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.multiplayer')}</div><h2 style="font-size:26px">${tr('mp.play_with_friends')}</h2></div><button class="x" data-act="mpBack" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('mp.intro')}</p>
<label class="f" for="mpName">${tr('title.name_your_network')}</label><input class="t" id="mpName" maxlength="24" value="${esc(UI.nm||'')}" autocomplete="off">
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
<div class="mpbox"><h3>${tr('mp.start_a_session')}</h3>${presetBtns(pr)}
<label class="f" for="mpTitle">${tr('mp.session_title')}</label><input class="t" id="mpTitle" maxlength="40" autocomplete="off">
<div class="btns">${btn(tr('mp.start_a_session'),'mpStart',{},'pink big mpgo')}</div></div>
<div class="mpbox"><h3>${tr('mp.join_a_session')}</h3><label class="f" for="mpCode">${tr('mp.code')}</label>
<div class="mpjoin"><input class="t" id="mpCode" maxlength="8" placeholder="K7Q-2XD" autocomplete="off" autocapitalize="characters" spellcheck="false">${btn(tr('mp.join'),'mpJoin',{},'big mpgo')}</div>
<p class="note">${tr('mp.join_note')}</p></div>
<p class="note" id="mpBusy" hidden>${tr('mp.talking')}</p>
<div class="btns cta">${btn(tr('common.back'),'mpBack',{},'ghost')}</div>`;}
function mpBusy(on){UI.mpBusy=on;document.querySelectorAll('.mpgo').forEach(b=>{b.disabled=on;});const b=$('mpBusy');if(b)b.hidden=!on;}
function mpErr(e){const st=e&&e.status;sfx('err');
toast(st===404?tr('mp.err_no_session'):st===409?tr('mp.err_full'):st===429?tr('mp.err_slow'):st===503?tr('mp.err_server_full'):st===400?tr('mp.err_refused'):tr('mp.err_offline'),'bad');}
const mpNameIn=()=>{const n=$('mpName'),v=String((n&&n.value)||UI.nm||randomNetworkName()).trim().slice(0,24)||randomNetworkName();UI.nm=v;return v;};
// The server said yes: the token goes to this browser's storage, the rest into a new game.
function mpBegin(j,nm,home,joined){const m=mpJoinOk(j);if(!m){toast(tr('mp.err_offline'),'bad');return;}
mpTokSet(m.code,m.pid,m.token);delete m.token;beginGame(nm,home,{mode:'normal',preset:m.preset,mp:{...m,joined}});}
// Called by beginGame just before its first save, which then pushes the day-0 save and the card: this player is on the
// leaderboard at once, and a link to another device works from the start.
function mpStarted(m){mpReset({day:-1,last:-1e9});mpHud();UI.mpLater={joined:!!(m&&m.joined)};}
// The code to share, with its buttons. A new Normal game asks for its charter first, on top of everything: the code
// waits until it is signed (ACT.charter), or its buttons could not be pressed.
function mpStartTell(){const b=UI.mpLater;if(!b||!mpIs())return;if(!$('modal').hidden&&$('modal').className==='charter')return;UI.mpLater=null;
const code=mpShow(S.mp.code),acts=[{l:tr('common.share'),act:'mpShare',args:{}},{l:tr('mp.session'),act:'mpOpen',args:{}}];
toast(b.joined?tr('mp.joined',{code}):tr('mp.session_live',{code}),'goal',acts);}
/* ---------- the session panel ---------- */
function mpBoardHtml(){const r=MP.roster;if(MP.gone)return `<p class="why">${tr('mp.not_in_session')}</p>`;
// Another device moved on: the toast with the choice is long gone, the choice stays here until it is made.
const st=MP.stale?`<p class="why">${tr('mp.moved_on_elsewhere')}</p><div class="btns">${btn(tr('mp.load_newer'),'mpNewer',{},'pink')}${btn(tr('mp.keep_mine'),'mpKeep',{},'')}</div>`:'';
if(st)return st;if(!r)return `<p class="note">${tr('mp.loading')}</p>`;const me=S&&S.mp&&S.mp.pid;
return mpRank(r.players).map((p,i)=>{const c=p.card,mine=p.pid===me;
const meta=c?[`AS${p.asn}`,c.t1?'Tier 1':c.tier==='t2'?'Tier 2':'Tier 3',trn('mp.n_pops',c.pops.length),fmtG(c.peak),trn('mp.n_customers',c.cust)].join(' · '):`AS${p.asn} · ${tr('mp.no_card')}`;
return `<div class="mprow${mine?' me':''}"><span class="mprk">${i+1}</span><i class="mpdot" style="background:${p.color}" aria-hidden="true"></i><div class="grow"><b>${esc(p.name)}</b>${mine?` <span class="tag">${tr('mp.you')}</span>`:''}<div class="meta">${meta}</div></div><small class="mpseen">${p.seen?slotAgo(p.seen):''}</small></div>`;}).join('');}
function mpFeedHtml(){const r=MP.roster;if(!r)return '';const f=r.feed.slice(-30).reverse();if(!f.length)return `<p class="note">${tr('mp.feed_empty')}</p>`;
const col=pid=>{const p=r.players.find(x=>x.pid===pid);return p?p.color:'#888888';};
return f.map(x=>{const who=`<b>${esc(x.name)}</b>`,t=x.k==='chat'?`${who}: ${esc(x.text)}`:tr(MP_FEED_L[x.k],{name:who});
return `<div class="mpf ${x.k}"><i class="mpdot" style="background:${col(x.pid)}" aria-hidden="true"></i><span class="grow">${t}</span><small>${x.at?slotAgo(x.at):''}</small></div>`;}).join('');}
function mpPanelHtml(){const m=S.mp,code=mpShow(m.code),link=mpLink(m);
return `<div class="mp-panel" id="mpPanel"><div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.session')} · ${esc(PRESETS[m.preset].n)}</div><h2 style="font-size:26px">${m.title?esc(m.title):tr('mp.session_code',{code})}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<div class="mpcode"><div class="grow"><small>${tr('mp.code')}</small><b>${code}</b></div>${btn(tr('common.share'),'mpShare',{},'pink')}</div>
<p class="note">${tr('mp.share_note')}</p>
<h3>${tr('mp.leaderboard')}</h3><div class="mpboard" id="mpBoard">${mpBoardHtml()}</div>
<h3>${tr('mp.feed')}</h3><div class="mpchat"><input class="t" id="mpSay" maxlength="200" placeholder="${esc(tr('mp.say'))}" aria-label="${esc(tr('mp.say'))}" autocomplete="off">${btn(tr('mp.send'),'mpChat',{},'')}</div><div class="mpfeed" id="mpFeed">${mpFeedHtml()}</div>
${link?`<details class="mpmove"><summary>${tr('mp.move_device')}</summary><p class="note">${tr('mp.move_note')}</p><input class="t" id="mpLink" readonly value="${esc(link)}" aria-label="${esc(tr('mp.move_device'))}"><p class="why">${tr('mp.move_warn')}</p><div class="btns">${btn(tr('mp.copy_link'),'mpCopyLink',{},'')}</div></details>`:''}
<div class="btns cta">${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${btn(tr('mp.leave'),'mpLeaveAsk',{},'ghost')}</div></div>`;}
// The roster moved on: only the leaderboard and the feed are redrawn, so a chat line being typed stays.
function mpPanelUpdate(){const b=$('mpBoard'),f=$('mpFeed');if(!b||$('modal').hidden)return;b.innerHTML=mpBoardHtml();if(f)f.innerHTML=mpFeedHtml();}
// While the panel is open, the roster every 5 s; it stops by itself once the panel is gone.
function mpPoll(){clearInterval(MP.poll);MP.poll=null;if(!mpIs())return;mpRefresh();if(!window.__TUBES_TEST__)MP.poll=setInterval(mpPollTick,MP_POLL);}
function mpPollTick(){if($('modal').hidden||!$('mpPanel')||!mpIs()){clearInterval(MP.poll);MP.poll=null;return;}mpRefresh(true);}
/* The HUD chip: the session code and where you stand. A phone's top bar has no room for it (the menu has the session):
there, and on a tablet whose top bar is still too full (fitHud's last step), where you stand is a badge on the menu
button instead. Made the first time a session network is on screen. */
function mpHud(){let c=$('hMp');const on=mpIs();
if(!c){if(!on)return;c=document.createElement('button');c.className='chip mpchip hide-sm';c.id='hMp';c.dataset.act='mpOpen';
c.innerHTML='<span class="lbl" id="hMpCode"></span><span class="val num" id="hMpRank"></span>';const n=$('hNoc');n.parentNode.insertBefore(c,n.nextSibling);
const b=document.createElement('span');b.className='badge mpbadge num';b.id='hMpB';b.setAttribute('aria-hidden','true');const mb=document.querySelector('#hud .menubtn');if(mb)mb.appendChild(b);}
const b=$('hMpB');c.hidden=!on;if(b)b.hidden=!on;if(!on)return;
const r=MP.roster,i=r?mpRank(r.players).findIndex(p=>p.pid===S.mp.pid):-1,rk=i>=0?`#${i+1}/${r.players.length}`:'—';
c.setAttribute('aria-label',tr('mp.session'));c.title=tr('mp.session');c.style.borderColor=S.mp.color;
$('hMpCode').textContent=mpShow(S.mp.code);$('hMpRank').textContent='🌐 '+rk;if(b)b.textContent=i>=0?`#${i+1}`:'🌐';}
// Share text: the phone's share sheet, or the clipboard.
function mpSend(t){const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good');
if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}
try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}

View file

@ -11,5 +11,5 @@ let PD={t:0,b:null};
document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true);
function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true;
if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;}
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','mpDoor','mpBack','mpStart','mpJoin'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});

View file

@ -43,7 +43,7 @@ function boot(data){
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;}}
if(okSave){slotIn(UI.slot,stamp);UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
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});}
@ -51,8 +51,9 @@ function boot(data){
// 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);
else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}}
renderHUD();renderLeft();
renderHUD();renderLeft();if(MP_API)mpBootTell();
window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}}));
if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);}
}
if(NOC.win)nocWinBoot();else if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));
// A #mp= link (a multiplayer network moving to this device) is read first: it picks the slot slotBoot opens.
if(NOC.win)nocWinBoot();else if(!RW_IN)mpBoot(()=>slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})));