Merge save slots: one network per window, consistent saves
This commit is contained in:
commit
efb14680cc
36 changed files with 1099 additions and 134 deletions
|
|
@ -30,7 +30,7 @@ const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chao
|
|||
function weekly(){const {y,w}=isoWeek(new Date());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;}newGame(nm,city);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();newGame(nm,city);S.mode=o.mode||'normal';
|
||||
// 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;}}
|
||||
|
|
|
|||
|
|
@ -81,9 +81,9 @@ function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==
|
|||
// ---------- entering and leaving ----------
|
||||
// Toasts from one world never carry over into the other (their buttons act on the S they came from).
|
||||
const pzToastsClear=()=>{$('toasts').textContent='';};
|
||||
// The running game gets its usual save first, so leaving the puzzle can load it back exactly as booting does. A huge
|
||||
// save is compressed in the background and may not have landed yet, so the game object is kept in memory too.
|
||||
function pzFlush(){save(true);UI.pzKeep=UI.gzBusy||saveFailing()?S:null;}
|
||||
// The running game gets its usual save first and is kept in memory, set aside: save() keeps writing it to its slot
|
||||
// (leaving the page mid-puzzle), and leaving the puzzle picks it up again.
|
||||
function pzFlush(){save(true);UI.pzKeep=S;}
|
||||
function pzBegin(def){if(!def)return;
|
||||
const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null;
|
||||
S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null};
|
||||
|
|
@ -96,7 +96,9 @@ function pzBegin(def){if(!def)return;
|
|||
if(live)pzFlush();go();}
|
||||
function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
|
||||
if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null;
|
||||
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){S=null;UI.started=false;}}}
|
||||
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
|
||||
// It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told.
|
||||
if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}}
|
||||
renderAll();showTitle();}
|
||||
// The camera frames the puzzle's cities beside the puzzle card: left on wide screens, right on phones on their side, a bottom sheet on phones.
|
||||
function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity;
|
||||
|
|
|
|||
|
|
@ -9,21 +9,24 @@ Object.assign(ACT,{
|
|||
// Puzzles live in their own module; until it ships, the door says so.
|
||||
puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');},
|
||||
scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();},
|
||||
startScn:({id,sure})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_name',{name:esc(sc.n)})}</h2><p class="tagline">${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}</p><div class="btns">${btn(tr('game_and_settings.start_the_scenario'),'startScn',{id,sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);return;}beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});},
|
||||
startWeekly:({sure}={})=>{if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_the_weekly_challenge')}</h2><p class="tagline">${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}</p><div class="btns">${btn(tr('game_and_settings.start_the_challenge'),'startWeekly',{sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);return;}const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});},
|
||||
startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});},
|
||||
startWeekly:()=>{const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});},
|
||||
pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city||(b.classList.contains('own')&&!START5.includes(city))));const s=$('homeSel');if(s&&START5.includes(city))s.value='';const w=$('homeWhat');if(w)w.innerHTML=homeWhat();},
|
||||
pickHome:({v})=>{if(v)ACT.pickStart({city:v});else ACT.pickStart({city:'fra'});},
|
||||
cont:()=>{migrate(S);track('game_continue',true);UI.started=true;closeModal();renderAll();},
|
||||
newgame:()=>{try{localStorage.removeItem('sot-save-v1');}catch(e){}S=null;UI.started=false;UI.sel=null;UI.nm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();},
|
||||
// Delete this window's network and go back to the title (the other networks stay).
|
||||
newgame:()=>{if(pzOn())pzLeave();const id=UI.slot;if(id){slotDrop(id);slotFree(id);}gameClear();showTitle();},
|
||||
keepPlaying:()=>{closeModal();},
|
||||
exportSave:()=>exportSave(),
|
||||
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;try{S=migrate(JSON.parse(JSON.stringify(s0)));compute();checkGoals();renderAll();}catch(e){S=prev;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;UI.speed=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;compute();renderAll();save();toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
|
||||
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)}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
|
||||
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;UI.speed=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');},
|
||||
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>`}${isPhone()?installRow():''}
|
||||
<div class="menu-list">
|
||||
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}
|
||||
${btn(tr('game_and_settings.export_save_download_a_file'),'exportSave',{},saveFailing()?'pink':'')}
|
||||
${btn(tr('slots.your_networks_switch_or_start_another'),'toTitle',{},'')}
|
||||
${btn(tr('game_and_settings.export_save_download_a_file'),'exportSave',{},saveFailing()?'pink':'')}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''}
|
||||
${btn(tr('game_and_settings.import_a_save_from_a_file'),'importPick',{},'')}
|
||||
${btn(tr('game_and_settings.share_your_network_image_card'),'share',{},'')}
|
||||
${btn(tr('game_and_settings.scenarios_amp_weekly_challenge'),'scenarios',{},'ghost')}
|
||||
|
|
|
|||
32
src/game/90-actions/91-slots.js
Normal file
32
src/game/90-actions/91-slots.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
Object.assign(ACT,{
|
||||
// Continue a network from the list (or the newest one).
|
||||
cont:({id}={})=>{if(!slotOkId(id)){const t=slotTop(slotIdx(true));if(!t)return;id=t.id;}
|
||||
if(id===UI.slot&&S&&!pzOn()){UI.started=true;closeModal();renderAll();return;}
|
||||
slotOpen(id,false,()=>track('game_continue',true));},
|
||||
// Back to the title with this network kept and saved.
|
||||
toTitle:()=>{if(pzOn()){pzLeave();}slotLeave();gameClear();showTitle();},
|
||||
slotBack:()=>{if(S&&UI.started)closeModal();else showTitle();},
|
||||
slotMenu:({id})=>{const h=slotMenuHtml(id);if(h)openModal(h);},
|
||||
slotExport:({id})=>exportSlot(id),
|
||||
slotDel:({id,back})=>{const e=slotIdx().find(x=>x.id===id);if(!e)return;
|
||||
openModal(`<h2 style="font-size:26px">${tr('slots.delete_name',{name:esc(e.name||tr('common.unnamed_network'))})}</h2><p class="tagline">${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(e.name||tr('common.unnamed_network'))})}</p>${slotBusy(id)?`<p class="note" style="color:var(--bad)">${tr('slots.it_is_open_in_another_window')}</p>`:''}<div class="btns">${btn(tr('slots.delete_forever'),'slotDelGo',{id,back},'red big')}${btn(tr('slots.keep_it'),back==='space'?'slotSpace':'slotBack',{},'ghost big')}</div>`);},
|
||||
slotDelGo:({id,back})=>{if(!slotIdx().some(e=>e.id===id))return;
|
||||
if(id===UI.slot){ACT.newgame();return;}
|
||||
slotDrop(id);try{BC&&BC.postMessage({t:'gone',id});}catch(e){}sfx('click');
|
||||
if(back==='space')openModal(slotSpaceHtml());else showTitle();},
|
||||
slotSpace:()=>openModal(slotSpaceHtml()),
|
||||
// The other window cannot be brought forward from here; it says hello when the player gets there.
|
||||
slotSwitch:({id})=>{try{BC&&BC.postMessage({t:'focus',id});}catch(e){}const e=slotIdx().find(x=>x.id===id);showTitle();toast(tr('slots.name_is_waiting_in_your_other',{name:esc(e&&e.name||'')}),'goal');},
|
||||
// Ask the other window to save and step aside, then open it here. Without an answer (it is frozen, or the browser has
|
||||
// no BroadcastChannel) it is taken anyway after a moment: the other window stops writing the moment it notices.
|
||||
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');},
|
||||
});
|
||||
// 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();}
|
||||
// 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;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
|
||||
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);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');}
|
||||
|
|
@ -2,20 +2,25 @@
|
|||
/* A network too big for the browser's storage fails to save every time, and turning it into text takes a
|
||||
moment on huge saves, every 5 seconds and after every click. After a failure the autosave waits before trying
|
||||
again (1 minute, then 2, 4, at most 5); leaving the page, exporting or another game (a new S) still try at once. */
|
||||
// A puzzle is never saved: only its stars are, under their own key (sot-puzzles).
|
||||
function save(force){if(!S||S.lost||S.mode==='puzzle')return;S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};const f=UI.saveFail;
|
||||
if(!force&&f&&f.s===S&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
|
||||
const txt=JSON.stringify(packSave(S));
|
||||
const seq=UI.saveSeq=(UI.saveSeq||0)+1;
|
||||
if(txt.length>=GZ_MIN&&gzOk())gzSave(S,txt,seq);
|
||||
else try{localStorage.setItem('sot-save-v1',txt);UI.saveFail=null;}catch(e){saveErr(e,S);}
|
||||
UI.lastSave=performance.now();}
|
||||
/* A puzzle is never saved: only its stars are, under their own key (sot-puzzles). While one runs, the network it set
|
||||
aside (UI.pzKeep) is the one saved, to its own slot, so closing the tab mid-puzzle loses nothing. */
|
||||
function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
|
||||
if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return;
|
||||
if(st===S){S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st;
|
||||
if(!force&&failed&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
|
||||
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));
|
||||
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));}
|
||||
function saveErr(e,s){const f=UI.saveFail,again=f&&f.s===s;UI.saveFail={s,at:performance.now(),wait:again?Math.min(300000,f.wait*2):60000,full:saveFull(e)};
|
||||
// Say so once per game (#176): a save that silently fails loses everything since the last one that worked.
|
||||
if(!again&&s===S)toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}}]);}
|
||||
if(!again&&(s===S||s===UI.pzKeep))toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}},...(UI.saveFail.full&&slotOthers().length?[{l:tr('slots.free_up_space'),act:'slotSpace',args:{}}]:[])]);}
|
||||
/* Saves of huge networks are gzipped by the browser (#176): about ten times smaller, so they fit in its storage.
|
||||
Compressing runs in the background, one at a time, and the newest save wins; one that a newer save or another
|
||||
game has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. */
|
||||
Compressing runs in the background, one at a time, and the newest save of each network wins; one that a newer save
|
||||
of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. */
|
||||
const GZ='gz:',GZ_MIN=1e6,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function';
|
||||
async function gzPipe(bytes,stream){const w=stream.writable.getWriter(),no=()=>{};w.write(bytes).catch(no);w.close().catch(no);// a bad stream is reported by read() below
|
||||
const r=stream.readable.getReader(),parts=[];let n=0;
|
||||
|
|
@ -25,15 +30,11 @@ const b64=u=>{let s='';for(let i=0;i<u.length;i+=0x8000)s+=String.fromCharCode.a
|
|||
const unb64=t=>{const s=atob(t),u=new Uint8Array(s.length);for(let i=0;i<s.length;i++)u[i]=s.charCodeAt(i);return u;};
|
||||
const gzip=async txt=>GZ+b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip')));
|
||||
const gunzip=async raw=>new TextDecoder().decode(await gzPipe(unb64(raw.slice(GZ.length)),new DecompressionStream('gzip')));
|
||||
function gzSave(s,txt,seq){if(UI.gzBusy){UI.gzNext={s,txt,seq};return;}UI.gzBusy=true;
|
||||
gzip(txt).then(v=>{if((s!==S&&s!==UI.pzKeep)||seq!==UI.saveSeq)return;try{localStorage.setItem('sot-save-v1',v);UI.saveFail=null;}catch(e){saveErr(e,s);}})
|
||||
// Jobs carry their slot, not the game object: a save still compressing lands in its own network whatever S is by then.
|
||||
function gzSave(j){if(UI.gzBusy){SLOT.gzQ.set(j.id,j);return;}UI.gzBusy=true;
|
||||
gzip(slotStamp(j.txt,j.seq)).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);})
|
||||
.catch(e=>{console.error('[tubes] compressing the save failed',e);})
|
||||
.finally(()=>{UI.gzBusy=false;const n=UI.gzNext;UI.gzNext=null;if(n&&n.s===S)gzSave(n.s,n.txt,n.seq);});}
|
||||
// A compressed save is unpacked before the game boots, so loadSave() stays synchronous for everything else.
|
||||
async function gzBoot(go){let raw=null;try{raw=localStorage.getItem('sot-save-v1');}catch(e){}
|
||||
if(raw&&raw.startsWith(GZ)){try{UI.gzRaw=raw;UI.gzText=await gunzip(raw);}catch(e){console.error('[tubes] unpacking the save failed',e);UI.gzRaw=UI.gzText=null;
|
||||
try{localStorage.setItem('sot-save-broken',raw);localStorage.removeItem('sot-save-v1');}catch(e2){}UI.gzBroken=true;}}
|
||||
go();}
|
||||
.finally(()=>{UI.gzBusy=false;const n=SLOT.gzQ.values().next().value;if(n){SLOT.gzQ.delete(n.id);gzSave(n);}else slotIdle();});}
|
||||
/* Big networks are mostly customers, and most of a customer record was defaults (#176): no second city, no
|
||||
requirements, the normal route, no warnings yet. The save leaves defaults out and sanitize() puts them back, so
|
||||
the game after loading is the same; older versions read a missing field as its default too. An alien wave's
|
||||
|
|
@ -42,7 +43,8 @@ const BIZ_DEF={city2:null,latMax:null,route:'normal',sites:null,slots:0,warned:f
|
|||
function packBiz(b){const o={};for(const k in b){const v=b[k];if(v===undefined||BIZ_DEF[k]===v||(k==='reqs'&&Array.isArray(v)&&!v.length)||(k==='pm'&&v===b.mood)||(k==='what'&&b.type==='wwave'&&b.link))continue;o[k]=v;}return o;}
|
||||
function unpackBiz(b,links){for(const k in BIZ_DEF)if(!(k in b))b[k]=BIZ_DEF[k];if(!('pm' in b)&&b.mood!==undefined)b.pm=b.mood;if(!Array.isArray(b.reqs))b.reqs=[];
|
||||
if(b.type==='wwave'&&b.what===undefined){const l=links.get(b.link);b.what=l?wwWhat(l,b.slots||1):'';}return b;}
|
||||
const packSave=s=>({...s,biz:s.biz.map(packBiz)});
|
||||
// sv (the slot's save stamp) is added when the text is written, never carried in the game.
|
||||
const packSave=s=>({...s,sv:undefined,biz:s.biz.map(packBiz)});
|
||||
// Out of room (quota) or not allowed to store at all (private window, blocked site data): different advice.
|
||||
const saveFull=e=>!!e&&(e.name==='QuotaExceededError'||e.name==='NS_ERROR_DOM_QUOTA_REACHED'||e.code===22||e.code===1014);
|
||||
const saveFailing=()=>!!(UI.saveFail&&UI.saveFail.s===S);
|
||||
|
|
@ -52,10 +54,14 @@ addEventListener('pagehide',()=>save(true));
|
|||
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save(true);else checkUpdate();});
|
||||
/* Export / import: move a network to another device or keep a backup. The file is the same
|
||||
object the autosave writes, wrapped with a little metadata. */
|
||||
function saveFileName(){const d=new Date().toISOString().slice(0,10),n=(S&&S.name||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;}
|
||||
function exportSave(){if(!S||S.mode==='puzzle')return;save(true);const blob=new Blob([JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S:packSave(S)},null,1)],{type:'application/json'});
|
||||
const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName();document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);
|
||||
toast(tr('save.save_exported_file_is_in_your',{file:esc(saveFileName())}),'good');}
|
||||
function saveFileName(nm){const d=new Date().toISOString().slice(0,10),n=String(nm||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;}
|
||||
function saveDl(txt,nm){const blob=new Blob([txt],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName(nm);document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);
|
||||
toast(tr('save.save_exported_file_is_in_your',{file:esc(saveFileName(nm))}),'good');}
|
||||
function exportSave(){if(!S||S.mode==='puzzle')return;save(true);saveDl(JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S:packSave(S)},null,1),S.name);}
|
||||
// Any network on this device, straight from storage: the file wraps the saved text as it is, without loading it.
|
||||
function exportSlot(id){const e=slotIdx().find(x=>x.id===id),raw=slotRaw(id);if(!e||raw==null)return;
|
||||
if(id===UI.slot&&S&&!pzOn()){exportSave();return;}
|
||||
(raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw)).then(t=>saveDl(`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},"exported":"${new Date().toISOString()}","S":${t}}`,e.name),()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));}
|
||||
function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_is_not_valid_json')};let j;try{j=JSON.parse(txt);}catch(e){return {err:tr('save.that_file_is_not_valid_json')};}
|
||||
const s=j&&j.app==='series-of-tubes'&&j.S?j.S:j;
|
||||
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))return {err:tr('save.that_does_not_look_like_a')};
|
||||
|
|
@ -64,7 +70,9 @@ function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_
|
|||
return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};}
|
||||
function importFile(file){if(!file)return;if(file.size>8e6){toast(tr('save.that_file_is_too_big_to'),'bad');return;}
|
||||
const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}
|
||||
UI.importing=r.s;openModal(`<div class="eyebrow">${tr('common.import_a_save')}</div><h2 style="font-size:26px">${tr('save.load_name',{name:esc(r.name)})}</h2><p class="tagline">${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}</p>${S&&UI.started&&!S.lost?`<p class="note" style="color:var(--bad)">${tr('save.this_replaces_name_export_it_first',{name:esc(S.name)})}</p>`:''}<div class="btns">${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}</div>`);};
|
||||
UI.importing=r.s;openModal(`<div class="eyebrow">${tr('common.import_a_save')}</div><h2 style="font-size:26px">${tr('save.load_name',{name:esc(r.name)})}</h2><p class="tagline">${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}</p><p class="note">${tr('slots.it_joins_your_networks_on_this')}</p><div class="btns">${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}</div>`);};
|
||||
rd.readAsText(file);}
|
||||
function loadSave(){try{let t=localStorage.getItem('sot-save-v1');if(t&&t.startsWith(GZ))t=t===UI.gzRaw?UI.gzText:null;if(t){const s=JSON.parse(t);if(s&&s.v===1&&!s.lost)return s;}}catch(e){}return null;}
|
||||
|
||||
// This window's network, read synchronously (a compressed one was unpacked before boot). UI.loadBad: there, but unreadable.
|
||||
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;}
|
||||
|
|
|
|||
157
src/game/91-slots.js
Normal file
157
src/game/91-slots.js
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
/* ================= SAVE SLOTS =================
|
||||
Several networks per browser, one per window. Each network (a slot) is its own key, sot-save-v1:<id>, plain JSON or
|
||||
gzipped exactly like the old single save. A small index (sot-slots) describes them for the title screen, so listing
|
||||
them never reads a save. A write goes to the slot first and to the index after, so the index never points at a save
|
||||
that is not there yet; each write carries a sequence number (in the save and in its index entry), and a window never
|
||||
writes over a newer one that another window saved. Each tab keeps its slot in sessionStorage: a reload continues it.
|
||||
Only one window plays a slot at a time: a Web Lock where the browser has them, else a heartbeat key, sot-open:<id>. */
|
||||
const SLOT_K='sot-save-v1:',SLOT_IX='sot-slots',SLOT_OLD='sot-save-v1',SLOT_HB='sot-open:',SLOT_SS='sot-slot',SLOT_MAIN='main';
|
||||
const SLOT={sq:{},top:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''};
|
||||
function slotRid(){try{const a=new Uint32Array(2);crypto.getRandomValues(a);return (a[0].toString(36)+a[1].toString(36)).slice(0,10);}catch(e){return (Date.now().toString(36)+(uidN++).toString(36)).slice(-10);}}
|
||||
const WIN=slotRid();// this page load; a reload is a new window that takes its tab's slot back
|
||||
const lsGet=k=>{try{return localStorage.getItem(k);}catch(e){return null;}};
|
||||
const lsDel=k=>{try{localStorage.removeItem(k);}catch(e){}};
|
||||
const ssGet=k=>{try{return sessionStorage.getItem(k);}catch(e){return null;}};
|
||||
const ssSet=(k,v)=>{try{if(v==null)sessionStorage.removeItem(k);else sessionStorage.setItem(k,v);}catch(e){}};
|
||||
const slotOkId=id=>typeof id==='string'&&/^[a-z0-9]{1,24}$/.test(id);
|
||||
const slotRaw=id=>slotOkId(id)?lsGet(SLOT_K+id)??(id===SLOT_MAIN?lsGet(SLOT_OLD):null):null;
|
||||
// ---------- the index: read like a save, never trusted ----------
|
||||
function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null;
|
||||
return {id:e.id,name:String(e.name==null?'':e.name).slice(0,24),asn:int(e.asn,0,4294967294,0),mode:['normal','sandbox','scenario'].includes(e.mode)?e.mode:'normal',
|
||||
preset:typeof e.preset==='string'&&own(PRESETS,e.preset)?e.preset:'oncall',scn:typeof e.scn==='string'?e.scn.slice(0,60):null,day:int(e.day,0,1e7,0),
|
||||
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,broken:!!e.broken};}
|
||||
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});
|
||||
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});
|
||||
try{const s=JSON.parse(raw);if(s&&s.v===1&&typeof s.day==='number')return slotClean({id,...slotMeta(s,null),seq:s.sv&&s.sv.seq,at:s.sv&&s.sv.at,size:raw.length});}catch(e){}
|
||||
return slotClean({id,size:raw.length,broken:true});}
|
||||
/* The list of networks. scan also looks at the keys themselves (cheap: no save is read unless its entry is missing):
|
||||
a save whose index write failed is added back, an entry whose save is gone is dropped. A damaged index is rebuilt. */
|
||||
function slotIdx(scan){const raw=lsGet(SLOT_IX);let list=null;
|
||||
// The same text as last time (every autosave): no need to parse and check it again.
|
||||
if(!scan&&raw!=null&&raw===SLOT.ixRaw)return SLOT.ixList.map(e=>({...e}));
|
||||
if(raw!=null)try{const j=JSON.parse(raw);if(j&&Array.isArray(j.slots))list=j.slots.map(slotClean).filter(Boolean);}catch(e){}
|
||||
const bad=raw!=null&&!list;if(!list)list=[];{const seen=new Set();list=list.filter(e=>!seen.has(e.id)&&seen.add(e.id));}
|
||||
if(scan||bad){const ks=slotKeys(),keys=new Set(ks);let ch=bad;const n=list.length;
|
||||
if(ks.old&&list.some(e=>e.id===SLOT_MAIN))keys.add(SLOT_MAIN);
|
||||
list=list.filter(e=>keys.has(e.id));if(list.length!==n)ch=true;
|
||||
for(const id of keys)if(!list.some(e=>e.id===id)){list.push(slotFromKey(id));ch=true;}
|
||||
if(ch)slotIdxPut(list);if(list.some(e=>e.gz&&!e.name&&!e.broken))slotFix(list);}
|
||||
else if(raw!=null&&list.length){SLOT.ixRaw=raw;SLOT.ixList=list.map(e=>({...e}));}
|
||||
return list;}
|
||||
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;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
|
||||
// minute, so it counts for longer. Tabs remove theirs when they close; a crashed one goes stale.
|
||||
function slotHb(id){try{const h=JSON.parse(lsGet(SLOT_HB+id));return h&&typeof h.w==='string'&&isFinite(h.t)?h:null;}catch(e){return null;}}
|
||||
const slotBusy=id=>{const h=slotHb(id);return !!h&&h.w!==WIN&&Date.now()-h.t<(h.h?180000:20000);};
|
||||
function slotBeat(){const id=UI.slot;if(!id)return;const h=slotHb(id);
|
||||
// Without Web Locks the heartbeat is the lock: a fresh one from another window means it took over.
|
||||
if(h&&h.w!==WIN&&!SLOT.locks.has(id)&&Date.now()-h.t<20000){slotLost(id,'take');return;}
|
||||
try{localStorage.setItem(SLOT_HB+id,JSON.stringify({w:WIN,t:Date.now(),h:document.visibilityState==='hidden'?1:0}));}catch(e){}}
|
||||
function slotUnbeat(id){const h=slotHb(id);if(h&&h.w===WIN)lsDel(SLOT_HB+id);}
|
||||
const LOCKS=()=>{try{const l=navigator.locks;return l&&typeof l.request==='function'?l:null;}catch(e){return null;}};
|
||||
// cb(true) when this window may play the slot, cb(false) when another window has it. steal takes it over.
|
||||
function slotClaim(id,steal,cb,n=4){const once=v=>{try{cb(v);}catch(e){console.error('[tubes] opening a network failed',e);}};
|
||||
if(SLOT.locks.has(id)){slotBeatFor(id);once(true);return;}
|
||||
const L=LOCKS();
|
||||
if(L){let got=false;
|
||||
L.request('sot-slot:'+id,steal?{steal:true}:{ifAvailable:true},lock=>{if(!lock){if(n>0&&(SLOT.rel.has(id)||!slotBusy(id)))setTimeout(()=>slotClaim(id,steal,cb,n-1),120);else once(false);return;}got=true;SLOT.rel.delete(id);
|
||||
return new Promise(r=>{SLOT.locks.set(id,r);slotBeatFor(id);once(true);});})
|
||||
.catch(()=>{SLOT.locks.delete(id);if(got)slotLost(id,'take');});// stolen: another window took over
|
||||
return;}
|
||||
if(!steal&&slotBusy(id)){once(false);return;}
|
||||
slotBeatFor(id);once(true);}
|
||||
function slotBeatFor(id){try{localStorage.setItem(SLOT_HB+id,JSON.stringify({w:WIN,t:Date.now(),h:0}));}catch(e){}}
|
||||
function slotFree(id){if(UI.slot===id)return;slotUnbeat(id);const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r){SLOT.rel.add(id);r();}}
|
||||
// Saves still compressing land before a slot is handed back.
|
||||
function whenIdle(f){if(!UI.gzBusy&&!SLOT.gzQ.size)f();else SLOT.idle.push(f);}
|
||||
function slotIdle(){if(UI.gzBusy||SLOT.gzQ.size)return;const l=SLOT.idle.splice(0);for(const f of l)try{f();}catch(e){console.error(e);}}
|
||||
// ---------- writing ----------
|
||||
// The sequence number rides along in the save, appended to the text (no second stringify).
|
||||
const slotStamp=(txt,seq)=>txt.slice(0,-1)+',"sv":{"seq":'+seq+',"at":'+Date.now()+'}}';
|
||||
// Throws when the browser refuses (quota): save() reports it. Returns false when it must not write.
|
||||
function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false;
|
||||
const list=slotIdx(),ent=list.find(e=>e.id===id);
|
||||
if(ent&&ent.seq>(SLOT.sq[id]||0)){slotLost(id,'newer');return false;}
|
||||
let k=SLOT_K+id;
|
||||
try{localStorage.setItem(k,data);}
|
||||
catch(e){// A migrated save the browser has no room to copy keeps living in the old key, as it always did.
|
||||
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}));
|
||||
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 ----------
|
||||
function slotIn(id,sv){const e=slotIdx().find(x=>x.id===id);UI.slot=id;ssSet(SLOT_SS,id);SLOT.no.delete(id);SLOT.top[id]=0;
|
||||
SLOT.sq[id]=Math.max(sv&&isFinite(sv.seq)?+sv.seq:0,e?e.seq:0);}
|
||||
function slotNew(){const id=slotRid();UI.slot=id;ssSet(SLOT_SS,id);SLOT.sq[id]=0;SLOT.no.delete(id);slotClaim(id,true,()=>{});return id;}
|
||||
// Leave this window's network (saved first); the slot is free for other windows once its last save has landed.
|
||||
function slotLeave(){const id=UI.slot;if(!id)return;save(true);UI.slot=null;UI.pzKeep=null;ssSet(SLOT_SS,null);whenIdle(()=>slotFree(id));}
|
||||
// Read a slot and play it. A save that cannot be read or loaded is marked damaged and kept, so it can still be exported.
|
||||
function slotOpen(id,steal,done){if(!slotIdx(true).some(e=>e.id===id)){showTitle();toast(tr('slots.that_network_is_gone'),'bad');return;}
|
||||
slotClaim(id,!!steal,ok=>{if(!ok){slotBusyModal(id);return;}
|
||||
const go=t=>{let s=null;try{s=JSON.parse(t);}catch(e){}
|
||||
if(!s||s.v!==1||s.lost){slotBroke(id);return;}const sv=s.sv;delete s.sv;
|
||||
const prev=S;try{S=migrate(s);compute();}catch(e){console.error('[tubes] loading a network failed',e);S=prev;slotBroke(id);return;}
|
||||
if(UI.slot&&UI.slot!==id){const nw=S;S=prev;slotLeave();S=nw;}
|
||||
slotIn(id,sv);gameResume();if(done)done();};
|
||||
const raw=slotRaw(id);if(raw==null){slotFree(id);slotDrop(id);showTitle();toast(tr('slots.that_network_is_gone'),'bad');return;}
|
||||
if(raw.startsWith(GZ)){if(raw===UI.gzRaw)go(UI.gzText);else gunzip(raw).then(go,()=>slotBroke(id));}else go(raw);});}
|
||||
function slotBroke(id){const l=slotIdx(),e=l.find(x=>x.id===id);if(e){e.broken=true;slotIdxPut(l);}
|
||||
if(UI.slot===id){UI.slot=null;ssSet(SLOT_SS,null);}slotFree(id);
|
||||
S=null;R=emptyR();UI.started=false;UI.sel=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();toast(tr('loop.your_saved_game_could_not_be'),'bad');}
|
||||
function slotDrop(id){if(!slotOkId(id))return;SLOT.no.add(id);lsDel(SLOT_K+id);if(id===SLOT_MAIN)lsDel(SLOT_OLD);slotUnbeat(id);
|
||||
const l=slotIdx();slotIdxPut(l.filter(e=>e.id!==id));if(UI.slot===id){UI.slot=null;ssSet(SLOT_SS,null);}}
|
||||
/* Another window took this network over, or saved a newer version of it: this one stops writing and says so calmly. */
|
||||
function slotLost(id,why){if(UI.slot!==id)return;SLOT.no.add(id);UI.slot=null;ssSet(SLOT_SS,null);SLOT.gzQ.delete(id);if(why==='gone')slotUnbeat(id);
|
||||
const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r)r();
|
||||
const s=pzOn()?UI.pzKeep:S,name=s?s.name:'';
|
||||
if(pzOn()){UI.pzKeep=null;UI.pzFrom='title';toast(tr('slots.name_moved_to_another_window_toast',{name:esc(name)}),'bad');return;}
|
||||
gameClear();if(why==='gone'){showTitle();toast(tr('slots.name_was_deleted_in_another_window',{name:esc(name)}),'bad');}else slotLostModal(id,name,why);}
|
||||
// ---------- the legacy single save becomes the first slot ----------
|
||||
/* Read old, write new, read it back, then add it to the index. The old key stays as a fallback until the slot's next
|
||||
save lands; if the browser has no room for a copy, the network keeps living in the old key (slotRaw reads it). */
|
||||
function slotMigrate(cb){const raw=lsGet(SLOT_OLD);
|
||||
if(raw==null||slotIdx(true).some(e=>e.id===SLOT_MAIN)){cb();return;}
|
||||
const done=s=>{if(s&&s.lost){cb();return;}
|
||||
let ok=false;try{localStorage.setItem(SLOT_K+SLOT_MAIN,raw);ok=localStorage.getItem(SLOT_K+SLOT_MAIN)===raw;}catch(e){}
|
||||
if(!ok)lsDel(SLOT_K+SLOT_MAIN);
|
||||
const l=slotIdx();l.push(slotClean({id:SLOT_MAIN,...(s?slotMeta(s,null):{}),seq:0,at:Date.now(),size:raw.length,gz:raw.startsWith(GZ),broken:!s}));slotIdxPut(l);if(!s)UI.bootBroken=true;cb();};
|
||||
if(!raw.startsWith(GZ)){let s=null;try{s=JSON.parse(raw);}catch(e){}done(s&&s.v===1?s:null);return;}
|
||||
if(!gzOk()){done(null);return;}
|
||||
gunzip(raw).then(t=>{UI.gzRaw=raw;UI.gzText=t;let s=null;try{s=JSON.parse(t);}catch(e){}done(s&&s.v===1?s:null);},()=>done(null));}
|
||||
/* Before the game boots: migrate, then pick this tab's network. A reload continues the tab's own slot; a new tab with
|
||||
exactly one network continues it as before; with more, the title screen lists them. A compressed save is unpacked
|
||||
here, so loadSave() stays synchronous for everything else. */
|
||||
function slotBoot(go){slotMigrate(()=>{const list=slotIdx(true),mine=ssGet(SLOT_SS);
|
||||
let id=list.some(e=>e.id===mine&&!e.broken)?mine:null;if(!id&&mine)ssSet(SLOT_SS,null);
|
||||
const auto=!id&&list.length===1&&!list[0].broken&&!slotBusy(list[0].id)?list[0].id:null;
|
||||
if(!id&&!auto){go();return;}
|
||||
slotClaim(id||auto,false,ok=>{const w=id||auto;
|
||||
if(!ok){if(id){ssSet(SLOT_SS,null);UI.bootBusy=id;}go();return;}
|
||||
UI.slot=w;const raw=slotRaw(w);
|
||||
if(raw&&raw.startsWith(GZ)&&raw!==UI.gzRaw){if(!gzOk()){go();return;}gunzip(raw).then(t=>{UI.gzRaw=raw;UI.gzText=t;go();},e=>{console.error('[tubes] unpacking the save failed',e);go();});}
|
||||
else go();});});}
|
||||
// ---------- other windows ----------
|
||||
const BC=(()=>{try{return typeof BroadcastChannel==='function'?new BroadcastChannel('sot-slots'):null;}catch(e){return null;}})();
|
||||
if(BC)BC.onmessage=({data:m})=>{if(!m||typeof m!=='object'||!slotOkId(m.id))return;
|
||||
if(m.t==='focus'&&UI.slot===m.id){try{window.focus();}catch(e){}toast(tr('slots.here_it_is_name',{name:esc(S?S.name:'')}),'goal');}
|
||||
// Asked to hand over: save what we have, wait for it to land, then step aside and say so.
|
||||
if(m.t==='take'&&UI.slot===m.id){save(true);whenIdle(()=>{slotLost(m.id,'take');try{BC.postMessage({t:'gave',id:m.id});}catch(e){}});}
|
||||
if(m.t==='gave'&&SLOT.wait&&SLOT.wait.id===m.id)SLOT.wait.go();
|
||||
if(m.t==='gone')slotLost(m.id,'gone');};
|
||||
addEventListener('storage',e=>{const k=e.key;if(!k)return;const id=UI.slot;
|
||||
if(id&&k===SLOT_HB+id&&e.newValue){let h=null;try{h=JSON.parse(e.newValue);}catch(_){}if(h&&h.w!==WIN)slotLost(id,'take');}
|
||||
else if(id&&k===SLOT_K+id&&e.newValue==null)slotLost(id,'gone');// deleted in another window: never written back
|
||||
else if(id&&k===SLOT_IX){const x=slotIdx().find(y=>y.id===id);if(x&&x.seq>(SLOT.sq[id]||0))slotLost(id,'newer');}
|
||||
if(k===SLOT_IX||k.startsWith(SLOT_HB))slotRefresh();});
|
||||
addEventListener('pagehide',()=>{if(UI.slot)slotUnbeat(UI.slot);});
|
||||
addEventListener('pageshow',e=>{if(e.persisted)slotBeat();});
|
||||
if(!window.__TUBES_TEST__)setInterval(slotBeat,5000);
|
||||
|
|
@ -8,20 +8,20 @@ function homePick(){const cs=Object.keys(CITY).filter(homeOk),cur=START5.include
|
|||
// A dropdown can't wrap, so long names (Yuzhno-Sakhalinsk) get cut on phones: the line above it says the whole name.
|
||||
const homeWhat=()=>START5.includes(UI.startCity)?trn('title.n_more_cities_with_transit',Object.keys(CITY).filter(c=>homeOk(c)&&!START5.includes(c)).length):`${esc(CITY[UI.startCity].name)} · ${esc(REG[CITY[UI.startCity].reg])}`;
|
||||
function showTitle(){
|
||||
const sv=loadSave();
|
||||
const list=slotIdx(true),top=slotTop(list),many=list.length>1||(list.length===1&&list[0]!==top);
|
||||
if(UI.nm==null)UI.nm=randomNetworkName();
|
||||
const starts=[['fra',tr('title.crossroads_of_europe_de_kicks_ix')],['nyc',tr('title.huge_eyeball_market_pricey')],['sin',tr('title.asia_hub_great_peering_far_from')],['sao',tr('title.big_hungry_market_few_providers')],['syd',tr('title.hard_mode_pricey_everything')]];
|
||||
openModal(`<div class="title-art"><svg width="74" height="74" viewBox="0 0 74 74" aria-hidden="true"><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#1E2640" stroke-width="16" stroke-linecap="round"/><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#FFD23F" stroke-width="9" stroke-linecap="round"/><circle cx="58" cy="16" r="11" fill="#FF4F9A" stroke="#1E2640" stroke-width="4"/><circle cx="21" cy="44" r="3" fill="#fff"/><circle cx="30" cy="27" r="3" fill="#fff"/></svg>
|
||||
<h1>Series<br>of <span>Tubes</span></h1></div>
|
||||
<p class="tagline">${tr('title.build_an_internet_lay_fiber_between')}</p>${plugHtml(false)}${isPhone()?installRow():''}
|
||||
${sv?`<div class="btns" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(sv.name),date:dateStr(sv.day)}),'cont',{},'pink big')}</div>`:''}
|
||||
${top?`<div class="btns" 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():''}
|
||||
${doorsHtml()}
|
||||
<label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off">${btn(tr('common.another_one'),'randomName',{},'ghost sm')}</div>
|
||||
<label class="f" id="homeLbl">${tr('title.pick_your_home_city')}</label><div class="starts homes">${starts.map(([c,d])=>`<button class="start ${UI.startCity===c?'on':''}" data-city="${c}" data-act="pickStart" data-args='{"city":"${c}"}'><b>${CITY[c].name}</b><span>${d}</span></button>`).join('')}<label class="start own ${START5.includes(UI.startCity)?'':'on'}" for="homeSel"><b>${tr('title.anywhere_else')}</b><span id="homeWhat">${homeWhat()}</span>${homePick()}</label></div>
|
||||
<label class="f" for="langTitle">${tr('common.language')}</label>${langPick('langTitle')}
|
||||
<div class="btns cta tcta" style="margin-top:16px">${btn(sv?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>`);
|
||||
<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;});
|
||||
if(sv){S=migrate(sv);compute();}
|
||||
}
|
||||
// "What's new": shown once to returning players after an update, or on demand.
|
||||
function whatsNew(returning,force){
|
||||
|
|
|
|||
37
src/game/95-modals/45-slots.js
Normal file
37
src/game/95-modals/45-slots.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/* "Your networks" on the title screen: drawn from the index alone, so it stays instant however big the saves are. */
|
||||
function slotAgo(t){const m=Math.max(0,Math.round((Date.now()-t)/60000));
|
||||
return m<1?tr('slots.just_now'):m<60?trn('notifications.n_min_ago',m):m<1440?trn('slots.n_h_ago',Math.round(m/60)):trn('peering_inbox.n_day_ago',Math.round(m/1440));}
|
||||
const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?'🏖️':(PRESETS[e.preset]||PRESETS.oncall).i;
|
||||
// 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);
|
||||
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>`:'';
|
||||
return `<div class="slot${top?' top':''}${busy?' busy':''}${e.broken?' broken':''}" data-slot="${e.id}"><button class="slot-go" data-act="${e.broken?'slotMenu':'cont'}" data-args='{"id":"${e.id}"}'><i aria-hidden="true">${slotIcon(e)}</i><span class="sn">${tag}<b>${nm}</b><small>${slotLine(e)}</small></span><span class="sm">${e.broken?'':`<em>${fmt$(e.cash)}</em>`}<small>${e.at?slotAgo(e.at):''}</small></span></button><button class="slot-more" data-act="slotMenu" data-args='{"id":"${e.id}"}' aria-label="${tr('slots.more_for_name',{name:nm})}">⋯</button></div>`;}
|
||||
function slotListHtml(){const list=slotByAt(slotIdx()),top=slotTop(list);
|
||||
return list.map(e=>slotRow(e,e===top)).join('');}
|
||||
function slotsHtml(){const list=slotIdx(true);if(!list.length)return '';
|
||||
SLOT.html=slotListHtml();return `<label class="f">${tr('slots.your_networks')}</label><div class="slots" id="slotList">${SLOT.html}</div>`;}
|
||||
// Another window saved, opened or closed a network: the list follows (only when it is on screen and changed).
|
||||
function slotRefresh(){const el=$('slotList');if(!el||UI.started)return;const h=slotListHtml();if(h!==SLOT.html){SLOT.html=h;el.innerHTML=h;}}
|
||||
function slotMenuHtml(id){const e=slotIdx().find(x=>x.id===id);if(!e)return '';const nm=esc(e.name||tr('common.unnamed_network'));
|
||||
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">${slotIcon(e)} ${slotLine(e)}</div><h2 style="font-size:26px">${nm}</h2></div><button class="x" data-act="slotBack" aria-label="${tr('common.close')}">×</button></div>
|
||||
<p class="tagline">${e.at?tr('slots.last_played_ago',{ago:slotAgo(e.at)}):''}${e.size?' · '+tr('slots.size_on_this_device',{size:slotSize(e.size)}):''}</p>
|
||||
<div class="menu-list">${e.broken?'':btn(tr('slots.continue_this_network'),'cont',{id},'pink big')}${btn(tr('game_and_settings.export_save_download_a_file'),'slotExport',{id},'')}${btn(tr('slots.delete_this_network'),'slotDel',{id},'red')}${btn(tr('common.back'),'slotBack',{},'ghost')}</div>`;}
|
||||
const slotSize=n=>n>=1e6?(n/1e6).toFixed(1)+' MB':Math.max(1,Math.round(n/1e3))+' kB';
|
||||
function slotBusyModal(id){const e=slotIdx().find(x=>x.id===id),nm=esc(e&&e.name||tr('common.unnamed_network'));
|
||||
openModal(`<div class="eyebrow">🪟 ${tr('slots.two_windows_one_network')}</div><h2 style="font-size:26px">${tr('slots.name_is_open_in_another_window',{name:nm})}</h2>
|
||||
<p class="tagline">${tr('slots.only_one_window_can_play_a')}</p><div class="btns">${btn(tr('slots.switch_to_that_window'),'slotSwitch',{id},'pink big')}${btn(tr('slots.take_over_here'),'slotTake',{id},'big')}${btn(tr('slots.your_networks'),'slotBack',{},'ghost')}</div>`);}
|
||||
// Shown in the window that stepped aside: calm, and nothing here writes.
|
||||
function slotLostModal(id,name,why){const nm=esc(name||tr('common.unnamed_network'));
|
||||
openModal(`<div class="eyebrow">🪟 ${tr('slots.two_windows_one_network')}</div><h2 style="font-size:26px">${why==='newer'?tr('slots.name_was_saved_in_another_window',{name:nm}):tr('slots.name_opened_in_another_window',{name:nm})}</h2>
|
||||
<p class="tagline">${why==='newer'?tr('slots.this_window_stopped_saving_so_it'):tr('slots.this_window_stepped_aside_so_the')}</p><div class="btns">${btn(why==='newer'?tr('slots.load_the_newest_version'):tr('slots.take_it_back_here'),why==='newer'?'cont':'slotTake',{id},'pink big')}${btn(tr('slots.your_networks'),'slotBack',{},'ghost big')}</div>`);}
|
||||
const slotOthers=()=>slotIdx().filter(e=>e.id!==UI.slot);
|
||||
// Out of room: which other networks take space, with export and delete right there.
|
||||
function slotSpaceHtml(){const l=slotOthers().sort((a,b)=>b.size-a.size);
|
||||
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">💾 ${tr('slots.storage_on_this_device')}</div><h2 style="font-size:26px">${tr('slots.free_up_space')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
|
||||
<p class="tagline">${tr('slots.your_other_networks_share_this_browser')}</p>
|
||||
${l.length?l.map(e=>`<div class="ibx space"><div class="grow"><b>${slotIcon(e)} ${esc(e.name||tr('common.unnamed_network'))}</b><div class="meta">${slotSize(e.size)}${e.at?' · '+slotAgo(e.at):''}</div></div><div class="btns">${btn(tr('common.export_save'),'slotExport',{id:e.id},'ghost sm')}${btn(tr('slots.delete'),'slotDel',{id:e.id,back:'space'},'red sm')}</div></div>`).join(''):`<p class="note">${tr('slots.no_other_networks_here')}</p>`}
|
||||
<div class="btns" style="margin-top:10px">${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}</div>`;}
|
||||
|
|
@ -21,4 +21,4 @@ function showHelp(){
|
|||
</dl><h3 style="margin:16px 0 0">${tr('help.want_to_know_how_it_really')}</h3>${plugHtml(true)}${chatHtml()}${issueHtml()}</dl><div class="btns" style="margin-top:14px">${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}</div><div class="btns" style="margin-top:6px">${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}</div>`);
|
||||
}
|
||||
function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`<div class="btns" style="margin-top:8px">${btn(tr('help.share_my_network'),'share',{},'pink')}</div><p class="meta" style="margin:12px 0 0">${tr('help.you_built_a_cartoon_internet_now')}</p>${plugHtml(true)}`);},0);openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">${tr('help.you_re_a_tier_1')}</h1><p class="tagline">${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:S.day,n:S.stats.incidents})}</p>${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');}
|
||||
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">${tr('common.bankrupt')}</h1><p class="tagline">${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}</p>${btn(tr('common.try_again'),'newgame',{},'pink big')}`);try{localStorage.removeItem('sot-save-v1');}catch(e){}}
|
||||
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">${tr('common.bankrupt')}</h1><p class="tagline">${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}</p>${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}}
|
||||
|
|
|
|||
|
|
@ -11,5 +11,5 @@ let PD={t:0,b:null};
|
|||
document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true);
|
||||
function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true;
|
||||
if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;}
|
||||
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
|
||||
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','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);});
|
||||
|
||||
|
|
|
|||
|
|
@ -33,16 +33,18 @@ function boot(data){
|
|||
try{UI.muted=localStorage.getItem('sot-mute')==='1';UI.anim=localStorage.getItem('sot-anim')||'auto';}catch(e){}
|
||||
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=loadSave();
|
||||
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){S=null;UI.started=false;try{localStorage.setItem('sot-save-broken',JSON.stringify(sv));localStorage.removeItem('sot-save-v1');}catch(e2){}}}
|
||||
if(okSave){UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
|
||||
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;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
|
||||
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);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});}
|
||||
if(!whatsNew(true))toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}
|
||||
else{showTitle();whatsNew(false);if(sv||UI.gzBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}}
|
||||
// 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();
|
||||
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);}
|
||||
}
|
||||
gzBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));
|
||||
slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));
|
||||
|
|
|
|||
|
|
@ -1798,14 +1798,9 @@
|
|||
"game_and_settings.import_a_save_from_a_file":"Import a save <small>from a file</small>",
|
||||
"game_and_settings.import_failed_that_save_is_damaged":"<b>Import failed.</b><br>That save is damaged and could not be loaded. Your current game is untouched.",
|
||||
"game_and_settings.name_and_everything_it_owns_will":"{name} and everything it owns will be deleted. This cannot be undone.",
|
||||
"game_and_settings.name_will_be_replaced_export_it":"{name} will be replaced. Export it from the menu first if you want to keep it.",
|
||||
"game_and_settings.scenarios_amp_weekly_challenge":"Scenarios & weekly challenge",
|
||||
"game_and_settings.share_your_network_image_card":"Share your network <small>image card</small>",
|
||||
"game_and_settings.start_a_new_network":"Start a new network?",
|
||||
"game_and_settings.start_name":"Start {name}?",
|
||||
"game_and_settings.start_the_challenge":"Start the challenge",
|
||||
"game_and_settings.start_the_scenario":"Start the scenario",
|
||||
"game_and_settings.start_the_weekly_challenge":"Start the weekly challenge?",
|
||||
"game_and_settings.welcome_back_name_imported_and_saved":"<b>Welcome back, {name}.</b><br>Imported and saved on this device.",
|
||||
"game_and_settings.your_game_saves_itself_every_few":"Your game saves itself every few seconds on this device.",
|
||||
"geography_and_latency.a_to_b":"{a} to {b}",
|
||||
|
|
@ -3281,7 +3276,6 @@
|
|||
"save.that_network_went_bankrupt_it_cannot":"That network went bankrupt. It cannot be brought back, only mourned.",
|
||||
"save.that_save_has_a_pop_in":"That save has a POP in a city this version does not know ({city}).",
|
||||
"save.this_browser_is_not_letting_the":"<b>Your game is not being saved.</b> This browser is not letting the game store anything (a private window, or site data turned off). Export a save to keep your network.",
|
||||
"save.this_replaces_name_export_it_first":"This replaces {name}. Export it first if you want to keep it.",
|
||||
"save.your_network_is_too_big_to":"<b>Your game is not being saved.</b> Your network has grown too big for this browser's storage. Export a save now and keep the file: it is your backup.",
|
||||
"scenario_progress.goal_goal_time_d_days_start":"<b>Goal:</b> {goal} · <b>Time:</b> {d} days · start in {city}",
|
||||
"scenario_progress.goal_was_not_reached_in_d":"{goal} was not reached in {d} days. Keep playing this network as free play, or try again.",
|
||||
|
|
@ -3418,6 +3412,47 @@
|
|||
"sites_peering_caches.your_account_manager_found_the_order":"<b>Your account manager found the order under a desk.</b><br>It is a month closer.",
|
||||
"sites_peering_caches.your_account_manager_is_on_paternity":"<b>Your account manager is on paternity leave.</b><br>His replacement is also on paternity leave.",
|
||||
"sites_peering_caches.your_ticket_was_merged_into_another":"<b>Your ticket was merged into another ticket.</b><br>That ticket was closed as a duplicate of yours.",
|
||||
"slots.continue":"Continue",
|
||||
"slots.continue_this_network":"Continue this network",
|
||||
"slots.damaged_export_or_delete":"Damaged: export it or delete it",
|
||||
"slots.delete":"Delete",
|
||||
"slots.delete_forever":"Delete forever",
|
||||
"slots.delete_name":"Delete {name}?",
|
||||
"slots.delete_this_network":"Delete this network",
|
||||
"slots.free_up_space":"Free up space",
|
||||
"slots.here_it_is_name":"<b>Here it is: {name}.</b><br>This is the window you were looking for.",
|
||||
"slots.it_is_open_in_another_window":"It is open in another window right now, and that window will stop too.",
|
||||
"slots.it_joins_your_networks_on_this":"It joins your networks on this device. The one you are playing stays saved.",
|
||||
"slots.just_now":"just now",
|
||||
"slots.keep_it":"Keep it",
|
||||
"slots.last_played_ago":"Last played {ago}",
|
||||
"slots.load_the_newest_version":"Load the newest version",
|
||||
"slots.more_for_name":"More for {name}",
|
||||
"slots.n_h_ago":{"one":"{n} h ago","other":"{n} h ago"},
|
||||
"slots.name_is_open_in_another_window":"{name} is open in another window",
|
||||
"slots.name_is_waiting_in_your_other":"<b>{name} is waiting in your other window.</b><br>Switch to it to keep playing.",
|
||||
"slots.name_moved_to_another_window_toast":"<b>{name} is now played in another window.</b><br>This puzzle carries on; your network is safe over there.",
|
||||
"slots.name_opened_in_another_window":"{name} opened in another window",
|
||||
"slots.name_was_deleted_in_another_window":"<b>{name} was deleted in another window.</b>",
|
||||
"slots.name_was_saved_in_another_window":"{name} was saved in another window",
|
||||
"slots.no_other_networks_here":"No other networks on this device. Exporting a save is your best backup.",
|
||||
"slots.only_one_window_can_play_a":"One network, one NOC: only one window can play it at a time, so two copies never overwrite each other.",
|
||||
"slots.open_in_another_window":"Open in another window",
|
||||
"slots.rename":"Rename",
|
||||
"slots.rename_your_network":"Rename your network",
|
||||
"slots.renamed_to_name":"<b>Renamed.</b><br>Say hello to {name}.",
|
||||
"slots.size_on_this_device":"{size} on this device",
|
||||
"slots.storage_on_this_device":"Storage on this device",
|
||||
"slots.switch_to_that_window":"Switch to that window",
|
||||
"slots.take_it_back_here":"Take it back here",
|
||||
"slots.take_over_here":"Take over here",
|
||||
"slots.that_network_is_gone":"<b>That network is gone.</b><br>It was deleted, maybe in another window.",
|
||||
"slots.this_window_stepped_aside_so_the":"You took it over in another window, so this one stepped aside and stopped saving. Nothing was lost.",
|
||||
"slots.this_window_stopped_saving_so_it":"A newer version was saved in another window, so this one stopped saving instead of overwriting it.",
|
||||
"slots.two_windows_one_network":"Two windows, one network",
|
||||
"slots.your_networks":"Your networks",
|
||||
"slots.your_networks_switch_or_start_another":"Your networks <small>switch, or start another</small>",
|
||||
"slots.your_other_networks_share_this_browser":"Your other networks share this browser's storage. Export the ones you want to keep, then delete them here to make room.",
|
||||
"sold_out.a_hyperscaler_bought_every_wave_of":"A hyperscaler bought every wave of that size on this route last week.",
|
||||
"sold_out.not_big_enough_yet_list":"Not big enough yet: {list}",
|
||||
"sold_out.only_peers_over_pnis_and_only":"Only peers over PNIs, and only with networks it considers important",
|
||||
|
|
|
|||
|
|
@ -154,3 +154,24 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi
|
|||
.gl dd{margin:2px 0 0;color:var(--ink2);line-height:1.45;font-size:13px}
|
||||
.kbd{display:inline-block;border:2px solid var(--ink);border-radius:6px;padding:0 5px;font-weight:900;font-size:11px;background:var(--soft)}
|
||||
|
||||
/* "Your networks" on the title screen: one big tap target per network, a small ⋯ for export and delete. */
|
||||
.slots{display:flex;flex-direction:column;gap:7px;margin-bottom:6px;max-height:min(46vh,330px);overflow:auto;padding:2px 2px 5px}
|
||||
.slot{display:flex;align-items:stretch;border:3px solid var(--ink);border-radius:16px;background:var(--paper);box-shadow:0 4px 0 var(--ink);flex:none;transition:transform .08s ease,box-shadow .08s ease}
|
||||
.slot:active{transform:translateY(3px);box-shadow:0 1px 0 var(--ink)}
|
||||
.slot.top{background:#FFE3F0;border-color:var(--me);box-shadow:0 4px 0 var(--me)}
|
||||
.slot.busy{background:var(--soft);border-style:dashed}
|
||||
.slot.broken{opacity:.75;border-style:dashed}
|
||||
.slot-go{flex:1;min-width:0;display:flex;align-items:center;gap:10px;background:none;border:0;padding:8px 6px 8px 11px;font:inherit;color:inherit;text-align:left;cursor:pointer;min-height:52px}
|
||||
.slot-go>i{font-style:normal;font-size:26px;line-height:1;flex:none}
|
||||
.slot .sn{flex:1;min-width:0;display:flex;flex-direction:column}
|
||||
.slot .sn b{font-family:var(--display);font-size:18px;line-height:1.1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.slot .sn small,.slot .sm small{font-size:12px;color:var(--ink2);line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.slot .tag{align-self:flex-start;font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em;color:var(--me);line-height:1.2}
|
||||
.slot.busy .tag{color:var(--ink2)}
|
||||
.slot .sm{flex:none;display:flex;flex-direction:column;align-items:flex-end;text-align:right}
|
||||
.slot .sm em{font:800 15px var(--display);font-style:normal}
|
||||
.slot-more{flex:none;width:44px;border:0;border-left:2px dashed var(--line);background:none;font:900 22px var(--display);color:var(--ink);cursor:pointer;border-radius:0 13px 13px 0}
|
||||
.slot-more:hover,.slot-go:hover{background:rgba(255,79,154,.06)}
|
||||
.slot-go:focus-visible,.slot-more:focus-visible{outline:3px solid #FF4F9A;outline-offset:-3px}
|
||||
.ibx.space{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.ibx.space .btns{margin:0}
|
||||
h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px}
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar
|
|||
#modal .cta{position:sticky;bottom:calc(-16px - env(safe-area-inset-bottom,0px));z-index:1;background:var(--paper);margin:12px -16px 0 !important;padding:10px 16px calc(10px + env(safe-area-inset-bottom,0px));border-top:2px solid var(--line)}
|
||||
.title-art h1{font-size:34px}.title-art svg{width:54px;height:54px}
|
||||
.tagline{font-size:13.5px;margin:8px 0 10px}
|
||||
.slots{max-height:38vh}.slot-go{padding:7px 4px 7px 9px;gap:8px}.slot-go>i{font-size:22px}.slot .sn b{font-size:16px}.slot .sm em{font-size:13.5px}.slot .sn small,.slot .sm small{font-size:11.5px}
|
||||
.door{padding:7px 9px 6px}.door i{font-size:22px}.door b{font-size:16px}.door span{font-size:11.5px}
|
||||
.presets{grid-template-columns:1fr;gap:6px}
|
||||
.preset{display:grid;grid-template-columns:auto 1fr;column-gap:9px;align-items:center;padding:6px 10px}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue