diff --git a/CHANGELOG.md b/CHANGELOG.md index c9aab50..055269f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +## [1.20.0] — 2026-10-25 + +- A proper Settings screen, from the menu or the title screen: alerts, animations, + sound and language in one place, saved on your device. +- The game can pause when a customer turns furious, so you no longer lose + customers to a notification you missed at 8× speed (#13). It is on by + default and can be switched off in Settings, where you can also choose to + pause on outages that cost you real traffic. +- Customer happiness is easier to keep an eye on (#15). You get an early warning + when a customer drops below 60%, with the reason. A Customers box in the top bar + (on phones, a red count on Deals) shows how happy they are overall. +- A Customers list in the NOC dashboard shows everyone who pays you, unhappiest + first, with what they pay, whether they are getting happier or angrier, and + exactly what is wrong. Filter it to the unhappy ones or by city, and tap Open + to go to them (#14). + ## [1.19.0] — 2026-10-25 - See all your connections in one place (#31, #33, #38): a new Connections list diff --git a/package-lock.json b/package-lock.json index 287000e..d9d2ff1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "1.19.0", + "version": "1.20.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "1.19.0", + "version": "1.20.0", "devDependencies": { "jsdom": "24.1.3" }, diff --git a/package.json b/package.json index ff68a37..f50aa1f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "1.19.0", + "version": "1.20.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", diff --git a/site/i18n/it.js b/site/i18n/it.js index 5fabea4..22444a5 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2122,4 +2122,40 @@ "It opens straight into your network, like any other app.":"Si apre direttamente sulla tua rete, come qualsiasi altra app.", "Install the app":"Installa l’app", "Play in the browser anyway":"Gioca comunque nel browser", +"Game paused.":"Gioco in pausa.", +"{name} is getting unhappy.
Happiness {p}% in {city}.":"{name} sta diventando scontento.
Soddisfazione {p}% a {city}.", +"Your customers":"I tuoi clienti", +"happiness {p}%":"soddisfazione {p}%", +"{n} unhappy customer, {price}/mo at risk":"{n} cliente scontento, {price}/mese a rischio", +"{n} unhappy customers, {price}/mo at risk":"{n} clienti scontenti, {price}/mese a rischio", +"See who":"Vedi chi", +"All customers":"Tutti i clienti", +"their fiber is down":"la loro fibra è giù", +"getting only {p} of the bandwidth they pay for":"ricevono solo {p} della banda che pagano", +"you cannot reach the whole internet ({p})":"non raggiungi tutta internet ({p})", +"No customers yet. Offers show up in the Deals tab.":"Ancora nessun cliente. Le offerte compaiono nella scheda Offerte.", +"Everyone who pays you, happiest last. Below 60% they start to grumble, below 30% they are furious, and at 0% they cancel.":"Tutti quelli che ti pagano, i più contenti in fondo. Sotto il 60% iniziano a brontolare, sotto il 30% sono furiosi, e a 0% disdicono.", +"Happiness":"Soddisfazione", +"weighted by what they pay":"pesata su quanto pagano", +"Unhappy":"Scontenti", +"{n} furious":"{n} furiosi", +"At risk":"A rischio", +"from unhappy customers":"dai clienti scontenti", +"Unhappy ({n})":"Scontenti ({n})", +"Nobody is unhappy. Enjoy it while it lasts.":"Nessuno è scontento. Goditela finché dura.", +"No customers here.":"Nessun cliente qui.", +"Name":"Nome", +"Resume":"Riprendi", +"Saved on this device.":"Salvate su questo dispositivo.", +"Customers and alerts":"Clienti e avvisi", +"Pause when a customer is furious":"Pausa quando un cliente è furioso", +"The game stops so you can fix their service before they cancel. Most useful at high speed.":"Il gioco si ferma così puoi sistemare il servizio prima che disdicano. Utilissimo ad alta velocità.", +"Warn when a customer gets unhappy":"Avvisa quando un cliente diventa scontento", +"An early heads-up below 60% happiness, long before they are furious.":"Un avviso in anticipo sotto il 60% di soddisfazione, molto prima che siano furiosi.", +"Pause on outages that hurt":"Pausa sui guasti che fanno male", +"Stops the game when a failure costs you real traffic, not when it reroutes by itself.":"Ferma il gioco quando un guasto ti costa traffico vero, non quando si reinstrada da solo.", +"Display and sound":"Schermo e audio", +"Viewport info":"Info viewport", +"For reporting layout bugs: shows what your screen tells the game.":"Per segnalare bug di layout: mostra cosa lo schermo dice al gioco.", +"Done":"Fatto", }; diff --git a/site/index.html b/site/index.html index 0515d98..9ff89d9 100644 --- a/site/index.html +++ b/site/index.html @@ -134,6 +134,8 @@ button{font:inherit;color:inherit} .hotk.hk-ix{color:#1E2640;background:#FFD23F} .noc.hot{background:var(--bad);color:#fff;animation:throb 1s ease-in-out infinite} .noc.hot .lbl{color:#FFE1E4} +#hCust .cnt{display:inline-block;min-width:18px;padding:0 5px;border-radius:9px;background:var(--bad);color:#fff;font-size:11px;line-height:18px;text-align:center;vertical-align:3px;margin-left:2px} +#hCust.hot{background:#FFE1E4} @keyframes throb{50%{transform:scale(1.05)}} .minibar{height:6px;border-radius:4px;background:var(--line);overflow:hidden;margin-top:2px;width:100%} .minibar i{display:block;height:100%;background:var(--ok)} @@ -498,6 +500,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar
Traffic served
0
Reach
0%
Rank
Tier 3
+
Date
Y1 · Jan 1
@@ -1778,7 +1781,7 @@ function sanitize(s){ for(const k of Object.keys(s.peers)){const [n,c]=k.split('@');if(!isNet(n)||!isIx(c))delete s.peers[k];} for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('Your IX')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);} const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity)); - const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('Customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';return b;}; + const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('Customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';return b;}; s.biz=s.biz.filter(okBiz).map(fixBiz);s.offers=s.offers.filter(okBiz).map(fixBiz); s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i)); s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank)); @@ -2120,7 +2123,7 @@ function fireFailure(){ const last=S.inc[S.inc.length-1]; last.impact=Math.max(0,before-R.served); if(before>1&&last.impact${incTitle(type)}
${esc(last.msg)} ${tr('Traffic rerouted, customers barely noticed.')}`,'good');} - else toast(`${incTitle(type)}
${esc(last.msg)}`,'bad',last.cost?[{l:`${last.fix||tr('Rush repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]); + else{const paused=pref('pauseIncident')&&autoPause();toast(`${incTitle(type)}
${esc(last.msg)}${paused?`
${tr('Game paused.')}`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('Rush repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]));} sfx('alert'); } function incTitle(t){return {ring:tr('Metro ring cut'),site:tr('Site outage'),cut:tr('Fiber cut'),crash:tr('Router crash'),power:tr('Power outage'),transit:tr('Upstream outage'),ixloop:tr('IX meltdown'),leak:tr('Route leak'),ddos:tr('DDoS attack'),fabric:tr('Fabric outage'),depeer:tr('Peering spat'),fatwave:tr('Fat-fingered wave'),label:tr('Patch panel mishap'),mtu:tr('MTU mismatch'),krroute:tr('Rerouted via Hong Kong'),ctrlplane:tr('Control plane meltdown'),lacp:tr('LACP trouble'),loss:tr('Packet loss'),pmtud:tr('PMTUD black hole'),oops:tr('Oops'),cleaner:tr('Vacuum incident'),maxpfx:tr('Max-prefix meltdown'),prepend:tr('Prepend-ageddon'),rpki:tr('RPKI invalid'),amp:tr('Amplifier failure'),roadmff:tr('Fat-fingered ROADM'),optic:tr('Dead optic'),maint:tr('Maintenance window'),ac:tr('Cooling failure'),hijack:tr('BGP hijack'),shutdown:tr('Government shutdown'),redsea:tr('Geopolitical cable cut')}[t]||tr('Incident');} @@ -2236,13 +2239,15 @@ function dayTick(){ b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; toast(tr('SLA breach: {name}.
The attack on {city} got through and your protected customer went down. You owe {pen} in SLA credits.',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood - for(const b of S.biz.slice()){if(eventTick(b,d))continue;const sf=bizSf(b),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99,scrubOk=b.type!=='scrub'||!!S.scrubAt,divOk=reqOk(b); + for(const b of S.biz.slice()){if(eventTick(b,d))continue;b.pm=b.mood;const sf=bizSf(b),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99,scrubOk=b.type!=='scrub'||!!S.scrubAt,divOk=reqOk(b); if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2); else if(S.day-(b.since||0)<15){} else{b.mood-=(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0)); if(b.mood<=0){S.biz=S.biz.filter(x=>x!==b);toast(tr('{name} cancelled.
Too many outages and too little bandwidth in {city}.',{name:esc(b.name),city:CITY[b.city].name}),'bad');sfx('err');} - else if(b.mood<30&&!b.warned){b.warned=true;toast(tr('{name} is furious.
Fix service in {city} or they leave.',{name:esc(b.name),city:CITY[b.city].name}),'bad',[{l:tr('Show me'),act:'focusCity',args:{city:b.city}}]);}} - if(b.mood>60)b.warned=false;} + else if(b.mood<30&&!b.warned){b.warned=b.warn60=true;const why=bizWhy(b)[0],paused=pref('pauseFurious')&&autoPause(); + toast(tr('{name} is furious.
Fix service in {city} or they leave.',{name:esc(b.name),city:CITY[b.city].name})+(why?`
${esc(why)}`:'')+(paused?`
${tr('Game paused.')}`:''),'bad',[{l:tr('Show me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');} + else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('{name} is getting unhappy.
Happiness {p}% in {city}.',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`
${esc(why)}`:''),'',[{l:tr('Show me'),act:'custGo',args:{id:b.id}}]);}} + if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;} // own IX members join for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.lengthn.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg))); @@ -2406,8 +2411,8 @@ const ACT={ if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;if(!spend(cost)){renderBank();return;}S.loans=S.loans.filter(x=>x!==l);track('loan_repaid'); toast(B.equity?tr('You bought out {bank}.
They flew off to find another startup.',{bank:esc(B.name)}):tr('Loan from {bank} repaid early.',{bank:esc(B.name)}),'good');after();renderBank();}, dashLink:({id})=>{$('dash').hidden=true;UI.confirm=null;UI.sel={type:'link',id};renderPanel();}, - animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();const m=$('modalCard'),r=m&&m.querySelector('.setrow');if(r)r.outerHTML=settingsRow();}, - soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();const m=$('modalCard'),r=m&&m.querySelector('.setrow');if(r)r.outerHTML=settingsRow();}, + animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();}, + soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();}, langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save();location.reload();}, mute:()=>{UI.muted=!UI.muted;try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();}, closePanel:()=>{UI.sel=null;UI.confirm=null;renderPanel();renderLeft();}, @@ -2520,6 +2525,11 @@ const ACT={ setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();}, setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();}, goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();}, + custGo:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b)return;$('dash').hidden=true;ACT.focusCity({city:b.city});UI.tab='cust';renderPanel();}, + custF:({v})=>{UI.kf=UI.kf||{};UI.kf.f=v==='sad'?'sad':'';renderDash();}, + custCity:({v})=>{UI.kf=UI.kf||{};UI.kf.city=isCity(v)?v:'';renderDash();}, + custSort:({k})=>{if(!['mood','mo','name','city'].includes(k))return;if(UI.custSort===k)UI.custDir=-(UI.custDir||1);else{UI.custSort=k;UI.custDir=k==='mo'?-1:1;}renderDash();}, + custOpen:({sad}={})=>{if(!S)return;UI.kf=sad?{f:'sad'}:{};const d=$('dash');d.hidden=false;renderDash();setTimeout(()=>{const el=$('custSec');if(el)el.scrollIntoView({block:'start'});},30);}, goConn:({city,k})=>{if(!isCity(city)||!own(CONN_K,k))return;$('dash').hidden=true;ACT.goEgress({city,k});}, connF:({f,v})=>{const F=UI.cf=UI.cf||{};if(f==='all'){UI.cf={};}else if(f==='k'){F.k=own(CONN_K,v)?v:'';}renderDash();}, connCity:({v})=>{UI.cf=UI.cf||{};UI.cf.city=isCity(v)?v:'';renderDash();}, @@ -2599,8 +2609,13 @@ const ACT={ ${btn(tr('Scenarios & weekly challenge'),'scenarios',{},'ghost')} ${btn(tr('How to play'),'help',{},'ghost')} ${RELEASE_NOTES.length?btn(tr('What’s new in {v}',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''} + ${btn(tr('Settings'),'settings',{},'ghost')} ${btn(tr('Start a new network'),'resetAsk',{},'red')} - ${settingsRow()}`);}, + `);}, + settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, + settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();}, + prefSet:({v})=>{const [k,b]=String(v).split(':');if(!own(PREF_DEF,k))return;setPref(k,b==='1');sfx('click');refreshSettings();}, + vpSet:({v})=>{vpOn(v==='on');refreshSettings();}, resetAsk:()=>openModal(`

${tr('Start a new network?')}

${tr('{name} and everything it owns will be deleted. This cannot be undone.',{name:esc(S?S.name:tr('Your network'))})}

${btn(tr('Delete and start over'),'newgame',{},'red big')}${btn(tr('Keep playing'),'closeModal',{},'ghost big')}
`), whatsNewShow:()=>whatsNew(true,true), updateNow:()=>{save();location.reload();}, @@ -2671,7 +2686,7 @@ function renderTabbar(){const tb=$('tabbar');if(!tb)return;if(!isPhone()||!S||!U const tab=(k,ic,l,cnt,red)=>``; const h=``+ ``+ - tab('goals','🎯',tr('Goals'),`${ndone}/${GOALS.length}`)+tab('deals','💼',tr('Deals'),S.offers.length||'')+tab('noc','🚨','NOC',S.inc.length||'',true)+tab('nets','🌐',tr('Networks')); + tab('goals','🎯',tr('Goals'),`${ndone}/${GOALS.length}`)+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('Deals'),u,true):tab('deals','💼',tr('Deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length||'',true)+tab('nets','🌐',tr('Networks')); if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;} document.body.classList.toggle('sheet-open',!!(UI.sel||UI.leftOpen));} function haptic(ms){if(UI.muted)return;try{navigator.vibrate&&navigator.vibrate(ms||12);}catch(e){}} @@ -2726,6 +2741,7 @@ function renderHUD(){ $('hTier').textContent=tierLabel(); $('hDate').textContent=dateStr(S.day); {const bo=(S.loanOffers||[]).length,hb=$('hBank');hb.hidden=!bo;hb.textContent=bo;} + {const st=custStats(),hc=$('hCust');hc.hidden=!st.n;if(st.n){$('hCustVal').innerHTML=`${st.avg>=80?'😀':st.avg>=60?'🙂':st.avg>=30?'😟':'😡'} ${Math.round(st.avg)}%${st.unhappy?` ${st.unhappy}`:''}`;hc.classList.toggle('hot',st.furious>0);}} const n=S.inc.length;$('hNoc').classList.toggle('hot',n>0);$('hNocVal').textContent=n?trn('{n} incident','{n} incidents',n):tr('All quiet'); if(!window.__TUBES_TEST__)fitHud(); renderTabbar(); @@ -2745,6 +2761,7 @@ function renderLeft(){ h+=GOALS.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `
${d?'✓':''}
${esc(g.t)}
${c||!d?`
${esc(g.d)}
`:''}${!d&&g.r?`
${tr('Reward {cash}',{cash:fmt$(g.r)})}
`:''}
`;}).join(''); h+=badgeGrid(); }else if(UI.left==='deals'){ + {const st=custStats();if(st.n)h+=`
${tr('Your customers')} ${st.n} · ${tr('happiness {p}%',{p:Math.round(st.avg)})}
${st.unhappy?`
${trn('{n} unhappy customer, {price}/mo at risk','{n} unhappy customers, {price}/mo at risk',st.unhappy,{price:fmt$(st.risk)})}
`:''}
${btn(st.unhappy?tr('See who'):tr('All customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}
`;} h+=confSection(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('Customer level {lv}: {name}',{lv,name:LEVELS[lv-1].n})}
${nx?tr('Next: {req} unlocks {what}',{req:nx.req,what:nx.unlock.toLowerCase()}):tr('Every customer type is unlocked. Go get those terabits.')}
`;} if(!S.offers.length)h+=`

${tr('No open offers right now. Businesses look for networks with POPs in their city. New ones pop up every few weeks.')}

`; @@ -3045,6 +3062,35 @@ function offTransitHint(id,city){const n=NET[id];if(n.type==='t1')return tr('Tie if(ixOk)return `${ixName(pick1)}: ${ixOk.why}`; return pniC.length?tr('PNI in {city}: {why}',{city:CITY[pniC[0]].name,why:pOk.why}):tr('Not present in any of your cities yet');} function transitTop(ids,k=5){const m={};for(const id of ids)for(const [n,v] of Object.entries(R.tNet[id]||{}))m[n]=(m[n]||0)+v;return Object.entries(m).filter(([,v])=>v>0.01).sort((a,b)=>b[1]-a[1]).slice(0,k);} +/* ---------- customers overview (#13, #14, #15) ---------- */ +const bizMo=b=>{const T=BIZ_T[b.type];return T.event?0:T.fiber?b.rate:b.bw*b.rate;}; +// Why a customer is unhappy, in the same terms the daily mood update uses. +function bizWhy(b){const T=BIZ_T[b.type],out=[];if(T.event&&!eventLive(b))return out; + const sf=bizSf(b);if(sf<0.95)out.push(T.fiber?tr('their fiber is down'):tr('getting only {p} of the bandwidth they pay for',{p:pct(sf)})); + if(!(T.l2||T.fiber)&&R.reach<=0.99)out.push(tr('you cannot reach the whole internet ({p})',{p:pct(R.reach)})); + if(b.type==='scrub'&&!S.scrubAt)out.push(tr('needs a scrubbing center')); + for(const k of b.reqs||[])if(REQS[k]&&!REQS[k].ok(b))out.push(typeof REQS[k].l==='function'?REQS[k].l(b):REQS[k].l); + return out;} +const moodCls=m=>m<30?'bad':m<60?'warn':''; +const custStats=()=>{const bz=S.biz.filter(b=>!BIZ_T[b.type].event),mo=bz.reduce((a,b)=>a+bizMo(b),0); + return {n:bz.length,unhappy:bz.filter(b=>b.mood<60).length,furious:bz.filter(b=>b.mood<30).length,avg:bz.length?(mo>0?bz.reduce((a,b)=>a+b.mood*bizMo(b),0)/mo:bz.reduce((a,b)=>a+b.mood,0)/bz.length):100,risk:bz.filter(b=>b.mood<60).reduce((a,b)=>a+bizMo(b),0)};}; +function custSection(){const F=UI.kf||{};let h=`

${tr('Customers')}

`; + if(!S.biz.length)return h+`

${tr('No customers yet. Offers show up in the Deals tab.')}

`; + const st=custStats(); + h+=`

${tr('Everyone who pays you, happiest last. Below 60% they start to grumble, below 30% they are furious, and at 0% they cancel.')}

`; + h+=`
${tr('Happiness')}
${Math.round(st.avg)}%
${tr('weighted by what they pay')}
${tr('Unhappy')}
${st.unhappy}
${trn('{n} furious','{n} furious',st.furious)}
${tr('At risk')}
${tr('{price}/mo',{price:fmt$(st.risk)})}
${tr('from unhappy customers')}
`; + const cities=[...new Set(S.biz.map(b=>b.city))].sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); + h+=`
${btn(tr('All ({n})',{n:S.biz.length}),'custF',{v:''},!F.f?'pink sm':'ghost sm')}${btn(tr('Unhappy ({n})',{n:S.biz.filter(b=>b.mood<60).length}),'custF',{v:'sad'},F.f==='sad'?'pink sm':'ghost sm')}
`; + const rows=S.biz.filter(b=>(!F.f||b.mood<60)&&(!F.city||b.city===F.city||b.city2===F.city||(b.sites||[]).includes(F.city))); + const sk=UI.custSort||'mood',dir=UI.custDir||1,val=b=>sk==='name'?b.name.toLowerCase():sk==='city'?CITY[b.city].name:sk==='mo'?bizMo(b):b.mood; + rows.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||a.mood-b.mood;}); + if(!rows.length)return h+`

${F.f?tr('Nobody is unhappy. Enjoy it while it lasts.'):tr('No customers here.')}

`; + const where=b=>b.sites?b.sites.map(c=>CITY[c].name).join(', '):b.city2?`${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:CITY[b.city].name; + const trend=b=>b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' ▲':' ▼'; + const sorts=[['mood',tr('Happiness')],['mo',tr('Per month')],['name',tr('Name')],['city',tr('Where')]]; + h+=`
${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; + h+=rows.map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); + return h+``;} /* ---------- connections overview (#31, #33, #38) ---------- Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and network, with a jump to the POP that holds it. The Networks tab shows the same per network. */ @@ -3104,6 +3150,7 @@ function renderDash(){ {const e={c:0,p:0,ix:0,t:0};let w=0;for(const n of NETS)if(n.tail){const x=R.netEg[n.id];if(x)for(const k in e)e[k]+=x[k]||0;w+=R.demTo[n.id]||0;}nets.push(row({id:'_tail',name:tr('The long tail ({n} small networks)',{n:NETS.filter(n=>n.tail).length}),asn:'many',type:'eye',col:'#8A93B8'},e,w));} for(let i=nets.length-1;i>=0;i--)if(!(nets[i].t>0.01||nets[i].want>0.01))nets.splice(i,1); {const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||b.t-a.t;});} + h+=custSection(); h+=connSection(); h+=`

${tr('Traffic by network (ASN)')}

${tr("Where your users' traffic comes from, and how it gets to you. Transit is the only part you pay per gigabit; caches, PNIs and IX peering are free or flat-rate. Tap a column to sort.")}

${['c','p','ix','t'].map(k=>`${EGC[k][0]}`).join('')}
${[['name',tr('Network'),''],['asn','AS',''],['type',tr('Type'),''],['traffic',tr('Traffic'),'r'],['mix',tr('How it arrives'),''],['cost',tr('Transit cost'),'r'],['lost',tr('Lost'),'r']].map(([k,l,c])=>``).join('')} ${nets.map(({n,e,t,want})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('{price}/mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}
`; @@ -3223,7 +3270,7 @@ function showHelp(){
DE-KICKS
${tr('The group behind several big exchanges (Frankfurt, Madrid, Marseille, Dubai, Mumbai, New York) treats price lists as a state secret. Ports are quoted per customer and go up the bigger you look. Haggling can work, backfire or stall for a week. Prices get "harmonised" upwards once a year, add-ons appear on your invoice until you opt out, and trying to leave earns you a retention discount that ends with a fee.')}
${tr('Remote peering')}
${tr('Reach an IX over a fabric circuit without a POP there. It works, and the route server still gets you every open network, but it is discouraged: the reseller charges 1.5× for the port and oversubscribes it to 80%, latency rides the fabric, one fabric outage drops every session, and many selective networks refuse remote members outright.')}
${tr('Peering policy')}
${tr('Open peers with anyone. Selective wants to see traffic first. Restrictive (Tier 1s) only peers with giants, over PNIs. Paid means exactly that. Big selective networks also have moods: in some cities they refuse new peers for a few months, or only take PNIs, and now and then they tear down a session you already had. Try another city or a PNI, and ask again later.')}
${tr('Waves')}
${tr('Your fiber links are leased waves at a flat monthly rate. Longer and bigger costs more (10G → 6.4T), and subsea is 1.8× the price.')}
${tr('95th percentile')}
${tr('Transit bills sample your usage every day and charge the 95th percentile of the last 30 days, so short spikes are forgiven but long ones are not.')}
${tr('Routers')}
${tr('Each POP\'s router model caps its fastest port (100G, 400G, 800G, 1.6T) and how much it can forward. Bigger waves and ports need better routers at both ends. Better models unlock with your customer level. With one router, upgrades mean a day of downtime.')}
${tr('Dark fiber')}
${tr('Lease an IRU or build your own (slow, with delays), then buy a line system with amplifiers and light channels with 400ZR+, 800ZR+ or 1.6T transponders. Much cheaper than waves at scale, but the gear can fail. A spares kit speeds up repairs.')}
${tr('Subsea cables')}
${tr('Subsea waves can only follow cable systems modelled on real ones, drawn faintly on the map (tap a city to highlight its cables). Teal ones are new and cheap, purple ones pricey, dashed ones old and cut-prone. All your waves on one cable die together when it is cut. Between continents on land, you can often choose overland (2.5×, many borders) or a cable.')}
${tr('Latency')}
${tr('Every link has latency. High-frequency traders pay a fortune for a circuit within their latency budget; route them “Lowest latency”. Bulk backup customers do not care, so route them “Scenic” over your quiet links to keep busy ones free.')}
${tr('NOC dashboard')}
${tr('The chart button at the top opens traffic graphs by exit (caches, PNIs, IX, transit), money over time, per-ASN traffic with how it reaches you and what its transit costs, plus your busiest links and routers.')}
${tr('Asia')}
${tr('A weird, underserved market. Transit costs 2.5× what it does in Europe (Africa 2×, Oceania 1.8×), local incumbents mostly peer only for pay, and IXs are fragmented. But demand is enormous and users sign up 60% faster than anywhere else. Peering and caches pay off most here.')}
${tr('Russia')}
${tr('Moscow needs a mandatory government box in every POP, Western CDNs are mostly gone, Goggle video is throttled to half speed, and the sovereign internet drills now and then cut Moscow off for a day.')}
${tr('Events, chains and wholesale')}
${tr('Event networks (a final, a festival, a keynote) need a burst of capacity in one city for a few days and pay once at the end, prorated by how much of the crowd you served; below 70% you pay a penalty. SD-WAN chains connect 3–6 of your POPs hub-and-spoke, so one broken spoke upsets the whole contract. Once you run your own dark fiber, carriers want to rent spare channels as alien waves, and on fiber you built yourself, a spare pair.')}
${tr('Bank')}
${tr('Tap your cash to open the bank. Lenders make offers now and then, and much more often when you are in the red. Each loan has a monthly payment and some odd conditions; break one and you pay a penalty. Your credit rating decides which banks talk to you. The loan shark is always there. Do not be late.')}
${tr('LAGs')}
${tr('Out of port speed? Bundle up to 8 identical ports to the same transit provider, IX or PNI into a LAG. Each member costs a full port; flow hashing is never perfectly even, so a bundle carries about 95% of the sum.')}
${tr('Traffic engineering')}
${tr('Tap a link to see which networks, which entry points and which customer cities fill it. Raise a link\'s metric to steer traffic around it, or set an egress (transit, IX, PNI) to Prefer or Backup only.')}
${tr('China')}
${tr('Mainland China needs a license and a local joint venture. Many foreign services are blocked there, and traffic crossing the border loses packets unless you pay for premium routes.')}
${tr('Weird requirements')}
${tr('Some customers come with conditions: no Cogentle anywhere, no subsea cables because of sharks, two routers, a generator, NetChill on-net, low-loss China reach and more. Each pays a bonus. Unmet ones make them grumpy until you fix it or they leave.')}
${tr('Customer levels')}
${tr('As your peak traffic and footprint grow, bigger customers show up: streaming startups and universities, then AI GPU data centers and cloud on-ramps, then AI training interconnects and hyperscaler DCI deals measured in terabits. Pink $$ bubbles mark the big ones.')}
${tr('L2VPN & DDoS protection')}
${tr('Businesses may want a private circuit between two of your POPs (it rides your backbone), or DDoS protection (needs your own scrubbing center).')}
${tr('NNI fabrics')}
${tr('Megapork, PocketFabric and Consolation Connect sell a port plus virtual circuits between cities. Great for small links and remote peering at an IX where you have no POP.')}
${tr('Conferences')}
${tr('NANOG, RIPE, DENOG and friends come round every year. Register in the Deals tab for $8k. For 45 days after, selective networks with a presence in that region need only half the usual traffic before they peer with you. Sometimes you also win the raffle.')}
${tr('Modes')}
${tr('Sandbox gives you a billion dollars, every unlock and no failures, but no badges. Scenarios are hand-built challenges with a goal and a deadline, and the weekly challenge gives everyone the same world for a week. Share your result with the card in the menu.')}
${tr('Traceroute')}
${tr('Tap 🔍 Traceroute on any of your cities, or open it from the NOC tab, to see the exact path to a network or POP, hop by hop, with latency, the exit and the AS path.')}
${tr('Badges')}
${tr('Below your goals sits a wall of badges, from common to legendary. Some take luck, some take years, and a couple are secret. Badges you earned in earlier games stay on this device with a dashed outline.')}
${tr('The giants')}
${tr('At customer level 3 and 4, hyperscalers and AI clouds show up with deals only they would ask for: terabit AI WANs between gigawatt campuses, training runs spread over several sites, week-long dataset ingests, and hundreds of fiber pairs in a trench you dug yourself. They pay like nobody else, and they want diverse paths, two sites per metro and zero excuses. Cities near their campuses list them under “Who’s here”.')}
RouteScript
${tr('Once Auto-TE is installed, you can program it from the NOC tab. Rules include spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams and blackhole ddos. Check runs a dry run against live traffic; Deploy makes it real, mistakes included.')}
Auto-TE
${tr('Traffic follows the shortest path by distance and link metric, and reroutes by itself when links fail. When a path is merely full, the overflow is dropped, just like a real IGP. From customer level 3 you can install Auto-TE in the NOC tab: it spills overflow onto up to two alternate paths with free capacity, as long as they are no more than twice as long.')}
${tr('Metro diversity')}
${tr('A POP is one building until you add a second site in the Infra tab. Then a power cut, cleaner or A/C failure only takes out half the city, and you choose which site each transit, PNI and IX port plugs into, or pick Both to split a LAG across the two buildings. Spread them out, or both halves of your redundancy will sit in the same dark room. Watch out for metro ring cuts, which cut site B off.')}
${tr('Wave markets')}
${tr('What a wave costs depends on where it runs. Europe is cheap (lots of competing fiber), North America is average, Asia and South America are pricier, and anything into Africa is several times the price. Every route has its own going rate, and new leases get about 8% cheaper each year, so waiting can pay. The link planner tells you how a route compares.')}
${tr('Regional quirks')}
${tr('In the Gulf, Saudi POPs need a local telecom licence and data on Saudi users stays in the Kingdom; gigaprojects ask for huge demo networks; and now and then the neighbours fall out and every link between Qatar and Saudi Arabia or the UAE goes dark for months, so keep a sea route. South America hangs off Miami: transit is pricier, nothing crosses the Darién Gap by land, and fiber over the Andes costs double and breaks often. IX.brrr in Brazil is run by a nonprofit with cheap public prices, and small Brazilian provedores buy transit in bulk. Inside the UAE only the duopoly may run fiber, so no dark fiber and 3× waves. Korea runs on “sender pays”: transit into Seoul costs about four times the usual price and the three incumbents only peer over paid PNIs, billed per gigabit you send them. Taiwan’s cables meet a lot of anchors, Indian fiber meets road widening and the monsoon, and South Africa has load shedding: bring a generator.')}
${tr('Boot times')}
${tr('Some routers take forever to boot. The Infra tab shows how long yours takes. Slow booters make crashes last longer and turn a one-router swap into a three-day outage. Bigger chassis, especially anything with a PacketOinker™ inside, are slow more often. Twin routers make it someone else’s problem.')}
${tr('Failures')}
${tr('Things break all the time: fiber cuts, router crashes, power cuts, IX loops, fabric outages, route leaks, DDoS, fat fingers, cooling failures, and geopolitics: sanctions, tariffs, BGP hijacks, landing permit disputes, exam-day shutdowns and Red Sea cable cuts. Traffic reroutes automatically over other paths and upstreams. Parallel links on diverse routes, a second router and a backup generator all help. Or pay to rush repairs.')}
-

${tr('Want to know how it really works?')}

${plugHtml(true)}
${btn(UI.started?tr('Back to the map'):tr('Got it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('What’s new in {v}',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('Start a new network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('Export save'),'exportSave',{},'ghost sm'):''}${btn(tr('Import a save'),'importPick',{},'ghost sm')}
${settingsRow()}`); +

${tr('Want to know how it really works?')}

${plugHtml(true)}
${btn(UI.started?tr('Back to the map'):tr('Got it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('What’s new in {v}',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('Start a new network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('Export save'),'exportSave',{},'ghost sm'):''}${btn(tr('Import a save'),'importPick',{},'ghost sm')}${btn(tr('Settings'),'settings',{},'ghost sm')}
`); } function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`
${btn(tr('Share my network'),'share',{},'pink')}

${tr('You built a cartoon internet. Now see how the real one works:')}

${plugHtml(true)}`);},0);openModal(`

${tr(`You're a Tier 1!`)}

${tr('{name} (AS{asn}) is transit-free. You peer with every giant on the planet and pay nobody to reach the internet. Took you {days} days and {n} incidents.',{name:esc(S.name),asn:S.asn,days:S.day,n:S.stats.incidents})}

${btn(tr('Keep building'),'keepPlaying',{},'pink big')}`);sfx('coin');} function showLose(){openModal(`

${tr('Bankrupt')}

${tr('The bank repossessed your routers and sold them on eBuy. {name} lasted {days} days and peaked at {peak}.',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}

${btn(tr('Try again'),'newgame',{},'pink big')}`);try{localStorage.removeItem('sot-save-v1');}catch(e){}} @@ -3326,8 +3373,28 @@ function i18nDom(){if(LANG==='en')return;for(const el of document.querySelectorA // One button per [value,label] option; the current one is highlighted. function segBtns(act,cur,opts){return opts.map(([v,l])=>btn(l,act,{v},cur===v?'pink sm':'ghost sm')).join('');} /* Animation setting: auto follows the system's reduced-motion preference, or force it on or off. */ -function settingsRow(){const seg=(lab,act,cur,opts)=>`
${lab}
${segBtns(act,cur,opts)}
`; - return `

${tr('Settings')}

${seg(tr('Animations'),'animSet',UI.anim||'auto',[['auto',tr('Auto')],['on',tr('On')],['off',tr('Off')]])}${seg(tr('Sound'),'soundSet',UI.muted?'off':'on',[['on',tr('On')],['off',tr('Off')]])}${seg(tr('Language'),'langSet',LANG,Object.entries(LANGS))}

${tr('Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.')}

${installRow()}
`;} +/* Settings are per device (localStorage), not part of the save: they are about how you like to play. */ +const PREF_DEF={pauseFurious:true,warnUnhappy:true,pauseIncident:false}; +let PREFS=(()=>{try{const j=JSON.parse(localStorage.getItem('sot-prefs')||'{}');return j&&typeof j==='object'?j:{};}catch(e){return {};}})(); +const pref=k=>typeof PREFS[k]==='boolean'?PREFS[k]:PREF_DEF[k]; +function setPref(k,v){if(!own(PREF_DEF,k))return;PREFS[k]=!!v;try{localStorage.setItem('sot-prefs',JSON.stringify(PREFS));}catch(e){}} +// Stop the clock for something the player must see. Nothing happens if the game is already paused. +function autoPause(){if(!S||!UI.speed)return false;UI.resumeSpeed=UI.speed;UI.speed=0;renderHUD();return true;} +const resumeAct=()=>({l:tr('Resume'),act:'speed',args:{v:UI.resumeSpeed||1}}); +function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${lab}
${segBtns(act,cur,opts)}
${note?`

${note}

`:''}`; + const onoff=k=>[[k+':1',tr('On')],[k+':0',tr('Off')]],cur=k=>k+':'+(pref(k)?1:0); + return `

⚙️ ${tr('Settings')}

${tr('Saved on this device.')}

+

${tr('Customers and alerts')}

+ ${seg(tr('Pause when a customer is furious'),'prefSet',cur('pauseFurious'),onoff('pauseFurious'),tr('The game stops so you can fix their service before they cancel. Most useful at high speed.'))} + ${seg(tr('Warn when a customer gets unhappy'),'prefSet',cur('warnUnhappy'),onoff('warnUnhappy'),tr('An early heads-up below 60% happiness, long before they are furious.'))} + ${seg(tr('Pause on outages that hurt'),'prefSet',cur('pauseIncident'),onoff('pauseIncident'),tr('Stops the game when a failure costs you real traffic, not when it reroutes by itself.'))} +

${tr('Display and sound')}

+ ${seg(tr('Animations'),'animSet',UI.anim||'auto',[['auto',tr('Auto')],['on',tr('On')],['off',tr('Off')]],tr('Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.'))} + ${seg(tr('Sound'),'soundSet',UI.muted?'off':'on',[['on',tr('On')],['off',tr('Off')]])} + ${seg(tr('Language'),'langSet',LANG,Object.entries(LANGS))} + ${seg(tr('Viewport info'),'vpSet',VP_T?'on':'off',[['on',tr('On')],['off',tr('Off')]],tr('For reporting layout bugs: shows what your screen tells the game.'))} + ${installRow()}
${btn(tr('Done'),'settingsClose',{},'pink')}
`;} +const refreshSettings=()=>{if(UI.setOpen)openModal(settingsHtml());}; function animOn(){const m=UI.anim||'auto';if(m==='on')return true;if(m==='off')return false;try{return !matchMedia('(prefers-reduced-motion: reduce)').matches;}catch(e){return true;}} function applyAnim(){const r=document.documentElement;r.classList.toggle('no-anim',UI.anim==='off');r.classList.toggle('anim-force',UI.anim==='on');if(!animOn())FLOATS.length=0;} const toS=(wx,wy,k=0)=>[(wx+k*W-cam.x)*cam.z+CW/2,(wy-cam.y)*cam.z+CH/2]; @@ -3606,7 +3673,7 @@ function frame(now){ const dt=Math.min(250,now-last);last=now; if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);} if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save(); - if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} + if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} if(n){renderHUD();if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}} if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ try{draw(animOn()?animT:0);}catch(e){tickErr(e);} diff --git a/tests/issues.test.js b/tests/issues.test.js index fc90d20..1086355 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -400,3 +400,75 @@ test('#31 #33 #38 connections overview lists every port, filters it and jumps to assert.match(jump.textContent, /Transit.*Frankfurt/); assert.deepEqual(errors, []); }); + +test('#13 #15 unhappy customers warn early, furious ones pause the game (optional)', () => { + const { ev, errors } = load(); + base(ev); + ev("S.biz.push({id:'b1',city:'fra',city2:null,reqs:[],name:'Llama Logistics',type:'dia',bw:5,rate:100,mood:100,since:-100});compute();ACT.speed({v:4})"); + const toasts = () => ev("document.getElementById('toasts').textContent"); + // service collapses: happiness falls through 60% (warning) then 30% (furious, paused) + ev("bizSf=()=>0.6"); + for (let i = 0; i < 3; i++) ev('dayTick()'); + assert.match(toasts(), /Llama Logistics is getting unhappy/); + assert.match(toasts(), /getting only 60%/, 'the warning says why'); + assert.equal(ev('UI.speed'), 4, 'a warning does not pause'); + for (let i = 0; i < 4 && ev('UI.speed') !== 0; i++) ev('dayTick()'); + assert.match(toasts(), /Llama Logistics is furious/); + assert.equal(ev('UI.speed'), 0, 'furious pauses the game'); + assert.match(toasts(), /Game paused/); + assert.equal(ev('UI.resumeSpeed'), 4, 'Resume goes back to the old speed'); + // the setting turns it off + ev("setPref('pauseFurious',false);setPref('warnUnhappy',false);S.biz.push({id:'b2',city:'fra',city2:null,reqs:[],name:'Snack Overflow',type:'dia',bw:5,rate:100,mood:100,since:-100});ACT.speed({v:2})"); + for (let i = 0; i < 5; i++) ev('dayTick()'); + assert.ok(ev("S.biz.find(b=>b.id==='b2').mood") < 30); + assert.equal(ev('UI.speed'), 2, 'no pause with the setting off'); + assert.doesNotMatch(toasts(), /Snack Overflow is getting unhappy/); + assert.equal(ev("JSON.parse(localStorage.getItem('sot-prefs')).pauseFurious"), false, 'stored per device'); + assert.deepEqual(errors, []); +}); + +test('#14 customers overview lists everyone with happiness, reasons and a jump', () => { + const { ev, dom, errors } = load(); + base(ev); + const doc = dom.window.document; + ev("ACT.buildPop({city:'ams'});S.biz.push({id:'c1',city:'fra',city2:null,reqs:[],name:'Happy Hamster',type:'dia',bw:10,rate:100,mood:95,since:-100},{id:'c2',city:'ams',city2:null,reqs:[],name:'Grumpy Goat',type:'host',bw:20,rate:100,mood:40,since:-100});compute();renderAll()"); + const st = JSON.parse(ev('JSON.stringify(custStats())')); + assert.equal(st.n, 2); + assert.equal(st.unhappy, 1); + assert.equal(st.risk, 2000, 'the unhappy customer pays 2000/mo'); + assert.ok(st.avg > 40 && st.avg < 95, 'happiness is weighted by what they pay'); + assert.equal(ev("$('hCust').hidden"), false, 'HUD shows customer happiness'); + assert.match(ev("$('hCustVal').textContent"), /%/); + ev('ACT.custOpen({})'); + const names = () => [...doc.querySelectorAll('#custSec .row .nm')].map((n) => n.textContent); + assert.equal(names().length, 2); + assert.match(names()[0], /Grumpy Goat/, 'unhappiest first'); + ev("ACT.custF({v:'sad'})"); + assert.equal(names().length, 1); + ev("ACT.custF({v:''});ACT.custCity({v:'fra'})"); + assert.deepEqual(names().map((n) => n.split(' ')[0]), ['Happy']); + ev("ACT.custGo({id:'c2'})"); + assert.equal(ev("$('dash').hidden"), true); + assert.equal(ev('UI.sel.id'), 'ams'); + assert.equal(ev('UI.tab'), 'cust'); + // the Deals tab summary + ev("UI.left='deals';UI.leftOpen=true;UI.sel=null;renderLeft()"); + assert.match(doc.getElementById('leftBody').textContent, /1 unhappy customer/); + assert.deepEqual(errors, []); +}); + +test('settings screen holds every option and opens from the menu and the title screen', () => { + const { ev, errors } = load(); + ev('showTitle();ACT.settings()'); + const card = () => ev("document.getElementById('modalCard').textContent"); + for (const t of [/Pause when a customer is furious/, /Warn when a customer gets unhappy/, /Pause on outages/, /Animations/, /Sound/, /Language/]) assert.match(card(), t); + ev("ACT.prefSet({v:'pauseIncident:1'})"); + assert.equal(ev("pref('pauseIncident')"), true); + ev("ACT.prefSet({v:'nope:1'})"); + assert.equal(ev("'nope' in PREFS"), false, 'unknown settings are ignored'); + ev('ACT.settingsClose()'); + assert.match(card(), /Start building|Name your network/, 'back to the title screen'); + ev('ACT.start({});ACT.menu();ACT.settings();ACT.settingsClose()'); + assert.equal(ev("document.getElementById('modal').hidden"), true); + assert.deepEqual(errors, []); +}); diff --git a/tests/modes.test.js b/tests/modes.test.js index f446658..7757378 100644 --- a/tests/modes.test.js +++ b/tests/modes.test.js @@ -106,6 +106,8 @@ test('the guided tutorial walks through the first steps and can be skipped', () test('animations can be switched off, on or follow the system, and the choice sticks', () => { const { ev, errors } = load(); ev("ACT.start({});ACT.menu()"); + assert.match(ev("document.getElementById('modalCard').textContent"), /Settings/); + ev("ACT.settings()"); assert.match(ev("document.getElementById('modalCard').textContent"), /Animations/); ev("ACT.animSet({v:'off'})"); assert.equal(ev("document.documentElement.classList.contains('no-anim')"), true);