diff --git a/CHANGELOG.md b/CHANGELOG.md index e56d08c..0dafde6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 - A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. -- Puzzles: small, calm network builds you can finish in a coffee break (#190). Connect a few cities on the real map with POPs and leased waves, with no clock, no bills and nothing breaking, and earn up to three stars: one for the goal, one for staying under budget, and one if the network survives any single cut (a trench, or a whole cable). Eighteen puzzles in four packs, with roomy budgets at first and tighter ones as you go (more stars open the next pack), some with a twist like a latency target, no subsea cables or a ring, plus a weekly puzzle that is the same for everyone, with a streak and a result to share. Puzzles never touch your saved network; only your stars are kept. -- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. +- Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. +- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. - Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, never breaks a customer's or a bank's transit requirement, and shows what it adds to your monthly bill. The Ops sheet opens with the intern's mood and a weekly shift report, which is also the one notice a week the intern leaves in the NOC (#98, #100, #102, #181, #185, #192, #177). - Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. - Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips the peering inbox, hardware shortages, sold-out routes and de-peering at exchanges. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f990db4..ecdacda 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -157,12 +157,14 @@ its Monday (the week starting Sunday 1 November 2026 is `2026-W45`); `pzWeekKey( Every Sunday `weekly-puzzle.yml` runs `scripts/weekly-puzzle.js`, which loads the real game headless, picks a theme the last three weeks did not have (region tour, ring, detour around a hub, ocean crossing, island hopping, -latency sprint) and cities the last four weeks did not use, and searches for the cheapest build that connects -them and the cheapest one that survives any single cut (a whole cable, or a trench). The budget sits just above -that N-1 build and, where there is room, below the obvious "second path along every hop", so three stars take -some thought. Both reference builds are then played through the game's own actions and must earn one and three -stars, or the puzzle is thrown away. The file holds only ids, numbers and translation labels with their fill-ins -(`{"v":1,"key","theme","cities","via","avoid","budget","twist","name":{"l","p"},"joke":{"l","p"},"ref"}`). +latency sprint) and cities the last four weeks did not use, gives them traffic (content in the first city, eyeballs +in the others, a circuit with a latency cap for a sprint), searches for the cheapest topology that connects them and +the cheapest one that survives any single cut (a whole cable, or a trench), then sizes both with the game's own +routing (`scripts/lib/puzzle-solver.js`: links and routers big enough for every flow, after any cut too, then as +small as they go). The budget sits just above that N-1 build. Both references are judged by the game's own star +code and must earn one and three stars, or the puzzle is thrown away. The file holds only ids, numbers and +translation labels with their fill-ins +(`{"v":2,"key","theme","cities","src","dem","via","avoid","budget","twist","name":{"l","p"},"joke":{"l","p"},"ref","rev"?}`). `--check` re-validates every file the way the game does. The game fetches `puzzles/weekly/.json` (relative, same origin) only when the Puzzles list opens, and checks diff --git a/scripts/lib/puzzle-solver.js b/scripts/lib/puzzle-solver.js new file mode 100644 index 0000000..a225744 --- /dev/null +++ b/scripts/lib/puzzle-solver.js @@ -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 }; diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js index 11c654f..5a9a0a1 100644 --- a/scripts/weekly-puzzle.js +++ b/scripts/weekly-puzzle.js @@ -13,15 +13,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 ---------- @@ -32,6 +35,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; @@ -220,6 +224,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; } @@ -241,41 +251,53 @@ 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()))')); } -// A first edition has no rev; refresh() adds rev 2, 3… when it regenerates a week. -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; + // The three-star build delivers too: when it is the cheaper one (a ring, sized down), it is the one-star reference. + const o = one.spend <= three.spend ? one : three; + return { one: { cost: Math.round(o.spend), b: o }, 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 }; } -// 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. -function budgetOf(sol) { - 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); - return budget; -} +// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, sized for its traffic. +const budgetOf = (sol) => Math.max(50000, ceil10k(sol.three.cost * 1.05)); function generate(g, key, dir) { const { ev } = g, W = world(ev); @@ -291,13 +313,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; - const budget = budgetOf(sol), 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, budgetOf(sol), c.w, sol), v = verify(g, W, j, key, sol); if (v.ok) return j; console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`); } @@ -343,10 +370,10 @@ function refresh(g, dir, now = Date.now()) { let n = null; if (valid) { const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${k}'))`)); - const sol = solve(W, { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: def.lat }); - if (sol.one && sol.three) { + const sol = sized(g, W, shape(def), def); + if (sol) { const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev }); - if (verify(g, W, c, k).ok) n = c; + if (verify(g, W, c, k, sol).ok) n = c; } } if (!n) { try { n = Object.assign(generate(g, k, dir), { rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } } @@ -359,7 +386,7 @@ function refresh(g, dir, now = Date.now()) { const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n'); const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); }; -module.exports = { game, generate, check, refresh, solve, world, writeWeek, writeIndex, list }; +module.exports = { game, generate, check, refresh, solve, sized, shape, world, writeWeek, writeIndex, list }; if (require.main === module) { const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; }; diff --git a/site/i18n/de.js b/site/i18n/de.js index bd56b10..7fd624d 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2908,56 +2908,78 @@ "progress.your_score_peak_traffic":"Dein Ergebnis: Spitzen-Traffic", "progress.your_traffic_to_and_from_asia":"Dein Traffic von und nach Asien", "puzzles.a_backhoe_walks_into_your_network":"Kommt ein Bagger in dein Netz. Nichts passiert.", +"puzzles.a_bigger_boat":"Wir brauchen ein größeres Boot", +"puzzles.a_cut_on_where_drops_g":"Ein Schnitt bei {where} kostet {g}", +"puzzles.a_different_route":"Eine andere Route", +"puzzles.a_diverse_route":"Eine diverse Route (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Ein POP kostet {setup} Einrichtung, dann {mo}/Monat. Puzzles rechnen die Einrichtung und ein Jahr Miete.", -"puzzles.a_tiny_island_where_half_the":"Eine winzige Insel, auf der die halbe Pazifik-Verkabelung Kaffeepause macht.", -"puzzles.a_to_b_under_ms":"{a} → {b} unter {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} unter {ms} ms (jetzt {now} ms)", -"puzzles.aloha_latency":"Aloha Latenz", +"puzzles.add_a_router_cost":"Router dazu {cost}/Jahr", +"puzzles.add_another_link_here":"Noch einen Link auf diesem Paar", +"puzzles.all_of_europe_s_cat_videos":"Alle Katzenvideos Europas wohnen in London, und jedes einzelne geht durch deinen Router.", +"puzzles.already_here_list":"Schon auf diesem Paar: {list}", +"puzzles.another_wave_on_this_cable":"Noch eine Wave auf diesem Kabel", "puzzles.avoid_list":"ohne {list}", "puzzles.back_to_my_network":"Zurück zu meinem Netz", "puzzles.back_to_the_title":"Zurück zum Startbildschirm", -"puzzles.beat_the_clock_light_in_glass":"Licht in Glasfaser schafft 200 km pro Millisekunde. Wähl deine Kabel, als ob es darauf ankäme.", +"puzzles.baltic_shortcut":"Baltische Abkürzung", "puzzles.belt_and_braces":"Gürtel und Hosenträger", +"puzzles.best_effort":"Best Effort", "puzzles.best_x":"Bestwert {x}", +"puzzles.biggest_wave":"Größte Wave", "puzzles.budget":"Budget", "puzzles.budget_x":"Budget {x}", -"puzzles.connect_list":"Verbinde {list}.", -"puzzles.connected":"Verbunden", +"puzzles.capacity_first_every_link_has_a":"Erst die Kapazität: Jeder Link hat eine Größe, und der Traffic muss reinpassen. Großzügige Budgets, die ersten zwei gehen aufs Haus.", +"puzzles.carry_list":"Zu transportieren: {list}.", +"puzzles.carrying":"Transportiert", +"puzzles.carrying_on_this_pair":"Transportiert (alle {n} Links dieses Paars)", +"puzzles.content_lives_in_list":"Die Inhalte liegen in {list}: Privatkunden ziehen vom nächsten.", "puzzles.copied_paste_it_anywhere":"Kopiert! Füg es irgendwo ein:
{t}", "puzzles.de_kicks_sales_has_your_number":"Der DE-KICKS-Vertrieb hat deine Nummer. Verbinde Deutschland ohne Frankfurt.", +"puzzles.delivered":"Geliefert", "puzzles.diverse_route_40_survives_a_backhoe":"Getrennte Trasse (+40 %, übersteht einen Bagger)", "puzzles.down_under_up_and_running":"Down Under, up and running", "puzzles.drag_from_a_pink_pop_to":"Zieh von einem pinken POP zu einer anderen Stadt, um eine Wave zu mieten", "puzzles.drag_from_this_pop_onto_another":"Zieh von diesem POP auf eine andere Puzzle-Stadt oder wähl eine hier.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro-Trip", +"puzzles.every_bit_arrives":"jedes Bit kommt an", "puzzles.every_internet_starts_with_one_tube":"Jedes Internet beginnt mit einer Röhre.", -"puzzles.every_link_n_g_or_more":"Jeder Link {n}G oder mehr", "puzzles.every_star_in_this_pack_is":"Alle Sterne in diesem Paket gehören dir.", -"puzzles.fat_pipes_only":"Nur dicke Rohre", +"puzzles.everything_at_once_across_oceans":"Alles auf einmal, über Ozeane. Knappe Budgets.", +"puzzles.fat_pipes":"Dicke Rohre", +"puzzles.fjord_focus":"Fjord im Fokus", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Für Architekten, die die Baggersaison verschlafen.", -"puzzles.four_capitals_one_very_long_winter":"Vier Hauptstädte, ein sehr langer Winter, null Ausreden für Ausfälle.", +"puzzles.flow_circuit_a_b":"Leitung {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Privatkunden in {city}", "puzzles.four_cities_four_cables_one_ring":"Vier Städte, ein Ring. Tolkien wäre begeistert, dein NOC sowieso.", "puzzles.four_cities_one_continent_and_a":"Vier Städte, ein Kontinent und dazwischen sehr viel Mais.", +"puzzles.framed_n_stars_from_the_old":"Gerahmt an der Wand: {n} ⭐ aus den alten Puzzles", "puzzles.frankfurt_to_singapore_the_short_way":"Frankfurt nach Singapur auf dem kurzen Weg. Der lange führt über Land, und das merkt man.", "puzzles.free":"Gratis", -"puzzles.goal":"Ziel", "puzzles.goal_city":"Zielstadt", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hallo, Welt", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: der malerischste Regenerator-Standort der Welt.", +"puzzles.hub_cap":"Radkappe", "puzzles.includes_a_new_pop_in_city":"Mit neuem POP in {city} ({price} für ein Jahr).", +"puzzles.installed":"verbaut", "puzzles.it_works_finance_and_the_backhoe":"Läuft! Die Buchhaltung und der Bagger hätten da noch Fragen.", "puzzles.keep_building":"Weiterbauen", "puzzles.kiwi_fruit_salad":"Kiwi-Obstsalat", +"puzzles.latency":"Latenz", +"puzzles.latency_caps":"Latenzgrenzen", "puzzles.lease_a_wave_to":"Wave mieten nach", "puzzles.loading_this_week_s_puzzle":"Lade das Puzzle dieser Woche…", +"puzzles.london_wants_half_a_terabit_your":"London will ein halbes Terabit, und deine Router sind von eBuy.", +"puzzles.model_facts":"{cap} · {ports} Ports · Waves bis {wave}", "puzzles.more_puzzles":"Mehr Puzzles", "puzzles.n_1_club":"N-1-Club", -"puzzles.n_1_connect_everything_first":"N-1: erst alles verbinden", -"puzzles.n_g_links":"{n}G-Links", +"puzzles.n_1_deliver_everything_first":"N-1: erst alles liefern", +"puzzles.n_circuits":{"one":"{n} Leitung","other":"{n} Leitungen"}, +"puzzles.n_g_of_eyeballs":"{n} Privatkunden", +"puzzles.n_links_on_this_pair":"{n} Links auf diesem Paar: {what}", "puzzles.n_stars_left_in_this_pack":{"one":"Noch {n} ⭐ in diesem Paket","other":"Noch {n} ⭐ in diesem Paket"}, "puzzles.n_week_streak":{"one":"{n} Woche in Folge","other":"{n} Wochen in Folge"}, +"puzzles.needs_what":"braucht {what}", "puzzles.new_this_sunday":"Neu diesen Sonntag!", "puzzles.new_zealand_is_far_from_everything":"Neuseeland ist weit weg von allem. Genau das ist der Witz, und das Problem.", "puzzles.next_pack_unlocks_at_n":"Nächstes Paket, {pack}, ab {n}⭐", @@ -2967,26 +2989,31 @@ "puzzles.no_budget":"kein Budget", "puzzles.no_budget_star_on_the_house":"kein Budget: ⭐ geht aufs Haus", "puzzles.no_cable_lands_in_both_try":"Kein Kabel landet in {a} und {b}. Versuch es mit einem Trittstein dazwischen.", -"puzzles.no_clock_no_bills_nothing_breaks":"Keine Uhr, keine Rechnungen, nichts geht kaputt. Verbinde die Städte und hol dir drei Sterne: unter Budget, und noch verbunden, wenn irgendein Link durchtrennt wird.", +"puzzles.no_clock_no_bills_real_traffic":"Keine Uhr, keine Rechnungen, nichts geht kaputt. Echter Traffic, geroutet wie im echten Spiel: Liefere jeden Flow, bleib im Budget, und halt alles am Laufen, wenn irgendein Graben oder Kabel gekappt wird.", +"puzzles.no_free_ports_in_list":"Keine freien Router-Ports in {list}: erst einen Router oder ein größeres Modell dazu.", "puzzles.no_subsea":"kein Seekabel", "puzzles.no_subsea_cables":"Keine Seekabel", -"puzzles.nobody_ever_got_fired_for_buying":"Für 100G ist noch nie jemand gefeuert worden.", +"puzzles.no_traffic_starts_or_ends_here":"Hier fängt kein Traffic an und keiner hört auf. Bauen darfst du trotzdem, wenn es dich weiterbringt.", +"puzzles.not_a_city_you_can_build_in":"In dieser Stadt kannst du nicht bauen.", +"puzzles.not_in_the_plan":"Nicht im Plan", "puzzles.not_this_one_find_a_way_around":"Die nicht. Such dir einen Weg drumherum.", "puzzles.not_through_frankfurt":"Nicht über Frankfurt", "puzzles.off_limits":"Tabu", "puzzles.on_the_house":"Aufs Haus", "puzzles.one_backhoe_away_from_a_very":"Ein Bagger trennt dich von einer sehr langen Nacht. Ein zweiter Weg gibt ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Ein Schnitt trennt es", -"puzzles.one_cut_splits_it_where":"Ein Schnitt trennt es: {where}", "puzzles.one_ring_through_every_pop":"Ein Ring durch jeden POP", "puzzles.one_very_big_island_and_a":"Eine sehr große Insel und sehr viel sehr leere Glasfaser.", "puzzles.open_a_pop_cost":"POP eröffnen · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping-Pong nach Tokio", +"puzzles.or_drag_to_any_city_on_the_map":"Oder zieh zu irgendeiner Stadt auf der Karte: Die ganze Welt ist offen.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris will 150G. Eine 100G-Wave ist ein Gartenschlauch.", +"puzzles.port_authority":"Hafenbehörde", +"puzzles.ports":"Ports", "puzzles.price_per_year":"{price}/Jahr", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle gelöst", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Die Puzzles haben jetzt Traffic! Jedes Puzzle transportiert echte Flows, deshalb fangen die Sterne neu an. Deine alten {n} ⭐ hängen gerahmt an der Wand.", +"puzzles.remove_a_router":"Einen Router weg", "puzzles.remove_this_link":"Diesen Link entfernen", "puzzles.remove_this_pop":"Diesen POP entfernen", "puzzles.reset":"Zurücksetzen", @@ -2994,41 +3021,49 @@ "puzzles.ring":"Ring", "puzzles.ring_of_fire":"Ring of Fire", "puzzles.rock_solid_and_gold_plated_the":"Felsenfest und vergoldet. Der CFO hat Fragen.", +"puzzles.router_load":"Router-Last", +"puzzles.router_model":"Router-Modell", +"puzzles.router_rodeo":"Router-Rodeo", +"puzzles.routers_have_ports_and_a_limit":"Router haben Ports und ein Limit. Ist einer voll, bleibt der Traffic vor der Tür.", "puzzles.rule_not_via_list":"Regel: nicht über {list}", "puzzles.samba_sprint":"Samba-Sprint", +"puzzles.same_cable_same_anchor":"Dasselbe Kabel wie ein Link, den du schon hast: Ein Anker erwischt beide.", "puzzles.same_puzzle_for_everyone_this_week":"Diese Woche für alle dasselbe Puzzle", +"puzzles.same_trench_cheaper":"Gleicher Graben (günstiger)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Gleicher Graben (billiger, ein Bagger kappt beide)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo nach Miami, bevor der Caipirinha warm wird.", "puzzles.sea_to_shining_sea":"Von Küste zu Küste", -"puzzles.seattle_to_singapore_with_a_stop":"Seattle nach Singapur, mit Zwischenstopp für Sushi und Dim Sum.", "puzzles.share_line":"Series of Tubes Puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Sechs Städte, je ein paar Gigabit, und ein Router mit acht Ports. Erst zählen, dann graben.", "puzzles.size":"Größe", -"puzzles.small_calm_network_builds":"Kleine, entspannte Netzbauten", -"puzzles.smorgasbord":"Smörgåsbord", -"puzzles.so_close_one_more_link_and":"Fast: noch ein Link, und kein Bagger kann dir was.", -"puzzles.speed_runs":"Speedruns", +"puzzles.small_networks_real_traffic":"Kleine Netze, echter Traffic", "puzzles.spent_x":"Ausgegeben {x}", "puzzles.spent_x_of_y":"Ausgegeben {x} / {y}", "puzzles.stepping_stone_optional":"Trittstein (optional)", "puzzles.suez_you_later":"Suez bald", -"puzzles.survives_any_single_cut":"Übersteht jeden einzelnen Schnitt", +"puzzles.survive_any_single_cut_with_the":"Überleb jeden einzelnen Schnitt, und der Traffic fließt weiter. Verbunden sein reicht nicht.", +"puzzles.survives_any_single_cut_under_load":"Übersteht jeden einzelnen Schnitt, unter Last", "puzzles.tap_a_goal_city_to_open":"Tipp auf eine leuchtende Stadt für deinen ersten POP", -"puzzles.that_city_is_not_part_of":"Diese Stadt gehört nicht zu diesem Puzzle.", -"puzzles.the_pacific_is_big_light_is":"Der Pazifik ist groß. Licht ist schnell. Dein Budget ist beides nicht.", -"puzzles.the_pacific_rim_where_every_hop":"Der Pazifikrand, wo jeder Hop ein Ozean ist.", +"puzzles.the_content_origin_lives_here":"Hier liegen die Inhalte. Privatkunden anderswo ziehen von hier.", +"puzzles.the_oil_rigs_want_their_numbers":"Die Bohrinseln wollen ihre Zahlen schnell. Der kürzeste Weg nach Stavanger ist nicht der schnellste.", +"puzzles.the_road_to_tallinn_is_short":"Der Weg nach Tallinn ist kurz. Das Licht über Helsinki ist kürzer.", "puzzles.the_shark_tank":"Das Haifischbecken", "puzzles.the_sharks_have_been_biting_again":"Die Haie haben wieder zugebissen. Bleib auf dem Trockenen.", "puzzles.the_sharks_say_no":"Die Haie sagen nein.", +"puzzles.this_link":"Dieser Link", "puzzles.three_cities_two_currencies_one_very":"Drei Städte, zwei Währungen, ein sehr kurzer Tunnel unter dem Meer.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Trader haben Millionen bezahlt, um hier Millisekunden zu sparen. Du schaffst es billiger.", +"puzzles.traffic_cops":"Verkehrspolizei", +"puzzles.trench_n":"Graben {n}", "puzzles.two_cables_across_the_atlantic_because":"Zwei Kabel über den Atlantik, denn eins ist eine Hoffnung, kein Plan.", -"puzzles.under_n_ms":"unter {n} ms", +"puzzles.u_of_m_used":"{u} von {m} belegt", "puzzles.undo":"Rückgängig", "puzzles.unlocks_at_n_stars":"Ab {n}⭐", "puzzles.weekly_puzzle":"Wochenpuzzle", "puzzles.weekly_puzzle_key":"Wochenpuzzle {key}", "puzzles.with_the_pop_price":"mit POP: {price}", -"puzzles.your_first_tubes_roomy_budgets":"Deine ersten Röhren. Großzügige Budgets, und die ersten zwei gehen aufs Haus.", +"puzzles.your_pop":"Dein POP", +"puzzles.your_routers_pick_the_path":"Deine Router wählen den Weg. Sag ihnen welchen: Metriken, niedrigste Latenz, Best Effort.", "puzzles.your_stars":"Deine Sterne", "puzzles_weekly.detour":"Umleitung", "puzzles_weekly.island_hopping":"Inselhüpfen", diff --git a/site/i18n/es.js b/site/i18n/es.js index 3f3a819..d300f54 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2906,56 +2906,78 @@ "progress.your_score_peak_traffic":"Tu puntuación: tráfico pico", "progress.your_traffic_to_and_from_asia":"Tu tráfico desde y hacia Asia", "puzzles.a_backhoe_walks_into_your_network":"Una retroexcavadora entra en tu red. No pasa nada.", +"puzzles.a_bigger_boat":"Necesitaremos un barco más grande", +"puzzles.a_cut_on_where_drops_g":"Un corte en {where} tira {g}", +"puzzles.a_different_route":"Otra ruta", +"puzzles.a_diverse_route":"Una ruta diversa (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Un POP cuesta {setup} de instalación y luego {mo}/mes. Los puzles cuentan la instalación y un año de alquiler.", -"puzzles.a_tiny_island_where_half_the":"Una isla diminuta donde medio Pacífico de cables para a tomar café.", -"puzzles.a_to_b_under_ms":"{a} → {b} en menos de {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} en menos de {ms} ms (ahora {now} ms)", -"puzzles.aloha_latency":"Aloha, latencia", +"puzzles.add_a_router_cost":"Añadir un router {cost}/año", +"puzzles.add_another_link_here":"Añadir otro enlace en este par", +"puzzles.all_of_europe_s_cat_videos":"Todos los vídeos de gatos de Europa viven en Londres, y todos pasan por tu router.", +"puzzles.already_here_list":"Ya en este par: {list}", +"puzzles.another_wave_on_this_cable":"Otra wave en este cable", "puzzles.avoid_list":"sin {list}", "puzzles.back_to_my_network":"Volver a mi red", "puzzles.back_to_the_title":"Volver a la pantalla de inicio", -"puzzles.beat_the_clock_light_in_glass":"La luz en la fibra hace 200 km por milisegundo. Elige tus cables como si importara.", +"puzzles.baltic_shortcut":"Atajo báltico", "puzzles.belt_and_braces":"Cinturón y tirantes", +"puzzles.best_effort":"best effort", "puzzles.best_x":"mejor {x}", +"puzzles.biggest_wave":"Wave más grande", "puzzles.budget":"Presupuesto", "puzzles.budget_x":"presupuesto {x}", -"puzzles.connect_list":"Conecta {list}.", -"puzzles.connected":"Conectado", +"puzzles.capacity_first_every_link_has_a":"Primero la capacidad: cada enlace tiene un tamaño y el tráfico tiene que caber. Presupuestos holgados, y los dos primeros invita la casa.", +"puzzles.carry_list":"A transportar: {list}.", +"puzzles.carrying":"Transporta", +"puzzles.carrying_on_this_pair":"Transporta (los {n} enlaces de este par)", +"puzzles.content_lives_in_list":"El contenido vive en {list}: los usuarios tiran del más cercano.", "puzzles.copied_paste_it_anywhere":"¡Copiado! Pégalo donde quieras:
{t}", "puzzles.de_kicks_sales_has_your_number":"Ventas de DE-KICKS tiene tu número. Conecta Alemania sin pasar por Fráncfort.", +"puzzles.delivered":"Entregado", "puzzles.diverse_route_40_survives_a_backhoe":"Ruta diversa (+40 %, sobrevive a una retroexcavadora)", "puzzles.down_under_up_and_running":"Down Under, en marcha", "puzzles.drag_from_a_pink_pop_to":"Arrastra desde un POP rosa a otra ciudad para alquilar una onda", "puzzles.drag_from_this_pop_onto_another":"Arrastra desde este POP a otra ciudad del puzle, o elige una aquí.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"cada bit llega", "puzzles.every_internet_starts_with_one_tube":"Todo internet empieza con un tubo.", -"puzzles.every_link_n_g_or_more":"Cada enlace de {n}G o más", "puzzles.every_star_in_this_pack_is":"Todas las estrellas de este paquete son tuyas.", -"puzzles.fat_pipes_only":"Solo tuberías gordas", +"puzzles.everything_at_once_across_oceans":"Todo a la vez, cruzando océanos. Presupuestos ajustados.", +"puzzles.fat_pipes":"Tubos gordos", +"puzzles.fjord_focus":"Rumbo al fiordo", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Para arquitectos que duermen tranquilos en temporada de retroexcavadoras.", -"puzzles.four_capitals_one_very_long_winter":"Cuatro capitales, un invierno larguísimo y cero excusas para caerse.", +"puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Usuarios en {city}", "puzzles.four_cities_four_cables_one_ring":"Cuatro ciudades, un anillo. Tolkien lo aprobaría; tu NOC, seguro.", "puzzles.four_cities_one_continent_and_a":"Cuatro ciudades, un continente y mucho maíz entre medias.", +"puzzles.framed_n_stars_from_the_old":"Enmarcadas en la pared: {n} ⭐ de los puzles antiguos", "puzzles.frankfurt_to_singapore_the_short_way":"De Fráncfort a Singapur por el camino corto. El largo va por tierra, y se nota.", "puzzles.free":"Gratis", -"puzzles.goal":"Objetivo", "puzzles.goal_city":"Ciudad objetivo", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hola, mundo", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: el sitio de regeneración más bonito del mundo.", +"puzzles.hub_cap":"Tapacubos", "puzzles.includes_a_new_pop_in_city":"Incluye un POP nuevo en {city} ({price} por un año).", +"puzzles.installed":"instalado", "puzzles.it_works_finance_and_the_backhoe":"¡Funciona! Finanzas y la retroexcavadora quieren hablar contigo.", "puzzles.keep_building":"Seguir construyendo", "puzzles.kiwi_fruit_salad":"Macedonia de kiwi", +"puzzles.latency":"Latencia", +"puzzles.latency_caps":"límites de latencia", "puzzles.lease_a_wave_to":"Alquilar una onda hasta", "puzzles.loading_this_week_s_puzzle":"Cargando el puzle de esta semana…", +"puzzles.london_wants_half_a_terabit_your":"Londres quiere medio terabit, y tus routers salieron de eBuy.", +"puzzles.model_facts":"{cap} · {ports} puertos · waves hasta {wave}", "puzzles.more_puzzles":"Más puzles", "puzzles.n_1_club":"Club N-1", -"puzzles.n_1_connect_everything_first":"N-1: primero conéctalo todo", -"puzzles.n_g_links":"enlaces de {n}G", +"puzzles.n_1_deliver_everything_first":"N-1: primero entrégalo todo", +"puzzles.n_circuits":{"one":"{n} circuito","other":"{n} circuitos"}, +"puzzles.n_g_of_eyeballs":"{n} de usuarios", +"puzzles.n_links_on_this_pair":"{n} enlaces en este par: {what}", "puzzles.n_stars_left_in_this_pack":{"one":"Queda {n} ⭐ en este paquete","other":"Quedan {n} ⭐ en este paquete"}, "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, +"puzzles.needs_what":"necesita {what}", "puzzles.new_this_sunday":"¡Nuevo este domingo!", "puzzles.new_zealand_is_far_from_everything":"Nueva Zelanda está lejos de todo. Esa es la gracia, y el problema.", "puzzles.next_pack_unlocks_at_n":"El siguiente pack, {pack}, se desbloquea con {n}⭐", @@ -2965,26 +2987,31 @@ "puzzles.no_budget":"sin presupuesto", "puzzles.no_budget_star_on_the_house":"sin presupuesto: ⭐ invita la casa", "puzzles.no_cable_lands_in_both_try":"Ningún cable llega a {a} y a {b}. Prueba con una escala entre medias.", -"puzzles.no_clock_no_bills_nothing_breaks":"Sin reloj, sin facturas, nada se rompe. Conecta las ciudades y ve a por tres estrellas: bajo presupuesto, y aún conectado si se corta cualquier enlace.", +"puzzles.no_clock_no_bills_real_traffic":"Sin reloj, sin facturas, nada se rompe. Tráfico de verdad, enrutado como en el juego de verdad: entrega cada flujo, no te pases del presupuesto y mantenlo todo en marcha cuando se corte cualquier zanja o cable.", +"puzzles.no_free_ports_in_list":"No quedan puertos libres en el router de {list}: añade un router o un modelo más grande antes.", "puzzles.no_subsea":"sin submarinos", "puzzles.no_subsea_cables":"Sin cables submarinos", -"puzzles.nobody_ever_got_fired_for_buying":"A nadie lo han despedido nunca por comprar 100G.", +"puzzles.no_traffic_starts_or_ends_here":"Aquí no empieza ni termina tráfico. Puedes construir igual, si te lleva a alguna parte.", +"puzzles.not_a_city_you_can_build_in":"No puedes construir en esa ciudad.", +"puzzles.not_in_the_plan":"Fuera del plan", "puzzles.not_this_one_find_a_way_around":"Esta no. Busca otro camino.", "puzzles.not_through_frankfurt":"Sin pasar por Fráncfort", "puzzles.off_limits":"Prohibida", "puzzles.on_the_house":"Invita la casa", "puzzles.one_backhoe_away_from_a_very":"A una retroexcavadora de una noche muy larga. Añade un segundo camino para ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Un corte la parte en dos", -"puzzles.one_cut_splits_it_where":"Un corte la parte en dos: {where}", "puzzles.one_ring_through_every_pop":"Un anillo por todos los POP", "puzzles.one_very_big_island_and_a":"Una isla enorme y muchísima fibra vacía.", "puzzles.open_a_pop_cost":"Abrir un POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping-pong a Tokio", +"puzzles.or_drag_to_any_city_on_the_map":"O arrastra a cualquier ciudad del mapa: el mundo entero está abierto.", +"puzzles.paris_wants_150g_one_100g_wave":"París quiere 150G. Una wave de 100G es una manguera de jardín.", +"puzzles.port_authority":"Autoridad portuaria", +"puzzles.ports":"Puertos", "puzzles.price_per_year":"{price}/año", "puzzles.puzzle":"Puzle", "puzzles.puzzle_solved":"Puzle resuelto", "puzzles.puzzles":"Puzles", +"puzzles.puzzles_got_traffic_note":"¡Los puzles tienen tráfico! Cada puzle transporta ahora flujos de verdad, así que las estrellas empiezan de nuevo. Tus {n} ⭐ antiguas están enmarcadas en la pared.", +"puzzles.remove_a_router":"Quitar un router", "puzzles.remove_this_link":"Quitar este enlace", "puzzles.remove_this_pop":"Quitar este POP", "puzzles.reset":"Reiniciar", @@ -2992,41 +3019,49 @@ "puzzles.ring":"anillo", "puzzles.ring_of_fire":"Anillo de fuego", "puzzles.rock_solid_and_gold_plated_the":"A prueba de bombas, y bañado en oro. El director financiero tiene preguntas.", +"puzzles.router_load":"Carga del router", +"puzzles.router_model":"Modelo de router", +"puzzles.router_rodeo":"Rodeo de routers", +"puzzles.routers_have_ports_and_a_limit":"Los routers tienen puertos y un límite. Llena uno y el tráfico se queda en la puerta.", "puzzles.rule_not_via_list":"Regla: sin pasar por {list}", "puzzles.samba_sprint":"Sprint de samba", +"puzzles.same_cable_same_anchor":"Mismo cable que un enlace que ya tienes: un ancla se lleva los dos.", "puzzles.same_puzzle_for_everyone_this_week":"El mismo puzle para todos esta semana", +"puzzles.same_trench_cheaper":"Misma zanja (más barato)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Misma zanja (más barata, una retroexcavadora corta las dos)", "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes de que se caliente la caipiriña.", "puzzles.sea_to_shining_sea":"De costa a costa", -"puzzles.seattle_to_singapore_with_a_stop":"De Seattle a Singapur, con parada para sushi y dim sum.", "puzzles.share_line":"Series of Tubes puzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Seis ciudades, pocos gigas cada una, y un router con ocho puertos. Cuenta antes de cavar.", "puzzles.size":"Tamaño", -"puzzles.small_calm_network_builds":"Redes pequeñas y tranquilas", -"puzzles.smorgasbord":"Smörgåsbord", -"puzzles.so_close_one_more_link_and":"Casi: un enlace más y ninguna retroexcavadora podrá contigo.", -"puzzles.speed_runs":"Contrarreloj", +"puzzles.small_networks_real_traffic":"Redes pequeñas, tráfico de verdad", "puzzles.spent_x":"Gastado {x}", "puzzles.spent_x_of_y":"Gastado {x} / {y}", "puzzles.stepping_stone_optional":"Escala (opcional)", "puzzles.suez_you_later":"Suez luego", -"puzzles.survives_any_single_cut":"Sobrevive a cualquier corte", +"puzzles.survive_any_single_cut_with_the":"Sobrevive a cualquier corte, con el tráfico todavía fluyendo. Estar conectado no basta.", +"puzzles.survives_any_single_cut_under_load":"Aguanta cualquier corte, con carga", "puzzles.tap_a_goal_city_to_open":"Toca una ciudad brillante para abrir tu primer POP", -"puzzles.that_city_is_not_part_of":"Esa ciudad no forma parte de este puzle.", -"puzzles.the_pacific_is_big_light_is":"El Pacífico es grande. La luz es rápida. Tu presupuesto no es ninguna de las dos cosas.", -"puzzles.the_pacific_rim_where_every_hop":"El borde del Pacífico, donde cada salto es un océano.", +"puzzles.the_content_origin_lives_here":"Aquí vive el contenido. Los usuarios de otros sitios tiran de aquí.", +"puzzles.the_oil_rigs_want_their_numbers":"Las plataformas quieren sus números rápido. El camino más corto a Stavanger no es el más rápido.", +"puzzles.the_road_to_tallinn_is_short":"El camino a Tallin es corto. La luz por Helsinki, más.", "puzzles.the_shark_tank":"La pecera de tiburones", "puzzles.the_sharks_have_been_biting_again":"Los tiburones vuelven a morder. Quédate en tierra firme.", "puzzles.the_sharks_say_no":"Los tiburones dicen que no.", +"puzzles.this_link":"Este enlace", "puzzles.three_cities_two_currencies_one_very":"Tres ciudades, dos monedas y un túnel muy corto bajo el mar.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Los traders pagaron millones por arañar milisegundos a esta ruta. Tú lo harás por menos.", +"puzzles.traffic_cops":"Guardias de tráfico", +"puzzles.trench_n":"zanja {n}", "puzzles.two_cables_across_the_atlantic_because":"Dos cables cruzando el Atlántico, porque uno es una esperanza, no un plan.", -"puzzles.under_n_ms":"menos de {n} ms", +"puzzles.u_of_m_used":"{u} de {m} en uso", "puzzles.undo":"Deshacer", "puzzles.unlocks_at_n_stars":"Se desbloquea con {n}⭐", "puzzles.weekly_puzzle":"Puzle semanal", "puzzles.weekly_puzzle_key":"Puzle semanal {key}", "puzzles.with_the_pop_price":"con el POP: {price}", -"puzzles.your_first_tubes_roomy_budgets":"Tus primeros tubos. Presupuestos holgados, y los dos primeros invita la casa.", +"puzzles.your_pop":"Tu POP", +"puzzles.your_routers_pick_the_path":"Tus routers eligen el camino. Diles cuál: métricas, menor latencia, best effort.", "puzzles.your_stars":"Tus estrellas", "puzzles_weekly.detour":"Desvío", "puzzles_weekly.island_hopping":"De isla en isla", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index acdf746..b84b1a5 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2906,56 +2906,78 @@ "progress.your_score_peak_traffic":"Ton score : pic de trafic", "progress.your_traffic_to_and_from_asia":"Ton trafic vers et depuis l’Asie", "puzzles.a_backhoe_walks_into_your_network":"C’est une pelleteuse qui entre dans ton réseau. Il ne se passe rien.", +"puzzles.a_bigger_boat":"Il nous faut un plus gros bateau", +"puzzles.a_cut_on_where_drops_g":"Une coupure sur {where} fait tomber {g}", +"puzzles.a_different_route":"Une autre route", +"puzzles.a_diverse_route":"Une route diverse (+40 %)", "puzzles.a_pop_costs_setup_plus_a_year":"Un POP coûte {setup} à installer, puis {mo}/mois. Les puzzles comptent l’installation et un an de loyer.", -"puzzles.a_tiny_island_where_half_the":"Une île minuscule où la moitié des câbles du Pacifique s’arrêtent pour un café.", -"puzzles.a_to_b_under_ms":"{a} → {b} en moins de {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} en moins de {ms} ms (actuellement {now} ms)", -"puzzles.aloha_latency":"Aloha la latence", +"puzzles.add_a_router_cost":"Ajouter un routeur {cost}/an", +"puzzles.add_another_link_here":"Ajouter un autre lien sur cette paire", +"puzzles.all_of_europe_s_cat_videos":"Toutes les vidéos de chats d'Europe vivent à Londres, et toutes passent par ton routeur.", +"puzzles.already_here_list":"Déjà sur cette paire : {list}", +"puzzles.another_wave_on_this_cable":"Une autre wave sur ce câble", "puzzles.avoid_list":"sans {list}", "puzzles.back_to_my_network":"Retour à mon réseau", "puzzles.back_to_the_title":"Retour à l’écran titre", -"puzzles.beat_the_clock_light_in_glass":"La lumière dans la fibre fait 200 km par milliseconde. Choisis tes câbles comme si ça comptait.", +"puzzles.baltic_shortcut":"Raccourci balte", "puzzles.belt_and_braces":"Ceinture et bretelles", +"puzzles.best_effort":"best effort", "puzzles.best_x":"record {x}", +"puzzles.biggest_wave":"Plus grosse wave", "puzzles.budget":"Budget", "puzzles.budget_x":"budget {x}", -"puzzles.connect_list":"Relie {list}.", -"puzzles.connected":"Relié", +"puzzles.capacity_first_every_link_has_a":"La capacité d'abord : chaque lien a une taille, et le trafic doit y tenir. Budgets confortables, et les deux premiers sont offerts.", +"puzzles.carry_list":"À transporter : {list}.", +"puzzles.carrying":"Transporte", +"puzzles.carrying_on_this_pair":"Transporte (les {n} liens de cette paire)", +"puzzles.content_lives_in_list":"Le contenu vit à {list} : les internautes tirent du plus proche.", "puzzles.copied_paste_it_anywhere":"Copié ! Colle-le où tu veux :
{t}", "puzzles.de_kicks_sales_has_your_number":"Les commerciaux de DE-KICKS ont ton numéro. Relie l’Allemagne sans passer par Francfort.", +"puzzles.delivered":"Livré", "puzzles.diverse_route_40_survives_a_backhoe":"Route diverse (+40 %, survit à une pelleteuse)", "puzzles.down_under_up_and_running":"Down Under, ça tourne", "puzzles.drag_from_a_pink_pop_to":"Glisse depuis un POP rose vers une autre ville pour louer une longueur d’onde", "puzzles.drag_from_this_pop_onto_another":"Glisse depuis ce POP vers une autre ville du puzzle, ou choisis-en une ici.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"chaque bit arrive", "puzzles.every_internet_starts_with_one_tube":"Tout internet commence par un tube.", -"puzzles.every_link_n_g_or_more":"Chaque lien à {n}G ou plus", "puzzles.every_star_in_this_pack_is":"Toutes les étoiles de ce pack sont à toi.", -"puzzles.fat_pipes_only":"Gros tuyaux uniquement", +"puzzles.everything_at_once_across_oceans":"Tout à la fois, par-delà les océans. Budgets serrés.", +"puzzles.fat_pipes":"Gros tuyaux", +"puzzles.fjord_focus":"Cap sur le fjord", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Pour les architectes qui dorment pendant la saison des pelleteuses.", -"puzzles.four_capitals_one_very_long_winter":"Quatre capitales, un très long hiver, zéro excuse pour une panne.", +"puzzles.flow_circuit_a_b":"Circuit {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Internautes à {city}", "puzzles.four_cities_four_cables_one_ring":"Quatre villes, un anneau. Tolkien approuverait ; ton NOC, à coup sûr.", "puzzles.four_cities_one_continent_and_a":"Quatre villes, un continent et beaucoup de maïs entre les deux.", +"puzzles.framed_n_stars_from_the_old":"Encadrées au mur : {n} ⭐ des anciens puzzles", "puzzles.frankfurt_to_singapore_the_short_way":"Francfort–Singapour par le chemin court. Le long passe par la terre, et ça se voit.", "puzzles.free":"Gratuit", -"puzzles.goal":"Objectif", "puzzles.goal_city":"Ville objectif", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hello, World", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu : le site de régénération le plus pittoresque du monde.", +"puzzles.hub_cap":"Enjoliveur", "puzzles.includes_a_new_pop_in_city":"Inclut un nouveau POP à {city} ({price} pour un an).", +"puzzles.installed":"installé", "puzzles.it_works_finance_and_the_backhoe":"Ça marche ! La compta et la pelleteuse aimeraient te dire un mot.", "puzzles.keep_building":"Continuer à construire", "puzzles.kiwi_fruit_salad":"Salade de kiwis", +"puzzles.latency":"Latence", +"puzzles.latency_caps":"plafonds de latence", "puzzles.lease_a_wave_to":"Louer une longueur d’onde vers", "puzzles.loading_this_week_s_puzzle":"Chargement du puzzle de la semaine…", +"puzzles.london_wants_half_a_terabit_your":"Londres veut un demi-térabit, et tes routeurs viennent d'eBuy.", +"puzzles.model_facts":"{cap} · {ports} ports · waves jusqu'à {wave}", "puzzles.more_puzzles":"Plus de puzzles", "puzzles.n_1_club":"Club N-1", -"puzzles.n_1_connect_everything_first":"N-1 : relie d’abord tout", -"puzzles.n_g_links":"liens {n}G", +"puzzles.n_1_deliver_everything_first":"N-1 : livre tout d'abord", +"puzzles.n_circuits":{"one":"{n} circuit","other":"{n} circuits"}, +"puzzles.n_g_of_eyeballs":"{n} d'internautes", +"puzzles.n_links_on_this_pair":"{n} liens sur cette paire : {what}", "puzzles.n_stars_left_in_this_pack":{"one":"Encore {n} ⭐ dans ce pack","other":"Encore {n} ⭐ dans ce pack"}, "puzzles.n_week_streak":{"one":"{n} semaine d’affilée","other":"{n} semaines d’affilée"}, +"puzzles.needs_what":"il faut {what}", "puzzles.new_this_sunday":"Nouveau ce dimanche !", "puzzles.new_zealand_is_far_from_everything":"La Nouvelle-Zélande est loin de tout. C’est tout l’intérêt, et tout le problème.", "puzzles.next_pack_unlocks_at_n":"Prochain pack, {pack}, à {n}⭐", @@ -2965,26 +2987,31 @@ "puzzles.no_budget":"sans budget", "puzzles.no_budget_star_on_the_house":"sans budget : ⭐ offerte par la maison", "puzzles.no_cable_lands_in_both_try":"Aucun câble n’atterrit à la fois à {a} et à {b}. Essaie une escale entre les deux.", -"puzzles.no_clock_no_bills_nothing_breaks":"Pas d’horloge, pas de factures, rien ne casse. Relie les villes, puis vise trois étoiles : sous le budget, et toujours relié si n’importe quel lien est coupé.", +"puzzles.no_clock_no_bills_real_traffic":"Pas d'horloge, pas de factures, rien ne casse. Du vrai trafic, routé comme dans le vrai jeu : livre chaque flux, reste dans le budget, et garde tout en marche quand une tranchée ou un câble est coupé.", +"puzzles.no_free_ports_in_list":"Plus de port libre sur le routeur à {list} : ajoute un routeur ou un plus gros modèle d'abord.", "puzzles.no_subsea":"pas de sous-marin", "puzzles.no_subsea_cables":"Pas de câbles sous-marins", -"puzzles.nobody_ever_got_fired_for_buying":"Personne ne s’est jamais fait virer pour avoir acheté du 100G.", +"puzzles.no_traffic_starts_or_ends_here":"Aucun trafic ne part ni n'arrive ici. Tu peux quand même construire, si ça te mène quelque part.", +"puzzles.not_a_city_you_can_build_in":"Impossible de construire dans cette ville.", +"puzzles.not_in_the_plan":"Hors du plan", "puzzles.not_this_one_find_a_way_around":"Pas celle-là. Trouve un détour.", "puzzles.not_through_frankfurt":"Pas par Francfort", "puzzles.off_limits":"Interdite", "puzzles.on_the_house":"Offert par la maison", "puzzles.one_backhoe_away_from_a_very":"À une pelleteuse d’une très longue nuit. Ajoute un deuxième chemin pour ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Une coupure le divise", -"puzzles.one_cut_splits_it_where":"Une coupure le divise : {where}", "puzzles.one_ring_through_every_pop":"Un anneau qui passe par chaque POP", "puzzles.one_very_big_island_and_a":"Une très grande île, et beaucoup de fibre très vide.", "puzzles.open_a_pop_cost":"Ouvrir un POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping-pong jusqu’à Tokyo", +"puzzles.or_drag_to_any_city_on_the_map":"Ou glisse vers n'importe quelle ville de la carte : le monde entier est ouvert.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris veut 150G. Une wave de 100G, c'est un tuyau d'arrosage.", +"puzzles.port_authority":"Autorité portuaire", +"puzzles.ports":"Ports", "puzzles.price_per_year":"{price}/an", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle résolu", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Les puzzles ont du trafic ! Chaque puzzle transporte maintenant de vrais flux, alors les étoiles repartent de zéro. Tes {n} ⭐ d'avant sont encadrées au mur.", +"puzzles.remove_a_router":"Retirer un routeur", "puzzles.remove_this_link":"Supprimer ce lien", "puzzles.remove_this_pop":"Supprimer ce POP", "puzzles.reset":"Recommencer", @@ -2992,41 +3019,49 @@ "puzzles.ring":"anneau", "puzzles.ring_of_fire":"Ceinture de feu", "puzzles.rock_solid_and_gold_plated_the":"Solide comme un roc, et plaqué or. Le DAF a des questions.", +"puzzles.router_load":"Charge du routeur", +"puzzles.router_model":"Modèle de routeur", +"puzzles.router_rodeo":"Rodéo des routeurs", +"puzzles.routers_have_ports_and_a_limit":"Les routeurs ont des ports et une limite. Remplis-en un et le trafic s'arrête à la porte.", "puzzles.rule_not_via_list":"Règle : pas par {list}", "puzzles.samba_sprint":"Sprint samba", +"puzzles.same_cable_same_anchor":"Même câble qu'un lien que tu as : une ancre emporte les deux.", "puzzles.same_puzzle_for_everyone_this_week":"Le même puzzle pour tout le monde cette semaine", +"puzzles.same_trench_cheaper":"Même tranchée (moins cher)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Même tranchée (moins cher, une pelleteuse coupe les deux)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo–Miami avant que la caïpirinha ne tiédisse.", "puzzles.sea_to_shining_sea":"D’une côte à l’autre", -"puzzles.seattle_to_singapore_with_a_stop":"Seattle–Singapour, avec une escale sushis et dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Six villes, quelques gigas chacune, et un routeur à huit ports. Compte avant de creuser.", "puzzles.size":"Taille", -"puzzles.small_calm_network_builds":"Petits réseaux, tranquillement", -"puzzles.smorgasbord":"Smörgåsbord", -"puzzles.so_close_one_more_link_and":"Presque : encore un lien et aucune pelleteuse ne pourra rien contre toi.", -"puzzles.speed_runs":"Contre la montre", +"puzzles.small_networks_real_traffic":"Petits réseaux, vrai trafic", "puzzles.spent_x":"Dépensé {x}", "puzzles.spent_x_of_y":"Dépensé {x} / {y}", "puzzles.stepping_stone_optional":"Escale (facultative)", "puzzles.suez_you_later":"Suez la prochaine", -"puzzles.survives_any_single_cut":"Survit à n’importe quelle coupure", +"puzzles.survive_any_single_cut_with_the":"Survis à n'importe quelle coupure, avec le trafic qui passe toujours. Être connecté ne suffit pas.", +"puzzles.survives_any_single_cut_under_load":"Tient n'importe quelle coupure, en charge", "puzzles.tap_a_goal_city_to_open":"Touche une ville lumineuse pour ouvrir ton premier POP", -"puzzles.that_city_is_not_part_of":"Cette ville ne fait pas partie de ce puzzle.", -"puzzles.the_pacific_is_big_light_is":"Le Pacifique est grand. La lumière est rapide. Ton budget n’est ni l’un ni l’autre.", -"puzzles.the_pacific_rim_where_every_hop":"Le pourtour du Pacifique, où chaque saut est un océan.", +"puzzles.the_content_origin_lives_here":"Le contenu vit ici. Les internautes d'ailleurs tirent d'ici.", +"puzzles.the_oil_rigs_want_their_numbers":"Les plateformes veulent leurs chiffres vite. La route la plus courte vers Stavanger n'est pas la plus rapide.", +"puzzles.the_road_to_tallinn_is_short":"La route vers Tallinn est courte. La lumière via Helsinki l'est encore plus.", "puzzles.the_shark_tank":"L’aquarium à requins", "puzzles.the_sharks_have_been_biting_again":"Les requins ont encore mordu. Reste sur la terre ferme.", "puzzles.the_sharks_say_no":"Les requins disent non.", +"puzzles.this_link":"Ce lien", "puzzles.three_cities_two_currencies_one_very":"Trois villes, deux monnaies, un tout petit tunnel sous la mer.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Des traders ont payé des millions pour gratter des millisecondes sur cette route. Toi, tu le fais pour moins cher.", +"puzzles.traffic_cops":"Agents de la circulation", +"puzzles.trench_n":"tranchée {n}", "puzzles.two_cables_across_the_atlantic_because":"Deux câbles à travers l’Atlantique, parce qu’un seul, c’est un espoir, pas un plan.", -"puzzles.under_n_ms":"moins de {n} ms", +"puzzles.u_of_m_used":"{u} sur {m} utilisés", "puzzles.undo":"Annuler", "puzzles.unlocks_at_n_stars":"À partir de {n}⭐", "puzzles.weekly_puzzle":"Puzzle de la semaine", "puzzles.weekly_puzzle_key":"Puzzle de la semaine {key}", "puzzles.with_the_pop_price":"avec le POP : {price}", -"puzzles.your_first_tubes_roomy_budgets":"Tes premiers tubes. Des budgets confortables, et les deux premiers sont offerts par la maison.", +"puzzles.your_pop":"Ton POP", +"puzzles.your_routers_pick_the_path":"Tes routeurs choisissent le chemin. Dis-leur lequel : métriques, latence minimale, best effort.", "puzzles.your_stars":"Tes étoiles", "puzzles_weekly.detour":"Détour", "puzzles_weekly.island_hopping":"Saut d’île en île", diff --git a/site/i18n/it.js b/site/i18n/it.js index f959550..94f2d17 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2906,56 +2906,78 @@ "progress.your_score_peak_traffic":"Il tuo punteggio: picco di traffico", "progress.your_traffic_to_and_from_asia":"Il tuo traffico da e per l’Asia", "puzzles.a_backhoe_walks_into_your_network":"Una ruspa entra nella tua rete. Non succede niente.", +"puzzles.a_bigger_boat":"Ci serve una barca più grande", +"puzzles.a_cut_on_where_drops_g":"Un taglio su {where} perde {g}", +"puzzles.a_different_route":"Un altro percorso", +"puzzles.a_diverse_route":"Un percorso diverso (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Un POP costa {setup} di attivazione, poi {mo}/mese. I puzzle contano l’attivazione e un anno di canone.", -"puzzles.a_tiny_island_where_half_the":"Un’isoletta dove metà dei cavi del Pacifico si ferma per un caffè.", -"puzzles.a_to_b_under_ms":"{a} → {b} sotto i {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} sotto i {ms} ms (ora {now} ms)", -"puzzles.aloha_latency":"Aloha latenza", +"puzzles.add_a_router_cost":"Aggiungi un router {cost}/anno", +"puzzles.add_another_link_here":"Aggiungi un altro link su questa coppia", +"puzzles.all_of_europe_s_cat_videos":"Tutti i video di gatti d'Europa vivono a Londra, e passano tutti dal tuo router.", +"puzzles.already_here_list":"Già su questa coppia: {list}", +"puzzles.another_wave_on_this_cable":"Un'altra wave su questo cavo", "puzzles.avoid_list":"senza {list}", "puzzles.back_to_my_network":"Torna alla mia rete", "puzzles.back_to_the_title":"Torna alla schermata iniziale", -"puzzles.beat_the_clock_light_in_glass":"La luce nella fibra fa 200 km al millisecondo. Scegli i cavi come se contasse.", +"puzzles.baltic_shortcut":"Scorciatoia baltica", "puzzles.belt_and_braces":"Cintura e bretelle", +"puzzles.best_effort":"best effort", "puzzles.best_x":"record {x}", +"puzzles.biggest_wave":"Wave più grande", "puzzles.budget":"Budget", "puzzles.budget_x":"budget {x}", -"puzzles.connect_list":"Collega {list}.", -"puzzles.connected":"Collegato", +"puzzles.capacity_first_every_link_has_a":"Prima la capacità: ogni link ha una taglia, e il traffico deve starci. Budget comodi, e i primi due li offre la casa.", +"puzzles.carry_list":"Da trasportare: {list}.", +"puzzles.carrying":"Trasporta", +"puzzles.carrying_on_this_pair":"Trasporta (tutti i {n} link di questa coppia)", +"puzzles.content_lives_in_list":"I contenuti vivono a {list}: gli utenti pescano dal più vicino.", "puzzles.copied_paste_it_anywhere":"Copiato! Incollalo dove vuoi:
{t}", "puzzles.de_kicks_sales_has_your_number":"Il commerciale di DE-KICKS ha il tuo numero. Collega la Germania senza passare da Francoforte.", +"puzzles.delivered":"Consegnato", "puzzles.diverse_route_40_survives_a_backhoe":"Percorso diverso (+40%, sopravvive a una ruspa)", "puzzles.down_under_up_and_running":"Down Under, operativi", "puzzles.drag_from_a_pink_pop_to":"Trascina da un POP rosa a un’altra città per noleggiare una wave", "puzzles.drag_from_this_pop_onto_another":"Trascina da questo POP su un’altra città del puzzle, o scegline una qui.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"ogni bit arriva", "puzzles.every_internet_starts_with_one_tube":"Ogni internet comincia con un tubo.", -"puzzles.every_link_n_g_or_more":"Ogni link da {n}G o più", "puzzles.every_star_in_this_pack_is":"Tutte le stelle di questo pacchetto sono tue.", -"puzzles.fat_pipes_only":"Solo tubi grossi", +"puzzles.everything_at_once_across_oceans":"Tutto insieme, oltre gli oceani. Budget stretti.", +"puzzles.fat_pipes":"Tubi grossi", +"puzzles.fjord_focus":"Fuoco sul fiordo", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Per architetti che dormono sonni tranquilli nella stagione delle ruspe.", -"puzzles.four_capitals_one_very_long_winter":"Quattro capitali, un inverno lunghissimo, zero scuse per i disservizi.", +"puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Utenti a {city}", "puzzles.four_cities_four_cables_one_ring":"Quattro città, un anello. Tolkien approverebbe; il tuo NOC di sicuro.", "puzzles.four_cities_one_continent_and_a":"Quattro città, un continente e tantissimo mais in mezzo.", +"puzzles.framed_n_stars_from_the_old":"Incorniciate sul muro: {n} ⭐ dei vecchi puzzle", "puzzles.frankfurt_to_singapore_the_short_way":"Da Francoforte a Singapore per la via corta. Quella lunga è via terra, e si vede.", "puzzles.free":"Gratis", -"puzzles.goal":"Obiettivo", "puzzles.goal_city":"Città obiettivo", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Ciao, mondo", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: il sito di rigenerazione più panoramico del mondo.", +"puzzles.hub_cap":"Coprimozzo", "puzzles.includes_a_new_pop_in_city":"Include un nuovo POP a {city} ({price} per un anno).", +"puzzles.installed":"installato", "puzzles.it_works_finance_and_the_backhoe":"Funziona! L’amministrazione e la ruspa vorrebbero parlarti.", "puzzles.keep_building":"Continua a costruire", "puzzles.kiwi_fruit_salad":"Macedonia di kiwi", +"puzzles.latency":"Latenza", +"puzzles.latency_caps":"limiti di latenza", "puzzles.lease_a_wave_to":"Noleggia una wave verso", "puzzles.loading_this_week_s_puzzle":"Carico il puzzle della settimana…", +"puzzles.london_wants_half_a_terabit_your":"Londra vuole mezzo terabit, e i tuoi router vengono da eBuy.", +"puzzles.model_facts":"{cap} · {ports} porte · wave fino a {wave}", "puzzles.more_puzzles":"Altri puzzle", "puzzles.n_1_club":"Club N-1", -"puzzles.n_1_connect_everything_first":"N-1: prima collega tutto", -"puzzles.n_g_links":"link da {n}G", +"puzzles.n_1_deliver_everything_first":"N-1: prima consegna tutto", +"puzzles.n_circuits":{"one":"{n} circuito","other":"{n} circuiti"}, +"puzzles.n_g_of_eyeballs":"{n} di utenti", +"puzzles.n_links_on_this_pair":"{n} link su questa coppia: {what}", "puzzles.n_stars_left_in_this_pack":{"one":"Ancora {n} ⭐ in questo pacchetto","other":"Ancora {n} ⭐ in questo pacchetto"}, "puzzles.n_week_streak":{"one":"{n} settimana di fila","other":"{n} settimane di fila"}, +"puzzles.needs_what":"servono {what}", "puzzles.new_this_sunday":"Nuovo questa domenica!", "puzzles.new_zealand_is_far_from_everything":"La Nuova Zelanda è lontana da tutto. È proprio questo il bello, e il problema.", "puzzles.next_pack_unlocks_at_n":"Il prossimo pacchetto, {pack}, si sblocca a {n}⭐", @@ -2965,26 +2987,31 @@ "puzzles.no_budget":"senza budget", "puzzles.no_budget_star_on_the_house":"senza budget: ⭐ offerta dalla casa", "puzzles.no_cable_lands_in_both_try":"Nessun cavo approda sia a {a} che a {b}. Prova con una tappa in mezzo.", -"puzzles.no_clock_no_bills_nothing_breaks":"Niente orologio, niente bollette, non si rompe niente. Collega le città, poi punta alle tre stelle: sotto budget, e ancora collegato se si taglia un link qualsiasi.", +"puzzles.no_clock_no_bills_real_traffic":"Niente orologio, niente bollette, non si rompe niente. Traffico vero, instradato come nel gioco vero: consegna ogni flusso, resta nel budget, e tieni tutto in piedi quando si taglia una qualsiasi trincea o cavo.", +"puzzles.no_free_ports_in_list":"Nessuna porta libera sul router a {list}: aggiungi un router o un modello più grande.", "puzzles.no_subsea":"niente sottomarini", "puzzles.no_subsea_cables":"Niente cavi sottomarini", -"puzzles.nobody_ever_got_fired_for_buying":"Nessuno è mai stato licenziato per aver comprato 100G.", +"puzzles.no_traffic_starts_or_ends_here":"Qui non parte né arriva traffico. Puoi costruire lo stesso, se ti porta da qualche parte.", +"puzzles.not_a_city_you_can_build_in":"In quella città non puoi costruire.", +"puzzles.not_in_the_plan":"Fuori dal piano", "puzzles.not_this_one_find_a_way_around":"Questa no. Trova un altro giro.", "puzzles.not_through_frankfurt":"Non da Francoforte", "puzzles.off_limits":"Vietata", "puzzles.on_the_house":"Offre la casa", "puzzles.one_backhoe_away_from_a_very":"A una ruspa da una nottata lunghissima. Aggiungi un secondo percorso per ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Un taglio la divide", -"puzzles.one_cut_splits_it_where":"Un taglio la divide: {where}", "puzzles.one_ring_through_every_pop":"Un anello che passa per ogni POP", "puzzles.one_very_big_island_and_a":"Un’isola enorme e tantissima fibra vuota.", "puzzles.open_a_pop_cost":"Apri un POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping pong fino a Tokyo", +"puzzles.or_drag_to_any_city_on_the_map":"Oppure trascina su qualsiasi città della mappa: il mondo intero è aperto.", +"puzzles.paris_wants_150g_one_100g_wave":"Parigi vuole 150G. Una wave da 100G è un tubo da giardino.", +"puzzles.port_authority":"Autorità portuale", +"puzzles.ports":"Porte", "puzzles.price_per_year":"{price}/anno", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle risolto", "puzzles.puzzles":"Puzzle", +"puzzles.puzzles_got_traffic_note":"I puzzle hanno il traffico! Ogni puzzle ora trasporta flussi veri, quindi le stelle ripartono da zero. Le tue vecchie {n} ⭐ sono incorniciate sul muro.", +"puzzles.remove_a_router":"Togli un router", "puzzles.remove_this_link":"Rimuovi questo link", "puzzles.remove_this_pop":"Rimuovi questo POP", "puzzles.reset":"Ricomincia", @@ -2992,41 +3019,49 @@ "puzzles.ring":"anello", "puzzles.ring_of_fire":"Cintura di fuoco", "puzzles.rock_solid_and_gold_plated_the":"Solida come una roccia, e placcata d’oro. Il CFO ha delle domande.", +"puzzles.router_load":"Carico del router", +"puzzles.router_model":"Modello di router", +"puzzles.router_rodeo":"Rodeo dei router", +"puzzles.routers_have_ports_and_a_limit":"I router hanno porte e un limite. Riempine uno e il traffico si ferma alla porta.", "puzzles.rule_not_via_list":"Regola: niente passaggi da {list}", "puzzles.samba_sprint":"Sprint di samba", +"puzzles.same_cable_same_anchor":"Stesso cavo di un link che hai già: un'ancora li prende tutti e due.", "puzzles.same_puzzle_for_everyone_this_week":"Lo stesso puzzle per tutti questa settimana", +"puzzles.same_trench_cheaper":"Stessa trincea (costa meno)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Stesso scavo (più economico, una ruspa li taglia tutti e due)", "puzzles.sao_paulo_to_miami_before_the":"Da São Paulo a Miami prima che la caipirinha si scaldi.", "puzzles.sea_to_shining_sea":"Da costa a costa", -"puzzles.seattle_to_singapore_with_a_stop":"Da Seattle a Singapore, con una sosta per sushi e dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Sei città, pochi giga ciascuna, e un router con otto porte. Conta prima di scavare.", "puzzles.size":"Taglia", -"puzzles.small_calm_network_builds":"Piccole reti, con calma", -"puzzles.smorgasbord":"Smörgåsbord", -"puzzles.so_close_one_more_link_and":"Ci sei quasi: ancora un link e nessuna ruspa può toccarti.", -"puzzles.speed_runs":"Corse contro il tempo", +"puzzles.small_networks_real_traffic":"Reti piccole, traffico vero", "puzzles.spent_x":"Speso {x}", "puzzles.spent_x_of_y":"Speso {x} / {y}", "puzzles.stepping_stone_optional":"Tappa (facoltativa)", "puzzles.suez_you_later":"Suez la prossima", -"puzzles.survives_any_single_cut":"Sopravvive a qualsiasi taglio", +"puzzles.survive_any_single_cut_with_the":"Sopravvivi a qualsiasi taglio, con il traffico che scorre ancora. Essere collegati non basta.", +"puzzles.survives_any_single_cut_under_load":"Regge qualsiasi taglio, sotto carico", "puzzles.tap_a_goal_city_to_open":"Tocca una città illuminata per aprire il tuo primo POP", -"puzzles.that_city_is_not_part_of":"Quella città non fa parte di questo puzzle.", -"puzzles.the_pacific_is_big_light_is":"Il Pacifico è grande. La luce è veloce. Il tuo budget non è né l’uno né l’altro.", -"puzzles.the_pacific_rim_where_every_hop":"Il bordo del Pacifico, dove ogni hop è un oceano.", +"puzzles.the_content_origin_lives_here":"Qui vivono i contenuti. Gli utenti altrove pescano da qui.", +"puzzles.the_oil_rigs_want_their_numbers":"Le piattaforme vogliono i numeri in fretta. La strada più corta per Stavanger non è la più veloce.", +"puzzles.the_road_to_tallinn_is_short":"La strada per Tallinn è corta. La luce via Helsinki è più corta.", "puzzles.the_shark_tank":"La vasca degli squali", "puzzles.the_sharks_have_been_biting_again":"Gli squali hanno ricominciato a mordere. Resta sulla terraferma.", "puzzles.the_sharks_say_no":"Gli squali dicono di no.", +"puzzles.this_link":"Questo link", "puzzles.three_cities_two_currencies_one_very":"Tre città, due valute, un tunnel cortissimo sotto il mare.", "puzzles.traders_paid_millions_to_shave_milliseconds":"I trader hanno pagato milioni per limare millisecondi su questa rotta. Tu ci riesci spendendo meno.", +"puzzles.traffic_cops":"Vigili del traffico", +"puzzles.trench_n":"trincea {n}", "puzzles.two_cables_across_the_atlantic_because":"Due cavi attraverso l’Atlantico, perché uno solo è una speranza, non un piano.", -"puzzles.under_n_ms":"sotto i {n} ms", +"puzzles.u_of_m_used":"{u} di {m} in uso", "puzzles.undo":"Annulla", "puzzles.unlocks_at_n_stars":"Si sblocca a {n}⭐", "puzzles.weekly_puzzle":"Puzzle della settimana", "puzzles.weekly_puzzle_key":"Puzzle della settimana {key}", "puzzles.with_the_pop_price":"con il POP: {price}", -"puzzles.your_first_tubes_roomy_budgets":"I tuoi primi tubi. Budget comodi, e i primi due li offre la casa.", +"puzzles.your_pop":"Il tuo POP", +"puzzles.your_routers_pick_the_path":"I tuoi router scelgono il percorso. Digli quale: metriche, latenza minima, best effort.", "puzzles.your_stars":"Le tue stelle", "puzzles_weekly.detour":"Deviazione", "puzzles_weekly.island_hopping":"Di isola in isola", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 1f7e31c..38ee4f2 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2906,56 +2906,78 @@ "progress.your_score_peak_traffic":"Sua pontuação: pico de tráfego", "progress.your_traffic_to_and_from_asia":"Seu tráfego de e para a Ásia", "puzzles.a_backhoe_walks_into_your_network":"Uma retroescavadeira entra na sua rede. Nada acontece.", +"puzzles.a_bigger_boat":"Vamos precisar de um barco maior", +"puzzles.a_cut_on_where_drops_g":"Um corte em {where} derruba {g}", +"puzzles.a_different_route":"Outra rota", +"puzzles.a_diverse_route":"Uma rota diversa (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Um POP custa {setup} de instalação e depois {mo}/mês. Os puzzles contam a instalação e um ano de aluguel.", -"puzzles.a_tiny_island_where_half_the":"Uma ilhota onde metade dos cabos do Pacífico para pra tomar um café.", -"puzzles.a_to_b_under_ms":"{a} → {b} abaixo de {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} abaixo de {ms} ms (agora {now} ms)", -"puzzles.aloha_latency":"Aloha, latência", +"puzzles.add_a_router_cost":"Adicionar um router {cost}/ano", +"puzzles.add_another_link_here":"Adicionar outro link neste par", +"puzzles.all_of_europe_s_cat_videos":"Todos os vídeos de gatos da Europa moram em Londres, e todos passam pelo seu router.", +"puzzles.already_here_list":"Já neste par: {list}", +"puzzles.another_wave_on_this_cable":"Outra wave neste cabo", "puzzles.avoid_list":"sem {list}", "puzzles.back_to_my_network":"Voltar à minha rede", "puzzles.back_to_the_title":"Voltar à tela inicial", -"puzzles.beat_the_clock_light_in_glass":"A luz na fibra faz 200 km por milissegundo. Escolha seus cabos como se isso importasse.", +"puzzles.baltic_shortcut":"Atalho báltico", "puzzles.belt_and_braces":"Cinto e suspensórios", +"puzzles.best_effort":"best effort", "puzzles.best_x":"recorde {x}", +"puzzles.biggest_wave":"Maior wave", "puzzles.budget":"Orçamento", "puzzles.budget_x":"orçamento {x}", -"puzzles.connect_list":"Conecte {list}.", -"puzzles.connected":"Conectado", +"puzzles.capacity_first_every_link_has_a":"Capacidade primeiro: cada link tem um tamanho, e o tráfego tem que caber. Orçamentos folgados, e os dois primeiros são por conta da casa.", +"puzzles.carry_list":"Transporte: {list}.", +"puzzles.carrying":"Transportando", +"puzzles.carrying_on_this_pair":"Transportando (todos os {n} links deste par)", +"puzzles.content_lives_in_list":"O conteúdo mora em {list}: os usuários puxam do mais próximo.", "puzzles.copied_paste_it_anywhere":"Copiado! Cole onde quiser:
{t}", "puzzles.de_kicks_sales_has_your_number":"O comercial da DE-KICKS tem seu número. Conecte a Alemanha sem passar por Frankfurt.", +"puzzles.delivered":"Entregue", "puzzles.diverse_route_40_survives_a_backhoe":"Rota diversa (+40%, sobrevive a uma retroescavadeira)", "puzzles.down_under_up_and_running":"Down Under, no ar", "puzzles.drag_from_a_pink_pop_to":"Arraste de um POP rosa até outra cidade para alugar uma wave", "puzzles.drag_from_this_pop_onto_another":"Arraste deste POP até outra cidade do puzzle, ou escolha uma aqui.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"cada bit chega", "puzzles.every_internet_starts_with_one_tube":"Toda internet começa com um tubo.", -"puzzles.every_link_n_g_or_more":"Todo link com {n}G ou mais", "puzzles.every_star_in_this_pack_is":"Todas as estrelas deste pacote são suas.", -"puzzles.fat_pipes_only":"Só tubos grossos", +"puzzles.everything_at_once_across_oceans":"Tudo de uma vez, atravessando oceanos. Orçamentos apertados.", +"puzzles.fat_pipes":"Canos grossos", +"puzzles.fjord_focus":"Foco no fiorde", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Para arquitetos que dormem tranquilos na temporada das retroescavadeiras.", -"puzzles.four_capitals_one_very_long_winter":"Quatro capitais, um inverno longuíssimo, zero desculpas para cair.", +"puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Usuários em {city}", "puzzles.four_cities_four_cables_one_ring":"Quatro cidades, um anel. Tolkien aprovaria; seu NOC, com certeza.", "puzzles.four_cities_one_continent_and_a":"Quatro cidades, um continente e muito milho no meio.", +"puzzles.framed_n_stars_from_the_old":"Emolduradas na parede: {n} ⭐ dos puzzles antigos", "puzzles.frankfurt_to_singapore_the_short_way":"De Frankfurt a Singapura pelo caminho curto. O longo vai por terra, e dá pra notar.", "puzzles.free":"Grátis", -"puzzles.goal":"Objetivo", "puzzles.goal_city":"Cidade objetivo", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Olá, mundo", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: o ponto de regeneração mais bonito do mundo.", +"puzzles.hub_cap":"Calota", "puzzles.includes_a_new_pop_in_city":"Inclui um POP novo em {city} ({price} por um ano).", +"puzzles.installed":"instalado", "puzzles.it_works_finance_and_the_backhoe":"Funciona! O financeiro e a retroescavadeira querem uma palavrinha.", "puzzles.keep_building":"Continuar construindo", "puzzles.kiwi_fruit_salad":"Salada de kiwi", +"puzzles.latency":"Latência", +"puzzles.latency_caps":"limites de latência", "puzzles.lease_a_wave_to":"Alugar uma wave até", "puzzles.loading_this_week_s_puzzle":"Carregando o puzzle da semana…", +"puzzles.london_wants_half_a_terabit_your":"Londres quer meio terabit, e seus routers vieram do eBuy.", +"puzzles.model_facts":"{cap} · {ports} portas · waves até {wave}", "puzzles.more_puzzles":"Mais puzzles", "puzzles.n_1_club":"Clube N-1", -"puzzles.n_1_connect_everything_first":"N-1: conecte tudo primeiro", -"puzzles.n_g_links":"links de {n}G", +"puzzles.n_1_deliver_everything_first":"N-1: entregue tudo primeiro", +"puzzles.n_circuits":{"one":"{n} circuito","other":"{n} circuitos"}, +"puzzles.n_g_of_eyeballs":"{n} de usuários", +"puzzles.n_links_on_this_pair":"{n} links neste par: {what}", "puzzles.n_stars_left_in_this_pack":{"one":"Falta {n} ⭐ neste pacote","other":"Faltam {n} ⭐ neste pacote"}, "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, +"puzzles.needs_what":"precisa de {what}", "puzzles.new_this_sunday":"Novo neste domingo!", "puzzles.new_zealand_is_far_from_everything":"A Nova Zelândia fica longe de tudo. Essa é a graça, e o problema.", "puzzles.next_pack_unlocks_at_n":"O próximo pacote, {pack}, abre com {n}⭐", @@ -2965,26 +2987,31 @@ "puzzles.no_budget":"sem orçamento", "puzzles.no_budget_star_on_the_house":"sem orçamento: ⭐ por conta da casa", "puzzles.no_cable_lands_in_both_try":"Nenhum cabo chega a {a} e a {b}. Tente uma escala no meio.", -"puzzles.no_clock_no_bills_nothing_breaks":"Sem relógio, sem contas, nada quebra. Conecte as cidades e busque três estrelas: dentro do orçamento, e ainda conectado se qualquer link for cortado.", +"puzzles.no_clock_no_bills_real_traffic":"Sem relógio, sem contas, nada quebra. Tráfego de verdade, roteado como no jogo de verdade: entregue cada fluxo, fique no orçamento e mantenha tudo fluindo quando qualquer vala ou cabo for cortado.", +"puzzles.no_free_ports_in_list":"Sem portas livres no router em {list}: adicione um router ou um modelo maior antes.", "puzzles.no_subsea":"sem submarino", "puzzles.no_subsea_cables":"Sem cabos submarinos", -"puzzles.nobody_ever_got_fired_for_buying":"Ninguém nunca foi demitido por comprar 100G.", +"puzzles.no_traffic_starts_or_ends_here":"Nenhum tráfego começa ou termina aqui. Ainda dá para construir, se isso te levar a algum lugar.", +"puzzles.not_a_city_you_can_build_in":"Não dá para construir nessa cidade.", +"puzzles.not_in_the_plan":"Fora do plano", "puzzles.not_this_one_find_a_way_around":"Essa não. Dê a volta.", "puzzles.not_through_frankfurt":"Sem passar por Frankfurt", "puzzles.off_limits":"Proibida", "puzzles.on_the_house":"Por conta da casa", "puzzles.one_backhoe_away_from_a_very":"A uma retroescavadeira de uma noite muito longa. Adicione um segundo caminho para ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Um corte divide a rede", -"puzzles.one_cut_splits_it_where":"Um corte divide a rede: {where}", "puzzles.one_ring_through_every_pop":"Um anel passando por todos os POPs", "puzzles.one_very_big_island_and_a":"Uma ilha enorme e muita fibra vazia.", "puzzles.open_a_pop_cost":"Abrir um POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Pingue-pongue até Tóquio", +"puzzles.or_drag_to_any_city_on_the_map":"Ou arraste para qualquer cidade do mapa: o mundo todo está aberto.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris quer 150G. Uma wave de 100G é uma mangueira de jardim.", +"puzzles.port_authority":"Autoridade portuária", +"puzzles.ports":"Portas", "puzzles.price_per_year":"{price}/ano", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle resolvido", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Os puzzles ganharam tráfego! Cada puzzle agora transporta fluxos de verdade, então as estrelas recomeçam. Suas {n} ⭐ antigas estão emolduradas na parede.", +"puzzles.remove_a_router":"Remover um router", "puzzles.remove_this_link":"Remover este link", "puzzles.remove_this_pop":"Remover este POP", "puzzles.reset":"Recomeçar", @@ -2992,41 +3019,49 @@ "puzzles.ring":"anel", "puzzles.ring_of_fire":"Anel de Fogo", "puzzles.rock_solid_and_gold_plated_the":"Sólida como rocha, e banhada a ouro. O CFO tem perguntas.", +"puzzles.router_load":"Carga do router", +"puzzles.router_model":"Modelo de router", +"puzzles.router_rodeo":"Rodeio dos routers", +"puzzles.routers_have_ports_and_a_limit":"Routers têm portas e um limite. Encha um e o tráfego para na porta.", "puzzles.rule_not_via_list":"Regra: sem passar por {list}", "puzzles.samba_sprint":"Corrida de samba", +"puzzles.same_cable_same_anchor":"Mesmo cabo de um link que você já tem: uma âncora leva os dois.", "puzzles.same_puzzle_for_everyone_this_week":"O mesmo puzzle para todo mundo nesta semana", +"puzzles.same_trench_cheaper":"Mesma vala (mais barato)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Mesma vala (mais barata, uma retroescavadeira corta as duas)", "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes que a caipirinha esquente.", "puzzles.sea_to_shining_sea":"De costa a costa", -"puzzles.seattle_to_singapore_with_a_stop":"De Seattle a Singapura, com parada para sushi e dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Seis cidades, poucos gigas cada, e um router com oito portas. Conte antes de cavar.", "puzzles.size":"Tamanho", -"puzzles.small_calm_network_builds":"Redes pequenas, com calma", -"puzzles.smorgasbord":"Smörgåsbord", -"puzzles.so_close_one_more_link_and":"Quase lá: mais um link e nenhuma retroescavadeira te alcança.", -"puzzles.speed_runs":"Contra o relógio", +"puzzles.small_networks_real_traffic":"Redes pequenas, tráfego de verdade", "puzzles.spent_x":"Gasto {x}", "puzzles.spent_x_of_y":"Gasto {x} / {y}", "puzzles.stepping_stone_optional":"Escala (opcional)", "puzzles.suez_you_later":"Suez mais tarde", -"puzzles.survives_any_single_cut":"Sobrevive a qualquer corte", +"puzzles.survive_any_single_cut_with_the":"Sobreviva a qualquer corte, com o tráfego ainda fluindo. Estar conectado não basta.", +"puzzles.survives_any_single_cut_under_load":"Aguenta qualquer corte, sob carga", "puzzles.tap_a_goal_city_to_open":"Toque numa cidade brilhante para abrir seu primeiro POP", -"puzzles.that_city_is_not_part_of":"Essa cidade não faz parte deste puzzle.", -"puzzles.the_pacific_is_big_light_is":"O Pacífico é grande. A luz é rápida. Seu orçamento não é nenhum dos dois.", -"puzzles.the_pacific_rim_where_every_hop":"A borda do Pacífico, onde cada salto é um oceano.", +"puzzles.the_content_origin_lives_here":"O conteúdo mora aqui. Usuários de outros lugares puxam daqui.", +"puzzles.the_oil_rigs_want_their_numbers":"As plataformas querem os números rápido. A estrada mais curta para Stavanger não é a mais rápida.", +"puzzles.the_road_to_tallinn_is_short":"A estrada para Tallinn é curta. A luz via Helsinque é mais curta.", "puzzles.the_shark_tank":"O aquário dos tubarões", "puzzles.the_sharks_have_been_biting_again":"Os tubarões voltaram a morder. Fique em terra firme.", "puzzles.the_sharks_say_no":"Os tubarões dizem não.", +"puzzles.this_link":"Este link", "puzzles.three_cities_two_currencies_one_very":"Três cidades, duas moedas e um túnel bem curtinho debaixo do mar.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Traders pagaram milhões para tirar milissegundos desta rota. Você faz por menos.", +"puzzles.traffic_cops":"Guardas de trânsito", +"puzzles.trench_n":"vala {n}", "puzzles.two_cables_across_the_atlantic_because":"Dois cabos atravessando o Atlântico, porque um só é esperança, não plano.", -"puzzles.under_n_ms":"abaixo de {n} ms", +"puzzles.u_of_m_used":"{u} de {m} em uso", "puzzles.undo":"Desfazer", "puzzles.unlocks_at_n_stars":"Abre com {n}⭐", "puzzles.weekly_puzzle":"Puzzle da semana", "puzzles.weekly_puzzle_key":"Puzzle da semana {key}", "puzzles.with_the_pop_price":"com o POP: {price}", -"puzzles.your_first_tubes_roomy_budgets":"Seus primeiros tubos. Orçamentos folgados, e os dois primeiros são por conta da casa.", +"puzzles.your_pop":"Seu POP", +"puzzles.your_routers_pick_the_path":"Seus routers escolhem o caminho. Diga qual: métricas, menor latência, best effort.", "puzzles.your_stars":"Suas estrelas", "puzzles_weekly.detour":"Desvio", "puzzles_weekly.island_hopping":"De ilha em ilha", diff --git a/site/puzzles/weekly/2026-W44.json b/site/puzzles/weekly/2026-W44.json index 128937c..be7a930 100644 --- a/site/puzzles/weekly/2026-W44.json +++ b/site/puzzles/weekly/2026-W44.json @@ -1 +1 @@ -{"v":1,"key":"2026-W44","theme":"ring","cities":["mil","vie","rom","mrs","stg"],"via":[],"avoid":[],"budget":240000,"twist":{"ring":true},"name":{"l":"puzzles_weekly.name_ring_around_reg","p":{"reg":"EU"}},"joke":{"l":"puzzles_weekly.joke_one_ring_through_every_pop","p":{}},"ref":{"one":226300,"three":226300}} +{"v":2,"key":"2026-W44","theme":"ring","cities":["ham","fra","bru","dus"],"src":["ham"],"dem":[{"t":"eye","a":"fra","g":30},{"t":"eye","a":"bru","g":60},{"t":"eye","a":"dus","g":60}],"via":[],"avoid":[],"budget":360000,"twist":{"ring":true},"name":{"l":"puzzles_weekly.name_one_ring_to_rule_reg","p":{"reg":"EU"}},"joke":{"l":"puzzles_weekly.joke_a_ring_survives_one_cut","p":{}},"ref":{"one":341708,"three":341708}} diff --git a/site/puzzles/weekly/2026-W45.json b/site/puzzles/weekly/2026-W45.json index 413d8ac..fc475a5 100644 --- a/site/puzzles/weekly/2026-W45.json +++ b/site/puzzles/weekly/2026-W45.json @@ -1 +1 @@ -{"v":1,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"via":["lag"],"avoid":[],"budget":740000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":457084,"three":695668}} +{"v":2,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"src":["abj"],"dem":[{"t":"eye","a":"fih","g":20},{"t":"eye","a":"acc","g":10},{"t":"eye","a":"dkr","g":30}],"via":["lag"],"avoid":[],"budget":1750000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":989200,"three":1657240}} diff --git a/site/puzzles/weekly/2026-W46.json b/site/puzzles/weekly/2026-W46.json index d7b9f26..11a7fbf 100644 --- a/site/puzzles/weekly/2026-W46.json +++ b/site/puzzles/weekly/2026-W46.json @@ -1 +1 @@ -{"v":1,"key":"2026-W46","theme":"ocean","cities":["for","ssa","lad","lun"],"via":["dla","sao"],"avoid":[],"budget":2060000,"twist":{},"name":{"l":"puzzles_weekly.name_across_the_big_blue","p":{}},"joke":{"l":"puzzles_weekly.joke_somewhere_between_a_and_b","p":{"a":"for","b":"lad"}},"ref":{"one":943664,"three":1959268}} +{"v":2,"key":"2026-W46","theme":"ocean","cities":["for","ssa","lad","lun"],"src":["for"],"dem":[{"t":"eye","a":"ssa","g":8},{"t":"eye","a":"lad","g":5},{"t":"eye","a":"lun","g":8}],"via":["sao","dla"],"avoid":[],"budget":4520000,"twist":{},"name":{"l":"puzzles_weekly.name_sea_you_in_b","p":{"b":"lad"}},"joke":{"l":"puzzles_weekly.joke_somewhere_between_a_and_b","p":{"a":"for","b":"lad"}},"ref":{"one":2368700,"three":4296628}} diff --git a/site/puzzles/weekly/index.json b/site/puzzles/weekly/index.json index 8955841..e112cc1 100644 --- a/site/puzzles/weekly/index.json +++ b/site/puzzles/weekly/index.json @@ -1 +1 @@ -{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} +{"v":2,"weeks":["2026-W44","2026-W45","2026-W46"]} diff --git a/src/game/10-catalog/40-ports.js b/src/game/10-catalog/40-ports.js index 6dbccc1..435cd37 100644 --- a/src/game/10-catalog/40-ports.js +++ b/src/game/10-catalog/40-ports.js @@ -3,7 +3,8 @@ const PORT_SLOT=i=>i===0?0.25:1; function portsUsed(c){let u=0; for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;u+=l.kind==='df'?(l.ch||[]).length:1;} - for(const t of S.transit)if(t.city===c)u+=PORT_SLOT(t.tier)*(t.n||1); + // A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours. + for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1); for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1); for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1); if(S.myIx[c])u+=1; @@ -17,6 +18,6 @@ const popIdle=c=>{const p=S.pops[c];return !!p&&!p.bb&&portsUsed(c)===0&&!S.biz. const fmtPorts=u=>Number.isInteger(u)?String(u):u.toFixed(2).replace(/0+$/,''); function modelFits(c,g){const G=RG[g],p=S.pops[c];if(!p)return ''; if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='wave'&&l.tier>G.maxLT))return tr('ports.a_wave_here_is_faster_than',{pn:G.pn}); - if([...S.transit,...S.pni].some(t=>t.city===c&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn}); + if([...S.transit,...S.pni].some(t=>t.city===c&&!t.pz&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn}); if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='df'&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this'); if(portsUsed(c)>portsMax(c,g))return tr('ports.you_use_u_ports_here_and',{u:fmtPorts(portsUsed(c)),r:p.routers||1,model:G.n,max:portsMax(c,g)});return '';} diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js index a6b7bba..b9c611e 100644 --- a/src/game/60-features/90-puzzles-data.js +++ b/src/game/60-features/90-puzzles-data.js @@ -1,33 +1,36 @@ /* Puzzles: one entry per line, in play order. A puzzle is data: - id, pack, n (name), j (one-line joke), cities (all must end up connected), via (optional stepping stones), - budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist or two: - noSub (no subsea cables), ring (one ring through every POP), lat:[a,b,ms] (best path under ms), minG (every link at - least this many Gbps), avoid (cities shown on the map that you may not build in). */ + id, pack, n (name), j (one-line joke), src (the content origins: eyeballs pull from the nearest), dem (the traffic: + {t:'eye',a,g} eyeballs in city a want g Gbps; {t:'l2',a,b,g,ms} a circuit of g Gbps between a and b, under ms + milliseconds one way; be:1 marks a flow best effort, which may drop when something is cut), via (suggested stepping + stones), budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist: + noSub (no subsea cables), ring (one ring through every POP), avoid (cities you may not build in). + Each pack teaches one idea; the budgets sit a little above the cheapest 3-star build found (tests/puzzles.test.js). */ const PZ_PACKS=[ - {id:'hello',n:tr('puzzles.hello_world'),d:tr('puzzles.your_first_tubes_roomy_budgets'),need:0}, - {id:'fire',n:tr('puzzles.ring_of_fire'),d:tr('puzzles.the_pacific_rim_where_every_hop'),need:6}, - {id:'speed',n:tr('puzzles.speed_runs'),d:tr('puzzles.beat_the_clock_light_in_glass'),need:14}, - {id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.for_architects_who_sleep_through_backhoes'),need:22}, + {id:'hello',n:tr('puzzles.fat_pipes'),d:tr('puzzles.capacity_first_every_link_has_a'),need:0}, + {id:'rodeo',n:tr('puzzles.router_rodeo'),d:tr('puzzles.routers_have_ports_and_a_limit'),need:10}, + {id:'cops',n:tr('puzzles.traffic_cops'),d:tr('puzzles.your_routers_pick_the_path'),need:18}, + {id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.survive_any_single_cut_with_the'),need:26}, + {id:'final',n:tr('puzzles.grand_tour'),d:tr('puzzles.everything_at_once_across_oceans'),need:36}, ]; const PZ=[ - {id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),cities:['lon','nyc'],budget:0}, - {id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),cities:['lon','ams','fra'],budget:0}, - {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),cities:['nyc','chi','dal','sjc'],budget:340000}, - {id:'smorgas',pack:'hello',n:tr('puzzles.smorgasbord'),j:tr('puzzles.four_capitals_one_very_long_winter'),cities:['osl','sto','cph','hel'],budget:210000}, - {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),cities:['syd','mel','bne','adl'],budget:320000}, - {id:'aloha',pack:'fire',n:tr('puzzles.aloha_latency'),j:tr('puzzles.honolulu_the_world_s_most_scenic'),cities:['sjc','hnl','syd'],budget:1830000}, - {id:'rimshot',pack:'fire',n:tr('puzzles.pacific_rim_shot'),j:tr('puzzles.seattle_to_singapore_with_a_stop'),cities:['sea','tok','hkg','sin'],budget:1240000}, - {id:'fire',pack:'fire',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),cities:['tok','hkg','sin','syd'],ring:true,budget:1610000}, - {id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv','lax'],budget:1450000}, - {id:'guam',pack:'fire',n:tr('puzzles.guam_slam'),j:tr('puzzles.a_tiny_island_where_half_the'),cities:['tok','mnl','syd'],via:['gum'],budget:1700000}, - {id:'flash',pack:'speed',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),cities:['nyc','lon'],lat:['nyc','lon',27],budget:465000}, - {id:'pingpong',pack:'speed',n:tr('puzzles.ping_pong_to_tokyo'),j:tr('puzzles.the_pacific_is_big_light_is'),cities:['lax','tok'],via:['sea','sjc'],lat:['lax','tok',47],budget:880000}, - {id:'suez',pack:'speed',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),cities:['fra','sin'],via:['mrs','bom'],lat:['fra','sin',68],budget:1010000}, - {id:'samba',pack:'speed',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),cities:['sao','mia'],via:['for','rio'],lat:['sao','mia',45],budget:1060000}, - {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),cities:['lis','mad','par','mil'],via:['bcn','mrs'],noSub:true,budget:210000}, - {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),cities:['nyc','lon','dub'],budget:380000}, - {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),cities:['ams','ber','muc','zrh'],via:['ham','dus'],avoid:['fra'],budget:192000}, - {id:'fatpipes',pack:'n1',n:tr('puzzles.fat_pipes_only'),j:tr('puzzles.nobody_ever_got_fired_for_buying'),cities:['par','mrs','mil','zrh'],minG:100,budget:235000}, + {id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),src:['nyc'],dem:[{t:'eye',a:'lon',g:8}],budget:0}, + {id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),src:['ams'],dem:[{t:'eye',a:'lon',g:30},{t:'eye',a:'fra',g:60}],budget:0}, + {id:'bigboat',pack:'hello',n:tr('puzzles.a_bigger_boat'),j:tr('puzzles.paris_wants_150g_one_100g_wave'),src:['fra'],dem:[{t:'eye',a:'par',g:150}],budget:175000}, + {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),src:['nyc'],dem:[{t:'eye',a:'chi',g:40},{t:'eye',a:'dal',g:30},{t:'eye',a:'sjc',g:60}],budget:715000}, + {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),src:['syd'],dem:[{t:'eye',a:'mel',g:50},{t:'eye',a:'bne',g:30},{t:'eye',a:'adl',g:20}],budget:585000}, + {id:'edgelord',pack:'rodeo',n:tr('puzzles.edge_lord'),j:tr('puzzles.london_wants_half_a_terabit_your'),src:['ams'],dem:[{t:'eye',a:'lon',g:500}],budget:240000}, + {id:'hubcap',pack:'rodeo',n:tr('puzzles.hub_cap'),j:tr('puzzles.all_of_europe_s_cat_videos'),src:['lon'],dem:[{t:'eye',a:'ams',g:150},{t:'eye',a:'par',g:150},{t:'eye',a:'fra',g:120}],budget:455000}, + {id:'ports',pack:'rodeo',n:tr('puzzles.port_authority'),j:tr('puzzles.six_cities_a_few_gigs_each'),src:['zrh'],dem:[{t:'eye',a:'mil',g:12},{t:'eye',a:'muc',g:12},{t:'eye',a:'fra',g:12},{t:'eye',a:'par',g:12},{t:'eye',a:'vie',g:12},{t:'eye',a:'prg',g:12}],budget:470000}, + {id:'flash',pack:'cops',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),src:['nyc'],dem:[{t:'l2',a:'nyc',b:'lon',g:10,ms:26},{t:'eye',a:'lon',g:80,be:1}],budget:660000}, + {id:'baltic',pack:'cops',n:tr('puzzles.baltic_shortcut'),j:tr('puzzles.the_road_to_tallinn_is_short'),src:['fra'],dem:[{t:'eye',a:'tll',g:60},{t:'l2',a:'fra',b:'tll',g:10,ms:8.8}],via:['hel'],budget:285000}, + {id:'fjord',pack:'cops',n:tr('puzzles.fjord_focus'),j:tr('puzzles.the_oil_rigs_want_their_numbers'),src:['par'],dem:[{t:'eye',a:'svg',g:30},{t:'l2',a:'par',b:'svg',g:10,ms:7.2}],via:['lon'],budget:265000}, + {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),src:['nyc'],dem:[{t:'eye',a:'lon',g:60},{t:'eye',a:'dub',g:40}],budget:840000}, + {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),src:['lis'],dem:[{t:'eye',a:'mad',g:40},{t:'eye',a:'par',g:60},{t:'eye',a:'mil',g:30}],via:['bcn','mrs'],noSub:true,budget:450000}, + {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),src:['ams'],dem:[{t:'eye',a:'ber',g:50},{t:'eye',a:'muc',g:50},{t:'eye',a:'zrh',g:40}],via:['ham','dus'],avoid:['fra'],budget:390000}, + {id:'fire',pack:'n1',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),src:['tok'],dem:[{t:'eye',a:'hkg',g:20},{t:'eye',a:'sin',g:20},{t:'eye',a:'syd',g:10}],ring:true,budget:4070000}, + {id:'suez',pack:'final',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),src:['fra'],dem:[{t:'l2',a:'fra',b:'sin',g:10,ms:68},{t:'eye',a:'sin',g:30,be:1}],via:['mrs','bom'],budget:1790000}, + {id:'kiwi',pack:'final',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),src:['sea'],dem:[{t:'eye',a:'akl',g:20},{t:'eye',a:'syd',g:40}],via:['hnl','suv','lax'],budget:4200000}, + {id:'samba',pack:'final',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),src:['mia'],dem:[{t:'l2',a:'sao',b:'mia',g:10,ms:45},{t:'eye',a:'sao',g:40},{t:'eye',a:'rio',g:20,be:1}],via:['for'],budget:2655000}, ]; // Weekly puzzle pools: each is one landmass and one region, so every pair has an overland route. const PZ_WEEK_POOLS=[ diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index 232a4cf..4b2b9ee 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -1,17 +1,30 @@ /* ================= PUZZLES (#190) ================= - Small, calm builds: connect a few cities, earn up to three stars. A puzzle runs as its own S (S.mode='puzzle'): - no clock, no bills, no incidents, links up at once. That S is never saved. Only progress (stars and best spend per - puzzle, weekly results and the weekly streak) is kept, under its own key, so the main save is never touched. */ -const PZ_KEY='sot-puzzles',PZ_YEAR=12; + Small, calm builds that carry real traffic: every puzzle has demand (eyeballs pulling from a content origin, circuits + between two cities with a latency cap), and the game's own compute() routes it: metrics, standby, LAGs, router + capacity and ports all behave as in the main game. A puzzle runs as its own S (S.mode='puzzle'): no clock, no bills, + no incidents, links up at once. The demand is ordinary game state, so compute() needs no puzzle cases: an origin is a + transit port (t.pz, which takes no router port), a circuit is an L2VPN customer, eyeballs are broadband with a fixed + demand. That S is never saved. Only progress (stars and best spend per puzzle, weekly results and the weekly streak) + is kept, under its own key, so the main save is never touched. */ +const PZ_KEY='sot-puzzles',PZ_YEAR=12,PZ_SET=2; const pzOn=()=>!!(S&&S.mode==='puzzle'&&S.pz); const pzDef=id=>PZ.find(p=>p.id===id)||null; -const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':null; +// goal: a city the traffic starts or ends in; via: a suggested stepping stone; avoid: off limits; off: any other city +// (the whole world is open, it just is not part of the plan). +const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)?'off':null; const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key',{key:d.key})):d.n; const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n); +// Every city a puzzle's traffic touches, origins first. +const pzCities=d=>[...new Set([...(d.src||[]),...d.dem.flatMap(f=>f.t==='l2'?[f.a,f.b]:[f.a])])]; // ---------- progress (localStorage, never trusted) ---------- -function pzClean(j){const o={s:{},wk:{},streak:{last:null,n:0,best:0}};if(!j||typeof j!=='object')return o; +// `set` is the puzzle set the stars belong to: the set with traffic (2) started again, and the stars won before hang +// framed on the wall (`old`), with a note shown once (`noted`). Weekly results and the streak carry on. +function pzClean(j){const o={set:PZ_SET,s:{},wk:{},streak:{last:null,n:0,best:0},old:null,noted:1};if(!j||typeof j!=='object')return o; const rec=r=>{if(!r||typeof r!=='object')return null;const o={st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)},rv=int(r.rv,1,999,1);if(rv>1)o.rv=rv;return o;}; - if(j.s&&typeof j.s==='object')for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;} + const cur=j.set===PZ_SET; + if(j.s&&typeof j.s==='object'){if(cur){for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;}} + else{let n=0;for(const k of Object.keys(j.s).slice(0,200)){const r=rec(j.s[k]);if(r&&/^[a-z0-9]{1,20}$/.test(k))n+=r.st;}if(n){o.old=n;o.noted=0;}}} + if(cur){o.old=j.old==null?null:int(j.old,0,9999,0)||null;o.noted=j.noted?1:0;if(o.old==null)o.noted=1;} if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;} const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);} return o;} @@ -21,7 +34,7 @@ function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{ function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}} const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0); const pzPackOpen=(k,p)=>{const P=PZ_PACKS.find(x=>x.id===k);return !!P&&pzStarsTotal(p||pzLoad())>=P.need;}; -// ---------- prices: the real game's waves, on day 0, for a year ---------- +// ---------- prices: the real game's waves and routers, on day 0, for a year ---------- const pzMood=(a,b,sub)=>{const k=waveMarket(a,b,sub);return k.m/k.ero;}; // Overland (when the two cities share a landmass) and every cable between them, each with its price factor and latency. function pzRoutes(a,b){const out=[],sub=isSub(a,b); @@ -31,53 +44,72 @@ function pzRoutes(a,b){const out=[],sub=isSub(a,b); const pzMo=(r,tier,div)=>Math.round(waveMo(r.km,r.sub,tier)*r.f*(div?DIVERSE:1)); const pzLinkCost=(r,tier,div)=>pzMo(r,tier,div)*PZ_YEAR;// leased waves have no setup fee: a year of rent const pzPopCost=c=>popCost(c)+PZ_YEAR*popMo(c);// thin markets cost more every month too (#94) -const PZ_TIERS=[0,1,2]; -function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c);for(const l of S.links)s+=l.mo*PZ_YEAR;return s;} +// 10G to 800G: an 800G wave needs an 800G router at both ends, as in the main game. +const PZ_TIERS=[0,1,2,3]; +// Router models on offer: the main game's catalogue up to its level-3 gear, cheapest class first. +const PZ_RG=RG.map((r,i)=>i).filter(i=>RG[i].lvl<=3).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cost-RG[b].cost); +// A POP's routers for a year: the chassis (the first Rusty Router is free), each extra one as the main game prices it +// (#157 cages included), and their rent. +function pzRtCost(g,rt){let s=Math.round(RG[g].cost*hwMul('rt'));for(let k=1;k{const p=S.pops[c];return p?pzRtCost(p.rgen||0,p.routers||1):0;}; +function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c)+pzRouterCost(c);for(const l of S.links)s+=l.mo*PZ_YEAR;return s;} // What one backhoe or one anchor takes out: waves in the same trench, or every wave on the same cable (a cable fails // as a whole, as in the main game's diversity checks). const pzUnit=l=>l.cable?'cab:'+l.cable:String(l.trench||l.id); +// ---------- the traffic ---------- +// Origins are transit ports the size of a content farm; circuits are L2VPN customers; eyeballs come with their POP. +const PZ_NET='lvl',PZ_ORIG=5; +const pzFlowId=i=>'pzf'+i; +const pzFlowName=f=>f.t==='l2'?tr('puzzles.flow_circuit_a_b',{a:CITY[f.a].name,b:CITY[f.b].name}):tr('puzzles.flow_eyeballs_in_city',{city:CITY[f.a].name}); +function pzDemand(){const P=S.pz;S.transit=P.src.map((c,i)=>({id:'pzo'+i,city:c,net:PZ_NET,tier:PZ_ORIG,n:1,pz:1,pref:'normal',hist:[]})); + S.biz=P.dem.map((f,i)=>f.t==='l2'?{id:pzFlowId(i),type:'l2vpn',name:pzFlowName(f),city:f.a,city2:f.b,bw:f.g,rate:0,route:'normal',reqs:[],day:0}:null).filter(Boolean);} +const pzEye=c=>{const f=pzOn()&&S.pz.dem.find(x=>x.t==='eye'&&x.a===c);return f?f.g:0;}; +const pzNewPop=c=>{const g=pzEye(c);return {day:0,bb:g?{d:g}:null,boost:0,down:0,routers:1,gen:false};}; +// What each flow gets from the last compute(): Gbps delivered, and a circuit's latency. +// Eyeball traffic to networks behind the Great Firewall loses a fifth at the border, as in the main game; that is not +// the player's doing, so a puzzle counts what crosses the border as delivered (pzGfw: the share that arrives). +let PZ_GFW=null;const pzGfw=()=>PZ_GFW||(PZ_GFW=1-0.2*NETS.filter(n=>n.cn).reduce((a,n)=>a+(NSH[n.id]||0),0)); +function pzGot(){return S.pz.dem.map((f,i)=>f.t==='l2'?{g:R.l2[pzFlowId(i)]||0,ms:isFinite(R.l2lat[pzFlowId(i)])?R.l2lat[pzFlowId(i)]:null}:{g:S.pops[f.a]?(R.citySrv[f.a]||0)/pzGfw():0,ms:null});} +const pzFull=(f,x)=>x.g>=f.g*0.999-1e-6; +const pzFast=(f,x)=>!f.ms||(x.ms!=null&&x.ms<=f.ms+1e-9); // ---------- checks ---------- -function pzComp(ls,skip,from){const adj={};for(const l of ls){if(skip&&pzUnit(l)===skip)continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);} - const seen=new Set([from]),q=[from];while(q.length){const u=q.pop();for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return seen;} function pzRingOk(ls){const nb={};for(const l of ls){(nb[l.a]=nb[l.a]||new Set()).add(l.b);(nb[l.b]=nb[l.b]||new Set()).add(l.a);} const ns=Object.keys(nb);if(ns.length<3||!S.pz.cities.every(c=>nb[c])||!Object.keys(S.pops).every(c=>nb[c])||!ns.every(c=>nb[c].size===2))return false; let prev=null,cur=ns[0],n=0;do{const nx=[...nb[cur]].find(x=>x!==prev);prev=cur;cur=nx;n++;}while(cur!==ns[0]&&n<=ns.length);return cur===ns[0]&&n===ns.length;} -function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend(); - // The checklist ticks the goal cities that are already joined up: the group holding the most of them. - let best=new Set();for(const c of cs){if(!S.pops[c]||best.has(c))continue;const g=pzComp(ls,null,c);if(cs.filter(x=>g.has(x)).length>cs.filter(x=>best.has(x)).length)best=g;} - const joined=cs.filter(c=>best.has(c)).length>=2?best:new Set(); - const marks=cs.map(c=>({c,st:joined.has(c)?2:S.pops[c]?1:0})); - const conn=cs.every(c=>joined.has(c)); +// The same build always gets the same answer, so pzEval() keeps the last one (it routes once, then once per cut). +const pzSig=()=>JSON.stringify([S.pops,S.links,S.pairMet||null,S.biz.map(b=>b.route),S.pz.budget]); +/* ⭐ every flow delivered in full (circuits within their latency cap), and the twists; ⭐⭐ the year's spend within + budget; ⭐⭐⭐ N-1 under load: whichever single trench or cable is cut, every priority flow still gets all of its traffic + (best-effort flows may drop). The cut is routed by compute() like the real thing. */ +function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&c0.sig===sig)return c0.e; + const P=S.pz,hot=UI.hotMap;compute();const R0=R,got=pzGot(),spend=pzSpend(),peak={},pk=()=>{for(const c in R.nodeLoad)peak[c]=Math.max(peak[c]||0,R.nodeLoad[c]);};pk(); + const flows=P.dem.map((f,i)=>({f,i,g:got[i].g,ms:got[i].ms,full:pzFull(f,got[i]),fast:pzFast(f,got[i])})); const tw=[];if(P.noSub)tw.push({k:'sub',ok:!S.links.some(l=>l.sub)}); - if(P.ring)tw.push({k:'ring',ok:pzRingOk(ls)}); - if(P.lat){const ms=S.pops[P.lat[0]]&&S.pops[P.lat[1]]?bestLat(P.lat[0],P.lat[1]):Infinity;tw.push({k:'lat',ok:ms<=P.lat[2],ms});} - if(P.minG)tw.push({k:'g',ok:ls.every(l=>LT[l.tier].g>=P.minG)}); + if(P.ring)tw.push({k:'ring',ok:pzRingOk(S.links)}); if(P.avoid.length)tw.push({k:'avoid',ok:P.avoid.every(c=>!S.pops[c])}); - const goal=conn&&tw.every(t=>t.ok),units=[...new Set(ls.map(pzUnit))]; - // N-1: the goal cities stay joined whichever single trench or cable is cut. - const weak=conn?units.filter(u=>{const g=pzComp(ls,u,cs[0]);return !cs.every(c=>g.has(c));}):[]; - const n1=conn&&units.length>0&&!weak.length,cheap=!P.budget||spend<=P.budget; - return {marks,conn,tw,goal,spend,cheap,n1,weak,stars:goal?1+(cheap?1:0)+(n1?1:0):0};} -// Two stars, and one more link within budget would survive any cut? Then the third star is close. Tries every route -// between the puzzle's cities at the smallest allowed size, so the nudge is true, not a guess. -function pzOneMore(e){const P=S.pz;if(e.stars!==2||!e.cheap||e.n1)return false;const cs=[...P.cities,...P.via],tier=P.minG?1:0,cs0=P.cities[0]; - for(const a of cs)for(const b of cs){if(a>=b)continue;for(const r of pzRoutes(a,b)){if((P.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))continue; - const div=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),cost=pzLinkCost(r,tier,div)+(S.pops[a]?0:pzPopCost(a))+(S.pops[b]?0:pzPopCost(b)); - if(e.spend+cost>P.budget)continue;const ls=[...S.links,{id:'pz?',a,b,cable:r.cab,trench:r.cab?'cab:'+r.cab:'pz?'}];if(P.ring&&!pzRingOk(ls))continue; - if([...new Set(ls.map(pzUnit))].every(u=>{const g=pzComp(ls,u,cs0);return P.cities.every(c=>g.has(c));}))return true;}} - return false;} + const del=flows.every(x=>x.full&&x.fast),goal=del&&tw.every(t=>t.ok),units=[...new Set(S.links.map(pzUnit))],cuts=[]; + if(goal)try{for(const u of units){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1; + try{compute();pk();const g=pzGot(),lost=[];P.dem.forEach((f,i)=>{if(!f.be&&!pzFull(f,g[i]))lost.push({i,g:Math.max(0,f.g-g[i].g)});});if(lost.length)cuts.push({u,lost,g:lost.reduce((a,x)=>a+x.g,0)});} + finally{for(const l of ls)l.cut=0;}}} + finally{R=R0;UI.hotMap=hot;} + cuts.sort((a,b)=>b.g-a.g); + const n1=goal&&units.length>0&&!cuts.length,cheap=!P.budget||spend<=P.budget; + const e={flows,del,tw,goal,spend,cheap,n1,weak:cuts.map(x=>x.u),worst:cuts[0]||null,peak,stars:goal?1+(cheap?1:0)+(n1?1:0):0}; + UI.pzEv={sig,e};return e;} // ---------- the seeded weekly puzzle: the same for everyone, and the stand-in when the published one (93-puzzles-weekly.js) is not there ---------- function pzWeekly(dt){const key=pzWeekKey(dt||new Date());let r=hstr('puzzle|'+key)||1;const nx=()=>{r=(Math.imul(r,1103515245)+12345)>>>0;return r/4294967296;}; const pool=PZ_WEEK_POOLS[Math.floor(nx()*PZ_WEEK_POOLS.length)].slice(),n=4+Math.floor(nx()*2),cities=[]; while(cities.lengthkmBetween(u,a)-kmBetween(u,b));ring.push(left.shift());} let cost=cities.reduce((a,c)=>a+pzPopCost(c),0);const used=new Set(),via=[]; for(let i=0;i!x.cab||!used.has(x.cab)).sort((x,y)=>pzLinkCost(x,0,false)-pzLinkCost(y,0,false))[0]; if(r.cab)used.add(r.cab);via.push(r.via);cost+=pzLinkCost(r,0,false);} - return {id:'weekly',key,cities,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring,refVia:via};} + const g=Math.floor(9/(n-1)),dem=cities.slice(1).map(c=>({t:'eye',a:c,g})); + return {id:'weekly',key,cities,src:[cities[0]],dem,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring,refVia:via};} function pzStreak(p,key){const st=p.streak;if(st.last===key)return;st.n=st.last&&st.last===pzPrevKey(key)?st.n+1:1;st.last=key;st.best=Math.max(st.best,st.n);} function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==='weekly'?P.key:pzName(pzDef(P.id)),stars:pzStarStr(e.stars),spend:fmt$(e.spend)});} // ---------- entering and leaving ---------- @@ -87,16 +119,18 @@ const pzToastsClear=()=>{$('toasts').textContent='';}; // (leaving the page mid-puzzle), and leaving the puzzle picks it up again. function pzFlush(){save(true);UI.pzKeep=S;} function pzBegin(def){if(!def)return; - const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null; - S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null,rev:def.rev||1}; - UI.pzHist=[];UI.pzTop=0;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null; + const go=()=>{const cs=pzCities(def);newGame(pzName(def),cs[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null; + S.pz={id:def.id,key:def.key||null,cities:cs,src:(def.src||[]).slice(),dem:def.dem.map(f=>({t:f.t,a:f.a,b:f.t==='l2'?f.b:null,g:f.g,ms:f.ms||0,be:!!f.be})), + via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null,rev:def.rev||1}; + pzDemand(); + UI.pzHist=[];UI.pzTop=0;UI.pzEv=null;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null; $('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz'); compute();pzCam();renderAll();track('puzzle_'+def.id); - toast(`${esc(pzName(def))}
${tr('puzzles.connect_list',{list:def.cities.map(c=>CITY[c].name).join(', ')})}`,'goal');}; + toast(`${esc(pzName(def))}
${tr('puzzles.carry_list',{list:S.pz.dem.map(f=>`${esc(pzFlowName(f))} ${fmtG(f.g)}`).join(', ')})}`,'goal');}; if(pzOn()){go();return;} const live=!!(S&&UI.started&&!S.lost);UI.pzFrom=live?'game':'title'; if(live)pzFlush();go();} -function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; +function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. @@ -108,8 +142,7 @@ function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0]. const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} // ---------- building ---------- -function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links}));if(h.length>60)h.shift();} -const pzNewPop=()=>({day:0,bb:null,boost:0,down:0,routers:1,gen:false}); +function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();} function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null; compute();renderAll();pzCheck();} // Stars count the moment they are earned: a better result than this attempt has had opens the results card. diff --git a/src/game/60-features/93-puzzles-weekly.js b/src/game/60-features/93-puzzles-weekly.js index 0f54890..08ae97b 100644 --- a/src/game/60-features/93-puzzles-weekly.js +++ b/src/game/60-features/93-puzzles-weekly.js @@ -42,19 +42,30 @@ function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l if(t==='c'&&pzCityOk(v))out[k]=v;else if(t==='r'&&typeof v==='string'&&own(WAVE_NAME,v))out[k]=v;else if(t==='n'&&Number.isInteger(v)&&v>0&&v<1000)out[k]=v;else return null;} return {l:o.l,p:out};} // rev: the file's revision, from 2 when a release's new prices made the week regenerate (scripts/weekly-puzzle.js). -const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref','rev']; -function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==1||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null; +const PZ_WK_FIELDS=['v','key','theme','cities','src','dem','via','avoid','budget','twist','name','joke','ref','rev']; +// Schema 2 (puzzles with traffic): `src` the content origins, `dem` the flows ({t:'eye',a,g} eyeballs in a; {t:'l2',a,b,g,ms} +// a circuit, ms its latency cap; be:true best effort), `cities` exactly the cities they touch. Older files are refused. +const PZ_WK_V=2; +function pzWkDem(a){if(!Array.isArray(a)||a.length<1||a.length>6)return null;const out=[],eye=new Set(); + for(const f of a){if(!pzObj(f)||Object.keys(f).some(k=>!['t','a','b','g','ms','be'].includes(k))||!pzCityOk(f.a)||!Number.isInteger(f.g)||f.g<1||f.g>2000)return null; + if(own(f,'be')&&f.be!==true)return null; + if(f.t==='eye'){if(own(f,'b')||own(f,'ms')||eye.has(f.a))return null;eye.add(f.a);out.push({t:'eye',a:f.a,g:f.g,be:!!f.be});} + else if(f.t==='l2'){if(!pzCityOk(f.b)||f.b===f.a||(own(f,'ms')&&!(typeof f.ms==='number'&&isFinite(f.ms)&&f.ms>=1&&f.ms<=500)))return null;out.push({t:'l2',a:f.a,b:f.b,g:f.g,ms:f.ms||0,be:!!f.be});} + else return null;} + return out;} +function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==PZ_WK_V||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null; const T=PZ_WK_THEMES[j.theme],ids=(a,lo,hi)=>Array.isArray(a)&&a.length>=lo&&a.length<=hi&&a.every(pzCityOk)&&new Set(a).size===a.length?a.slice():null; - const cities=ids(j.cities,3,6),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2);if(!cities||!via||!avoid)return null; + const cities=ids(j.cities,2,6),src=ids(j.src==null?[]:j.src,0,3),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2),dem=pzWkDem(j.dem);if(!cities||!src||!via||!avoid||!dem)return null; + // Eyeballs need somewhere to pull from; an origin is not also a city of eyeballs. + if(dem.some(f=>f.t==='eye')&&!src.length||dem.some(f=>f.t==='eye'&&src.includes(f.a)))return null; + const d0={src,dem},cs=pzCities(d0);if(cs.length!==cities.length||!cs.every(c=>cities.includes(c)))return null; const all=[...cities,...via,...avoid];if(new Set(all).size!==all.length)return null; - if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>1e7)return null; - const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['lat','ring','noSub','minG'].includes(k)))return null; + if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>2e7)return null; + const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['ring','noSub'].includes(k)))return null; if(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null; - const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null,rev:j.rev||1}; + const d={id:'weekly',key,theme:j.theme,cities,src,dem,via,avoid,budget:j.budget,noSub:false,ring:false,rev:j.rev||1}; if(own(tw,'ring')){if(tw.ring!==true)return null;d.ring=true;} if(own(tw,'noSub')){if(tw.noSub!==true)return null;d.noSub=true;} - if(own(tw,'minG')){if(![100,400].includes(tw.minG))return null;d.minG=tw.minG;} - if(own(tw,'lat')){const l=tw.lat;if(!Array.isArray(l)||l.length!==3||!cities.includes(l[0])||!cities.includes(l[1])||l[0]===l[1]||!Number.isInteger(l[2])||l[2]<1||l[2]>500)return null;d.lat=l.slice();} d.wn=pzWkTxt(j.name,T.names);d.wj=pzWkTxt(j.joke,T.jokes);if(!d.wn||!d.wj)return null; return d;} // ---------- fetching it: when Puzzles opens, never on page load ---------- diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 0efe713..32e9458 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -22,7 +22,7 @@ function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return tr('action_helpers.unlo if((l.ch||[]).length+soldSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)}); for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].clsinnerWidth>760&&innerWidth<=1200; function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();} function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;const P=$('panel');if(P)P.classList.remove('full');if(!S.pops[c])UI.tab='cust';renderPanel();} diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 26f158e..a874829 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -1,3 +1,7 @@ +// Can a wave of this size be lit between a and b here? Router ports and models as in the main game; a city without a +// POP yet will get a Rusty Router. +function pzWaveWhy(a,b,tier,r){if(r&&subWaveWhy(tier,r.km,r.sub))return tr('common.too_far_for_this_cable');if(!waveOk(a,b,tier))return tr('puzzles.needs_what',{what:waveNeed(tier)});return '';} +const pzPortsFree=c=>!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9; Object.assign(ACT,{ // The puzzle list. The ruleset's title-screen door calls this. puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();}, @@ -5,27 +9,47 @@ Object.assign(ACT,{ pzWeekly:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());}, pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, pzLeave:()=>{if(pzOn())pzLeave();}, - pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop();sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();}, - pzRmPop:({city})=>{if(!pzOn()||!S.pops[city])return;pzSnap();delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);sfx('click');UI.sel=null;pzAfter();}, + pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via','off'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop(city);sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();}, + pzRmPop:({city})=>{if(!pzOn()||!S.pops[city])return;pzSnap();delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, pzLinkTo:({a,b})=>{if(!pzOn()||!S.pops[a]||a===b)return;pzLinkModal(a,b);}, pzVia:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzVia=v;pzLinkModal(p.a,p.b,true);}, pzDiv:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzDiv=!!+v;pzLinkModal(p.a,p.b,true);}, - pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p;if(!S.pops[a]||!['goal','via'].includes(pzKind(b)))return; - const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))return; - const same=!r.sub&&UI.pzDiv===false?S.links.find(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):null,div=!r.sub&&!same&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable); - pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop();const id=uid(),f=r.f*(div?DIVERSE:1); - 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:f,trench:r.cab?'cab:'+r.cab:same?(same.trench||same.id):id,cut:0,day:0}); + pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return; + const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub))return; + const why=pzWaveWhy(a,b,tier,r);if(why){toast(esc(why),'bad');sfx('err');return;} + if(!portGate(a,1)||(S.pops[b]&&!portGate(b,1)))return; + // Overland: the same trench as a link already on the pair (the one picked from, or the first), or a diverse route + // of its own. Every trench but the first runs the long way round and costs 40% more. + const lands=pzOn()&&!r.sub?S.links.filter(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):[],t0=lands.length?pzUnit(lands[0]):null; + const same=UI.pzDiv===false&&lands.length?(lands.find(l=>pzUnit(l)===UI.pzTrench)||lands[0]):null,trench=same?pzUnit(same):null,div=!!t0&&trench!==t0; + pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop(b);const id=uid(),f=r.f*(div?DIVERSE:1); + 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:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0}); closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();}, - pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier||subWaveWhy(tier,l.km,l.sub))return;pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();}, - pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);sfx('click');UI.sel=null;pzAfter();}, - pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;sfx('click');pzAfter();}, - pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];UI.sel=null;sfx('click');pzAfter();}, + // Another link next to this one: the picker opens on the same pair, on the same route, in the same trench or a diverse one. + pzAddPar:({id,div})=>{const l=pzOn()&&S.links.find(x=>x.id===id);if(!l)return;UI.pzVia=l.cable||'land';UI.pzDiv=!!+div;UI.pzTrench=l.cable?null:pzUnit(l); + if(+div&&l.cable){const o=pzRoutes(l.a,l.b).find(x=>x.via!==l.cable&&!(S.pz.noSub&&x.sub));if(o)UI.pzVia=o.via;} + pzLinkModal(l.a,l.b,true);}, + pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;} + pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();}, + pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + // Routers: one more of the same model, one fewer, or every router in the POP swapped for another model. + pzRtAdd:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();}, + pzRtRm:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;} + pzSnap();p.routers--;sfx('click');pzAfter();}, + pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;} + pzSnap();p.rgen=g;sfx('build');floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');pzAfter();}, + // A circuit follows the metrics (the IGP's shortest path) or takes the lowest-latency path, as customers can in the main game. + pzRoute:({i,m})=>{const b=pzOn()&&S.biz.find(x=>x.id===pzFlowId(+i));if(!b||!['normal','fast'].includes(m)||b.route===m)return;pzSnap();b.route=m;sfx('click');pzAfter();}, + pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();}, + pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();}, pzShare:()=>{if(!pzOn())return;const t=pzShareText(pzEval()); const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'),copy=()=>{try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}; if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}copy();track('puzzle_share');}, }); // A puzzle is its own S: a leftover main-game button (an old toast, a stale panel, a shortcut) must not build, buy or -// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. This file is the -// last of the actions, so every one is here to wrap. -const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','menu','mute','prefSet','puzzleDoor','puzzleMenu','selLink','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); -for(const k of Object.keys(ACT))if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k)){const f=ACT[k];ACT[k]=a=>pzOn()?undefined:f(a);} +// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's +// routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone. +// This file is the last of the actions, so every one is here to wrap. +const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); +const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']); +for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);} diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index 1a1f639..cb22b32 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -1,62 +1,103 @@ /* ---------- puzzles: the card, the panels, the link picker, the results and the list ---------- */ -const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫'}; -function pzTwistTxt(t){const P=S.pz; - if(t.k==='sub')return tr('puzzles.no_subsea_cables'); - if(t.k==='ring')return tr('puzzles.one_ring_through_every_pop'); - if(t.k==='g')return tr('puzzles.every_link_n_g_or_more',{n:P.minG}); - const [a,b,ms]=P.lat;return isFinite(t.ms)?tr('puzzles.a_to_b_under_ms_now',{a:CITY[a].name,b:CITY[b].name,ms,now:t.ms.toFixed(1)}):tr('puzzles.a_to_b_under_ms',{a:CITY[a].name,b:CITY[b].name,ms});} -// The short version, for the puzzle list. -function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} +const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫',off:'📍'}; +function pzTwistTxt(t){if(t.k==='sub')return tr('puzzles.no_subsea_cables');return tr('puzzles.one_ring_through_every_pop');} +// The short version, for the puzzle list: what has to be carried, and the twists. +function pzDemTag(d){const t=[];const eye=d.dem.filter(f=>f.t==='eye'),l2=d.dem.filter(f=>f.t==='l2'); + if(eye.length)t.push(tr('puzzles.n_g_of_eyeballs',{n:fmtG(eye.reduce((a,f)=>a+f.g,0))}));if(l2.length)t.push(trn('puzzles.n_circuits',l2.length)); + if(d.dem.some(f=>f.ms))t.push(tr('puzzles.latency_caps'));if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} // A cable carrying several of your waves is named on its own: cutting it takes them all. const pzUnitName=u=>{const ls=S.links.filter(x=>pzUnit(x)===u),l=ls[0];return !l?'':l.cable&&ls.length>1?esc(CAB[l.cable].name):`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`;}; +// Each flow on the card: what it is, how much of it arrives, and a circuit's latency against its cap. +function pzFlowRow(x){const f=x.f,ok=x.full&&x.fast,u=f.g?Math.min(1,x.g/f.g):0; + const lat=f.ms?` · ${x.ms==null?tr('common.no_path'):x.ms.toFixed(1)+' ms'} / ${f.ms} ms`:''; + return `
${f.t==='l2'?'🔗':'👀'} ${esc(pzFlowName(f))}${f.be?` ${tr('puzzles.best_effort')}`:''}${fmtG(x.g)} / ${fmtG(f.g)}
${lat?`
${tr('puzzles.latency')}${lat}
`:''}${f.t==='l2'?pzRouteCtl(x.i):''}
`;} +// A circuit's path: the metrics, or the lowest latency. +function pzRouteCtl(i){const b=S.biz.find(x=>x.id===pzFlowId(i));if(!b)return '';return `
${['normal','fast'].map(m=>btn(RT[m],'pzRoute',{i,m},b.route===m?'pink sm':'ghost sm')).join('')}
`;} function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false; const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); const star=(on,l)=>`⭐${l}`; let h=`
${pk?esc(pk.n):P.theme&&own(PZ_WK_THEMES,P.theme)?`${PZ_WK_THEMES[P.theme].i} ${tr('puzzles.weekly_puzzle')} · ${tr(PZ_WK_THEMES[P.theme].t)}`:tr('puzzles.weekly_puzzle')}

${esc(pzName(d||P))}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; if(d)h+=`

${esc(d.j)}

`;else if(P.wj)h+=`

${esc(pzTxt(P.wj))}

`; - h+=`
${star(e.goal,tr('puzzles.goal'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; - // ○ still to reach, ◐ has a POP, ✓ joined up. A leading mark, so nothing looks cut off. - h+=`
${e.marks.map(m=>` ${esc(CITY[m.c].name)}`).join('')}
`; + h+=`
${star(e.goal,tr('puzzles.delivered'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; + if(P.src.length)h+=`
🗄️ ${tr('puzzles.content_lives_in_list',{list:P.src.map(c=>esc(CITY[c].name)).join(', ')})}
`; + h+=`
${e.flows.map(pzFlowRow).join('')}
`; // Cities to avoid cannot be built in at all, so they read as a rule, not as a box to tick. for(const t of e.tw)h+=t.k==='avoid'?`
🚫 ${tr('puzzles.rule_not_via_list',{list:P.avoid.map(c=>esc(CITY[c].name)).join(', ')})}
`:`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; const sp=fmt$(e.spend); h+=P.budget?`
${tr('puzzles.spent_x_of_y',{x:sp,y:fmt$(P.budget)})}${e.cheap?'✓':'✗'}
` :`
${tr('puzzles.spent_x',{x:sp})}${tr('puzzles.no_budget_star_on_the_house')}
`; - h+=!e.conn?`
🛡 ${tr('puzzles.n_1_connect_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut')}
`:`
⚠️ ${tr('puzzles.one_cut_splits_it_where',{where:pzUnitName(e.weak[0])})}${pzOneMore(e)?`
${tr('puzzles.so_close_one_more_link_and')}`:''}
`; + const w=e.worst; + h+=!e.goal?`
🛡 ${tr('puzzles.n_1_deliver_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut_under_load')}
` + :`
⚠️ ${tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(w.u),g:fmtG(w.g)})}
${w.lost.map(x=>esc(pzFlowName(P.dem[x.i]))).join(', ')}
`; h+=`
${btn('↶ '+tr('puzzles.undo'),'pzUndo',{},'ghost sm',!(UI.pzHist&&UI.pzHist.length))}${btn(tr('puzzles.reset'),'pzReset',{},'ghost sm',!S.links.length&&!Object.keys(S.pops).length)}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}
`; if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +// Trenches on a pair get numbers, cables their names, so parallel links say where they run. +function pzTrench(l){if(l.cable)return esc(CAB[l.cable].name);const us=[...new Set(pairLinks(l.a,l.b).filter(x=>!x.cable).map(pzUnit))];return tr('puzzles.trench_n',{n:us.indexOf(pzUnit(l))+1});} +const pzLoadTxt=l=>`${fmtG(R.load[l.id]||0)} / ${fmtG(capOf(l))}`; +function pzPopSection(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1,G=RG[g],cap=nodeCap(c),ld=R.nodeLoad[c]||0,u=cap?ld/cap:0,pu=portsUsed(c),pm=portsMax(c),cur=pzRtCost(g,rt); + const dl=v=>(v>=0?'+':'−')+fmt$(Math.abs(v)); + let h=`

${tr('puzzles.your_pop')}

${rt>1?rt+' × ':''}${esc(G.n)}${tr('puzzles.price_per_year',{price:fmt$(cur)})}
+
${tr('puzzles.router_load')}${fmtG(ld)} / ${fmtG(cap)}
+
${tr('puzzles.ports')}${tr('puzzles.u_of_m_used',{u:fmtPorts(pu),m:pm})}
${tr('puzzles.biggest_wave')}${LT[G.maxLT].n}
+
${btn(tr('puzzles.add_a_router_cost',{cost:dl(pzRtCost(g,rt+1)-cur)}),'pzRtAdd',{city:c},'sm',rt>=RMAX)}${rt>1?btn(tr('puzzles.remove_a_router'),'pzRtRm',{city:c},'ghost sm'):''}
+

${tr('puzzles.router_model')}

`; + h+=PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i);return `
${esc(M.n)}${i===g?` ${tr('puzzles.installed')}`:''}
${tr('puzzles.model_facts',{cap:fmtG(M.cap),ports:M.ports,wave:LT[M.maxLT].n})}
${why?`
${esc(why)}
`:''}
${i===g?'':btn(dl(pzRtCost(i,rt)-cur),'pzRtModel',{city:c,g:i},'ghost sm',!!why)}
`;}).join(''); + return h;} function pzPanel(sel){const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; - if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c];if(!k)return ''; - const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):tr('puzzles.off_limits'); + if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c],P=S.pz;if(!k)return ''; + const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):k==='off'?tr('puzzles.not_in_the_plan'):tr('puzzles.off_limits'); let h=head(`${PZ_ICON[k]} ${eb}`,esc(C.name),p?`${tr('common.your_pop')}`:'')+'
'; if(k==='avoid')return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

`; - if(!p)h+=`

${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}

${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`; - else{const others=[...S.pz.cities,...S.pz.via].filter(x=>x!==c); - h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

${tr('puzzles.lease_a_wave_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}
`; - const ls=S.links.filter(l=>l.a===c||l.b===c);if(ls.length)h+=`

${tr('common.links')}

`+ls.map(l=>`
${esc(CITY[l.a===c?l.b:l.a].name)}
${capName(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join(''); - h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`;} + // What this city sends or asks for. + const fl=P.dem.map((f,i)=>({f,i})).filter(({f})=>f.a===c||f.b===c),ev=pzEval(); + if(P.src.includes(c))h+=`

🗄️ ${tr('puzzles.the_content_origin_lives_here')}

`; + if(fl.length)h+=`
${fl.map(({i})=>pzFlowRow(ev.flows[i])).join('')}
`; + if(k==='off'&&!p)h+=`

${tr('puzzles.no_traffic_starts_or_ends_here')}

`; + if(!p)return h+`

${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}

${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`; + h+=pzPopSection(c); + // Every pair this POP has links on, with what each member carries, so a second link is never a guess. + const nb=[...new Set(S.links.filter(l=>l.a===c||l.b===c).map(l=>l.a===c?l.b:l.a))]; + h+=`

${tr('common.links')}

`; + if(!nb.length)h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

`; + for(const x of nb){const ls=pairLinks(c,x),ld=ls.reduce((a,l)=>a+(R.load[l.id]||0),0),cp=ls.filter(l=>!linkDown(l)).reduce((a,l)=>a+capOf(l),0); + h+=`
${esc(CITY[x].name)} · ${groupLabel(ls,ls)}${fmtG(ld)} / ${fmtG(cp)}
${ls.map(l=>`
${capName(l)} · ${pzTrench(l)}${l.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join('')}
`;} + const others=[...P.cities,...P.via].filter(x=>x!==c); + h+=`

${tr('puzzles.lease_a_wave_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}

${tr('puzzles.or_drag_to_any_city_on_the_map')}

`; + h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`; return h+'';} - const l=S.links.find(x=>x.id===sel.id);if(!l)return ''; + const l=S.links.find(x=>x.id===sel.id);if(!l)return '';const pl=pairLinks(l.a,l.b); let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${capName(l)}${l.km.toLocaleString()} km${linkLat(l).toFixed(1)} ms${tr('puzzles.price_per_year',{price:fmt$(l.mo*PZ_YEAR)})}`)+'
'; - h+=`

${tr('puzzles.size')}

${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=subWaveWhy(i,l.km,l.sub);return btn(`${LT[i].n} ${tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; + // What it carries now: each circuit by name, the eyeball traffic by where it is going. + {const rec=R.ef[edgeKey(l)],u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`; + if(rec){const rows=[];let l2=0;S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){rows.push([pzFlowName(f),v]);}}); + const byc={};for(const k in rec.dst)byc[k]=rec.dst[k];S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){byc[f.b]=(byc[f.b]||0)-v;l2+=v;}}); + for(const k in byc)if(byc[k]>0.01)rows.push([tr('puzzles.flow_eyeballs_in_city',{city:CITY[k].name}),byc[k]]); + if(rows.length)h+=`

${pl.length>1?tr('puzzles.carrying_on_this_pair',{n:pl.length}):tr('puzzles.carrying')}

`+rows.map(([n,v])=>`
${esc(n)}${fmtG(v)}
`).join('');void l2;}} + if(pl.length>1)h+=`

${tr('puzzles.n_links_on_this_pair',{n:pl.length,what:groupLabel(pl,pl)})}

`+pl.map(x=>`
${capName(x)} · ${pzTrench(x)}${x.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(x)}
${x===l?'':btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join(''); + h+=`

${tr('puzzles.size')}

${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=pzWaveWhy(l.a,l.b,i,r);return btn(`${LT[i].n} ${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; + h+=`

${tr('puzzles.add_another_link_here')}

${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}
`; + h+=metricSection(l)+linkCheckControl(l); return h+`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} // The link picker: overland or one of the real cables between the two cities, and a size. Prices are for a year. function pzLinkModal(a,b,keep){const kb=pzKind(b); - if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.that_city_is_not_part_of'),'bad');sfx('err');return;} - if(!keep){UI.pzVia=null;UI.pzDiv=true;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; + if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;} + if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; if(!rs.length){openModal(head+`

${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}

`);return;} const r=rs.find(x=>x.via===UI.pzVia)||rs.find(x=>!(P.noSub&&x.sub))||rs[0];UI.pzVia=r.via; - const land=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b); - let h=head+`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${x.cab&&CAB[x.cab].age==='old'?'':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; + const pl=pairLinks(a,b),land=!r.sub&&pl.some(l=>!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b); + let h=head; + if(pl.length)h+=`

${tr('puzzles.already_here_list',{list:groupLabel(pl,pl)+' · '+[...new Set(pl.map(pzTrench))].join(', ')})}

`; + h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; if(P.noSub&&r.sub)h+=`

${tr('puzzles.the_sharks_say_no')}

`; - if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}

`; + if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; - h+=`
${PZ_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),c=pzLinkCost(r,i,div)+pop;return ``;}).join('')}
`; + const full=[a,b].filter(c=>!pzPortsFree(c));if(full.length)h+=`

${tr('puzzles.no_free_ports_in_list',{list:full.map(c=>esc(CITY[c].name)).join(', ')})}

`; + h+=`
${PZ_TIERS.map(i=>{const why=pzWaveWhy(a,b,i,r),c=pzLinkCost(r,i,div)+pop;return ``;}).join('')}
`; openModal(h);} // ---------- results ---------- -function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?(pzOneMore(e)?tr('puzzles.so_close_one_more_link_and'):tr('puzzles.one_backhoe_away_from_a_very')):tr('puzzles.rock_solid_and_gold_plated_the');} +function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?tr('puzzles.one_backhoe_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');} // Stars still to win in this puzzle's pack, from the progress just saved. function pzPackLeft(P){const d=pzDef(P.id);if(!d)return null;const p=pzLoad(),xs=PZ.filter(x=>x.pack===d.pack);return xs.length*3-xs.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);} function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h=''; @@ -67,7 +108,7 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left const stars=[0,1,2].map(i=>`⭐`).join(''); openModal(`
${e.stars>=3?pzConfetti():''}
${tr('puzzles.puzzle_solved')}

${esc(pzName(pzDef(P.id)||P))}

${stars}

${pzLine(e)}

${left==null?'':`

${left?trn('puzzles.n_stars_left_in_this_pack',left):tr('puzzles.every_star_in_this_pack_is')}

`} - ${row(true,tr('puzzles.goal'),tr('puzzles.connected'))}${row(e.cheap,tr('puzzles.budget'),P.budget?tr('puzzles.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):tr('puzzles.on_the_house'))}${row(e.n1,'N-1',e.n1?tr('puzzles.survives_any_single_cut'):tr('puzzles.one_cut_splits_it'))} + ${row(true,tr('puzzles.delivered'),tr('puzzles.every_bit_arrives'))}${row(e.cheap,tr('puzzles.budget'),P.budget?tr('puzzles.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):tr('puzzles.on_the_house'))}${row(e.n1,'N-1',e.n1?tr('puzzles.survives_any_single_cut_under_load'):tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(e.worst.u),g:fmtG(e.worst.g)}))}
${nx?btn(tr('puzzles.next_puzzle')+(done?' →':''),'pzStart',{id:nx.id},'pink big pznext'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big pznext')}${!done?btn(tr('puzzles.retry_for_3_stars'),'pzRetry',{},''):''}${btn(tr('common.share_2cd9'),'pzShare',{},done?'ghost':'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`); // Three stars: Next is the one big obvious tap (and the keyboard's default). if(done){const b=document.querySelector('#modalCard .pznext');if(b)try{b.focus({preventScroll:true});}catch(_){}} @@ -75,19 +116,21 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} // ---------- the list ---------- // The weekly row: the published puzzle once it has come (or the seeded one), its countdown and the streak. -function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=pzWkRec(p,w),st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzTwistTag(w); +function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=pzWkRec(p,w),st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzDemTag(w); return `
📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` ${tr('puzzles.new_this_sunday')}`}
${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`${pzStarStr(wr.st)}`:''}
${w.wj?`
${esc(pzTxt(w.wj))}
`:''} -
${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · '+tg.join(' · ')+'':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}
+
${pzCities(w).map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · '+tg.join(' · ')+'':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}
${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}
⏳ ${pzWkNext(Date.now())}
${btn(tr('common.play'),'pzWeekly',{},wr&&wr.st>=3?'ghost':'pink',load)}
`;} function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot); - let h=`
${tr('puzzles.puzzles')}

${tr('puzzles.small_calm_network_builds')}

-

${tr('puzzles.no_clock_no_bills_nothing_breaks')}

-
${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}
`; + let h=`
${tr('puzzles.puzzles')}

${tr('puzzles.small_networks_real_traffic')}

+

${tr('puzzles.no_clock_no_bills_real_traffic')}

`; + // Once, after the puzzles got traffic: the old stars are kept on the wall, the new set starts at zero. + if(p.old&&!p.noted){h+=`
🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}
`;p.noted=1;pzStore(p);} + h+=`
${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}${p.old?`
🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}
`:''}
`; if(pzOn())h+=`
${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; h+=pzWkRow(); for(const pk of PZ_PACKS){const open=tot>=pk.need,got=PZ.filter(x=>x.pack===pk.id).reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0),n=PZ.filter(x=>x.pack===pk.id).length; h+=`

${open?'':'🔒 '}${esc(pk.n)} ⭐ ${got}/${n*3}

${open?esc(pk.d):tr('puzzles.unlocks_at_n_stars',{n:pk.need})}

`; - for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzTwistTag(d); - h+=`
${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${d.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · '+tg.join(' · ')+'':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}
${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}
`;}} + for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzDemTag(d); + h+=`
${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${pzCities(d).map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · '+tg.join(' · ')+'':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}
${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}
`;}} openModal(h);} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index de49bd3..f82dee0 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -28,7 +28,7 @@ function drawFrame(now){ const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY; for(let gi=0;gi1,up=many?grp.filter(x=>!linkDown(x)):null; const gm=GM[gi],cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); - const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);let lab=null; + const pz=pzOn(),sel=(UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id))||(pz&&pzLinkHot(grp));let lab=null; const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length; if(SX.length0.9&&!busy)){const t=lab||(lab=many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} + else if(sel||pz||(z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} } } // drag preview diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index 3c2a0f0..954a64a 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -1,10 +1,16 @@ -/* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring, stepping stones with a dashed one, cities to - avoid crossed out); every other city stays on the map, faded and untappable. */ +/* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring and a badge for what they send or ask for, + stepping stones with a dashed one, cities to avoid crossed out); every other city is on the map as usual, open to + build in but not emphasised. */ +function pzBadge(c){const P=S.pz;return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); - if(!k){ctx.save();ctx.globalAlpha=0.3;drawCity(v.C,v.sx,v.sy,sc,now,null);ctx.restore();return;} + if(!k||k==='off'){drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);return;} const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id]; ctx.save();ctx.lineWidth=3; if(k==='avoid'){ctx.strokeStyle='#FF4D5E';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.moveTo(v.sx-r*.7,y-r*.7);ctx.lineTo(v.sx+r*.7,y+r*.7);ctx.stroke();} else{const a=animOn()?.55+.35*Math.sin(now/300):.8;ctx.strokeStyle=k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(k==='via')ctx.setLineDash([5,5]); ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);} - ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);} + ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly); + const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx+r*.75,y-r*.75);}} +// In a puzzle every line says what it is ("2×100G · 70%"), and a selected POP lights up every pair it has links on. +function pzLinkLab(grp,up,load,cap){return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} +const pzLinkHot=grp=>!!(UI.sel&&UI.sel.type==='city'&&grp.some(x=>x.a===UI.sel.id||x.b===UI.sel.id)); diff --git a/src/i18n/en.js b/src/i18n/en.js index 193d061..a0e51dc 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2907,56 +2907,78 @@ "progress.your_score_peak_traffic":"Your score: peak traffic", "progress.your_traffic_to_and_from_asia":"Your traffic to and from Asia", "puzzles.a_backhoe_walks_into_your_network":"A backhoe walks into your network. Nothing happens.", +"puzzles.a_bigger_boat":"A Bigger Boat", +"puzzles.a_cut_on_where_drops_g":"A cut on {where} drops {g}", +"puzzles.a_different_route":"A different route", +"puzzles.a_diverse_route":"A diverse route (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"A POP costs {setup} to set up, then {mo}/mo. Puzzles count the setup and a year of rent.", -"puzzles.a_tiny_island_where_half_the":"A tiny island where half the Pacific's cables stop for coffee.", -"puzzles.a_to_b_under_ms":"{a} → {b} under {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} under {ms} ms (now {now} ms)", -"puzzles.aloha_latency":"Aloha Latency", +"puzzles.add_a_router_cost":"Add a router {cost}/yr", +"puzzles.add_another_link_here":"Add another link on this pair", +"puzzles.all_of_europe_s_cat_videos":"All of Europe's cat videos live in London, and every one of them goes through your router.", +"puzzles.already_here_list":"Already on this pair: {list}", +"puzzles.another_wave_on_this_cable":"Another wave on this cable", "puzzles.avoid_list":"avoid {list}", "puzzles.back_to_my_network":"Back to my network", "puzzles.back_to_the_title":"Back to the title screen", -"puzzles.beat_the_clock_light_in_glass":"Light in glass does 200 km per millisecond. Pick your cables like it matters.", +"puzzles.baltic_shortcut":"Baltic Shortcut", "puzzles.belt_and_braces":"Belt and Braces", +"puzzles.best_effort":"best effort", "puzzles.best_x":"best {x}", +"puzzles.biggest_wave":"Biggest wave", "puzzles.budget":"Budget", "puzzles.budget_x":"budget {x}", -"puzzles.connect_list":"Connect {list}.", -"puzzles.connected":"Connected", +"puzzles.capacity_first_every_link_has_a":"Capacity first: every link has a size, and the traffic has to fit. Roomy budgets, and the first two are on the house.", +"puzzles.carry_list":"Carry: {list}.", +"puzzles.carrying":"Carrying", +"puzzles.carrying_on_this_pair":"Carrying (all {n} links on this pair)", +"puzzles.content_lives_in_list":"Content lives in {list}: eyeballs pull from the nearest.", "puzzles.copied_paste_it_anywhere":"Copied! Paste it anywhere:
{t}", "puzzles.de_kicks_sales_has_your_number":"DE-KICKS sales has your number. Connect Germany without Frankfurt.", +"puzzles.delivered":"Delivered", "puzzles.diverse_route_40_survives_a_backhoe":"Diverse route (+40%, survives a backhoe)", "puzzles.down_under_up_and_running":"Down Under, Up and Running", "puzzles.drag_from_a_pink_pop_to":"Drag from a pink POP to another city to lease a wave", "puzzles.drag_from_this_pop_onto_another":"Drag from this POP onto another puzzle city, or pick one here.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"every bit arrives", "puzzles.every_internet_starts_with_one_tube":"Every internet starts with one tube.", -"puzzles.every_link_n_g_or_more":"Every link {n}G or more", "puzzles.every_star_in_this_pack_is":"Every star in this pack is yours.", -"puzzles.fat_pipes_only":"Fat Pipes Only", +"puzzles.everything_at_once_across_oceans":"Everything at once, across oceans. Tight budgets.", +"puzzles.fat_pipes":"Fat Pipes", +"puzzles.fjord_focus":"Fjord Focus", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"For architects who sleep through backhoe season.", -"puzzles.four_capitals_one_very_long_winter":"Four capitals, one very long winter, zero excuses for downtime.", +"puzzles.flow_circuit_a_b":"{a} ⇄ {b} circuit", +"puzzles.flow_eyeballs_in_city":"Eyeballs in {city}", "puzzles.four_cities_four_cables_one_ring":"Four cities, one ring. Tolkien would approve; your NOC definitely does.", "puzzles.four_cities_one_continent_and_a":"Four cities, one continent and a lot of corn between them.", +"puzzles.framed_n_stars_from_the_old":"Framed on the wall: {n} ⭐ from the old puzzles", "puzzles.frankfurt_to_singapore_the_short_way":"Frankfurt to Singapore the short way. The long way is overland, and it shows.", "puzzles.free":"Free", -"puzzles.goal":"Goal", "puzzles.goal_city":"Goal city", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hello, World", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: the world's most scenic regeneration site.", +"puzzles.hub_cap":"Hub Cap", "puzzles.includes_a_new_pop_in_city":"Includes a new POP in {city} ({price} for a year).", +"puzzles.installed":"installed", "puzzles.it_works_finance_and_the_backhoe":"It works! Finance and the backhoe would like a word.", "puzzles.keep_building":"Keep building", "puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad", +"puzzles.latency":"Latency", +"puzzles.latency_caps":"latency caps", "puzzles.lease_a_wave_to":"Lease a wave to", "puzzles.loading_this_week_s_puzzle":"Loading this week's puzzle…", +"puzzles.london_wants_half_a_terabit_your":"London wants half a terabit, and your routers came off eBuy.", +"puzzles.model_facts":"{cap} · {ports} ports · waves up to {wave}", "puzzles.more_puzzles":"More puzzles", "puzzles.n_1_club":"N-1 Club", -"puzzles.n_1_connect_everything_first":"N-1: connect everything first", -"puzzles.n_g_links":"{n}G links", +"puzzles.n_1_deliver_everything_first":"N-1: deliver everything first", +"puzzles.n_circuits":{"one":"{n} circuit","other":"{n} circuits"}, +"puzzles.n_g_of_eyeballs":"{n} of eyeballs", +"puzzles.n_links_on_this_pair":"{n} links on this pair: {what}", "puzzles.n_stars_left_in_this_pack":{"one":"{n} ⭐ left in this pack","other":"{n} ⭐ left in this pack"}, "puzzles.n_week_streak":{"one":"{n} week in a row","other":"{n} weeks in a row"}, +"puzzles.needs_what":"needs {what}", "puzzles.new_this_sunday":"New this Sunday!", "puzzles.new_zealand_is_far_from_everything":"New Zealand is far from everything. That is the point, and the problem.", "puzzles.next_pack_unlocks_at_n":"Next pack, {pack}, unlocks at {n}⭐", @@ -2966,26 +2988,31 @@ "puzzles.no_budget":"no budget", "puzzles.no_budget_star_on_the_house":"no budget: ⭐ on the house", "puzzles.no_cable_lands_in_both_try":"No cable lands in both {a} and {b}. Try a stepping stone in between.", -"puzzles.no_clock_no_bills_nothing_breaks":"No clock, no bills, nothing breaks. Connect the cities, then go for three stars: under budget, and still connected when any one link is cut.", +"puzzles.no_clock_no_bills_real_traffic":"No clock, no bills, nothing breaks. Real traffic, routed like the real game: deliver every flow, stay under budget, and keep it all flowing when any one trench or cable is cut.", +"puzzles.no_free_ports_in_list":"No free router ports in {list}: add a router or a bigger model first.", "puzzles.no_subsea":"no subsea", "puzzles.no_subsea_cables":"No subsea cables", -"puzzles.nobody_ever_got_fired_for_buying":"Nobody ever got fired for buying 100G.", +"puzzles.no_traffic_starts_or_ends_here":"No traffic starts or ends here. You can still build here, if it gets you somewhere.", +"puzzles.not_a_city_you_can_build_in":"You can't build in that city.", +"puzzles.not_in_the_plan":"Not in the plan", "puzzles.not_this_one_find_a_way_around":"Not this one. Find a way around.", "puzzles.not_through_frankfurt":"Not Through Frankfurt", "puzzles.off_limits":"Off limits", "puzzles.on_the_house":"On the house", "puzzles.one_backhoe_away_from_a_very":"One backhoe away from a very long night. Add a second path for ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"One cut splits it", -"puzzles.one_cut_splits_it_where":"One cut splits it: {where}", "puzzles.one_ring_through_every_pop":"One ring through every POP", "puzzles.one_very_big_island_and_a":"One very big island, and a lot of very empty fiber.", "puzzles.open_a_pop_cost":"Open a POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping Pong to Tokyo", +"puzzles.or_drag_to_any_city_on_the_map":"Or drag to any city on the map: the whole world is open.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris wants 150G. One 100G wave is a garden hose.", +"puzzles.port_authority":"Port Authority", +"puzzles.ports":"Ports", "puzzles.price_per_year":"{price}/yr", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle solved", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Puzzles got traffic! Every puzzle now carries real flows, so the stars start again. Your old {n} ⭐ are framed on the wall.", +"puzzles.remove_a_router":"Remove a router", "puzzles.remove_this_link":"Remove this link", "puzzles.remove_this_pop":"Remove this POP", "puzzles.reset":"Reset", @@ -2993,41 +3020,49 @@ "puzzles.ring":"ring", "puzzles.ring_of_fire":"Ring of Fire", "puzzles.rock_solid_and_gold_plated_the":"Rock solid, and gold plated. The CFO has questions.", +"puzzles.router_load":"Router load", +"puzzles.router_model":"Router model", +"puzzles.router_rodeo":"Router Rodeo", +"puzzles.routers_have_ports_and_a_limit":"Routers have ports and a limit. Fill one and the traffic stops at the door.", "puzzles.rule_not_via_list":"Rule: not via {list}", "puzzles.samba_sprint":"Samba Sprint", +"puzzles.same_cable_same_anchor":"Same cable as a link you have: one anchor takes both.", "puzzles.same_puzzle_for_everyone_this_week":"Same puzzle for everyone this week", +"puzzles.same_trench_cheaper":"Same trench (cheaper)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Same trench (cheaper, one backhoe cuts both)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo to Miami before the caipirinha gets warm.", "puzzles.sea_to_shining_sea":"Sea to Shining Sea", -"puzzles.seattle_to_singapore_with_a_stop":"Seattle to Singapore, with a stop for sushi and dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Six cities, a few gigs each, and a router with eight ports. Count before you dig.", "puzzles.size":"Size", -"puzzles.small_calm_network_builds":"Small, calm network builds", -"puzzles.smorgasbord":"Smörgåsbord", -"puzzles.so_close_one_more_link_and":"So close: one more link and a backhoe can't touch you.", -"puzzles.speed_runs":"Speed Runs", +"puzzles.small_networks_real_traffic":"Small networks, real traffic", "puzzles.spent_x":"Spent {x}", "puzzles.spent_x_of_y":"Spent {x} / {y}", "puzzles.stepping_stone_optional":"Stepping stone (optional)", "puzzles.suez_you_later":"Suez You Later", -"puzzles.survives_any_single_cut":"Survives any single cut", +"puzzles.survive_any_single_cut_with_the":"Survive any single cut, with the traffic still flowing. Connected is not enough.", +"puzzles.survives_any_single_cut_under_load":"Survives any single cut, under load", "puzzles.tap_a_goal_city_to_open":"Tap a glowing city to open your first POP", -"puzzles.that_city_is_not_part_of":"That city is not part of this puzzle.", -"puzzles.the_pacific_is_big_light_is":"The Pacific is big. Light is fast. Your budget is neither.", -"puzzles.the_pacific_rim_where_every_hop":"The Pacific rim, where every hop is an ocean.", +"puzzles.the_content_origin_lives_here":"The content lives here. Eyeballs elsewhere pull from it.", +"puzzles.the_oil_rigs_want_their_numbers":"The oil rigs want their numbers fast. The shortest road to Stavanger is not the quickest.", +"puzzles.the_road_to_tallinn_is_short":"The road to Tallinn is short. The light through Helsinki is shorter.", "puzzles.the_shark_tank":"The Shark Tank", "puzzles.the_sharks_have_been_biting_again":"The sharks have been biting again. Keep it on dry land.", "puzzles.the_sharks_say_no":"The sharks say no.", +"puzzles.this_link":"This link", "puzzles.three_cities_two_currencies_one_very":"Three cities, two currencies, one very short tunnel under the sea.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Traders paid millions to shave milliseconds off this route. You get to do it for less.", +"puzzles.traffic_cops":"Traffic Cops", +"puzzles.trench_n":"trench {n}", "puzzles.two_cables_across_the_atlantic_because":"Two cables across the Atlantic, because one is a hope, not a plan.", -"puzzles.under_n_ms":"under {n} ms", +"puzzles.u_of_m_used":"{u} of {m} used", "puzzles.undo":"Undo", "puzzles.unlocks_at_n_stars":"Unlocks at {n}⭐", "puzzles.weekly_puzzle":"Weekly puzzle", "puzzles.weekly_puzzle_key":"Weekly puzzle {key}", "puzzles.with_the_pop_price":"with the POP: {price}", -"puzzles.your_first_tubes_roomy_budgets":"Your first tubes. Roomy budgets, and the first two are on the house.", +"puzzles.your_pop":"Your POP", +"puzzles.your_routers_pick_the_path":"Your routers pick the path. Tell them which: metrics, lowest latency, best effort.", "puzzles.your_stars":"Your stars", "puzzles_weekly.detour":"Detour", "puzzles_weekly.island_hopping":"Island hopping", diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index e879143..a126f60 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -8,6 +8,12 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzck{display:flex;flex-wrap:wrap;gap:5px;margin:6px 0}.pzc{font-weight:900;font-size:12px;border:2px solid var(--ink);border-radius:999px;padding:1px 8px;background:#fff} .pzc i{font-style:normal} .pzc.s1{background:#FFE3F0}.pzc.s2{background:var(--ok);color:#fff} +.pzsrc{font-size:12px;font-weight:800;color:var(--ink2);margin:4px 0} +.pzfl{margin:4px 0 6px}.pzf{margin:4px 0;padding:3px 6px;border:2px solid var(--line);border-radius:10px}.pzf.ok{border-color:var(--ok)} +.pzf .kv{font-size:12px;gap:6px}.pzf .bar{margin:2px 0}.pzf .meta .bad{color:var(--bad);font-weight:900}.pzf .seg.pzrt{margin-top:3px} +.pzpair{border-top:2px dashed var(--line);padding-top:4px;margin-top:4px}.pzhave{font-size:13px;font-weight:800;margin:6px 0;padding:4px 8px;border-radius:10px;background:#FFF4D6} +.pznote{font-weight:800;font-size:13.5px;margin:8px 0;padding:8px 10px;border:2.5px solid var(--ink);border-radius:12px;background:#FFF3C4} +.row.on{background:#FFE3F0;border-radius:10px} .pztw{font-size:12.5px;font-weight:800;color:var(--bad);margin:3px 0}.pztw.ok{color:var(--eye)}.pztw.rule{color:var(--ink2)} .pzbud{margin:6px 0}.pzbud .kv{font-size:12.5px} .pzn1{font-size:12.5px;font-weight:800;margin:6px 0;padding:4px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 9290a77..8e1db0d 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -1,99 +1,94 @@ -// Puzzle mode (#190): small builds with stars, no clock, and a main save that is never touched. +// Puzzle mode (#190), with traffic: small builds that carry real flows, routed by the game's own compute(), 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'); +const SV = require('../scripts/lib/puzzle-solver'); -// 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. +/* Reference solutions, played through the player's own actions. A link is [a, b, route ('land' or a cable id), tier + (0 = 10G, 1 = 100G, 2 = 400G), same]: a further overland link on a pair takes a diverse route, or with same = k + goes into the k-th trench already there (added from the link panel). ['@rt', city, model, count] sets a POP's + routers (RG index), ['@route', flow, 'fast'] sends a circuit the lowest-latency way. `one` earns the delivery star, + `three` all three: the three-star ones are the cheapest builds the solver (scripts/lib/puzzle-solver.js) found. */ const REF = { - hello: { one: [['lon', 'nyc', 'grace']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'amitie']] }, - eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['ams', 'lon', 'concerto'], ['ams', 'lon', 'nshuttle'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] }, - shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['chi', 'nyc', 'land'], ['chi', 'sjc', 'land'], ['dal', 'nyc', 'land'], ['dal', 'sjc', 'land']] }, - smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['cph', 'osl', 'land'], ['cph', 'hel', 'land'], ['hel', 'sto', 'land']] }, - downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['mel', 'syd', 'land'], ['bne', 'syd', 'land'], ['adl', 'mel', 'land'], ['adl', 'bne', 'land']] }, - aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['hnl', 'sjc', 'scx'], ['hnl', 'sjc', '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'], ['hkg', 'tok', 'apg'], ['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['hkg', 'sin', 'land']] }, - fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] }, - // Hawaiki is Seattle's only cable south, so the second way out runs overland to LA and on via Suva. - kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'syd', 'tasman'], ['akl', 'sea', 'hwk'], ['suv', 'syd', 'scxn'], ['lax', 'sea', 'land'], ['lax', 'suv', 'scxn']] }, - guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['mnl', 'tok', 'jup'], ['syd', 'tok', 'sushi'], ['gum', 'mnl', 'bifrost'], ['gum', 'syd', 'guam']] }, - flash: { one: [['nyc', 'lon', 'hibx']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'hibx']] }, - 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'], ['bom', 'sin', 'land'], ['bom', 'mrs', 'twoaf']] }, - samba: { one: [['sao', 'mia', 'monet']], three: [['for', 'sao', 'land'], ['for', 'sao', 'land'], ['for', 'mia', 'monet'], ['for', 'mia', 'sam1']] }, - sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['lis', 'mil', 'land'], ['mad', 'par', 'land'], ['mil', 'par', 'land']] }, - braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['lon', 'nyc', 'grace'], ['dub', 'nyc', 'havf'], ['dub', 'lon', 'celtix']] }, - nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ams', 'zrh', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']] }, - fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'zrh', 'land', 1], ['mrs', 'par', 'land', 1], ['mil', 'mrs', 'land', 1], ['mil', 'zrh', 'land', 1]] }, + hello: { one: [['nyc', 'lon', 'grace', 0]], three: [['nyc', 'lon', 'grace', 0], ['nyc', 'lon', 'amitie', 0]] }, + eurotrip: { one: [['ams', 'lon', 'nshuttle', 1], ['ams', 'fra', 'land', 1]], three: [['ams', 'lon', 'concerto', 1], ['ams', 'lon', 'nshuttle', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]] }, + bigboat: { one: [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1]], three: [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1]] }, + shining: { one: [['nyc', 'chi', 'land', 1], ['dal', 'sjc', 'land', 1], ['nyc', 'dal', 'land', 1]], three: [['nyc', 'chi', 'land', 1], ['nyc', 'chi', 'land', 1], ['chi', 'sjc', 'land', 1], ['dal', 'sjc', 'land', 1], ['nyc', 'dal', 'land', 1]] }, + downunder: { one: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1]], three: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1], ['bne', 'adl', 'land', 1]] }, + edgelord: { one: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]], three: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]] }, + hubcap: { one: [['@rt', 'lon', 5, 1], ['lon', 'par', 'pasdc', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]], three: [['@rt', 'lon', 5, 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'uly', 1]] }, + flash: { one: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]] }, + baltic: { one: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['@route', 1, 'fast']], three: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['fra', 'tll', 'land', 1], ['@route', 1, 'fast']] }, + fjord: { one: [['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']], three: [['par', 'svg', 'land', 1], ['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']] }, + braces: { one: [['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]] }, + sharks: { one: [['lis', 'mad', 'land', 1], ['lis', 'bcn', 'land', 1], ['par', 'mil', 'land', 1], ['par', 'mrs', 'land', 1], ['bcn', 'mrs', 'land', 1]], three: [['lis', 'mad', 'land', 1], ['lis', 'mad', 'land', 1], ['lis', 'bcn', 'land', 1], ['mad', 'bcn', 'land', 1], ['par', 'mil', 'land', 1], ['par', 'mrs', 'land', 1], ['mil', 'bcn', 'land', 1], ['bcn', 'mrs', 'land', 1]] }, + nofra: { one: [['ams', 'dus', 'land', 1], ['ams', 'dus', 'land', 1], ['ber', 'ham', 'land', 1], ['muc', 'zrh', 'land', 1], ['muc', 'dus', 'land', 1], ['ham', 'dus', 'land', 1]], three: [['ams', 'ham', 'land', 1], ['ams', 'dus', 'land', 1], ['ams', 'dus', 'land', 1], ['ber', 'ham', 'land', 1], ['ber', 'ham', 'land', 1], ['muc', 'zrh', 'land', 1], ['muc', 'dus', 'land', 1], ['zrh', 'dus', 'land', 1], ['ham', 'dus', 'land', 1]] }, + fire: { one: [['tok', 'hkg', 'adc', 1], ['hkg', 'sin', 'land', 1], ['sin', 'syd', 'indigo', 1], ['syd', 'tok', 'guam', 1]], three: [['tok', 'hkg', 'adc', 1], ['hkg', 'sin', 'land', 1], ['sin', 'syd', 'indigo', 1], ['syd', 'tok', 'guam', 1]] }, + suez: { one: [['fra', 'mrs', 'land', 1], ['sin', 'mrs', 'peace', 1]], three: [['fra', 'mrs', 'land', 1], ['fra', 'mrs', 'land', 0], ['sin', 'mrs', 'peace', 1], ['sin', 'bom', 'land', 0], ['mrs', 'bom', 'twoaf', 0]] }, + kiwi: { one: [['sea', 'lax', 'land', 1], ['akl', 'syd', 'tasman', 1], ['akl', 'hnl', 'hwk', 1], ['hnl', 'lax', 'seaus', 1]], three: [['sea', 'hnl', 'hwk', 1], ['sea', 'lax', 'land', 1], ['akl', 'syd', 'scx', 1], ['akl', 'syd', 'tasman', 1], ['akl', 'hnl', 'hwk', 1], ['akl', 'suv', 'scx', 1], ['hnl', 'suv', 'scx', 1], ['hnl', 'lax', 'seaus', 1]] }, + samba: { one: [['mia', 'for', 'monet', 1], ['sao', 'rio', 'land', 1], ['sao', 'for', 'land', 1]], three: [['mia', 'for', 'monet', 1], ['mia', 'for', 'sam1', 1], ['sao', 'rio', 'land', 1], ['sao', 'for', 'land', 1], ['rio', 'for', 'land', 1]] }, + ports: { one: [['@rt', 'zrh', 4, 1], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0]], three: [['@rt', 'zrh', 5, 1], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0]] }, }; -// 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) { +function build(ev, steps) { + for (const s of steps) { + if (s[0] === '@rt') { const [, c, g, n] = s; if (!ev(`!!S.pops['${c}']`)) ev(`ACT.pzPop({city:'${c}'})`); if (g) ev(`ACT.pzRtModel({city:'${c}',g:${g}})`); for (let i = 1; i < n; i++) ev(`ACT.pzRtAdd({city:'${c}'})`); continue; } + if (s[0] === '@route') { ev(`ACT.pzRoute({i:${s[1]},m:'${s[2]}'})`); continue; } + const [a, b, via, tier, same] = s; 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}})`); + if (same) ev(`(()=>{const ls=S.links.filter(l=>edgeKey(l)===edgeKey({a:'${a}',b:'${b}'})&&!l.cable),ts=[...new Set(ls.map(pzUnit))],l=ls.find(x=>pzUnit(x)===ts[${same - 1}]);ACT.pzAddPar({id:l.id,div:0});ACT.pzLink({tier:${tier}})})()`); + else 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())')); +const links = (steps) => steps.filter((s) => s[0] !== '@rt'); -test('puzzle data: every puzzle is valid, solvable, and its 3-star reference earns three stars', () => { +test('puzzle data: every puzzle is valid, carries traffic, and its references earn their stars through the real routing', () => { 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.ok(ids.length >= 16 && ids.length <= 20, '16 to 20 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=>PZ_PACKS.some(k=>k.id===p.pack)&&p.n&&p.j&&p.dem.length>=1&&pzCities(p).length>=2&&pzCities(p).length<=7&&[...pzCities(p),...(p.via||[]),...(p.avoid||[])].every(pzCityOk))"), 'cities exist and are playable'); + assert.ok(ev("PZ.every(p=>p.dem.every(f=>f.g>0&&(f.t==='eye'?(p.src||[]).length>0&&!p.src.includes(f.a):f.t==='l2'&&f.a!==f.b)))"), 'eyeballs have an origin, circuits two ends'); 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_PACKS.every(k=>PZ.filter(p=>p.pack===k.id).length>=3)"), 'every pack has at least three puzzles'); 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`); + assert.ok(e.goal, `${id}: the one-star reference delivers everything (${JSON.stringify(e.flows.map((x) => [x.g, x.ms]))})`); 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.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, worst cut ${JSON.stringify(e.worst)})`); } assert.deepEqual(errors, []); }); -// Brute force over every route between the puzzle's cities (one size: 10G, or 100G under minG): is any 3-star build -// cheaper than `limit`? Each cable is one failure unit; each overland link its own trench (a second one is diverse). -function cheaper3(ev, id, limit) { - const D = JSON.parse(ev(`(()=>{pzBegin(pzDef('${id}'));const P=S.pz,cs=[...P.cities,...P.via],tier=P.minG?1:0,o=[]; - for(const a of cs)for(const b of cs)if(a o[i].cab ? 'c' + o[i].cab : 't' + i; - const reach = (ls, skip) => { const adj = {}; for (const i of ls) { if (unit(i) === skip) continue; const { a, b } = o[i]; (adj[a] = adj[a] || []).push(b); (adj[b] = adj[b] || []).push(a); } - const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) for (const v of adj[q.pop()] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } return P.cities.every((c) => seen.has(c)); }; - const lat = (ls) => { const d = { [P.lat[0]]: 0 }, done = new Set(); for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null) return Infinity; if (u === P.lat[1]) return d[u]; done.add(u); - for (const i of ls) { const l = o[i]; if (l.a !== u && l.b !== u) continue; const v = l.a === u ? l.b : l.a, nd = d[u] + l.ms + 0.05; if (!(nd >= d[v])) d[v] = nd; } } }; - const ring = (ls) => { const nb = {}; for (const i of ls) { const { a, b } = o[i]; (nb[a] = nb[a] || new Set()).add(b); (nb[b] = nb[b] || new Set()).add(a); } const ns = Object.keys(nb); - if (ns.length < 3 || !ns.every((c) => nb[c].size === 2)) return false; let prev = null, cur = ns[0], n = 0; do { const nx = [...nb[cur]].find((x) => x !== prev); prev = cur; cur = nx; n++; } while (cur !== ns[0] && n <= ns.length); return n === ns.length; }; - const ok = (ls) => { if (!reach(ls, null) || (P.ring && !ring(ls)) || (P.lat && lat(ls) > P.lat[2])) return false; return [...new Set(ls.map(unit))].every((u) => reach(ls, u)); }; - let found = null; - const rec = (start, ls, cost) => { if (found) return; if (ls.length && cost < limit - 1) { const pops = new Set(P.cities); for (const i of ls) { pops.add(o[i].a); pops.add(o[i].b); } const tot = cost + [...pops].reduce((x, c) => x + pop[c], 0); if (tot < limit - 1 && ok(ls)) { found = tot; return; } } - if (ls.length >= 7) return; for (let i = start; i < o.length; i++) { if (o[i].div && !ls.some((j) => !o[j].div && !o[j].cab && o[j].a === o[i].a && o[j].b === o[i].b)) continue; if (cost + o[i].cost < limit - 1) rec(i + 1, [...ls, i], cost + o[i].cost); } }; - rec(0, [], 0); - return found; -} - -test('budgets follow the difficulty curve: roomy first pack, ~10% in the middle, tight N-1 Club', () => { +test('budgets follow the teaching curve, and each 3-star reference is the cheapest build nearby', () => { const { ev, errors } = load(); - const SLACK = { hello: [0.15, 0.2], fire: [0.09, 0.11], speed: [0.09, 0.11], n1: [0.05, 0.08] }; + SV.install(ev); + // Slack over the cheapest 3-star build found: roomy first, tight at the end. Traffic Cops is tight on purpose: the + // routing trick (a circuit on the lowest-latency path) is what brings it under budget. + const SLACK = { hello: [0.15, 0.22], rodeo: [0.09, 0.13], cops: [0.03, 0.06], n1: [0.05, 0.08], final: [0.04, 0.07] }; const rows = JSON.parse(ev('JSON.stringify(PZ.filter(p=>p.budget).map(p=>({id:p.id,pack:p.pack,budget:p.budget})))')); for (const { id, pack, budget } of rows) { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].three); const e = evalP(ev); assert.equal(e.stars, 3, id); - assert.equal(cheaper3(ev, id, e.spend), null, `${id}: the reference is the cheapest 3-star build`); + // The routers in the reference are the cheapest that carry it: the solver prices the same build the same. + const L = links(REF[id].three), j = SV.judge(ev, L); + assert.ok(j.three && Math.abs(j.spend - e.spend) < 1, `${id}: solver ${j.spend} vs game ${e.spend}`); + // No single change (drop a link, shrink one, move it to another route or trench) keeps three stars for less. + const r = SV.improve(ev, L); + assert.ok(r.spend >= e.spend - 1, `${id}: ${JSON.stringify(r.links)} is cheaper (${r.spend})`); const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack]; assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`); } @@ -101,58 +96,331 @@ test('budgets follow the difficulty curve: roomy first pack, ~10% in the middle, assert.deepEqual(errors, []); }); -test('stars: goal, budget, N-1 and twists each count', () => { +test('stars come from traffic: capacity, latency caps, best effort and N-1 under load', () => { const { ev, errors } = load(); - ev("pzBegin(pzDef('braces'))"); - build(ev, REF.braces.one); + // Connected is not delivered: a 10G wave for 30G of London eyeballs gets 10G there. + ev("pzBegin(pzDef('eurotrip'))"); + build(ev, [['ams', 'lon', 'nshuttle', 0], ['ams', 'fra', 'land', 1]]); 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.ok(!e.goal && Math.abs(e.flows[0].g - 10) < 0.1, `10G of 30G (${e.flows[0].g})`); + assert.match(ev("document.getElementById('pzBox').textContent"), /Eyeballs in London(9\.\d|10\.0) Gbps \/ 30\.0 Gbps/); + ev("ACT.pzTier({id:S.links[0].id,tier:1})"); + assert.ok(evalP(ev).goal, 'a 100G wave carries it'); + // N-1 under load: two trenches into Paris are connected after a cut, but one 100G wave cannot carry 150G. + ev("pzBegin(pzDef('bigboat'))"); + build(ev, [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1, 1], ['fra', 'par', 'land', 1]]); + e = evalP(ev); + assert.ok(e.goal && !e.n1, 'still connected after a cut, but short'); + assert.equal(Math.round(e.worst.g), 50, 'cutting the trench with two waves leaves 100G for 150G: 50G drop'); + assert.match(ev("document.getElementById('pzBox').textContent"), /A cut on Frankfurt ⇄ Paris drops 50\.\d Gbps/); + build(ev, [['fra', 'par', 'land', 1, 2]]); + assert.ok(evalP(ev).n1, 'two waves in each trench: either one carries Paris alone'); + // A latency cap: Grace Hopscotch is too slow for the traders; the eyeballs are best effort and may drop on a cut. + ev("pzBegin(pzDef('flash'))"); + build(ev, [['nyc', 'lon', 'grace', 1]]); + e = evalP(ev); + assert.ok(!e.goal && e.flows[0].full && !e.flows[0].fast, 'all of the circuit, but at 29 ms'); + build(ev, [['nyc', 'lon', 'hibx', 0]]); + e = evalP(ev); + assert.equal(e.stars, 3, 'the fast cable for the circuit; when the big one is cut, only best effort drops'); + // A circuit follows the metrics unless told otherwise: the road to Tallinn is shorter, the light via Helsinki faster. + ev("pzBegin(pzDef('baltic'))"); + build(ev, links(REF.baltic.three).filter((s) => s[0] !== '@route')); + e = evalP(ev); + assert.ok(!e.goal && e.flows[1].ms > 8.8, `the metric path is too slow (${e.flows[1].ms})`); + assert.ok(ev("!!document.querySelector('#pzBox [data-act=pzRoute]')"), 'the card has the circuit\'s route switch'); + ev("document.querySelector('#pzBox [data-act=pzRoute][data-args*=fast]').click()"); + e = evalP(ev); + assert.ok(e.goal && e.flows[1].ms <= 8.8, 'lowest latency goes via Helsinki'); + ev('ACT.pzUndo({})'); + assert.equal(ev("S.biz[0].route"), 'normal', 'undo takes the route back'); + // The main game's metric control works in a puzzle and moves the traffic: Backup only on the road pushes the + // eyeballs through Helsinki too. + ev("ACT.pzRoute({i:1,m:'fast'});ACT.selLink({id:S.links.find(l=>edgeKey(l)==='fra|tll').id})"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Routing metric/); + ev("ACT.setMetric({id:S.links.find(l=>edgeKey(l)==='fra|tll').id,v:'backup'})"); + assert.ok(ev("(R.load[S.links.find(l=>edgeKey(l)==='fra|tll').id]||0)<0.01"), 'nothing on a backup-only link while the others are up'); + ev('ACT.pzUndo({})'); + assert.ok(ev("!S.pairMet['fra|tll']"), 'undo takes the metric back'); + // Over budget loses the second star only. + ev("pzBegin(pzDef('braces'))");build(ev, REF.braces.three); 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'); - // A cable fails as a whole: two waves on one cable, even between different cities, are one cut. - ev("pzBegin(pzDef('guam'))"); - build(ev, [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']]); - e = evalP(ev); - assert.ok(e.goal && !e.n1, 'both of Sydney\'s links ride the Guam cable: one anchor splits Sydney off'); - assert.equal(ev("new Set(S.links.filter(l=>l.cable==='guam').map(pzUnit)).size"), 1, 'one cable, one failure unit'); - assert.ok(ev("document.getElementById('pzBox').textContent").includes('One cut splits it: ' + ev('CAB.guam.name')), 'the weak spot names the cable'); - ev("ACT.pzRmLink({id:S.links[3].id})");build(ev, [['tok', 'syd', 'sushi']]); - assert.equal(evalP(ev).stars, 3, 'a second cable into Sydney fixes it'); - // 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.equal(evalP(ev).stars, 2); + // A cable fails as a whole: two waves on one cable are one cut. + ev("pzBegin(pzDef('kiwi'))"); + build(ev, [['akl', 'syd', 'scx', 1], ['akl', 'suv', 'scx', 1]]); + assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 1, 'one cable, one failure unit'); assert.deepEqual(errors, []); }); +test('parallel links say how many they are and where they run; diversity from the link panel', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('bigboat'))"); + build(ev, [['fra', 'par', 'land', 1]]); + const id = ev('S.links[0].id'); + ev(`ACT.selLink({id:'${id}'})`); + let panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /Add another link on this pair/); + // Same trench from the panel: no surcharge, one failure unit, one line on the map labelled 2×100G. + ev(`ACT.pzAddPar({id:'${id}',div:0})`); + assert.match(ev("document.getElementById('modalCard').textContent"), /Already on this pair: 1×100G · trench 1/); + ev('ACT.pzLink({tier:1})'); + assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 1); + assert.equal(ev('S.links[1].mo'), ev('S.links[0].mo')); + assert.equal(ev("pzLinkLab(S.links,S.links,R.load[S.links[0].id]+R.load[S.links[1].id],200)"), '2×100G · 75%'); + assert.equal(ev("groupLabel(linkGroups()[0],linkGroups()[0])"), '2×100G', 'the map draws one line for the trench, labelled with its count'); + // A diverse one from the panel: its own trench, 40% dearer, its own line. + ev(`ACT.pzAddPar({id:'${id}',div:1});ACT.pzLink({tier:1})`); + assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 2); + assert.equal(ev('S.links[2].mo'), ev('Math.round(S.links[0].mo*DIVERSE)')); + assert.equal(ev('linkGroups().length'), 2); + ev(`ACT.selLink({id:'${id}'})`); + panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /3 links on this pair: 3×100G/); + assert.match(panel, /trench 1/); + assert.match(panel, /trench 2/); + // Selecting a city lights up every pair it has links on, and its panel lists them with their loads. + ev("selectCity('par')"); + assert.ok(ev('pzLinkHot(S.links)')); + panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /Frankfurt · 3×100G150 Gbps \/ 300 Gbps/); + // A subsea link: "a different route" picks another cable. + ev("pzBegin(pzDef('hello'))");build(ev, [['nyc', 'lon', 'grace', 0]]); + ev("ACT.pzAddPar({id:S.links[0].id,div:1})"); + assert.notEqual(ev('UI.pzVia'), 'grace'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Already on this pair: 1×10G/); + assert.deepEqual(errors, []); +}); + +test('routers in a puzzle: ports, wave sizes and capacity as in the main game, priced into the budget', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('edgelord'))"); + build(ev, [['ams', 'lon', 'nshuttle', 0]]); + // A Rusty Router lights 100G at most. + ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'concerto'})"); + assert.match(ev("document.querySelector('#modalCard .tierbtn[data-args*=\"2\"]').textContent"), /needs 400G routers/); + assert.equal(ev("document.querySelector('#modalCard .tierbtn[data-args*=\"2\"]').disabled"), true); + ev('closeModal()'); + // Eight ports: the ninth wave is refused, a second router makes room, and it is in the bill. + for (let i = 0; i < 7; i++) ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})"); + assert.equal(ev('S.links.length'), 8); + ev("ACT.pzLinkTo({a:'ams',b:'lon'})"); + assert.match(ev("document.getElementById('modalCard').textContent"), /No free router ports in Amsterdam, London/); + ev("ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})"); + assert.equal(ev('S.links.length'), 8, 'no port, no wave'); + const sp0 = evalP(ev).spend; + ev("ACT.pzRtAdd({city:'ams'});ACT.pzRtAdd({city:'lon'})"); + assert.equal(evalP(ev).spend - sp0, ev('2*pzRtCost(0,2)'), 'two second routers, priced as the main game prices them'); + ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})"); + assert.equal(ev('S.links.length'), 9); + ev("ACT.pzRtRm({city:'ams'})"); + assert.equal(ev('S.pops.ams.routers'), 2, 'cannot drop a router whose ports are in use'); + // The city panel shows the POP: model, load against capacity, ports. + ev("selectCity('lon')"); + const panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /2 × Rusty Router 9000/); + assert.match(panel, /Ports9 of 16 used/); + assert.match(panel, /Router load90\.0 Gbps \/ 800 Gbps/); + // Capacity: a Rusty Router moves 400G. Three 400G waves on Sonic routers bring 1.2T, but a Rusty-sized POP would + // stop at 400G of the 500G London wants. + ev("pzBegin(pzDef('edgelord'))"); + build(ev, [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2]]); + assert.equal(Math.round(evalP(ev).flows[0].g), 500); + ev("ACT.pzRtModel({city:'lon',g:0})"); + assert.equal(ev('S.pops.lon.rgen'), 5, 'a Rusty Router cannot take a 400G wave: the swap is refused'); + ev("S.pops.lon.rgen=4;UI.pzEv=null");// a Mikrowtik moves 300G (set directly: it refuses 400G waves too) + assert.ok(Math.abs(evalP(ev).flows[0].g - 300) < 5, 'the router is the bottleneck'); + assert.deepEqual(errors, []); +}); + +test('the whole world is open: an off-plan city can get a POP and links, and it counts in the budget', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('bigboat'))"); + assert.equal(ev("pzKind('bru')"), 'off'); + ev("selectCity('bru')"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Not in the plan/); + ev("ACT.pzPop({city:'bru'})"); + assert.ok(ev('!!S.pops.bru')); + const sp = evalP(ev).spend; + assert.equal(sp, ev("pzPopCost('bru')")); + ev("ACT.pzLinkTo({a:'bru',b:'par'});ACT.pzVia({v:'land'});ACT.pzLink({tier:1})"); + ev("ACT.pzLinkTo({a:'bru',b:'fra'});ACT.pzVia({v:'land'});ACT.pzLink({tier:1})"); + const e = evalP(ev); + assert.ok(e.spend > sp && Math.round(e.flows[0].g) === 100, 'Paris gets 100G through Brussels'); + assert.equal(ev("pzKind('pek')"), null, 'cities that need a licence stay out'); + ev("pzBegin(pzDef('nofra'));ACT.pzPop({city:'fra'})"); + assert.equal(ev('!!S.pops.fra'), false, 'a city to avoid stays off limits'); + assert.deepEqual(errors, []); +}); + +test('determinism and speed: the same build always gets the same stars, fast enough on the biggest puzzle', () => { + const { ev, errors } = load(); + const run = (id) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].three); ev('UI.pzEv=null'); const a = ev('JSON.stringify(pzEval())'); ev('UI.pzEv=null'); return [a, ev('JSON.stringify(pzEval())')]; }; + const [a, b] = run('kiwi'), [c] = run('kiwi'); + assert.equal(a, b, 'twice in a row'); + assert.equal(a, c, 'and from scratch'); + // The biggest puzzle by failure units: one full evaluation (routing plus every single cut). + const big = ev("PZ.map(p=>p.id).sort()[0]") && JSON.parse(ev('JSON.stringify(PZ.map(p=>p.id))')).map((id) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].three); return [id, ev('new Set(S.links.map(pzUnit)).size')]; }).sort((x, y) => y[1] - x[1])[0]; + ev(`pzBegin(pzDef('${big[0]}'))`); build(ev, REF[big[0]].three); + for (let i = 0; i < 3; i++) ev('UI.pzEv=null;pzEval()'); + const ms = ev('(()=>{const t=performance.now();for(let i=0;i<5;i++){UI.pzEv=null;pzEval();}return (performance.now()-t)/5})()'); + console.log(`# star evaluation on ${big[0]} (${big[1]} failure units): ${ms.toFixed(1)} ms`); + assert.ok(ms < 150, `${big[0]}: ${ms.toFixed(1)} ms`); + assert.deepEqual(errors, []); +}); + +test('progress: the puzzle set with traffic starts the stars again once, with the old ones framed', () => { + const { ev, errors } = load(); + ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:3,sp:1},eurotrip:{st:2},gone:{st:3}},wk:{'2026-W40':{st:3,sp:9}},streak:{last:'2026-W40',n:2,best:4}}))"); + let p = JSON.parse(ev('JSON.stringify(pzLoad())')); + assert.deepEqual(p.s, {}, 'old stars do not count in the new set'); + assert.equal(p.old, 8); + assert.deepEqual(p.wk, { '2026-W40': { st: 3, sp: 9 } }, 'weekly results stay'); + assert.equal(p.streak.best, 4, 'and so does the streak'); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Puzzles got traffic!.*Your old 8 ⭐ are framed on the wall/); + ev('closeModal();ACT.puzzleMenu({})'); + assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /Puzzles got traffic!/, 'the note shows once'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Framed on the wall: 8 ⭐/); + // New stars are kept under the new set. + ev("pzBegin(pzDef('hello'))");build(ev, REF.hello.three); + p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); + assert.equal(p.set, 2); + assert.equal(p.s.hello.st, 3); + assert.equal(JSON.parse(ev('JSON.stringify(pzLoad())')).old, 8); + // Bad data is ignored. + ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:{hello:{st:99,sp:'x'},nope:{st:3}},old:'',wk:{bad:{st:3}},streak:{n:-4,last:''}}))"); + p = JSON.parse(ev('JSON.stringify(pzLoad())')); + assert.deepEqual(p.s, { hello: { st: 3, sp: null } }); + assert.equal(p.old, 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); + // Packs unlock by the new stars. + ev("localStorage.removeItem('sot-puzzles')"); + assert.equal(ev("pzPackOpen('rodeo')"), false); + ev("ACT.pzStart({id:'edgelord'})"); + assert.notEqual(ev('S.pz.id'), 'edgelord', 'a locked puzzle does not start'); + ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:{hello:{st:3},eurotrip:{st:3},bigboat:{st:2},shining:{st:2}}}))"); + assert.equal(ev("pzPackOpen('rodeo')"), true, '10 stars open pack 2'); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Next pack, Traffic Cops, unlocks at 18/); + assert.deepEqual(errors, []); +}); + +test('results card: stars, the next puzzle, a retry, a share line and stars left in the pack', () => { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('eurotrip'))"); + build(ev, REF.eurotrip.one); + let card = ev("document.getElementById('modalCard').textContent"); + assert.match(card, /Puzzle solved/); + assert.equal(evalP(ev).stars, 2, 'delivered, and the budget star is on the house'); + assert.match(card, /One backhoe away/); + assert.match(card, /13 ⭐ left in this pack/); + assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); + build(ev, [['ams', 'lon', 'concerto', 1], ['ams', 'fra', 'land', 1]]); + 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); + assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')")); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/); + assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars'); + assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle Euro Trip ⭐⭐⭐ \$[\d.]+[kM] · seriesoftub\.es$/); + // The last puzzle points back to the list. + ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:Object.fromEntries(PZ.map(p=>[p.id,{st:3}]))}));pzBegin(pzDef('samba'))"); + build(ev, REF.samba.three); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/); + assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/); + assert.deepEqual(errors, []); +}); + +test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))"); + const rec = () => JSON.parse(ev("JSON.stringify(pzLoad().s.braces||null)")); + build(ev, REF.braces.three); + const three = evalP(ev); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:2})'); + assert.equal(ev('S.links[0].tier'), 1, 'a 400G wave needs 400G routers: refused'); + ev("ACT.pzRtAdd({city:'nyc'})"); + assert.equal(evalP(ev).stars, 3); + assert.deepEqual(rec(), { st: 3, sp: three.spend }, 'a dearer 3-star build does not replace it'); + ev("ACT.pzRmLink({id:S.links[0].id})"); + assert.deepEqual(rec(), { st: 3, sp: three.spend }, 'fewer stars never overwrite more'); + ev('ACT.puzzleMenu({})'); + assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`))); + assert.deepEqual(errors, []); +}); + +test('weekly puzzle (seeded stand-in): stable per week, carries traffic, its reference ring earns three stars, 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.dem.length === w.cities.length - 1 && w.src[0] === w.cities[0]); + for (let i = 0; i < 400; i += 28) { + const wi = JSON.parse(ev(`JSON.stringify(pzWeekly(new Date(2026,0,1+${i})))`)); + ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`); + build(ev, wi.ref.map((x, j) => [x, wi.ref[(j + 1) % wi.ref.length], wi.refVia[j], 0])); + assert.equal(evalP(ev).stars, 3, `week +${i}`); + } + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))"); + build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j], 0])); + assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$[\d.]+[kM] · seriesoftub\.es$/); + assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1); + 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.deepEqual(errors, []); +}); + +test('puzzle HUD and panels fit a 360 px phone, portrait and landscape', () => { + const { ev, errors } = load(); + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'))"); + ev("pzBegin(pzDef('baltic'))"); + assert.equal(ev("document.getElementById('tabbar').hidden"), true); + assert.equal(ev("document.getElementById('pzBox').hidden"), false); + const box = ev("document.getElementById('pzBox').textContent"); + assert.match(box, /Eyeballs in Tallinn/); + assert.match(box, /Frankfurt ⇄ Tallinn circuit/); + assert.match(box, /Content lives in Frankfurt/); + ev("selectCity('fra')"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Open a POP/); + ev("document.querySelector('#panelBody [data-act=pzPop]').click()"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Your POP[\s\S]*Router load[\s\S]*Ports[\s\S]*Router model/); + ev("pzLinkModal('fra','tll')"); + assert.equal(ev("document.querySelectorAll('#modalCard .tierbtn').length"), 4, 'four sizes'); + ev("closeModal();innerWidth=740;innerHeight=360;dispatchEvent(new Event('resize'));renderAll()"); + assert.equal(ev("document.getElementById('pzBox').hidden"), false, 'landscape too'); + // jsdom has no layout: the phone rules keep 40 px targets and pin the action row. + const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText)) + .flatMap(m=>[...m.cssRules]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),pos:r.style.getPropertyValue('position')})))`)); + assert.ok(rules.some((r) => /#pzBox \.btns \.b/.test(r.sel) && parseFloat(r.mh) >= 40), 'touch targets'); + assert.ok(rules.some((r) => /^#pzBox ?> ?\.btns$/.test(r.sel) && r.pos === 'sticky'), 'pinned actions'); + assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes'); + assert.deepEqual(errors, []); +}); + +test('puzzles in every language', () => { + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, errors } = load({ lang }); + ev("ACT.puzzleMenu({});pzBegin(pzDef('baltic'))"); + build(ev, REF.baltic.three); + ev("selectCity('hel');renderAll()"); + const seen = ev("['pzBox','modalCard','hud','panelBody'].map(id=>document.getElementById(id).textContent).join(' ')"); + assert.ok(!/puzzles\./.test(seen), `${lang}: no raw labels`); + assert.match(seen, /⭐/); + assert.deepEqual(errors, [], lang); + } +}); + test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => { const { ev, errors } = load(); ev("pzBegin(pzDef('hello'))"); @@ -205,152 +473,6 @@ test('leaving a puzzle with no game goes back to the title screen', () => { 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 < 400; i += 7) { - ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`); - const w = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')))')); - const cabs = w.refVia.filter((v) => v !== 'land'); - assert.equal(new Set(cabs).size, cabs.length, `week +${i}: no two hops of the reference ring share a cable`); - build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]])); - assert.equal(evalP(ev).stars, 3, `week +${i}`); - } - ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))"); - build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]])); - 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:''}}))"); - 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); - } -}); - -test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => { - const { ev, errors } = load(); - ev("pzBegin(pzDef('kiwi'))"); - assert.ok(ev('colo("suv")') > 1, 'Suva is a thin market'); - assert.equal(ev("pzPopCost('suv')"), ev("popCost('suv')+12*popMo('suv')")); - assert.ok(ev("pzPopCost('suv')") > ev("popCost('suv')+12*POP_MO")); - ev("selectCity('suv')"); - assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo')); - assert.deepEqual(errors, []); -}); - -test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => { - const { ev, errors } = load(); - ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))"); - const rec = () => JSON.parse(ev("JSON.stringify(pzLoad().s.braces||null)")); - build(ev, REF.braces.one); - const two = evalP(ev).spend; - assert.deepEqual(rec(), { st: 2, sp: two }); - // A gold-plated third link: N-1 but over budget is still two stars, and dearer, so the best stays. - ev("ACT.pzLinkTo({a:'dub',b:'nyc'});ACT.pzVia({v:'havf'});ACT.pzLink({tier:2});closeModal()"); - assert.equal(evalP(ev).stars, 2); - assert.deepEqual(rec(), { st: 2, sp: two }); - // Shrinking it to 10G earns the third star: the best spend starts again at the 3-star build. - ev('ACT.pzTier({id:S.links[2].id,tier:0})'); - const three = evalP(ev); - assert.equal(three.stars, 3); - assert.deepEqual(rec(), { st: 3, sp: three.spend }); - // With a looser budget, a dearer 3-star build does not replace it; going back to the cheaper one keeps it. - ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:1})'); - assert.equal(evalP(ev).stars, 3); - assert.deepEqual(rec(), { st: 3, sp: three.spend }); - // A cheaper 3-star build after a dearer first one is recorded (the old code only recorded star rises). - ev("localStorage.removeItem('sot-puzzles')"); - ev('ACT.pzTier({id:S.links[1].id,tier:1})'); - const dear = evalP(ev).spend; - assert.deepEqual(rec(), { st: 3, sp: dear }); - ev('ACT.pzTier({id:S.links[1].id,tier:0});ACT.pzTier({id:S.links[0].id,tier:0})'); - assert.deepEqual(rec(), { st: 3, sp: three.spend }); - // Fewer stars never overwrite more. - ev('ACT.pzRmLink({id:S.links[2].id})'); - assert.deepEqual(rec(), { st: 3, sp: three.spend }); - ev('ACT.puzzleMenu({})'); - assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`))); - assert.deepEqual(errors, []); -}); - test('main-game toasts and leftover buttons do nothing in 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)"); @@ -394,56 +516,13 @@ test('a city to avoid reads as a rule, not a goal that can fail', () => { assert.deepEqual(errors, []); }); -test('phone sheet: 40 px touch targets, pinned actions, and goal chips with a clear mark', () => { +test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => { const { ev, errors } = load(); - // jsdom has no layout: read the phone media rules from the page's stylesheet (Chromium at 360 px measures 40 px). - const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText)) - .flatMap(m=>[...m.cssRules]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),mw:r.style.getPropertyValue('min-width'),pos:r.style.getPropertyValue('position'),bottom:r.style.getPropertyValue('bottom')})))`)); - const tap = rules.find((r) => /#pzBox \.btns \.b/.test(r.sel) && /#pzBox \.pzh \.b/.test(r.sel)); - assert.ok(tap && parseFloat(tap.mh) >= 40 && parseFloat(tap.mw) >= 40, `Undo/Reset/Back/☰ are at least 40 px (${JSON.stringify(tap)})`); - const pin = rules.find((r) => /^#pzBox ?> ?\.btns$/.test(r.sel)); - assert.ok(pin && pin.pos === 'sticky' && parseFloat(pin.bottom) === 0, `the action row stays at the foot of a scrolling sheet (${JSON.stringify(pin)})`); - ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));pzBegin(pzDef('braces'))"); - const chips = () => ev("[...document.querySelectorAll('#pzBox .pzc')].map(x=>x.textContent).join('|')"); - assert.equal(chips(), '○ New York|○ London|○ Dublin', 'not reached yet: a hollow mark, nothing that looks cut off'); - assert.doesNotMatch(chips(), /…/); - build(ev, [['nyc', 'lon', 'grace']]); - ev("ACT.pzPop({city:'dub'})"); - assert.equal(chips(), '✓ New York|✓ London|◐ Dublin'); - assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes'); - assert.deepEqual(errors, []); -}); - -test('results pull you on: Next is the big tap after three stars, stars left in the pack, and a nudge when 3 stars are one link away', () => { - const { ev, errors } = load(); - ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))"); - build(ev, REF.braces.one); - let card = ev("document.getElementById('modalCard').textContent"); - assert.equal(evalP(ev).stars, 2); - assert.match(card, /So close: one more link and a backhoe can't touch you\./, 'Dublin to New York would do it, within budget'); - assert.match(ev("document.getElementById('pzBox').textContent"), /So close/); - assert.match(card, /10 ⭐ left in this pack/, '4 puzzles × 3 stars, 2 won'); - assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); - assert.ok(!ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')")); - build(ev, [['dub', 'nyc', 'havf']]); - card = ev("document.getElementById('modalCard').textContent"); - assert.match(card, /9 ⭐ left in this pack/); - assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"), 'three stars: the big Next layout'); - assert.ok(ev("document.activeElement===document.querySelector('#modalCard .pznext')"), 'the big button has the focus'); - assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars'); - assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/, 'the last pack points back to the list'); - ev("pzBegin(pzDef('eurotrip'))");build(ev, REF.eurotrip.three); - assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/); - assert.equal(ev("document.activeElement.dataset.act"), 'pzStart'); - // No nudge when no single link fits the budget: an over-budget gold plate is not "close". - ev("pzBegin(pzDef('braces'));S.pz.budget=245000"); - build(ev, REF.braces.one); - assert.equal(evalP(ev).stars, 2); - assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /So close/); - assert.match(ev("document.getElementById('modalCard').textContent"), /One backhoe away/); - // A finished pack says so. - ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{sharks:{st:3},braces:{st:3},nofra:{st:3},fatpipes:{st:2}}}));pzBegin(pzDef('fatpipes'))"); - build(ev, REF.fatpipes.three); - assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/); + ev("pzBegin(pzDef('kiwi'))"); + assert.ok(ev('colo("suv")') > 1, 'Suva is a thin market'); + assert.equal(ev("pzPopCost('suv')"), ev("popCost('suv')+12*popMo('suv')")); + assert.ok(ev("pzPopCost('suv')") > ev("popCost('suv')+12*POP_MO")); + ev("selectCity('suv')"); + assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo')); assert.deepEqual(errors, []); }); diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js index e41c26e..8c3c118 100644 --- a/tests/weekly-puzzle.test.js +++ b/tests/weekly-puzzle.test.js @@ -88,8 +88,9 @@ test('generator: a quarter of weeks, all verified, varied, small and in the sche for (const j of out) { assert.ok(j.cities.length >= 3 && j.cities.length <= 6); assert.ok(j.ref.one <= j.ref.three && j.ref.three <= j.budget && j.budget <= j.ref.three * 1.06 + 10000, `${j.key}: budget ${j.budget} just above the N-1 build ${j.ref.three}`); - assert.ok(JSON.stringify(j).length < 600, 'small file'); - assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'via', 'avoid', 'budget', 'twist', 'name', 'joke', 'ref']); + assert.ok(JSON.stringify(j).length < 900, 'small file'); + assert.ok(j.dem.length >= 2 && j.src.length === 1 && j.dem.every((f) => f.g > 0), `${j.key}: it carries traffic`); + assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'src', 'dem', 'via', 'avoid', 'budget', 'twist', 'name', 'joke', 'ref']); } assert.deepEqual(JSON.parse(fs.readFileSync(path.join(d, 'index.json'), 'utf8')).weeks, out.map((j) => j.key)); }); @@ -113,7 +114,8 @@ test('--check passes on the committed files and rejects tampered ones', () => { bad((j) => { j.joke.p = { hub: 'fra' }; }, 'parameters the label does not take'); bad((j) => { j.extra = ''; }, 'an unknown field'); bad((j) => { j.key = '2030-W01'; }, 'a file under another week\'s name'); - bad((j) => { j.twist = { lat: [j.cities[0], j.cities[1], 0.5] }; }, 'an impossible latency target'); + bad((j) => { j.dem.push({ t: 'l2', a: j.cities[0], b: j.cities[1], g: 10, ms: 1 }); }, 'an impossible latency target'); + bad((j) => { j.dem[0].g = 5000; }, 'more traffic than a puzzle carries'); bad(() => '{nope', 'not JSON'); bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks'); }); @@ -221,11 +223,12 @@ test('the published puzzle is played when it is good, the seeded one when it is assert.equal(ev('S.pz.budget'), good.budget); assert.match(ev("document.getElementById('pzBox').textContent"), new RegExp(ev('pzTxt(S.pz.wj)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); // Solve it with three stars: the share line and the streak use the published key. - const sol = G.solve(G.world(ev), { cities: good.cities, via: good.via, avoid: good.avoid, ring: !!good.twist.ring, noSub: false, lat: good.twist.lat || null }).three; - for (const l of sol.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})`); - } + // The generator's sized 3-star reference, played into this puzzle (links, routers, routes). + const SV = require('../scripts/lib/puzzle-solver');SV.install(ev); + const def = JSON.parse(ev('JSON.stringify(pzWkDef())')), sol = G.sized({ ev }, G.world(ev), G.shape(def), def).three.b; + ev('pzBegin(pzWkDef())'); + SV.judge(ev, sol.links); + ev(`pzsApplyRt(${JSON.stringify(sol.rt)});pzAfter()`); assert.equal(ev('pzEval().stars'), 3); assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`)); const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); @@ -242,7 +245,13 @@ test('the file is checked field by field', () => { const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`); assert.ok(ok(j)); const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); }; - no((o) => { o.v = 2; }, 'a newer schema'); + no((o) => { o.v = 3; }, 'a newer schema'); + no((o) => { o.v = 1; }, 'an old file without traffic'); + no((o) => { o.dem = []; }, 'no traffic'); + no((o) => { o.dem = [{ t: 'warp', a: o.cities[0], g: 1 }]; }, 'an unknown kind of flow'); + no((o) => { o.dem = [{ ...o.dem[0], g: 1.5 }, ...o.dem.slice(1)]; }, 'fractional gigabits'); + no((o) => { o.src = []; }, 'eyeballs with nowhere to pull from'); + no((o) => { o.cities = o.cities.slice(0, -1); }, 'cities that do not match the traffic'); no((o) => { o.theme = 'constructor'; }, 'an unknown theme'); no((o) => { o.cities = ['fra']; }, 'too few cities'); no((o) => { o.cities = [...o.cities, o.cities[0]]; }, 'a city twice');