Split the game page into partials under src/, assembled into one index.html at build
site/index.html (900 KB of HTML, CSS and JS in one file) becomes src/: a shell (src/index.html), styles/ and game/, concatenated in path order by scripts/lib/page.js. The assembled page is byte-identical to the old file, so load time and in-game performance are unchanged. - scripts/build.js replaces build.sh (same env vars, same output) - npm run dev: a zero-dependency dev server that assembles on every request - tests assemble the page in memory; npm test runs every tests/*.test.js - perf-bench takes --base-ref to build a git ref's page - scripts/legacy/split-index-html.js is the splitter, kept for older branches
This commit is contained in:
parent
295e68cc46
commit
67a40942b4
113 changed files with 5584 additions and 5195 deletions
109
src/game/60-features/10-banks.js
Normal file
109
src/game/60-features/10-banks.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
/* ================= BANKS & LOANS =================
|
||||
Lenders make offers now and then (more often when you are broke). Each loan
|
||||
is a fixed monthly payment that shows up in your costs; conditions are checked
|
||||
daily and breaking one costs a penalty. */
|
||||
const BANKS={
|
||||
gs:{name:'Goldman Sacks',col:'#6F8FAF',min:'AA',apr:[.07,.11],amt:[4,9],term:[24,48],covs:['peer30','continents2','golf','yacht'],blurb:tr('Only lends to people who do not need it.')},
|
||||
db:{name:'Deutsche Bankrupt',col:'#0018A8',min:'A',apr:[.08,.13],amt:[3,7],term:[18,36],covs:['nocog','gen','fax'],blurb:tr('Very solid. Mostly.')},
|
||||
jpm:{name:'JP Morgain',col:'#5B4636',min:'A',apr:[.09,.14],amt:[3,6],term:[12,36],covs:['uptime','logo','nephew'],blurb:tr('Lends you money and also a little bit of their own.')},
|
||||
cs:{name:'Credit Sweaty',col:'#7A9CC6',min:'BBB',apr:[.11,.17],amt:[2,5],term:[12,30],covs:['cash50','nochina'],blurb:tr('Nervous, but enthusiastic.')},
|
||||
wf:{name:'Wells Far-Gone',col:'#D71E28',min:'BB',apr:[.12,.18],amt:[2,4],term:[12,24],covs:['nosub','logo','reach99'],blurb:tr('Opened three accounts for you while you read this.')},
|
||||
spk:{name:'Spätzle-Sparkasse',col:'#E30613',min:'B',apr:[.05,.08],amt:[1,3],term:[24,60],covs:['spaetzle','kehrwoche'],blurb:tr('Cheap, patient, and very particular about Stuttgart.')},
|
||||
rev:{name:'Revoloot',col:'#191C1F',min:'B',apr:[.13,.2],amt:[1,3],term:[6,18],covs:['app'],blurb:tr('Instant approval. Instant regret.')},
|
||||
gov:{name:'Ministry of Tubes',col:'#2E7D32',min:'CCC',apr:[.01,.02],amt:[1,2],term:[36,60],covs:['rural','forms'],blurb:tr('Cheap state money for connecting the underserved. Bring a pen.')},
|
||||
crypto:{name:'Crypto Bros Capital',col:'#F7931A',min:'CCC',apr:[.15,.25],amt:[2,6],term:[6,18],covs:['hodl','tier3'],crypto:true,blurb:tr('Pays out in TubeCoin. Value may vary. A lot.')},
|
||||
vult:{name:'Venture Vultures',col:'#8E44AD',min:'CCC',amt:[6,12],share:[.1,.15],covs:['blitz'],equity:true,blurb:tr('No repayments, ever. Just a slice of your revenue, forever, and a lot of opinions.')},
|
||||
balloon:{name:'Ballooney Brothers',col:'#E91E63',min:'B',apr:[.1,.15],amt:[2,6],term:[12,24],covs:['oddpops'],model:'balloon',blurb:tr('No payments at all! Until the very end. Then all of them, at once.')},
|
||||
storm:{name:'Stormy Weather Lending',col:'#546E7A',min:'BB',apr:[.04,.06],amt:[2,5],term:[12,36],covs:['nogen'],model:'storm',blurb:tr('Cheap while the sun shines. Every open incident adds 2% to your rate.')},
|
||||
ppp:{name:'Peer Pressure Partners',col:'#00897B',min:'B',amt:[2,5],term:[24,36],covs:['nocache'],model:'transit',blurb:tr('You repay with 30% of your transit bill. Go transit-free and you stop paying. Until the end.')},
|
||||
astro:{name:'Horoscope Holdings',col:'#5E35B1',min:'CCC',apr:[.02,.3],amt:[1,4],term:[12,24],covs:['friday','nobude'],model:'astro',blurb:tr('Your rate is set by the stars every month. Mercury is in retrograde a lot.')},
|
||||
pizza:{name:'Papa Pizza Capital',col:'#FF7043',min:'BB',apr:[.03,.05],amt:[1,3],term:[12,24],covs:['pizza'],blurb:tr('The cheapest money in town. There is a catch, and it has extra cheese.')},
|
||||
shark:{name:'Loan Shark Telecom Finance',col:'#37474F',min:'C',apr:[.6,.9],amt:[1,2],term:[4,8],covs:[],shark:true,blurb:tr('Always open. Ask no questions. Do not be late.')},
|
||||
};
|
||||
const RATINGS=['C','CCC','B','BB','BBB','A','AA','AAA'];
|
||||
const COVS={
|
||||
peer30:{l:tr('Keep your peering ratio above 30%. The bank read a blog post about peering.'),ok:()=>(R.peerShare||0)>=0.3},
|
||||
continents2:{l:tr('Keep POPs on at least 2 continents. Diversification!'),ok:()=>regionsCount()>=2},
|
||||
golf:{l:tr('Your CEO plays golf with our CEO every Thursday.'),ok:()=>true},
|
||||
nocog:{l:tr('No Cogentle transit anywhere. Our CEO got de-peered once and has not recovered.'),ok:()=>!S.transit.some(t=>t.net==='cog')},
|
||||
gen:{l:tr('Every POP needs a backup generator. Our risk team saw one disaster movie.'),ok:()=>Object.values(S.pops).every(p=>p.gen)},
|
||||
fax:{l:tr('Send us your monthly report by fax.'),ok:()=>true},
|
||||
uptime:{l:tr('Deliver at least 95% of what your customers want.'),ok:()=>!R.demand||R.served/R.demand>=0.95},
|
||||
logo:{l:tr('Our logo goes on every router you own.'),ok:()=>true},
|
||||
cash50:{l:tr('Never let cash drop below $50k. It makes us sweat.'),ok:()=>S.cash>=50000},
|
||||
nochina:{l:tr('Stay out of mainland China. Compliance said so.'),ok:()=>!Object.keys(S.pops).some(cnCity)},
|
||||
nosub:{l:tr('No new subsea links while this loan runs. We are afraid of sharks.'),ok:l=>S.links.filter(x=>x.sub).length<=(l.base&&l.base.sub||0)},
|
||||
spaetzle:{l:tr('Peer at the Spätzle-IX in Stuttgart. Local money for local packets.'),ok:()=>S.ixp.stg!==undefined},
|
||||
kehrwoche:{l:tr('Do the Kehrwoche: keep your NOC free of incidents older than a week.'),ok:()=>!S.inc.some(i=>S.day-i.start>7)},
|
||||
app:{l:tr('Download our app and enable all notifications.'),ok:()=>true},
|
||||
rural:{l:tr('Run home broadband somewhere underserved (Asia, Africa, Oceania or South America).'),ok:()=>Object.keys(S.pops).some(c=>S.pops[c].bb&&['AS','AF','OC','SA'].includes(CITY[c].reg))},
|
||||
forms:{l:tr('Fill in form T-17b in triplicate, every month, forever.'),ok:()=>true},
|
||||
hodl:{l:tr('Never sell your TubeCoin. Diamond hands.'),ok:()=>true},
|
||||
oddpops:{l:tr('Always run an odd number of POPs. Our numerologist insists.'),ok:()=>Object.keys(S.pops).length%2===1},
|
||||
nobude:{l:tr('Never build in Bude. The loan officer had a bad surfing holiday there.'),ok:()=>!S.pops.bde},
|
||||
nogen:{l:tr('No diesel generators anywhere. Our sustainability team is watching.'),ok:()=>!Object.values(S.pops).some(p=>p.gen)},
|
||||
friday:{l:tr('No new links on a Friday. The stars do not allow it.'),ok:l=>!S.links.some(x=>(x.day||0)>=l.start&&(x.day||0)%7===4)},
|
||||
nocache:{l:tr('No Goggle cache boxes. Our chairman lost an argument with a search engine.'),ok:()=>!S.caches.some(c=>c.net==='ggl')},
|
||||
reach99:{l:tr('Reach 99% of the internet at all times. We looked up what a network is for.'),ok:()=>(R.reach||0)>=0.99},
|
||||
tier3:{l:tr('Stay Tier 3. Number go up, rank stay down.'),ok:()=>tierLabel()==='Tier 3'},
|
||||
nephew:{l:tr('Give our CEO’s nephew a job. He needs {price}/mo and a parking spot.'),fee:3000,ok:()=>true},
|
||||
yacht:{l:tr('Our chairman needs a yacht for the summer. You don’t own one, so you rent one: {price}/mo.'),fee:8000,ok:()=>true},
|
||||
pizza:{l:tr('Pizza for the whole NOC after every incident: {price} each.'),each:400,ok:()=>true},
|
||||
blitz:{l:tr('Open a new POP at least every 90 days. Blitzscale or die.'),ok:l=>S.day-Math.max(l.start,...Object.values(S.pops).map(p=>p.day||0))<=90},
|
||||
};
|
||||
// Conditions read with their price filled in; some cost money every month, one costs money per incident.
|
||||
const covLabel=c=>COVS[c]?COVS[c].l.replace('{price}',fmt$(COVS[c].fee||COVS[c].each||0)):c;
|
||||
const loanFees=l=>(l.covs||[]).reduce((a,c)=>a+((COVS[c]&&COVS[c].fee)||0),0);
|
||||
// Good terms are for good credit: every notch below AAA adds to the rate.
|
||||
const RATE_PREM={AAA:0,AA:.005,A:.01,BBB:.02,BB:.04,B:.07,CCC:.12,C:.2};
|
||||
// A loan worth more than this many months of revenue also wants a slice of revenue until it is repaid.
|
||||
const BIG_LOAN=5;
|
||||
const STAR_SIGNS=[N_('Mercury'),N_('Saturn'),N_('Venus'),N_('Your rising sign'),N_('The moon'),N_('Pluto, which is not even a planet')];
|
||||
function niceAmt(v){const m=Math.pow(10,Math.floor(Math.log10(Math.max(1,v)))-1);return Math.max(50000,Math.round(v/m)*m);}
|
||||
function rating(){if(!S)return 'BB';const rev=R.revMo||0,pay=(R.cost&&R.cost.loans)||0;let sc=2;
|
||||
if(rev>100000)sc++;if(rev>500000)sc++;if(rev>2000000)sc++;if(R.revMo>R.costMo)sc++;else sc--;if(rev&&(R.revMo-R.costMo)/rev>=0.25)sc++;
|
||||
if(S.cash<0)sc-=2;if(rev&&pay/rev>0.3)sc--;if(rev&&pay/rev>0.6)sc--;sc-=Math.min(3,S.loanStrikes||0);
|
||||
return RATINGS[clamp(sc,0,RATINGS.length-1)];}
|
||||
const rIdx=r=>RATINGS.indexOf(r);
|
||||
function annuity(P,apr,n){const r=apr/12;return r?P*r/(1-Math.pow(1+r,-n)):P/n;}
|
||||
function spawnLoanOffer(emergency){
|
||||
const rt=rating(),keys=Object.keys(BANKS).filter(k=>rIdx(rt)>=rIdx(BANKS[k].min)&&!S.loanOffers.some(o=>o.bank===k)&&!(BANKS[k].equity&&S.loans.some(l=>l.bank===k)));
|
||||
let pool=emergency?keys.filter(k=>['shark','gov','crypto','vult','rev','spk','astro','balloon'].includes(k)):keys.filter(k=>k!=='shark');if(!pool.length)pool=keys;if(!pool.length)return;
|
||||
const k=pick(pool),B=BANKS[k],base=Math.max(60000,R.revMo||0),ra=(a)=>a[0]+Math.random()*(a[1]-a[0]);
|
||||
const amount=niceAmt(base*ra(B.amt)*(emergency?0.6:1)),o={id:uid(),bank:k,amount,exp:S.day+(emergency?10:25),covs:B.covs.slice()};
|
||||
if(B.equity){o.share=+ra(B.share).toFixed(3);}
|
||||
else if(B.model==='transit'){o.model='transit';o.cut=0.3;o.term=Math.round(ra(B.term)/6)*6||6;o.owe=Math.round(amount*1.3);o.apr=0;o.pay=0;}
|
||||
else{o.apr=+(ra(B.apr)+(RATE_PREM[rt]||0)).toFixed(3);o.term=Math.round(ra(B.term)/6)*6||6;o.pay=B.model==='balloon'?0:Math.round(annuity(amount,o.apr,o.term));if(B.model)o.model=B.model;}
|
||||
if(!B.equity&&amount>BIG_LOAN*base)o.share=+Math.min(0.08,0.02+0.01*(amount/base-BIG_LOAN)).toFixed(3);
|
||||
S.loanOffers.push(o);
|
||||
toast(tr('<b>{bank} would like to lend you {amount}.</b>',{bank:esc(B.name),amount:fmt$(amount)})+'<br>'+(emergency?tr('They heard you might be in a spot of bother.'):tr('Terms apply. Several terms.')),emergency?'bad':'goal',[{l:tr('Open bank'),act:'bank',args:{}}]);
|
||||
}
|
||||
function loanTick(d){
|
||||
// conditions: 15-day grace, then a penalty every 30 days while broken
|
||||
for(const l of S.loans){const B=BANKS[l.bank];
|
||||
const broken=l.covs.filter(c=>COVS[c]&&!COVS[c].ok(l));
|
||||
if(d-l.start<15||!broken.length){l.breach=0;continue;}
|
||||
l.breach=(l.breach||0)+1;
|
||||
if(l.breach===1)toast(tr('<b>{bank} is unhappy.</b><br>You broke a loan condition: {cond} Fix it within 10 days or pay a penalty.',{bank:esc(B.name),cond:esc(covLabel(broken[0]))}),'bad',[{l:tr('Open bank'),act:'bank',args:{}}]);
|
||||
if(l.breach===10||(l.breach>10&&(l.breach-10)%30===0)){
|
||||
if(B.equity){l.share=+(l.share+0.02).toFixed(3);toast(tr('<b>{bank} are circling.</b><br>They now take {pct} of your revenue.',{bank:esc(B.name),pct:pct(l.share)}),'bad');}
|
||||
else{const fee=Math.round(l.bal*0.05);l.bal+=fee;l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left)));S.loanStrikes=(S.loanStrikes||0)+1;toast(tr('<b>Penalty from {bank}: {fee}</b><br>Added to what you owe. Your monthly payment is now {pay}.',{bank:esc(B.name),fee:fmt$(fee),pay:fmt$(l.pay)}),'bad');}
|
||||
sfx('err');}}
|
||||
// monthly statement: payments already leave your cash daily as part of costs
|
||||
for(const l of S.loans.slice()){const B0=BANKS[l.bank];if(B0.equity||(d-l.start)%30!==0||d===l.start)continue;
|
||||
if(l.model==='transit')l.bal=Math.max(0,l.bal-Math.round(((R.cost&&R.cost.transit)||0)*(l.cut||0.3)));else l.bal=Math.max(0,l.bal*(1+l.apr/12)-l.pay);l.left--;
|
||||
// A balloon, or what a transit-free network never paid, is due in one go at the end.
|
||||
if(l.left<=0&&l.bal>=1&&(l.model==='balloon'||l.model==='transit')){S.cash-=Math.round(l.bal);toast(tr('<b>{bank}: the balloon popped.</b><br>The remaining {price} was due today, all at once. It has left your account.',{bank:esc(B0.name),price:fmt$(l.bal)}),'bad');sfx('err');l.bal=0;}
|
||||
if(l.left>0&&l.bal>=1){if(l.model==='storm'){l.apr=+((l.apr0||0)+0.02*S.inc.length).toFixed(3);l.pay=Math.round(annuity(l.bal,l.apr,l.left));}
|
||||
else if(l.model==='astro'){const a=+(0.02+Math.random()*0.28).toFixed(3);if(Math.abs(a-l.apr)>=0.08)toast(tr('<b>{bank}: {sign} is in retrograde.</b><br>Your rate is now {apr}%.',{bank:esc(B0.name),sign:tr(pick(STAR_SIGNS)),apr:(a*100).toFixed(1)}),a>l.apr?'bad':'good');l.apr=a;l.pay=Math.round(annuity(l.bal,l.apr,l.left));}}
|
||||
if(l.left<=0||l.bal<1){S.loans=S.loans.filter(x=>x!==l);track('loan_repaid');toast(tr('<b>Loan from {bank} paid off!</b><br>They sent a fruit basket. It is mostly bananas.',{bank:esc(BANKS[l.bank].name)}),'good');sfx('coin');}}
|
||||
// the shark's collectors come by when you are broke
|
||||
if(S.cash<0&&S.loans.some(l=>BANKS[l.bank].shark)&&Math.random()<0.03){const c=pick(Object.keys(S.pops));const p=S.pops[c];p.down=Math.max(p.down||0,d+1);const en=N_('Two very large gentlemen from Loan Shark Telecom Finance unplugged your router in {city} "as a reminder".');addInc({type:'shutdown',ref:c,until:d+1,msg:tr(en,{city:CITY[c].name}),cost:0},en);toast(tr('<b>The loan shark sent a reminder.</b><br>Your POP in {city} is dark until tomorrow.',{city:CITY[c].name}),'bad');sfx('alert');}
|
||||
// offers: now and then, and much more often when you are in trouble
|
||||
S.loanOffers=S.loanOffers.filter(o=>o.exp>d);
|
||||
const broke=S.cash<0;
|
||||
// With half a billion in the vault, loan offers are just noise (#52): banks stop calling, open offers lapse.
|
||||
if(S.cash>=RICH_NO_LOANS){if(S.loanOffers.length||!S.richTold){S.loanOffers=[];if(!S.richTold&&S.mode!=='sandbox'){S.richTold=1;toast(tr('<b>The banks have stopped calling.</b><br>You have more money than most of them. Loan offers come back if your cash ever drops below {cash}.',{cash:fmt$(RICH_NO_LOANS)}),'good');}}return;}
|
||||
if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d>20&&Math.random()<1/40)))spawnLoanOffer(broke);
|
||||
}
|
||||
const RICH_NO_LOANS=5e8;
|
||||
40
src/game/60-features/20-scenarios.js
Normal file
40
src/game/60-features/20-scenarios.js
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
/* Seeded games (scenarios, weekly challenge) draw every random number from S.rng, so the same seed
|
||||
gives the same world. Free play keeps using the browser's Math.random. */
|
||||
const _rand=Math.random;
|
||||
Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();};
|
||||
function isoWeek(dt){const d=new Date(Date.UTC(dt.getFullYear(),dt.getMonth(),dt.getDate()));const n=d.getUTCDay()||7;d.setUTCDate(d.getUTCDate()+4-n);const y0=new Date(Date.UTC(d.getUTCFullYear(),0,1));return {y:d.getUTCFullYear(),w:Math.ceil(((d-y0)/864e5+1)/7)};}
|
||||
const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g;
|
||||
function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)<g)continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
|
||||
function pathExists(a,b){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l))continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
|
||||
// Looked up rather than read from the save, so it follows a language switch mid-scenario.
|
||||
const scnName=()=>S.scn.id==='weekly'?tr('Weekly {key}',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name;
|
||||
const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>l.sub&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size;
|
||||
const brIxN=()=>CITIES.filter(c=>c.br&&S.ixp[c.id]!==undefined).length;
|
||||
const SCN=[
|
||||
{id:'stg',n:tr('Only Spätzle-IX'),city:'stg',cash:400000,days:730,rules:{noTransit:true,local:true},d:tr('Start in Stuttgart, where nobody sells transit. Reach the internet through peering, PNIs, caches and your own fiber only. No transit anywhere, ever.'),goal:tr('Reach 45% of the internet and serve 300 Gbps'),ok:()=>R.reach>=0.45&&R.served>=300},
|
||||
{id:'redsea',n:tr('Red Sea Crisis'),city:'mrs',cash:2500000,days:540,rules:{banCities:['cai','jed'],banPairs:['eig:dxb-mrs','gbi:fuj-mrs','smw4:khi-mrs','smw6:mrs-bom','smw6:mrs-sin','peace:mrs-sin','aae:mrs-hkg','twoaf:mrs-bom','medn:cai-mrs','medn:ist-mrs','twoaf:jnb-mrs','eassy:nbo-mrs']},d:tr('Every cable through the Red Sea is cut, and so is the hop to Egypt. Get Marseille talking to Singapore anyway: round Africa, overland, or the other way round the planet.'),goal:tr('A path from Marseille to Singapore, and 80 Gbps between Asia and the rest of your network for 30 days in a row'),ok:()=>pathExists('mrs','sin')&&(S.stats.asiaRun||0)>=RS_DAYS},
|
||||
{id:'spat',n:tr('The Cogentle Spat'),city:'nyc',cash:700000,days:540,rules:{spat:true},d:tr('Cogentle and Goggle are not speaking, and this time it is permanent. Buy the cheap transit if you dare.'),goal:tr('99% reach and 150 Gbps served'),ok:()=>R.reach>=0.99&&R.served>=150},
|
||||
{id:'carnaval',n:tr('Carnaval'),city:'rio',cash:600000,days:100,rules:{},setup:()=>{S.biz.push({id:uid(),scripted:true,city:'rio',city2:null,reqs:[],name:'Carnaval Parade in Rio de Janeiro',type:'event',bw:400,rate:0,mood:100,since:0,start:90,dur:5,fee:400*5*70});},d:tr('Rio from scratch. Carnaval starts in 90 days and wants 400 Gbps for five days straight. The whole world is watching.'),goal:tr('Deliver Carnaval in full'),ok:()=>(S.stats.evFull||0)>=1},
|
||||
{id:'darien',n:tr('Mind the Gap'),city:'pan',cash:900000,days:730,rules:{},d:tr('Start in Panama City. Nothing crosses the Darién Gap by land, and the Andes are in the way of everything else.'),goal:tr('POPs in Bogotá, Lima, Santiago and São Paulo, and 150 Gbps served'),ok:()=>['bog','lim','scl','sao'].every(c=>S.pops[c])&&R.served>=150},
|
||||
{id:'c2c',n:tr('Cape to Cairo'),city:'cpt',cash:2000000,days:1095,rules:{},d:tr('Cape Town. Build a network across Africa: every border wants its own permit, and half the power grids are not on your side.'),goal:tr('A path from Cape Town to Cairo, POPs in Lagos and Nairobi, and 150 Gbps served'),ok:()=>pathExists('cpt','cai')&&S.pops.lag&&S.pops.nbo&&R.served>=150},
|
||||
{id:'ixbr',n:tr('Order and Progress'),city:'sao',cash:2500000,days:1095,rules:{},d:tr('São Paulo. Brazil is a continent: forty IX.brrr exchanges, thousands of provedores, and the Amazon between you and the north.'),goal:tr('Ports on 20 IX.brrr exchanges, one of them in Manaus, and 200 Gbps served'),ok:()=>brIxN()>=20&&S.ixp.mao!==undefined&&R.served>=200},
|
||||
{id:'gangnam',n:tr('Gangnam Style Peering'),city:'icn',cash:900000,days:365,rules:{},d:tr('Seoul. The fastest, hungriest eyeballs on Earth, transit at four times the price, and three incumbents who bill you for every gigabit you send them.'),goal:tr('99% reach and 200 Gbps served without going broke'),ok:()=>R.reach>=0.99&&R.served>=200},
|
||||
{id:'flood',n:tr('Flood Season'),city:'ams',cash:2000000,days:365,rules:{ddos:true},setup:()=>{S.lvl=Math.max(S.lvl||1,3);},d:tr('Amsterdam, hosting capital of Europe, in peak botnet season. Every smart toaster, baby monitor and unpatched fridge on Earth has picked a side, and it is not yours. A flood every few days, more and more of them in the terabits, while everything else keeps breaking too. You start with bigger gear unlocked, and you will need it.'),goal:tr('Hold 20 floods, 5 of them over 1 Tbps, keeping the city under attack at 97% or better'),ok:()=>(S.stats.ddosOk||0)>=20&&(S.stats.ddosOkBig||0)>=5},
|
||||
{id:'fttb',n:tr('Fibre to the Basement'),city:'syd',cash:1500000,days:730,rules:{levy:true},d:tr('Sydney, 2013. The Toilet Paper Group ran its own fibre into apartment basements, and the national network cried cherry-picking. Your turn: skip the Nearly Broadband Network, pay the levy, and get there first.'),goal:tr('Broadband in Sydney, Melbourne, Brisbane, Adelaide and Perth, and two different cables overseas'),ok:()=>AU_BB.every(c=>S.pops[c]&&S.pops[c].bb)&&auExits()>=2},
|
||||
{id:'baltic',n:tr('Anchors Away'),city:'tll',cash:500000,days:540,rules:{anchors:3},d:tr('Tallinn. Ships drag their anchors over Baltic cables three times as often as usual.'),goal:tr('90 days in a row with 99.5% of demand served'),ok:()=>(S.stats.clean||0)>=90},
|
||||
{id:'pac',n:tr('Stepping Stones'),city:'hnl',cash:3000000,days:1095,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('Honolulu, in the middle of the Pacific. The cables between the Americas, Asia and Australia are so long that a wave on them carries only 400G or 800G. Stop the light on an island, start it fresh, and every hop gets shorter and faster. You start with 1.6T gear unlocked.'),goal:tr('A path from Los Angeles to Sydney with 1.6T on every hop, a path from Los Angeles to Tokyo, and 150 Gbps served'),ok:()=>fastPath('lax','syd',1600)&&pathExists('lax','tok')&&R.served>=150},
|
||||
{id:'atl',n:tr('Mid-Atlantic Accent'),city:'pdl',cash:3000000,days:1095,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('Ponta Delgada, in the Azores, halfway across the Atlantic. Florida to Spain and Lisbon to Lagos are just too long for a 1.6T wave: straight across, each carries 1.2T. Land on the islands in between, start the light fresh, and every hop runs at 1.6T or better. You start with 1.6T gear unlocked.'),goal:tr('1.6T on every hop from Miami to Madrid and from Lisbon to Lagos, and 100 Gbps served'),ok:()=>fastPath('mia','mad',1600)&&fastPath('lis','lag',1600)&&R.served>=100},
|
||||
];
|
||||
const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','scl','hkg'];
|
||||
const WEEK_MODS=[{id:'pricey',n:tr('Transit costs 30% more')},{id:'chaos',n:tr('Twice the failures')},{id:'poor',n:tr('Start with only $100k')},{id:'boom',n:tr('Eyeballs grow 50% faster')},{id:'dk',n:tr('Every IX is run by DE-KICKS')},{id:'sharks',n:tr('Shark season: subsea cuts twice as likely')}];
|
||||
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';
|
||||
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;S.nextFail=1e9;S.nextEvent=1e9;}
|
||||
if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('Weekly challenge {key}',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000);
|
||||
if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup();
|
||||
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}
|
||||
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
|
||||
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('Serve as much traffic as you can in one year.')} ${tr('You have {n} days.',{n:S.scn.days})}`:S.mode==='sandbox'?tr('<b>Sandbox mode</b><br>A billion dollars, every unlock, and nothing ever breaks. Build the internet you always wanted.'):tr('<b>Welcome, {name}!</b><br>The RIPE NCC assigned you AS{asn}. Your first router is humming in {city}.',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal');
|
||||
renderAll();save();if(!S.scn&&S.mode!=='sandbox')tutorialStart();}
|
||||
15
src/game/60-features/30-conferences.js
Normal file
15
src/game/60-features/30-conferences.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
/* ---------- conference season ---------- */
|
||||
const CONFS=[{n:'NANOG',c:'chi',m:1},{n:'APRICOT',c:'sin',m:1},{n:'Peering Days',c:'waw',m:2},{n:'DKNOG',c:'cph',m:2,j:N_('The hallway track moved to a bar by the harbour, where the woman behind the bar kept pouring aquavit long past midnight and asked nobody about their AS path. Back at the hotel bar, someone said “just one more drink”. Your BGP sessions stayed up all night. So did you.')},{n:'UKNOF',c:'lon',m:3},{n:'MENOG',c:'dxb',m:3},{n:'NZNOG',c:'akl',m:3},{n:'RIPE',c:'ams',m:4},{n:'NANOG',c:'sea',m:5},{n:'IX Forum',c:'tok',m:6},{n:'AfPIF',c:'nbo',m:7},{n:'AusNOG',c:'syd',m:8},{n:'NLNOG Day',c:'ams',m:8},{n:'LACNOG',c:'sao',m:9},{n:'NANOG',c:'ash',m:9},{n:'DENOG',c:'fra',m:10},{n:'RIPE',c:'ber',m:10},{n:'PTT Forum',c:'sao',m:11},{n:'PacNOG',c:'suv',m:11}];
|
||||
const CONF_COST=8000,CONF_DAYS=45;
|
||||
const confDay=(cf,y)=>y*360+cf.m*30+9;
|
||||
function confKey(cf,y){return cf.n+'@'+cf.c+'@'+y;}
|
||||
function upcomingConfs(within){const y0=Math.floor(S.day/360),out=[];for(const y of [y0,y0+1])for(const cf of CONFS){const d=confDay(cf,y);if(d>=S.day&&d-S.day<=within)out.push({...cf,day:d,key:confKey(cf,y)});}return out.sort((a,b)=>a.day-b.day);}
|
||||
function confBoost(id){const cb=S.conf;if(!cb||!(cb.until>S.day))return 1;const n=NET[id];return n&&n.pops.some(c=>CITY[c]&&CITY[c].reg===cb.reg)?0.5:1;}
|
||||
function confTick(d){S.confReg=S.confReg||{};
|
||||
for(const cf of upcomingConfs(30)){if(cf.day-d===30&&!S.confReg[cf.key])toast(tr('<b>{conf} comes to {city} in 30 days.</b><br>Peering coordinators, hallway track, free stickers. Register in the Deals tab.',{conf:esc(cf.n),city:esc(CITY[cf.c].name)}),'goal',[{l:tr('Show me'),act:'leftTab',args:{t:'deals'}}]);}
|
||||
for(const cf of upcomingConfs(0)){if(cf.day!==d||!S.confReg[cf.key])continue;const reg=CITY[cf.c].reg;S.conf={until:d+CONF_DAYS,reg,name:cf.n};S.stats.confs=(S.stats.confs||0)+1;
|
||||
const r=Math.random();let extra='';if(r<0.3){const cash=5000+Math.floor(Math.random()*4)*5000;S.cash+=cash;extra=' '+tr('You also won the raffle: {cash} worth of optics, sold on eBuy the same evening.',{cash:fmt$(cash)});}else if(r<0.5)extra=' '+tr('Someone from Goggle bought you a beer. You did not get their name, only a sticker.');if(cf.j)extra=' '+tr(cf.j)+(r<0.3?extra:'');
|
||||
toast(tr('<b>{conf} in {city}</b><br>You shook a lot of hands. For {n} days, selective networks with a presence in {region} want half the usual traffic before they peer.',{conf:esc(cf.n),city:esc(CITY[cf.c].name),n:CONF_DAYS,region:esc(REG[reg])})+extra,'goal');sfx('coin');}}
|
||||
function confSection(){const up=upcomingConfs(75).slice(0,3),cb=S.conf&&S.conf.until>S.day?S.conf:null;if(!up.length&&!cb)return '';
|
||||
return `<h3 style="font-size:15px;margin:10px 0 4px">${tr('Conferences')}</h3>${cb?`<div class="inc" style="background:#EAF7EE"><div class="nm">${tr('{name} glow: {n} days left',{name:esc(cb.name),n:cb.until-S.day})}</div><div class="meta">${tr('Selective networks in {region} need half the usual traffic to peer. Now is the time to ask for that PNI.',{region:esc(REG[cb.reg])})}</div></div>`:''}${up.map(cf=>{const reg=S.confReg&&S.confReg[cf.key];return `<div class="row"><div class="grow"><div class="nm">${esc(cf.n)} · ${esc(CITY[cf.c].name)}</div><div class="meta">${cf.day===S.day?tr('Today'):tr('in {n} days',{n:cf.day-S.day})} · ${esc(REG[CITY[cf.c].reg])}</div></div>${reg?'<span class="tag st on">'+tr('Registered')+'</span>':cf.day<=S.day?'<span class="tag st">'+tr('Registration closed')+'</span>':btn(tr('Attend <small>{cost}</small>',{cost:fmt$(CONF_COST)}),'confGo',{key:cf.key},'sm',S.cash<CONF_COST)}</div>`;}).join('')}`;}
|
||||
|
||||
16
src/game/60-features/40-tutorial.js
Normal file
16
src/game/60-features/40-tutorial.js
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
/* ---------- guided first game ---------- */
|
||||
const TUT=[
|
||||
{t:tr('Your router is live. Press “Launch broadband” to sell internet to the people of your city.'),sel:'[data-act="launchBB"]',ok:()=>S.pops[S.home]&&S.pops[S.home].bb},
|
||||
{t:tr('Your customers want the whole internet. Open the Transit tab and buy a port from a carrier.'),sel:'[data-act="tab"][data-args*=\'"up"\'],[data-act="buyTransit"]',ok:()=>S.transit.length>0,skip:()=>!NETS.some(n=>sellsAt(n,S.home))},
|
||||
{t:tr('Transit costs money per gigabit. Peering is free: open the Peering tab, buy an IX port, then join the route server.'),sel:'[data-act="tab"][data-args*=\'"peer"\'],[data-act="buyIx"],[data-act="rs"]',ok:()=>Object.keys(S.rs).length>0,skip:()=>!ixName(S.home)},
|
||||
{t:tr('Start the clock with 1× and watch traffic and money flow. You can pause any time.'),sel:'#sp1',ok:()=>S.day>=5},
|
||||
{t:tr('Grow: drag from your pink router onto a nearby city to lay fiber and open a second POP.'),sel:null,ok:()=>S.links.length>0},
|
||||
{t:tr('Businesses pop up as $ bubbles on the map. Open Deals and sign your first customer.'),sel:'[data-act="leftTab"][data-args*=\'"deals"\']',ok:()=>S.biz.length>0},
|
||||
];
|
||||
function tutorialStart(){let done=false;try{done=!!localStorage.getItem('sot-tut');}catch(e){}if(done||window.__TUBES_TEST__&&!window.__TUBES_TUT__)return;S.tut=0;renderCoach();}
|
||||
function renderCoach(){const el=$('coach');if(!el)return;document.querySelectorAll('.coach-glow').forEach(x=>x.classList.remove('coach-glow'));
|
||||
if(!S||S.tut===undefined||S.tut===null||S.lost){el.hidden=true;return;}
|
||||
while(S.tut<TUT.length){const st=TUT[S.tut];let ok=false;try{ok=st.ok()||(st.skip&&st.skip());}catch(e){}if(!ok)break;S.tut++;}
|
||||
if(S.tut>=TUT.length){S.tut=null;el.hidden=true;try{localStorage.setItem('sot-tut','1');}catch(e){}toast(tr('<b>You know the basics.</b><br>The goals on the left take it from here. Things will break. That is the fun part.'),'goal');return;}
|
||||
const st=TUT[S.tut];el.innerHTML=`<div class="ct"><span class="cs">${tr('Step {n} of {total}',{n:S.tut+1,total:TUT.length})}</span>${esc(st.t)}</div>${btn(tr('Skip tutorial'),'tutSkip',{},'ghost sm')}`;el.hidden=false;
|
||||
if(st.sel){const t=document.querySelector(st.sel);if(t)t.classList.add('coach-glow');}}
|
||||
43
src/game/60-features/50-traceroute.js
Normal file
43
src/game/60-features/50-traceroute.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/* ---------- traceroute and looking glass ---------- */
|
||||
const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x';
|
||||
function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
|
||||
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=(l.km+60)*MET[l.metric||'normal'].f;(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);}
|
||||
const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
|
||||
const path=dst=>{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};}
|
||||
function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[];
|
||||
for(const x of S.caches)if(x.net===net&&popUp(x.city)&&!siteDown(x.city,'a'))out.push({k:'c',rank:0,city:x.city,pref:'normal',lab:tr('{name} cache',{name:NET[net].cache.name}),used:R.useCache[x.id]||0,cap:CACHE_CAP});
|
||||
for(const p of S.pni)if(p.net===net&&pniOn(p)&&popUp(p.city)&&liveN(p.city,p.site,p.n))out.push({k:'p',rank:1,city:p.city,pref:p.pref||'normal',lab:tr('PNI with {net}',{net:NET[net].name}),used:R.usePni[p.id]||0,cap:liveCap(pniG(p),p.city,p.site,p.n)});
|
||||
for(const c in S.ixp)if(ixSessions(c).has(net)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:2,city:ixCity(c),id:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('{ix} peering',{ix:ixName(c)}),used:R.useIx[c]||0,cap:ixCap(c)});
|
||||
for(const t of S.transit)if(popUp(t.city)&&!(t.down>day)&&liveN(t.city,t.site,t.n)&&net!==leak&&!((ev.depeer>day||scnRule('spat'))&&t.net==='cog'&&net==='ggl'))out.push({k:'t',rank:3,city:t.city,pref:t.pref||'normal',lab:tr('{name} transit',{name:NET[t.net].name}),tnet:t.net,used:R.useT[t.id]||0,cap:liveCap(PORT[t.tier].g,t.city,t.site,t.n)});
|
||||
return out;}
|
||||
function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1;
|
||||
const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);};
|
||||
hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,tr('{city}, your router',{city:CITY[src].name}));
|
||||
const walk=path=>{for(const h of path){const l=h.l,lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('own dark fiber'):l.kind==='vxc'?tr('fabric circuit'):l.cable?CAB[l.cable].name:tr('terrestrial wave')} · ${capName(l)}`);}};
|
||||
if(to.city){const path=P.path(to.city);lines.unshift(`traceroute to ${to.city}.${me} (${CITY[to.city].name}), 30 hops max`);if(!path){lines.push(' 2 * * * ← '+tr('no working path between these POPs'));return {text:lines.join('\n'),why:tr('No path: every route between these cities is down or missing.')};}walk(path);return {text:lines.join('\n'),why:S.te&&S.te.on?trn('Internal path over {n} link, chosen by distance and link metrics. Auto-TE may move overflow elsewhere when this is full.','Internal path over {n} links, chosen by distance and link metrics. Auto-TE may move overflow elsewhere when this is full.',path.length):trn('Internal path over {n} link, chosen by distance and link metrics.','Internal path over {n} links, chosen by distance and link metrics.',path.length)};}
|
||||
const N=NET[to.net],ex=trExits(to.net).filter(e=>P.dist[e.city]!==undefined);
|
||||
lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`);
|
||||
if(!ex.length){lines.push(' 2 * * *\n 3 * * * ← '+tr('!N network unreachable'));return {text:lines.join('\n'),why:tr('Nothing on your network reaches {net}: no transit, IX session, PNI or cache with a working path from {city}.',{net:N.name,city:CITY[src].name}),asPath:null};}
|
||||
ex.sort((a,b)=>(a.pref==='low'?4:a.rank)-(b.pref==='low'?4:b.rank)||(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||P.dist[a.city]-P.dist[b.city]);
|
||||
const e=ex.find(x=>x.used<x.cap*0.999)||ex[0];walk(P.path(e.city));
|
||||
let asPath=[S.asn];
|
||||
if(e.k==='t'){const T=NET[e.tnet];asPath.push(T.asn);hop(`be-${S.asn}.${e.city}.${slug(T.name)}.net`,`203.0.113.${hstr(e.city)%250}`,0.4,tr('hand-off to {net}',{net:T.name}));
|
||||
if(T.id!==N.id){const far=(N.pops&&N.pops.length?N.pops:[e.city]).reduce((a,c)=>kmBetween(e.city,c)<kmBetween(e.city,a)?c:a,(N.pops||[e.city])[0]);const km=CITY[far]?kmBetween(e.city,far):0;
|
||||
hop(`ae-2.core.${far}.${slug(T.name)}.net`,`203.0.113.${(hstr(far)+7)%250}`,km*1.3/100+0.3,CITY[far]?tr('{net} carries it to {city}',{net:T.name,city:CITY[far].name}):'');
|
||||
hop(`${slug(N.name)}-peer.${far}.${slug(T.name)}.net`,`198.51.100.${hstr(N.id)%250}`,0.4,tr('{net} hands it to {to}',{net:T.name,to:N.name}));}}
|
||||
else if(e.k==='ix'){hop(`${slug(ixName(e.city))}.peering.${e.city}`,`185.0.${hstr(e.city)%250}.${hstr(N.id)%250}`,0.3,tr('across the {ix} switch',{ix:ixName(e.city)}));}
|
||||
else if(e.k==='p'){hop(`pni-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,tr('private cross-connect'));}
|
||||
else{hop(`cache-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),4),0.1,tr('embedded cache in your rack'));}
|
||||
asPath.push(N.asn);if(e.k!=='c')hop(`www.${slug(N.name)}.example`,`198.51.100.${(hstr(N.id)+1)%250}`,0.5+(e.k==='t'?1:0.2),`${N.name}`);
|
||||
const order={c:tr('caches beat PNIs'),p:tr('PNIs beat IX peering'),ix:tr('IX peering beats transit'),t:tr('transit is the last resort')}[e.k];
|
||||
const cn=cnCity(src)!==!!N.cn?' '+tr('Crossing the Great Firewall here loses about {p}% of packets.',{p:S.ev.gfw>S.day?35:20}):'';
|
||||
return {text:lines.join('\n'),why:`${tr('Exit: {exit} in {city}.',{exit:e.lab,city:CITY[e.city].name})} ${tr('{rule}, and closer exits win ties',{rule:order[0].toUpperCase()+order.slice(1)})}${e.pref!=='normal'?tr('; this one is set to {mode}',{mode:e.pref==='high'?tr('Prefer'):tr('Backup only')}):''}.${e.used>=e.cap*0.999?' '+tr('It is full, so some traffic overflows to the next exit.'):''}${cn}`,asPath};}
|
||||
function traceModal(src,to){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0];
|
||||
const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t;
|
||||
const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)}):traceroute(src,{city:t.slice(5)});
|
||||
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('Looking glass')}</div><h2 style="font-size:26px">${tr('Traceroute')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('Close')}">×</button></div>
|
||||
<div class="trsel"><label>${tr('From')} <select id="trFrom">${pops.map(c=>`<option value="${c}"${c===src?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label>
|
||||
<label>${tr('To')} <select id="trTo"><optgroup label="${tr('Networks')}">${nets.map(n=>`<option value="net:${n.id}"${t==='net:'+n.id?' selected':''}>${esc(n.name)} (AS${n.asn})</option>`).join('')}</optgroup><optgroup label="${tr('Your POPs')}">${pops.filter(c=>c!==src).map(c=>`<option value="city:${c}"${t==='city:'+c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</optgroup></select></label>${btn(tr('Run'),'traceRun',{},'pink sm')}</div>
|
||||
<pre class="term">${esc(r.text)}</pre>${r.asPath?`<p class="meta">${tr('<b>AS path:</b> {path}',{path:r.asPath.map(a=>'AS'+a).join(' → ')})}</p>`:''}<p class="note">${esc(r.why)}</p>
|
||||
<div class="btns">${btn(tr('Copy'),'traceCopy',{},'ghost sm')}</div>`);UI.trText=r.text;}
|
||||
|
||||
27
src/game/60-features/60-share-card.js
Normal file
27
src/game/60-features/60-share-card.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
/* ---------- share card ---------- */
|
||||
// Straight link segments in map coordinates for flat maps. A link across the date line leaves one edge
|
||||
// and comes back in at the other, so it becomes two segments, one per edge (#42).
|
||||
function linkSegs(){const out=[];for(const l of S.links){const A=CITY[l.a],B=CITY[l.b];if(!A||!B)continue;const d=Math.abs(B.x-A.x)>W/2?(B.x<A.x?W:-W):0;
|
||||
for(const o of d?[0,-d]:[0])out.push([A.x+o,A.y,B.x+d+o,B.y]);}return out;}
|
||||
function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas');cv.width=Wc;cv.height=Hc;const g=cv.getContext&&cv.getContext('2d');if(!g)return null;
|
||||
g.fillStyle='#57C4E5';g.fillRect(0,0,Wc,Hc);
|
||||
// mini map
|
||||
const mx=40,my=150,mw=700,mh=350,sx=mw/W,sy=mh/H;g.save();g.beginPath();g.rect(mx,my,mw,mh);g.clip();g.fillStyle='#3AA6CF';g.fillRect(mx,my,mw,mh);
|
||||
g.fillStyle='#9BDA6C';g.strokeStyle='#1E2640';g.lineWidth=1.5;for(const pts of COAST){g.beginPath();pts.forEach((q,i)=>i?g.lineTo(mx+q[0]*sx,my+q[1]*sy):g.moveTo(mx+q[0]*sx,my+q[1]*sy));g.closePath();g.fill();g.stroke();}
|
||||
g.strokeStyle='#FF4F9A';g.lineWidth=2.5;for(const [x1,y1,x2,y2] of linkSegs()){g.beginPath();g.moveTo(mx+x1*sx,my+y1*sy);g.lineTo(mx+x2*sx,my+y2*sy);g.stroke();}
|
||||
for(const c in S.pops){const C=CITY[c];g.fillStyle='#FF4F9A';g.strokeStyle='#1E2640';g.lineWidth=2;g.beginPath();g.arc(mx+C.x*sx,my+C.y*sy,5,0,7);g.fill();g.stroke();}
|
||||
g.restore();g.strokeStyle='#1E2640';g.lineWidth=5;g.strokeRect(mx,my,mw,mh);
|
||||
// header
|
||||
g.fillStyle='#1E2640';g.font='900 54px "Baloo 2", sans-serif';g.textBaseline='top';g.fillText(S.name,40,28);
|
||||
g.font='800 26px Nunito, sans-serif';g.fillText(`AS${S.asn} · ${tierLabel()} · ${dateStr(S.day)}${S.mode==='sandbox'?' · '+tr('Sandbox'):''}`,42,92);
|
||||
// stats
|
||||
const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]).slice(0,8);
|
||||
const rows=[[tr('Peak traffic'),fmtG(S.stats.peak||0)],[tr('Peered'),pct(R.peerShare||0)],[tr('POPs'),tr('{n} in {r} regions',{n:Object.keys(S.pops).length,r:regionsCount()})],[tr('Links'),String(S.links.length)],[tr('Customers'),String(S.biz.length)],[tr('Incidents survived'),String(S.stats.survived||0)],[tr('Shark bites'),String(S.stats.sharks||0)],[tr('Badges'),`${got.length}/${BADGES.length}`]];
|
||||
if(S.scn)rows.unshift([scnName(),S.scn.done?(S.scn.id==='weekly'?tr('score {v}',{v:fmtG(S.scn.score||S.stats.peak||0)}):tr('done in {d} days',{d:S.scn.done})):S.scn.failed?tr('not this time'):tr('in progress')]);
|
||||
let y=150;for(const [k,v] of rows.slice(0,9)){g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=3;g.beginPath();g.roundRect?g.roundRect(770,y,390,42,12):g.rect(770,y,390,42);g.fill();g.stroke();g.fillStyle='#5A6280';g.font='800 18px Nunito, sans-serif';g.fillText(k,786,y+11);g.fillStyle='#1E2640';g.font='900 22px Nunito, sans-serif';const tw=g.measureText(v).width;g.fillText(v,1146-tw,y+9);y+=48;}
|
||||
g.font='34px sans-serif';top.forEach((b,i)=>g.fillText(b.i,40+i*48,520));
|
||||
g.fillStyle='#1E2640';g.font='900 30px "Baloo 2", sans-serif';g.fillText('seriesoftub.es',40,572);g.font='700 20px Nunito, sans-serif';g.fillText(tr('Build the internet, one tube at a time'),300,580);
|
||||
return cv;}
|
||||
function shareModal(){const cv=shareCanvas();if(!cv){toast(tr('<b>Your browser cannot draw the card.</b>'),'bad');return;}let url='';try{url=cv.toDataURL('image/png');}catch(e){}
|
||||
UI.shareCv=cv;openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('Share')}</div><h2 style="font-size:26px">${tr('Your network card')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('Close')}">×</button></div>${url?`<img src="${url}" alt="${tr('Stats card for {name}',{name:esc(S.name)})}" style="width:100%;border:3px solid var(--ink);border-radius:12px;margin-top:8px">`:''}<div class="btns" style="margin-top:10px">${navigator.share?btn(tr('Share…'),'shareGo',{},'pink'):''}${btn(tr('Download PNG'),'shareDl',{},navigator.share?'':'pink')}</div><p class="note">${tr('Post it wherever your peering friends hang out.')}</p>`);track('share_open');}
|
||||
function shareFile(cb){const cv=UI.shareCv;if(!cv||!cv.toBlob){cb(null);return;}cv.toBlob(b=>cb(b?new File([b],`series-of-tubes-${slug(S.name)}.png`,{type:'image/png'}):null),'image/png');}
|
||||
12
src/game/60-features/70-scenario-progress.js
Normal file
12
src/game/60-features/70-scenario-progress.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)return;
|
||||
if(sc.id==='weekly'){if(d>=sc.days){sc.done=d;const score=Math.round(S.stats.peak||0);sc.score=score;let best=null;try{const wk=JSON.parse(localStorage.getItem('sot-weekly')||'{}');best=wk[sc.key];if(!best||score>best){wk[sc.key]=score;localStorage.setItem('sot-weekly',JSON.stringify(wk));}}catch(e){}
|
||||
const h=scnHof();h.weekly=h.weekly||{d:new Date().toISOString().slice(0,10)};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){}
|
||||
openModal(`<div class="eyebrow">${tr('Weekly challenge {key}',{key:esc(sc.key)})}</div><h2 style="font-size:30px">${tr('Your score: {score}',{score:fmtG(score)})}</h2><p class="tagline">${best&&best>score?tr('Peak traffic served in one year. Your best this week is {best}.',{best:fmtG(best)}):best?tr('Peak traffic served in one year. A new personal best for this week!.'):tr('Peak traffic served in one year.')}</p><div class="btns">${btn(tr('Share my result'),'share',{},'pink big')}${btn(tr('Keep playing'),'closeModal',{},'ghost big')}</div>`);track('weekly_done');}return;}
|
||||
const def=SCN.find(x=>x.id===sc.id);if(!def)return;let ok=false;try{ok=def.ok();}catch(e){}
|
||||
if(ok){sc.done=d;const h=scnHof();if(!h[sc.id]||h[sc.id].days>d)h[sc.id]={d:new Date().toISOString().slice(0,10),days:d};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){}track('scenario_'+sc.id);
|
||||
openModal(`<div class="eyebrow">${tr('Scenario complete')}</div><h2 style="font-size:30px">${tr('{name}: done in {d} days',{name:esc(def.n),d})}</h2><p class="tagline">${esc(def.goal)}. ${d<def.days/2?tr('With time to spare.'):tr('Just in time.')}</p><div class="btns">${btn(tr('Share my result'),'share',{},'pink big')}${btn(tr('Keep playing'),'closeModal',{},'ghost big')}${btn(tr('More scenarios'),'scenarios',{},'ghost')}</div>`);sfx('coin');}
|
||||
else if(d>=def.days){sc.failed=d;openModal(`<div class="eyebrow">${tr('Scenario over')}</div><h2 style="font-size:30px">${tr("Time's up")}</h2><p class="tagline">${tr('{goal} was not reached in {d} days. Keep playing this network as free play, or try again.',{goal:esc(def.goal),d:def.days})}</p><div class="btns">${btn(tr('Try again'),'startScn',{id:def.id},'pink big')}${btn(tr('Keep playing'),'closeModal',{},'ghost big')}</div>`);}}
|
||||
function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){}
|
||||
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('Scenarios')}</div><h2 style="font-size:28px">${tr('Pick a challenge')}</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="${tr('Close')}">×</button></div>
|
||||
<div class="scn wk"><div class="grow"><div class="nm">${tr('Weekly challenge {key}',{key:esc(wk.key)})}</div><div class="meta">${tr('Start in {city} · {mods} · one year, score = peak traffic. The same world for everyone this week.',{city:esc(CITY[wk.city].name),mods:wk.mods.map(m=>esc(m.n)).join(' · ')})}${best?' '+tr('Your best: {best}.',{best:fmtG(best)}):''}</div></div>${btn(tr('Play'),'startWeekly',{},'pink')}</div>
|
||||
${SCN.map(x=>`<div class="scn"><div class="grow"><div class="nm">${esc(x.n)} ${h[x.id]?`<span class="tag open">${tr('done in {d} days',{d:h[x.id].days})}</span>`:''}</div><div class="meta">${esc(x.d)}</div><div class="meta">${tr('<b>Goal:</b> {goal} · <b>Time:</b> {d} days · start in {city}',{goal:esc(x.goal),d:x.days,city:esc(CITY[x.city].name)})}</div></div>${btn(tr('Play'),'startScn',{id:x.id},'')}</div>`).join('')}`);}
|
||||
6
src/game/60-features/80-new-game.js
Normal file
6
src/game/60-features/80-new-game.js
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
function newGame(name,home){
|
||||
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
|
||||
ltv:2,t1v:2,auV:1,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},
|
||||
done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}};
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue