Puzzles: real traffic routed by the game, routers, link sizes and paths
Every puzzle now carries demand (eyeballs pulling from a content origin, circuits with latency caps, best-effort flows) routed by compute(). Stars: delivered, within budget, N-1 under load. Routers, ports, metrics, standby and the redundancy check work in puzzles; the whole world is open. Weekly schema 2 carries the demand; scripts/lib/puzzle-solver.js sizes and searches builds.
This commit is contained in:
parent
9b7b1c150c
commit
e90f5f675e
18 changed files with 817 additions and 364 deletions
89
scripts/lib/puzzle-solver.js
Normal file
89
scripts/lib/puzzle-solver.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// Puzzle tools (the weekly generator, the puzzle tests): build a puzzle network straight into a headless game, judge
|
||||
// it with the game's own star code, and search for the cheapest build that earns three stars.
|
||||
//
|
||||
// A build is a list of links [a, b, via, tier, same]: via is 'land' or a cable id, tier an index into LT, and `same`
|
||||
// (k > 0) puts an overland link in the k-th trench already on that pair (otherwise a further one takes a diverse
|
||||
// route, +40%). Routers
|
||||
// are not part of the search: each POP gets the cheapest models that carry its busiest moment (across every single
|
||||
// cut), its ports and its biggest wave, which is what any sensible player would buy for that build.
|
||||
|
||||
// Runs inside the page.
|
||||
function page() {
|
||||
window.pzsReset = () => { S.pops = {}; S.links = []; S.pairMet = {}; for (const b of S.biz) b.route = 'normal'; UI.pzEv = null; };
|
||||
window.pzsLink = (a, b, via, tier, same) => {
|
||||
const r = pzRoutes(a, b).find((x) => x.via === via); if (!r) throw new Error(`no route ${via} for ${a}-${b}`);
|
||||
for (const c of [a, b]) if (!S.pops[c]) S.pops[c] = pzNewPop(c);
|
||||
// `same` k > 0: in the k-th overland trench on this pair; 0: a trench of its own (diverse, unless it is the first).
|
||||
const tr = !r.sub ? [...new Set(S.links.filter((l) => edgeKey(l) === edgeKey({ a, b }) && !l.cable).map((l) => l.trench))] : [], sm = same && tr[same - 1], div = !!(tr.length && sm !== tr[0]), id = uid();
|
||||
S.links.push({ id, a, b, kind: 'wave', border: false, premium: false, tier, km: r.km, sub: r.sub, cable: r.cab, mo: pzMo(r, tier, div), mult: r.f * (div ? DIVERSE : 1), trench: r.cab ? 'cab:' + r.cab : sm || id, cut: 0, day: 0 });
|
||||
};
|
||||
// The cheapest routers for POP c: enough ports, a model that lights its biggest wave, and capacity for its peak.
|
||||
window.pzsRouters = (c, peak) => {
|
||||
const used = portsUsed(c), lt = Math.max(0, ...S.links.filter((l) => l.a === c || l.b === c).map((l) => l.tier)); let best = null;
|
||||
for (const g of PZ_RG) for (let rt = 1; rt <= 6; rt++) { const M = RG[g]; if (M.maxLT < lt || M.ports * rt < used - 1e-9 || M.cap * rt < peak - 1e-6) continue;
|
||||
const cost = pzRtCost(g, rt); if (!best || cost < best.cost) best = { g, rt, cost }; }
|
||||
return best;
|
||||
};
|
||||
// Judge the build on routers big enough for anything, then price the routers it really needs. With those, routing
|
||||
// is the same (no router is ever full), so the stars are too.
|
||||
window.pzsJudge = () => {
|
||||
const BIG = RG.findIndex((r) => r.n === 'Arrrhipster 7800R'), keep = {};
|
||||
for (const c in S.pops) { keep[c] = [S.pops[c].rgen, S.pops[c].routers]; S.pops[c].rgen = BIG; S.pops[c].routers = 1; }
|
||||
UI.pzEv = null; const b0 = S.pz.budget; S.pz.budget = 0; const e = pzEval(); S.pz.budget = b0; UI.pzEv = null;
|
||||
const rt = {}; let spend = 0, bad = false;
|
||||
for (const c in S.pops) { const r = pzsRouters(c, e.peak[c] || 0); if (!r) { bad = true; continue; } rt[c] = [r.g, r.rt]; spend += r.cost + pzPopCost(c); S.pops[c].rgen = keep[c][0]; S.pops[c].routers = keep[c][1]; }
|
||||
for (const l of S.links) spend += l.mo * PZ_YEAR;
|
||||
return { one: e.goal && !bad, three: e.goal && e.n1 && !bad, spend, rt };
|
||||
};
|
||||
window.pzsApplyRt = (rt) => { for (const c in rt) { S.pops[c].rgen = rt[c][0]; S.pops[c].routers = rt[c][1]; } UI.pzEv = null; };
|
||||
}
|
||||
const install = (ev) => { if (ev("typeof pzsJudge!=='function'")) ev(`(${page.toString()})()`); };
|
||||
|
||||
const key = (L) => JSON.stringify(L);
|
||||
// Steps that are not links set what a player sets in the panels: ['@route', flow, 'fast'] a circuit's path,
|
||||
// ['@met', a, b, 'avoid'] a pair's metric. The search keeps them as they are.
|
||||
const step = ([a, b, v, t, s]) => a === '@route' ? `S.biz.find(x=>x.id===pzFlowId(${b})).route='${v}';` : a === '@met' ? `(S.pairMet=S.pairMet||{})[edgeKey({a:'${b}',b:'${v}'})]='${t}';`
|
||||
: `pzsLink('${a}','${b}','${v}',${t},${s || 0});`;
|
||||
function judge(ev, L) {
|
||||
return JSON.parse(ev(`pzsReset();${L.map(step).join('')}JSON.stringify(pzsJudge())`));
|
||||
}
|
||||
// Every link option between the given cities: each route, at tiers up to maxTier.
|
||||
function options(ev, cities, maxTier, noSub) {
|
||||
const out = [];
|
||||
for (let i = 0; i < cities.length; i++) for (let j = i + 1; j < cities.length; j++) {
|
||||
const [a, b] = [cities[i], cities[j]];
|
||||
const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>({via:r.via,sub:r.sub,ok:[0,1,2,3].map(t=>!subWaveWhy(t,r.km,r.sub))})))`));
|
||||
for (const r of rs) { if (noSub && r.sub) continue; for (let t = 0; t <= maxTier; t++) if (r.ok[t]) { out.push([a, b, r.via, t, 0]); if (!r.sub) { out.push([a, b, r.via, t, 1]); out.push([a, b, r.via, t, 2]); } } }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Local search from a 3-star build: drop a link, shrink one, move one to another route, put it in the first trench
|
||||
// or out of it, or swap one link for another option, while it is cheaper and still three stars.
|
||||
function improve(ev, start, opts = {}) {
|
||||
const memo = new Map(), J = (L) => { const k = key(L); if (!memo.has(k)) memo.set(k, judge(ev, L)); return memo.get(k); };
|
||||
let cur = start.map((x) => x.slice()), cj = J(cur);
|
||||
if (!cj.three) throw new Error('the starting build does not earn three stars');
|
||||
const routes = {}, via = (a, b) => { const k = a < b ? a + '|' + b : b + '|' + a; if (!routes[k]) routes[k] = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>r.via))`)); return routes[k]; };
|
||||
const opt = opts.options || [];
|
||||
for (let round = 0; round < 60; round++) {
|
||||
const nb = [];
|
||||
for (let i = 0; i < cur.length; i++) {
|
||||
const w = (x) => { const L = cur.slice(); L[i] = x; return L; }, [a, b, v, t, s] = cur[i];
|
||||
if (a[0] === '@') continue;
|
||||
nb.push(cur.filter((_, k) => k !== i));
|
||||
if (t > 0) nb.push(w([a, b, v, t - 1, s]));
|
||||
for (const v2 of via(a, b)) if (v2 !== v) nb.push(w([a, b, v2, t, 0]));
|
||||
if (v === 'land') for (const s2 of [0, 1, 2]) if (s2 !== (s || 0)) nb.push(w([a, b, v, t, s2]));
|
||||
}
|
||||
if (opts.swap) for (const o of opt) for (let i = 0; i < cur.length; i++) { if (cur[i][0][0] === '@') continue; const L = cur.slice(); L[i] = o; nb.push(L); }
|
||||
let best = null;
|
||||
for (const L of nb) { const j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; }
|
||||
if (!best && opts.add) for (const o of opt) for (let i = 0; i < cur.length; i++) for (let k = i + 1; k < cur.length; k++) {
|
||||
if (cur[i][0][0] === '@' || cur[k][0][0] === '@') continue;
|
||||
const L = [...cur.filter((_, x) => x !== i && x !== k), o], j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; }
|
||||
if (!best) break;
|
||||
cur = best.L; cj = best.j;
|
||||
}
|
||||
return { links: cur, ...cj };
|
||||
}
|
||||
module.exports = { install, judge, options, improve };
|
||||
|
|
@ -12,15 +12,18 @@
|
|||
// --dir DIR where the files live (default site/puzzles/weekly)
|
||||
//
|
||||
// How a puzzle is made: pick a theme the last weeks did not have, choose 4-6 cities for it (avoiding last weeks'
|
||||
// cities), then search for the cheapest build that connects them and the cheapest build that survives any single cut
|
||||
// (a whole cable or a trench). The budget is that N-1 build plus a little, so three stars need the smart design, not
|
||||
// the obvious "double everything". Both reference builds are then played through the game's own actions and must earn
|
||||
// their stars, or the candidate is thrown away and another one tried.
|
||||
// cities) and the traffic they carry (content in the first city, eyeballs in the others; a latency sprint adds a
|
||||
// circuit with a latency cap). Search for the cheapest topology that connects them and the cheapest one that survives
|
||||
// any single cut (a whole cable or a trench), then size each with the game's own routing (scripts/lib/puzzle-solver.js):
|
||||
// links and routers big enough for every flow, after any single cut too, then as small as they can be. The budget is
|
||||
// that N-1 build plus a little. Both reference builds are judged by the game's own star code and must earn their
|
||||
// stars, or the candidate is thrown away and another one tried.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SCHEMA = 1, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6;
|
||||
const SV = require('./lib/puzzle-solver');
|
||||
const SCHEMA = 2, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6;
|
||||
const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint'];
|
||||
|
||||
// ---------- the game, headless ----------
|
||||
|
|
@ -31,6 +34,7 @@ function game(file) {
|
|||
console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`);
|
||||
g = load();
|
||||
}
|
||||
SV.install(g.ev);
|
||||
// N-1 counts a whole cable as one failure (every segment of a cable shares its risk), as the solver does.
|
||||
if (g.ev("pzUnit({cable:'x',a:'a',b:'b'})") !== 'cab:x') throw new Error('this game counts cable segments separately; the solver would not match its N-1 check');
|
||||
return g;
|
||||
|
|
@ -219,6 +223,12 @@ function draft(W, theme, r, banned) {
|
|||
}
|
||||
if (new Set([...P.cities, ...P.via, ...P.avoid]).size !== P.cities.length + P.via.length + P.avoid.length) return null;
|
||||
if (P.cities.length < 3 || P.cities.length > 6) return null;
|
||||
// The traffic: content in the first city, eyeballs in the others (less across an ocean, where waves are dear), and
|
||||
// for a sprint a circuit between its two cities under the latency cap.
|
||||
const far = theme === 'ocean' || theme === 'islands', sizes = far ? [5, 8, 10, 15] : [10, 20, 30, 40, 60];
|
||||
P.src = [P.cities[0]];
|
||||
P.dem = P.cities.slice(1).map((c) => ({ t: 'eye', a: c, g: pick(r, sizes) }));
|
||||
if (P.lat) P.dem.unshift({ t: 'l2', a: P.lat[0], b: P.lat[1], g: 10, ms: P.lat[2] });
|
||||
return P;
|
||||
}
|
||||
|
||||
|
|
@ -240,29 +250,45 @@ function history(dir, key) {
|
|||
}
|
||||
const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []);
|
||||
|
||||
// Plays a build through the game's own actions and returns the stars it earns.
|
||||
function play(ev, def, links) {
|
||||
ev(`localStorage.removeItem('sot-puzzles');pzBegin(${JSON.stringify(def)})`);
|
||||
for (const l of links) {
|
||||
if (!ev(`!!S.pops['${l.a}']`)) ev(`ACT.pzPop({city:'${l.a}'})`);
|
||||
ev(`ACT.pzLinkTo({a:'${l.a}',b:'${l.b}'});ACT.pzVia({v:'${l.via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:0})`);
|
||||
// A topology's links, sized for the traffic: every wave at the smallest size that carries it all (after any single cut
|
||||
// too, for the N-1 build), as the game routes it, with the cheapest routers that fit.
|
||||
const TIER_G = [10, 100, 400];
|
||||
function size(ev, def, links, n1) {
|
||||
ev(`pzBegin(${JSON.stringify(def)})`);
|
||||
const tot = def.dem.reduce((a, f) => a + f.g, 0), t0 = Math.max(0, TIER_G.findIndex((g) => g >= tot));
|
||||
for (let t = t0; t < TIER_G.length; t++) {
|
||||
const L = [...links.map((l) => [l.a, l.b, l.via, t, 0]), ...def.dem.map((f, i) => f.ms ? ['@route', i, 'fast'] : null).filter(Boolean)], j = SV.judge(ev, L);
|
||||
if (n1 ? j.three : j.one) { const r = n1 ? SV.improve(ev, L) : { links: L, ...j }; return r; }
|
||||
}
|
||||
ev('closeModal()');
|
||||
return null;
|
||||
}
|
||||
// Plays a sized build (links and routers) in the game and returns the stars it earns.
|
||||
function play(ev, def, b) {
|
||||
ev(`localStorage.removeItem('sot-puzzles');pzBegin(${JSON.stringify(def)})`);
|
||||
SV.judge(ev, b.links); ev(`pzsApplyRt(${JSON.stringify(b.rt)})`);
|
||||
return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))'));
|
||||
}
|
||||
const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, via: P.via, avoid: P.avoid, budget,
|
||||
twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}, P.lat ? { lat: P.lat } : {}),
|
||||
const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, src: P.src, dem: P.dem, via: P.via, avoid: P.avoid, budget,
|
||||
twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}),
|
||||
name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } });
|
||||
// The topology search reads a sprint's latency cap from its circuit.
|
||||
const shape = (def) => { const l2 = def.dem.find((f) => f.t === 'l2' && f.ms); return { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: l2 ? [l2.a, l2.b, l2.ms] : null }; };
|
||||
// Topology, then sizes: the 1-star and 3-star references with their prices.
|
||||
function sized(g, W, P, def) {
|
||||
const sol = solve(W, P); if (!sol.one || !sol.three) return null;
|
||||
const one = size(g.ev, def, sol.one.links, false), three = size(g.ev, def, sol.three.links, true);
|
||||
if (!one || !three) return null;
|
||||
return { one: { cost: Math.round(one.spend), b: one }, three: { cost: Math.round(three.spend), b: three } };
|
||||
}
|
||||
// The game's own validator decides what a puzzle is; then both references must earn their stars.
|
||||
function verify(g, W, j, key) {
|
||||
function verify(g, W, j, key, known) {
|
||||
const { ev } = g, def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${key}'))`));
|
||||
if (!def) return { ok: false, why: 'the game rejects the file' };
|
||||
const P = { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: def.lat };
|
||||
const sol = solve(W, P);
|
||||
if (!sol.one || !sol.three) return { ok: false, why: 'no build reaches the goal and survives a cut' };
|
||||
const P = shape(def), sol = known || sized(g, W, P, def);
|
||||
if (!sol) return { ok: false, why: 'no build delivers the traffic and survives a cut' };
|
||||
if (sol.three.cost > def.budget) return { ok: false, why: `the cheapest N-1 build found costs ${sol.three.cost}, over the budget ${def.budget}` };
|
||||
const s1 = play(ev, def, sol.one.links), s3 = play(ev, def, sol.three.links);
|
||||
if (s1.stars < 1 || (!P.ring && s1.stars !== 2)) return { ok: false, why: `the one-star reference earns ${s1.stars} stars` };
|
||||
const s1 = play(ev, def, sol.one.b), s3 = play(ev, def, sol.three.b);
|
||||
if (s1.stars < 1) return { ok: false, why: `the one-star reference earns ${s1.stars} stars` };
|
||||
if (s3.stars !== 3) return { ok: false, why: `the three-star reference earns ${s3.stars} stars (${JSON.stringify(s3)})` };
|
||||
return { ok: true, sol, s1, s3 };
|
||||
}
|
||||
|
|
@ -281,17 +307,18 @@ function generate(g, key, dir) {
|
|||
if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue;
|
||||
const sol = solve(W, P);
|
||||
if (!sol.one || !sol.three) continue;
|
||||
// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the
|
||||
// obvious one (a second way along every hop) whenever there is room.
|
||||
let budget = ceil10k(sol.three.cost * 1.05);
|
||||
if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000);
|
||||
const smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost;
|
||||
// Prefer puzzles where surviving a cut takes real thought: the obvious "double everything" costs a lot more.
|
||||
const smart = sol.naive ? sol.naive.cost / sol.three.cost : 1.05, slack = sol.three.cost / sol.one.cost;
|
||||
const score = Math.min(smart, 1.6) + Math.min(slack, 2) * 0.2 + r() * 0.05;
|
||||
cands.push({ P, sol, budget, score, w: words(ev, W, P, r) });
|
||||
cands.push({ P, score, w: words(ev, W, P, r) });
|
||||
}
|
||||
cands.sort((a, b) => b.score - a.score);
|
||||
for (const c of cands) {
|
||||
const j = fileOf(key, c.P, c.budget, c.w, c.sol), v = verify(g, W, j, key);
|
||||
// Sized with the traffic: the budget sits just above the cheapest N-1 build found.
|
||||
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(fileOf(key, c.P, 1e6, c.w, { one: { cost: 0 }, three: { cost: 0 } }))},'${key}'))`));
|
||||
const sol = def && sized(g, W, c.P, def);
|
||||
if (!sol) { console.warn(`${key}: rejected a ${theme} puzzle: no build carries its traffic`); continue; }
|
||||
const j = fileOf(key, c.P, Math.max(50000, ceil10k(sol.three.cost * 1.05)), c.w, sol), v = verify(g, W, j, key, sol);
|
||||
if (v.ok) return j;
|
||||
console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue