Merge Puzzles, Tier 1 by customer cone and badge variants into v2

This commit is contained in:
Frederic Jung 2026-10-28 18:14:56 +01:00
commit 946da17c8b
No known key found for this signature in database
47 changed files with 1777 additions and 84 deletions

View file

@ -0,0 +1,137 @@
// Badge variants by ruleset preset (2.0): On-call earns the standard badge, Change Freeze a frosted one and BGP at
// 3 a.m. a fiery one; Sandbox and puzzles earn none. A harder preset upgrades a badge you already have.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// The preset is read from S.rules.preset until the ruleset feature lands with rulePreset().
const start = (ev, preset) => {
ev("localStorage.removeItem('sot-badges');ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
if (preset) ev(`S.rules={preset:'${preset}'}`);
ev("S.ach={};S.achP={};compute()");
};
const earnHello = (ev) => ev("S.pni.push({id:'x',net:'nfx',city:'fra',tier:0});compute();checkBadges()");
const hof = (ev) => JSON.parse(ev("localStorage.getItem('sot-badges')||'{}'"));
test('every save without a preset plays On-call and earns the standard badge', () => {
const { ev, errors } = load();
start(ev);
assert.equal(ev('badgeVar()'), 'oncall');
earnHello(ev);
assert.ok(ev('S.ach.hello!==undefined'));
assert.equal(ev('S.achP.hello'), 'oncall');
assert.deepEqual(hof(ev).hello.vs && Object.keys(hof(ev).hello.vs), ['oncall']);
assert.equal(hof(ev).hello.v, 'oncall');
assert.deepEqual(errors, []);
});
test('Change Freeze earns frosted badges and BGP at 3 a.m. fiery ones, shown in the toast and the list', () => {
for (const [p, name, cls] of [['freeze', /Freeze-dried/, 'v-freeze'], ['bgp', /Forged at 3 a\.m\./, 'v-bgp']]) {
const { ev, dom, errors } = load();
start(ev, p);
ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}");
earnHello(ev);
assert.equal(ev('S.achP.hello'), p);
assert.match(ev("window.__t.join(' ')"), name, `${p}: the toast names the variant`);
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
const card = dom.window.document.querySelector(`#leftBody .bdg.on.${cls}`);
assert.ok(card, `${p}: the badge list shows the variant`);
assert.match(card.textContent, name);
assert.equal(hof(ev).hello.v, p, 'remembered on this device');
assert.deepEqual(errors, []);
}
});
test('Sandbox and puzzles earn no badges', () => {
for (const p of ['sandbox', 'puzzle']) {
const { ev, errors } = load();
start(ev, p);
earnHello(ev);
assert.equal(ev('badgeVar()'), null);
assert.equal(ev('Object.keys(S.ach).length'), 0, p);
assert.deepEqual(errors, []);
}
const { ev, errors } = load();
start(ev);
ev("S.mode='sandbox'");
earnHello(ev);
assert.equal(ev('Object.keys(S.ach).length'), 0, 'the old sandbox mode too');
assert.deepEqual(errors, []);
});
test('a harder preset upgrades a badge, an easier one never downgrades it', () => {
const { ev, errors } = load();
start(ev, 'freeze');
earnHello(ev);
const day = ev('S.ach.hello');
ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}");
ev("S.rules.preset='oncall';checkBadges()");
assert.equal(ev('S.achP.hello'), 'oncall', 'On-call beats Change Freeze');
assert.match(ev("window.__t.join(' ')"), /Badge upgraded/);
ev("S.day+=10;S.rules.preset='bgp';checkBadges()");
assert.equal(ev('S.achP.hello'), 'bgp');
assert.equal(ev('S.ach.hello'), day, 'the day it was first earned stays');
ev("window.__t=[];S.rules.preset='freeze';checkBadges()");
assert.equal(ev('S.achP.hello'), 'bgp', 'never downgraded');
assert.equal(ev("window.__t.length"), 0, 'and no toast');
const h = hof(ev).hello;
assert.deepEqual(Object.keys(h.vs).sort(), ['bgp', 'freeze', 'oncall'], 'the collection holds every variant earned');
assert.equal(h.v, 'bgp', 'the shelf shows the best one');
assert.deepEqual(errors, []);
});
test('the collection counts badges per variant on this device, and fits a phone', () => {
const { ev, dom, errors } = load();
ev('window.innerWidth=360');
start(ev, 'bgp');
earnHello(ev);
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
const shelf = dom.window.document.querySelector('#leftBody .bshelf');
assert.ok(shelf);
const total = ev('BADGES.length');
assert.match(shelf.textContent, new RegExp(`Forged at 3 a\\.m\\. 1/${total}`));
assert.match(shelf.textContent, new RegExp(`Freeze-dried 0/${total}`));
assert.ok(dom.window.document.querySelector('#leftBody .bsh.v-bgp.cur'), 'the variant this game earns is marked');
assert.match(dom.window.document.getElementById('leftBody').textContent, /forged in fire/);
assert.deepEqual(JSON.parse(ev('JSON.stringify(badgeShelf(hof()))')), { freeze: 0, oncall: 0, bgp: 1 });
assert.deepEqual(errors, []);
});
test('old saves and old halls of fame keep loading, as standard badges', () => {
const { ev, errors } = load();
start(ev);
// a 1.x save: S.ach holds days, no S.achP; a 1.x hall of fame: {d, n} per badge
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2025-01-02',n:'Old'},t1:{d:'2025-03-04',n:'Old'},junk:5}))");
ev("const o=JSON.parse(JSON.stringify(S));o.ach={hello:12,t1:'400'};delete o.achP;S=migrate(o)");
assert.equal(ev('S.achP.hello'), 'oncall');
assert.equal(ev('S.ach.t1'), 400, 'days are numbers');
assert.deepEqual(JSON.parse(ev("JSON.stringify(Object.keys(S.achP).sort())")), ['hello', 't1']);
const h = JSON.parse(ev('JSON.stringify(hof())'));
assert.equal(h.hello.v, 'oncall');
assert.equal(h.hello.vs.oncall, '2025-01-02');
assert.equal(h.junk, undefined, 'broken entries are dropped');
// a hand-edited variant is not trusted
ev("const o=JSON.parse(JSON.stringify(S));o.achP={hello:'lava',t1:'bgp'};S=migrate(o)");
assert.equal(ev('S.achP.hello'), 'oncall');
assert.equal(ev('S.achP.t1'), 'bgp');
ev("localStorage.setItem('sot-badges','[1,2]')");
assert.equal(ev('JSON.stringify(hof())'), '{}');
ev("UI.left='goals';UI.leftOpen=true;renderLeft()");
// new games start with an empty variant map
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
assert.equal(ev('JSON.stringify(S.achP)'), '{}');
assert.deepEqual(errors, []);
});
test('the share card rings the variant badges', () => {
const { ev, errors } = load();
start(ev, 'bgp');
earnHello(ev);
// count the strokes the card draws with a variant badge and with the same badge in its standard look
const calls = () => ev("(()=>{const cv=shareCanvas();return cv.getContext('2d').calls.n;})()");
const fiery = calls();
ev("S.achP.hello='oncall'");
const plain = calls();
assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`);
assert.deepEqual(errors, []);
});

View file

@ -6,7 +6,7 @@ module.exports = `
if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue;
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
const candidates=E.filter(e=>e.used<e.cap&&(f.pin?e.ek===f.pin:e.ok(f.n))&&
(f.pin?base(e):TR?eff(e,f.n):base(e))===rank&&Dv[CIDX[e.city]]<Infinity)
(f.pin?base(e):TR?eff(e,f.n):base(e,f.n))===rank&&Dv[CIDX[e.city]]<Infinity)
.sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]);
for(let i=0;i<candidates.length&&f.rem>1e-6;){
let j=i+1;while(j<candidates.length&&(candidates[j].pref==='high')===(candidates[i].pref==='high')&&

255
tests/puzzles.test.js Normal file
View file

@ -0,0 +1,255 @@
// Puzzle mode (#190): small builds with stars, no clock, and a main save that is never touched.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Reference solutions: [a, b, route ('land' or a cable id), tier (0 = 10G, 1 = 100G)].
// `one` earns the goal star, `three` earns all three. A second land link on the same pair is a diverse route.
const REF = {
hello: { one: [['lon', 'nyc', 'grace']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'amitie']] },
eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['lon', 'ams', 'uly'], ['lon', 'ams', 'concerto'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] },
shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['nyc', 'chi', 'land'], ['chi', 'sjc', 'land'], ['sjc', 'dal', 'land'], ['dal', 'nyc', 'land']] },
smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['hel', 'cph', 'land'], ['cph', 'osl', 'land']] },
downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['adl', 'bne', 'land'], ['bne', 'syd', 'land']] },
aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['sjc', 'hnl', 'scx'], ['sjc', 'hnl', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] },
rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['tok', 'hkg', 'adc'], ['tok', 'hkg', 'apg'], ['hkg', 'sin', 'sjc2'], ['hkg', 'sin', 'land']] },
fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] },
kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'sea', 'hwk'], ['sea', 'hnl', 'hwk'], ['hnl', 'akl', 'hwk'], ['akl', 'syd', 'tasman'], ['akl', 'syd', 'scx']] },
guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']] },
flash: { one: [['nyc', 'lon', 'hibx']], three: [['nyc', 'lon', 'hibx'], ['nyc', 'lon', 'grace']] },
pingpong: { one: [['lax', 'tok', 'jup']], three: [['lax', 'tok', 'jup'], ['lax', 'sea', 'land'], ['sea', 'tok', 'fast']] },
suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['mrs', 'bom', 'twoaf'], ['bom', 'sin', 'land']] },
samba: { one: [['sao', 'mia', 'monet']], three: [['sao', 'mia', 'monet'], ['sao', 'for', 'land'], ['for', 'mia', 'monet']] },
sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land'], ['mil', 'lis', 'land']] },
braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix'], ['dub', 'nyc', 'havf']] },
nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land'], ['zrh', 'ams', 'land']] },
fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1], ['zrh', 'par', 'land', 1]] },
};
// Builds links the way a player does: POP at the first city, then the link picker for each hop.
function build(ev, links) {
for (const [a, b, via, tier] of links) {
if (!ev(`!!S.pops['${a}']`)) ev(`ACT.pzPop({city:'${a}'})`);
ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${tier || 0}})`);
}
ev('closeModal()');
}
const evalP = (ev) => JSON.parse(ev('JSON.stringify(pzEval())'));
test('puzzle data: every puzzle is valid, solvable, and its 3-star reference earns three stars', () => {
const { ev, errors } = load();
const ids = JSON.parse(ev('JSON.stringify(PZ.map(p=>p.id))'));
assert.ok(ids.length >= 16, 'at least 16 puzzles');
assert.equal(new Set(ids).size, ids.length, 'ids are unique');
assert.deepEqual(Object.keys(REF).sort(), ids.slice().sort(), 'every puzzle has a reference solution');
assert.ok(ev("PZ.every(p=>PZ_PACKS.some(k=>k.id===p.pack)&&p.n&&p.j&&p.cities.length>=2&&p.cities.length<=6&&[...p.cities,...(p.via||[]),...(p.avoid||[])].every(c=>isCity(c)&&!CITY[c].off&&!CITY[c].cn))"), 'cities exist and are playable');
assert.ok(ev("PZ.every(p=>!p.budget||(p.budget>=100000&&p.budget<=5e6))"), 'budgets are sane');
assert.ok(ev("PZ_PACKS[0].need===0&&PZ_PACKS.every((k,i)=>!i||k.need>PZ_PACKS[i-1].need)"), 'packs unlock in order');
assert.ok(ev("PZ.filter(p=>p.pack==='hello'&&!p.budget).length>=2"), 'the first puzzles give the budget star away');
for (const id of ids) {
ev(`pzBegin(pzDef('${id}'))`);
build(ev, REF[id].one);
let e = evalP(ev);
assert.ok(e.goal, `${id}: the one-star reference reaches the goal`);
assert.ok(e.stars >= 1, `${id}: one star`);
ev('ACT.pzReset({})');
assert.equal(evalP(ev).stars, 0, `${id}: reset clears it`);
build(ev, REF[id].three);
e = evalP(ev);
assert.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, twists ${JSON.stringify(e.tw)})`);
}
assert.deepEqual(errors, []);
});
test('stars: goal, budget, N-1 and twists each count', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('braces'))");
build(ev, REF.braces.one);
let e = evalP(ev);
assert.equal(e.stars, 2, 'connected and under budget, but one cut splits it');
assert.ok(!e.n1 && e.weak.length > 0);
build(ev, [['dub', 'nyc', 'havf']]);
assert.equal(evalP(ev).stars, 3);
ev('S.pz.budget=1000');
assert.equal(evalP(ev).stars, 2, 'over budget loses the second star');
// Two waves in the same trench are one backhoe away from nothing.
ev("pzBegin(pzDef('shining'))");
build(ev, REF.shining.one);
ev("ACT.pzLinkTo({a:'nyc',b:'chi'});ACT.pzVia({v:'land'});ACT.pzDiv({v:0});ACT.pzLink({tier:0})");
assert.equal(ev("new Set(S.links.filter(l=>edgeKey(l)==='chi|nyc').map(pzUnit)).size"), 1, 'same trench shares the cut');
// Twists: no subsea, ring, latency, minimum size, cities to avoid.
ev("pzBegin(pzDef('sharks'))");build(ev, REF.sharks.one);
assert.ok(evalP(ev).goal);
ev("pzBegin(pzDef('fire'))");build(ev, REF.fire.one);ev("ACT.pzRmLink({id:S.links[3].id})");
e = evalP(ev);
assert.ok(e.conn && !e.goal, 'a line is not a ring');
ev('ACT.pzUndo({})');
assert.ok(evalP(ev).goal, 'undo puts the ring back');
ev("pzBegin(pzDef('flash'))");build(ev, [['nyc', 'lon', 'grace']]);
e = evalP(ev);
assert.ok(e.conn && !e.goal, 'Grace Hopscotch is too slow for the traders');
ev("pzBegin(pzDef('fatpipes'))");build(ev, REF.fatpipes.one.map(([a, b, v]) => [a, b, v, 0]));
assert.ok(!evalP(ev).goal, '10G is too thin');
ev("ACT.pzTier({id:S.links[0].id,tier:1});ACT.pzTier({id:S.links[1].id,tier:1});ACT.pzTier({id:S.links[2].id,tier:1})");
assert.ok(evalP(ev).goal, 'upgraded in place');
ev("pzBegin(pzDef('nofra'))");
ev("ACT.pzPop({city:'fra'})");
assert.equal(ev("!!S.pops.fra"), false, 'no POP in a city to avoid');
assert.equal(ev("pzKind('lon')"), null, 'cities outside the puzzle are inert');
ev("ACT.pzPop({city:'lon'})");
assert.equal(ev("Object.keys(S.pops).length"), 0);
// Subsea is greyed out in the shark tank.
ev("pzBegin(pzDef('sharks'));ACT.pzPop({city:'lis'});ACT.pzLinkTo({a:'lis',b:'bcn'});ACT.pzVia({v:'medusa'});ACT.pzLink({tier:0})");
assert.equal(ev('S.links.length'), 0);
assert.deepEqual(errors, []);
});
test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('hello'))");
build(ev, REF.hello.three);
ev('ACT.speed({v:8});ACT.phonePlay({});for(let i=0;i<50;i++)frame(performance.now()+i*3000)');
assert.equal(ev('S.day'), 0);
assert.equal(ev('UI.speed'), 0);
assert.equal(ev('S.inc.length'), 0);
assert.equal(ev('S.cash'), ev('START_CASH'), 'nothing is charged');
assert.equal(ev("document.getElementById('left').hidden"), true, 'no goals/deals/NOC/networks drawer');
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
assert.deepEqual(errors, []);
});
test('the main save is byte-identical before and after playing and solving a puzzle', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true)");
const before = ev("localStorage.getItem('sot-save-v1')");
const name = ev('S.name'), day = ev('S.day');
ev('ACT.puzzleMenu({})');
assert.match(ev("document.getElementById('modalCard').textContent"), /Hello, World/);
ev("ACT.pzStart({id:'hello'})");
assert.equal(ev('S.mode'), 'puzzle');
build(ev, REF.hello.three);
ev("save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);window.dispatchEvent(new Event('pagehide'));ACT.exportSave({})");
assert.equal(ev("localStorage.getItem('sot-save-v1')"), before, 'untouched while in the puzzle');
assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).s.hello.st"), 3, 'the stars are kept');
ev('ACT.pzLeave({})');
assert.equal(ev('S.mode'), 'normal');
assert.equal(ev('S.name'), name);
assert.equal(ev('S.day'), day);
assert.ok(ev('!!S.pops.ams'));
assert.equal(ev('UI.started'), true);
assert.equal(ev("localStorage.getItem('sot-save-v1')"), before, 'and after');
assert.deepEqual(errors, []);
});
test('leaving a puzzle with no game goes back to the title screen', () => {
const { ev, errors } = load();
assert.ok(ev("!!document.querySelector('#modalCard .door[data-door=puzzle]')"), 'the title screen has a Puzzles door');
ev("document.querySelector('#modalCard .door[data-door=puzzle]').click()");
ev("document.querySelector('#modalCard [data-act=pzStart]').click()");
assert.equal(ev('S.mode'), 'puzzle');
ev('ACT.pzLeave({})');
assert.equal(ev('S'), null);
assert.equal(ev("localStorage.getItem('sot-save-v1')"), null, 'no main save appeared');
assert.match(ev("document.getElementById('modalCard').textContent"), /Series/);
assert.deepEqual(errors, []);
});
test('results card pops the stars, offers the next puzzle, a retry and a share line', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('eurotrip'))");
build(ev, REF.eurotrip.one);
let card = ev("document.getElementById('modalCard').textContent");
assert.match(card, /Puzzle solved/);
assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')"));
assert.match(ev("document.querySelector('#modalCard [data-act=pzStart]').dataset.args"), /shining/);
build(ev, [['lon', 'ams', 'concerto'], ['ams', 'fra', 'land']]);
card = ev("document.getElementById('modalCard').textContent");
assert.match(card, /A backhoe walks into your network/);
assert.equal(ev("document.querySelectorAll('#modalCard .pzbig.on').length"), 3);
const line = ev('pzShareText(pzEval())');
assert.match(line, /^Series of Tubes puzzle Euro Trip ⭐⭐⭐ \$\d+k · seriesoftub\.es$/);
assert.deepEqual(errors, []);
});
test('weekly puzzle: stable seed per ISO week, solvable, share string and streak', () => {
const { ev, errors } = load();
const a = ev("JSON.stringify(pzWeekly(new Date(2026,9,28)))"), b = ev("JSON.stringify(pzWeekly(new Date(2026,10,1)))"), c = ev("JSON.stringify(pzWeekly(new Date(2026,10,2)))");
assert.equal(a, b, 'same week, same puzzle');
assert.notEqual(a, c, 'next week, a new one');
const w = JSON.parse(a);
assert.equal(w.key, '2026-W44');
assert.ok(w.cities.length >= 4 && w.cities.length <= 5 && w.budget > 0);
// Every week of a few years can be solved with three stars by its own reference ring.
for (let i = 0; i < 160; i += 7) {
ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`);
const ring = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')).ref)'));
const links = ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; });
build(ev, links);
assert.equal(evalP(ev).stars, 3, `week +${i}`);
}
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))");
const ring = w.ref;
build(ev, ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; }));
assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$\d+k · seriesoftub\.es$/);
assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1);
// A streak counts weeks in a row; a gap starts again.
ev("const p=pzLoad();pzStreak(p,'2026-W45');pzStreak(p,'2026-W45');pzStreak(p,'2026-W46');window.__p=p");
assert.equal(ev('__p.streak.n'), 3);
ev("pzStreak(__p,'2026-W49')");
assert.equal(ev('__p.streak.n'), 1);
assert.equal(ev('__p.streak.best'), 3);
assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53');
assert.equal(ev("pzPrevKey('2026-W01')"), '2025-W52');
assert.deepEqual(errors, []);
});
test('pack unlocking follows the stars, and bad progress data is ignored', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-puzzles')");
assert.equal(ev("pzPackOpen('hello')"), true);
assert.equal(ev("pzPackOpen('fire')"), false);
ev("ACT.pzStart({id:'aloha'})");
assert.notEqual(ev('S&&S.mode'), 'puzzle', 'a locked puzzle does not start');
ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:3},eurotrip:{st:3}}}))");
assert.equal(ev("pzPackOpen('fire')"), true, '6 stars open pack 2');
ev('ACT.puzzleMenu({})');
assert.match(ev("document.getElementById('modalCard').textContent"), /Next pack, Speed Runs, unlocks at 14/);
ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:99,sp:'x'},nope:{st:3},__proto__:{st:3}},wk:{bad:{st:3}},streak:{n:-4,last:'<b>'}}))");
const p = JSON.parse(ev('JSON.stringify(pzLoad())'));
assert.deepEqual(p.s, { hello: { st: 3, sp: null } });
assert.deepEqual(p.wk, {});
assert.deepEqual(p.streak, { last: null, n: 0, best: 0 });
ev("localStorage.setItem('sot-puzzles','{nope')");
assert.equal(ev('pzStarsTotal(pzLoad())'), 0);
assert.deepEqual(errors, []);
});
test('puzzle HUD fits a 360 px phone: bottom sheet, no tab bar, panels work', () => {
const { dom, ev, errors } = load();
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'))");
ev("pzBegin(pzDef('hello'))");
assert.equal(ev("document.getElementById('tabbar').hidden"), true);
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
ev("selectCity('lon')");
assert.match(ev("document.getElementById('panelBody').textContent"), /Open a POP/);
ev("document.querySelector('#panelBody [data-act=pzPop]').click()");
assert.ok(ev('!!S.pops.lon'));
ev("selectCity('par')");
assert.equal(ev("document.getElementById('panel').hidden"), true, 'other cities do nothing');
ev("pzLinkModal('lon','nyc')");
assert.ok(ev("document.querySelectorAll('#modalCard .tierbtn').length") === 3, 'three sizes');
assert.deepEqual(errors, []);
void dom;
});
test('puzzles in every language', () => {
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
const { ev, errors } = load({ lang });
ev("ACT.puzzleMenu({});pzBegin(pzDef('braces'))");
build(ev, REF.braces.three);
const seen = ev("['pzBox','modalCard','hud'].map(id=>document.getElementById(id).textContent).join(' ')");
assert.ok(!/puzzles\./.test(seen), `${lang}: no raw labels`);
assert.match(seen, /⭐/);
assert.deepEqual(errors, [], lang);
}
});

View file

@ -60,8 +60,6 @@ test('the title screen: four doors, three Normal presets, a chaos picker for San
assert.equal(doc.getElementById('doorSandbox').hidden, false);
assert.equal(doc.getElementById('doorNormal').hidden, true);
doc.querySelector('.chs[data-chaos=spicy]').click();
doc.querySelector('.door[data-door=puzzle]').click();
assert.match(doc.getElementById('toasts').textContent, /coming soon/, 'puzzles are not here yet');
doc.querySelector('.door[data-door=normal]').click();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
assert.equal(ev('rulePreset()'), 'freeze');

148
tests/tier1-cone.test.js Normal file
View file

@ -0,0 +1,148 @@
// Tier 1 by customer cone (#85): peering with every Tier 1 reaches their customers and their customers' customers,
// so the long tail stops mattering for the win; networks in nobody's cone still need peering of their own.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// A transit-free network in Frankfurt with a PNI to every Tier 1 it needs.
const t1Club = (ev) => {
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;delete S.done.t1;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=500");
ev("S.transit=[];S.ixp={};S.peers={};S.pni=[];S.grace=null;for(const n of t1Need())S.pni.push({id:'p'+n.id,net:n.id,city:'fra',tier:2});compute()");
};
test('cones are built once at load and hold customers of customers', () => {
const { ev, errors } = load();
assert.equal(ev("CONE.voc.includes('ddo')&&CONE.voc.includes('spn')"), true, 'Hocus Pocus brings its own customers');
// Doodoo buys from Hocus Pocus, which buys from Not That Telecom: two levels down
assert.equal(ev("NET.ddo.up.includes('voc')&&NET.voc.up.includes('ntt')"), true);
assert.equal(ev("CONE_S.ntt.has('ddo')"), true, 'the Tier 1 cone is transitive');
assert.equal(ev("CONE.ntt[0]"), 'ntt', 'a network is first in its own cone');
assert.equal(ev("PNI_NETS===CONE"), true);
assert.equal(ev("ANC.ddo[0]"), 'voc', 'nearest upstream first');
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>n.up&&n.up.length&&n.up.every(u=>NET[u]))"), true, 'the long tail buys transit');
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>ANC[n.id].some(u=>NET[u].type==='t1'))"), true, 'from a Tier 1, directly or through a carrier');
assert.equal(ev("NET.tail45.up.join()"), 'mag', 'Auckland has no Tier 1: Hobbit Hole buys from a carrier that is there');
assert.equal(ev("NETS.filter(n=>n.tail).map(n=>n.up.join('+')).join()"), ev("NETS.filter(n=>n.tail).map(n=>tailUp(n.name,n.pops).join('+')).join()"), 'stable: picked by name');
// Australians buy only from Australian carriers, so a Tier 1 PNI is still no back door into Australia.
assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false);
assert.deepEqual(errors, []);
});
test('a transit-free network with PNIs to every Tier 1 reaches the long tail through their cones', () => {
const { ev, errors } = load();
t1Club(ev);
const tail = ev("NETS.find(n=>n.tail&&n.pops.includes('akl')).id");
for (const id of ['tail0', 'tail38', tail, 'sky', 'kys', 'tim']) {
assert.equal(ev(`!!R.reachable.${id}`), true, `${id} is reachable`);
assert.equal(ev(`!!R.nt.${id}`), true, `${id} without transit`);
assert.equal(ev(`!!R.cone.${id}`), true, `${id} through a peer's cone`);
}
// the traffic really goes over the PNI with the upstream, not some made-up exit
const up = ev("NET.tail0.up[0]");
assert.ok(ev("(R.netEg.tail0||{}).p") > 0, 'over a PNI');
assert.ok(ev(`R.usePni['p${up}']`) > 0, 'the PNI with its upstream carries it');
// the traceroute shows the hand-off to the customer and an AS path one hop longer
const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'tail0'}))"));
assert.match(tr.text, /hands it to its customer/);
assert.equal(tr.asPath.length, 3, 'you, the Tier 1, the customer');
assert.equal(tr.asPath[1], ev(`NET.${up}.asn`), 'through the upstream it buys transit from');
assert.match(tr.why, /customers come after direct peers/);
assert.deepEqual(errors, []);
});
test('a network in nobody\'s cone still needs reaching directly', () => {
const { ev, errors } = load();
t1Club(ev);
// Doitsche Telekomm buys from no one: no Tier 1 PNI reaches it
assert.equal(ev("(NET.dtk.up||[]).length"), 0);
assert.equal(ev("R.reachable.dtk"), false);
assert.equal(ev("isTier1()"), false);
assert.match(ev('t1Why()'), /nobody you peer with sells transit to/);
// peer with every island directly and the win comes
ev("for(const n of NETS)if(!R.reachable[n.id])S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});for(const n of NETS)if(n.pops.length&&!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};compute()");
assert.ok(ev("R.reach") > 0.999, `reach ${ev('R.reach')}`);
assert.equal(ev("isTier1()"), true);
assert.deepEqual(errors, []);
});
test('the long tail no longer stands between you and Tier 1', () => {
const { ev, errors } = load();
t1Club(ev);
// peer directly only with the networks in nobody's cone, never with the long tail itself
ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute()");
assert.equal(ev("S.pni.some(p=>NET[p.net].tail)"), false, 'no session with any long-tail network');
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>R.reachable[n.id])"), true);
assert.equal(ev("isTier1()"), true);
// the peers you need directly are all real networks of some size, and fewer than before
const islands = ev("S.pni.filter(p=>p.id[0]==='i').length");
assert.ok(islands < 70, `${islands} networks to peer with directly`);
assert.deepEqual(errors, []);
});
test('a peer\'s cone comes after direct peering and before transit, so peering widely still pays', () => {
const { ev, errors } = load();
t1Club(ev);
ev("ACT.buyTransit({city:'fra',net:'cog',tier:2});S.pni=S.pni.filter(p=>p.net!=='cog');compute()");
// a Cogentle customer is reached through another Tier 1's cone only if it buys from one; transit is the fallback
const id = ev("NETS.find(n=>n.tail&&n.up.length===1&&n.up[0]==='tly').id");
assert.ok(ev(`(R.netEg.${id}||{}).p`) > 0, 'over the PNI with its upstream, not over transit');
assert.equal(ev(`(R.netEg.${id}||{}).t||0`), 0);
// a direct session beats the cone: peer with it at the exchange and its traffic moves there
ev(`S.pops.fra.bb.d=500;ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute()`);
if (ev(`ixSessions('fra').has('${id}')`)) {
assert.ok(ev(`(R.netEg.${id}||{}).ix`) > 0, 'direct peering wins over the cone');
assert.equal(ev(`(R.netEg.${id}||{}).p||0`), 0);
}
// an IX session also brings the member's customers along
assert.equal(ev("ixSessions('fra').has('gsl')"), true);
const down = ev("DOWN.gsl.find(id=>!t1Need().some(t=>CONE_S[t.id].has(id))&&!ixSessions('fra').has(id))||''");
if (down) assert.equal(ev(`R.reachable.${down}`), true, `${down} comes along with Glowball Sakura Lager's session`);
assert.deepEqual(errors, []);
});
test('old saves keep their win: cones only ever add reach', () => {
const { ev, errors } = load();
t1Club(ev);
ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute()");
ev("S.won=true;S.done.t1=S.day;S.t1Now=true");
// a save from before 2.0, with an older Tier 1 set and no record of cones, loads and is still Tier 1
ev("const o=JSON.parse(JSON.stringify(S));o.t1v=2;S=migrate(o);compute()");
assert.equal(ev("S.won"), true);
assert.equal(ev("isTier1()"), true);
assert.equal(ev("tierLabel()"), 'Tier 1');
// and reach with cones is never lower than reach without: every exit still reaches what it did
const before = ev("R.reach");
ev("for(const id of NET_IDS){CONE_S[id]=new Set([id]);DOWN[id]=[];}compute()");
assert.ok(ev("R.reach") <= before + 1e-9, 'switching cones off can only lose reach');
assert.deepEqual(errors, []);
});
test('the Road to Tier 1 card and the network list explain the cone, on a phone too', () => {
for (const w of [1280, 360]) {
const { ev, dom, errors } = load();
ev(`window.innerWidth=${w}`);
t1Club(ev);
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
const txt = dom.window.document.getElementById('leftBody').textContent;
assert.match(txt, /Road to Tier 1/);
assert.match(txt, /their customers come along for free/);
assert.match(txt, /\d+ networks already come along with a peer/);
ev("ACT.netFocus({id:'tail0'})");
assert.match(dom.window.document.getElementById('leftBody').textContent, /Reached through the customer cone of/);
ev("S.pni=[];compute();ACT.netFocus({id:'tail0'})");
assert.match(dom.window.document.getElementById('leftBody').textContent, /Buys transit from .*Peer with/);
assert.match(ev("GOALS.find(g=>g.id==='t1').d"), /customers come along for free/);
assert.deepEqual(errors, [], `${w}px`);
}
});
test('routing with cones costs about what it did: exits are asked once, cones are built at load', () => {
const { ev, errors } = load();
t1Club(ev);
ev("for(const n of NETS.filter(n=>!n.tail&&!n.cn).slice(0,40))for(const c of ['fra','ams','lon']){if(!S.pops[c])S.pops[c]={day:0,bb:{d:400},boost:0,down:0,routers:4,gen:true};S.pni.push({id:n.id+c,net:n.id,city:c,tier:2});}compute()");
const t = ev("(()=>{for(let i=0;i<3;i++)compute();const a=performance.now();for(let i=0;i<10;i++)compute();return (performance.now()-a)/10;})()");
const plain = ev(`(()=>{const keep={};for(const id of NET_IDS){keep[id]=[CONE_S[id],DOWN[id]];CONE_S[id]=new Set([id]);DOWN[id]=[];}
for(let i=0;i<3;i++)compute();const a=performance.now();for(let i=0;i<10;i++)compute();const r=(performance.now()-a)/10;for(const id of NET_IDS){CONE_S[id]=keep[id][0];DOWN[id]=keep[id][1];}return r;})()`);
assert.ok(t < plain * 2 + 20, `compute() with cones ${t.toFixed(1)} ms vs without ${plain.toFixed(1)} ms`);
assert.deepEqual(errors, []);
});