diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 6e691fb..99ea7eb 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -55,6 +55,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. | | C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | | C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | +| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one tube, and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. | ## Fun and fairness diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0d1ad7a..c9e813f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -74,7 +74,7 @@ jobs: run: | set -euo pipefail git fetch --no-tags --depth=1 origin main - for d in site/puzzles/weekly site/scenarios/weekly; do + for d in site/puzzles/weekly site/scenarios/weekly site/architect/weekly; do if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then rm -rf "$d" git checkout FETCH_HEAD -- "$d" @@ -92,11 +92,12 @@ jobs: if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi node scripts/weekly-puzzle.js --check if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi + if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi - run: npm test if: ${{ !inputs.weekly }} - name: Test the weekly puzzles against this release if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} - run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js 2>/dev/null) + run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null) - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - uses: actions/upload-pages-artifact@v5 diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml index 9ac5cfa..fdff934 100644 --- a/.github/workflows/weekly-puzzle.yml +++ b/.github/workflows/weekly-puzzle.yml @@ -1,6 +1,7 @@ name: Weekly puzzle -# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js) and scenario (scripts/weekly-scenario.js), +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), scenario (scripts/weekly-scenario.js) and +# Architect run (scripts/weekly-architect.js), # commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday # 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts. # @@ -47,7 +48,7 @@ jobs: - run: npm ci # Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current. - name: Fit the published weeks to main - run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check - name: Make the puzzle and the scenario run: | set -euo pipefail @@ -55,18 +56,20 @@ jobs: [[ "$KEY" =~ ^[0-9]{4}-W[0-9]{2}$ ]] || { echo "::error::$KEY is not a week key"; exit 1; } node scripts/weekly-puzzle.js --key "$KEY" node scripts/weekly-scenario.js --key "$KEY" + node scripts/weekly-architect.js --key "$KEY" else node scripts/weekly-puzzle.js node scripts/weekly-scenario.js + node scripts/weekly-architect.js fi - name: Check every weekly puzzle - run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js tests/weekly-architect.test.js - name: Commit it to main run: | set -euo pipefail - git add site/puzzles/weekly site/scenarios/weekly + git add site/puzzles/weekly site/scenarios/weekly site/architect/weekly # Data only: anything else changed means something is wrong. - if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi + if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' -e ' site/architect/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi if git diff --cached --quiet; then echo "Nothing new to commit."; exit 0; fi git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ commit -m "Weekly puzzle and scenario $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')" diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5bd5d..4d59bb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Later briefs stay a surprise in every Architect run: their cities only appear when they come. - In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. - A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. diff --git a/scripts/weekly-architect.js b/scripts/weekly-architect.js new file mode 100644 index 0000000..e3dd253 --- /dev/null +++ b/scripts/weekly-architect.js @@ -0,0 +1,217 @@ +#!/usr/bin/env node +// The weekly Architect run generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml +// runs it to publish site/architect/weekly/.json, which the game fetches when Puzzles opens +// (src/game/60-features/98-architect-weekly.js). It plays the real game headless, so the briefs are judged by the game's +// own checklist and chaos monkey review. +// +// node scripts/weekly-architect.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing +// node scripts/weekly-architect.js --key 2026-W45 that week (--force replaces an existing file) +// node scripts/weekly-architect.js --next 3 this week and the next two +// node scripts/weekly-architect.js --check re-play every week not over yet; one whose reference no longer +// earns three stars is regenerated with rev + 1; then validate every file +// --page FILE / --dir DIR another build of the game / where the files live +// +// How a run is made: an HQ in a region the last weeks did not have, and its nearest cities as the sites to come. Then a +// reference architect plays it brief by brief, and each brief is designed against the network it has built so far, so +// every brief asks for something new: a site to connect, a site that one cut would strand made mission-critical, a ring +// it does not have yet, a latency cap its paths miss, a site that closes. The reference builds the cheapest fix it finds +// (connect to the nearest POP; for a site a cut strands, the cheapest tube from the stranded side to the rest on another +// trench or cable) until the game's review passes. Its tube count is the brief's plan, its spend plus a little the +// budget, and the whole run is then replayed from the file and must earn three stars. +const fs = require('node:fs'); +const path = require('node:path'); +const { game, world } = require('./weekly-puzzle'); + +const ROOT = path.join(__dirname, '..'); +const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 100; +const NAMES = ['architect_weekly.name_all_roads_lead_to_hq', 'architect_weekly.name_the_hq_job', 'architect_weekly.name_hq_and_friends']; +const JOKES = ['architect_weekly.joke_hq_signed_the_lease', 'architect_weekly.joke_one_network_a_handful']; + +const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }; +function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } +const pick = (r, a) => a[Math.floor(r() * a.length)]; +const shuffle = (r, a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }; +const ceil10k = (x) => Math.ceil(x / 10000) * 10000; +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() : []); +const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`)); + +// ---------- playing the game ---------- +// Load a run definition into the page as this week's, with the briefs known so far. +function stage(ev, key, hq, briefs) { + ev(`UI.arWk={key:'${key}',def:{id:arWkId('${key}'),key:'${key}',wk:true,n:'',j:'',hq:'${hq}',via:[],budget:2e7,briefs:${JSON.stringify(briefs)},rev:1},at:Date.now()}`); +} +// Lay one tube the way a player does: a diverse trench when the pair already has one overland. +function lay(ev, a, b, via) { + if (!ev(`!!S.pops['${a}']`)) [a, b] = [b, a]; + const n = ev('S.links.length'); + ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:AR_TIER});closeModal()`); + if (ev('S.links.length') !== n + 1) throw new Error(`could not lay ${a}-${b} ${via}`); + return [a, b, via]; +} +// What the review would say: the first cut that strands a mission-critical site or leaves a site short. +const reviewFail = (ev) => J(ev, `(()=>{let f=null;for(const u of [...new Set(S.links.map(pzUnit))]){const x=arCut(u);for(const l of x.ls)l.cut=0;if(x.gold.length||x.short.length){f={u,gold:x.gold,short:x.short,dark:x.dark};break;}}compute();return f;})()`); +const passes = (ev) => ev('arShowStart();arShowSkip();S.ar.passed===pzSig()'); + +// The reference architect: fix what the checklist and the review find, cheapest first, until the brief passes. +function solveBrief(ev, W, steps) { + for (let guard = 0; guard < 24; guard++) { + for (const c of J(ev, 'S.pz.avoid.filter(c=>S.pops[c])')) { ev(`ACT.pzRmPop({city:'${c}'})`); steps.push(['@rm', c]); } + const e = J(ev, '(()=>{const e=arEval(),r=[...arReach(S.ar.hq,arAdj())];return {conn:e.conn,lat:e.lat,rings:e.rings,ready:e.ready,why:e.why,r,miss:e.sites.filter(s=>!s.ok).map(s=>s.c)};})()'); + const best = (from, to, skip) => { let o = null; for (const a of from) for (const b of to) if (a !== b) for (const x of W.opts(a, b)) if (!x.second && x.unit !== skip && (!o || x.cost < o.cost)) o = x; return o; }; + if (!e.conn) { const c = e.miss[0], o = best([c], e.r); if (!o) throw new Error(`no way to ${c}`); steps.push(lay(ev, o.a, o.b, o.via)); continue; } + if (e.lat && !e.lat.ok) { const os = W.opts(e.lat.a, e.lat.b).filter((x) => !x.second && x.ms <= e.lat.cap).sort((x, y) => x.cost - y.cost); if (!os.length) throw new Error('latency cap out of reach'); steps.push(lay(ev, os[0].a, os[0].b, os[0].via)); continue; } + const rg = e.rings.find((x) => !x.ok); + if (rg) { const cs = rg.cs, has = J(ev, 'S.links.map(l=>edgeKey(l))'); let done = false; + for (let i = 0; i < cs.length && !done; i++) { const a = cs[i], b = cs[(i + 1) % cs.length]; if (has.includes(ev(`edgeKey({a:'${a}',b:'${b}'})`))) continue; const o = best([a], [b]); if (o) { steps.push(lay(ev, o.a, o.b, o.via)); done = true; } } + if (!done) throw new Error('ring out of reach'); continue; } + if (!e.ready) throw new Error(`not ready: ${e.why}`); + const f = reviewFail(ev); if (!f) return; + if (f.short.length) throw new Error('short of capacity'); + // A cut strands a mission-critical site: join the stranded side to the rest another way. + const rest = J(ev, `Object.keys(S.pops).filter(c=>!${JSON.stringify(f.dark)}.includes(c))`), o = best(f.dark, rest, f.u); + if (!o) throw new Error('no second way'); steps.push(lay(ev, o.a, o.b, o.via)); + } + throw new Error('the brief would not pass'); +} + +// ---------- designing a run ---------- +// The brief kinds after the first two. Each is designed against the reference network as it stands, or refused (null). +function design(kind, ev, W, r, s) { + const pops = J(ev, 'S.pz.cities'), gold = J(ev, 'S.ar.gold'), hq = s.hq, next = () => s.todo.shift(), dem = (c) => { const g = Math.min(s.room, pick(r, [10, 20, 20, 30])); s.room -= g; return { [c]: g }; }; + const weak = J(ev, `S.pz.cities.filter(c=>c!==S.ar.hq&&!S.ar.gold.includes(c)&&[...new Set(S.links.map(pzUnit))].some(u=>arDark(u).includes(c)))`); + if (kind === 'gold') { if (!weak.length) return null; const c = weak.sort((a, b) => W.km(hq, b) - W.km(hq, a))[0]; return { gold: [c] }; } + if (kind === 'addgold') { if (!s.todo.length || s.room < 10) return null; const c = next(); return { add: [c], dem: dem(c), gold: [c] }; } + if (kind === 'move') { const c = pops.filter((x) => x !== hq && !gold.includes(x) && !(s.lat || []).includes(x)).sort((a, b) => W.km(hq, b) - W.km(hq, a))[0]; + if (!c || !s.todo.length || s.room < 10) return null; const n = next(); return { drop: [c], add: [n], dem: dem(n), gold: [n] }; } + if (kind === 'lat') { let bestP = null; + for (const a of pops) for (const b of pops) { if (a >= b) continue; const cur = J(ev, `arLat('${a}','${b}')`), os = W.opts(a, b).filter((x) => !x.second); if (cur == null || !os.length) continue; + const ms = Math.min(...os.map((x) => x.ms)), cap = Math.ceil(ms * 1.12 * 10) / 10; if (cap < 2 || cap >= cur * 0.85) continue; + if (!bestP || cur / cap > bestP.k) bestP = { a, b, cap, k: cur / cap }; } + if (!bestP) return null; s.lat = [bestP.a, bestP.b]; return { lat: [bestP.a, bestP.b, bestP.cap] }; } + if (kind === 'ring') { const cs = pops.filter((c) => c !== hq).sort((a, b) => W.km(hq, a) - W.km(hq, b)).slice(0, 2); if (cs.length < 2) return null; + const ring = [hq, ...cs]; if (ev(`arRingOk(${JSON.stringify(ring)})`)) return null; return { ring }; } + return null; +} + +// Play a run from scratch: stage, start, then brief by brief design (when designing) or follow the file, solve, review, next. +function play(g, W, key, hq, plan, r, sites) { + const { ev } = g, briefs = [], steps = [], s = { hq, todo: sites.slice(), room: DEM_MAX, lat: null }; + const first = () => { const c = s.todo.shift(), g0 = Math.min(s.room, pick(r, [20, 30, 40])); s.room -= g0; return { add: [c], dem: { [c]: g0 } }; }; + for (let i = 0; i < plan.length; i++) { + let b = null; + if (plan[i] === 'add1') b = first(); + else if (plan[i] === 'add2') { if (s.todo.length < 2) throw new Error('not enough sites'); const a = s.todo.shift(), c = s.todo.shift(), ga = Math.min(s.room, 20); s.room -= ga; const gc = Math.min(s.room, pick(r, [10, 20])); s.room -= gc; b = { add: [a, c], dem: { [a]: ga, [c]: gc } }; } + // A kind that cannot be made here gives way to one the run has not had yet, then to a new mission-critical site. + else for (const k of [plan[i], ...['lat', 'ring', 'move', 'gold'].filter((x) => !plan.slice(0, i).includes(x) && x !== plan[i]), 'addgold']) { b = design(k, ev, W, r, s); if (b) { plan[i] = k; break; } } + if (!b) throw new Error(`brief ${i + 1}: nothing left to ask`); + b.tubes = 9; briefs.push(b); stage(ev, key, hq, briefs.map((x) => Object.assign({ t: '' }, x))); + if (i === 0) ev(`ACT.pzArStart({id:arWkId('${key}')})`); else ev('ACT.pzArNext()'); + if (ev('S.ar.bi') !== i) throw new Error(`brief ${i + 1} did not start`); + const st = []; solveBrief(ev, W, st); steps.push(st); + b.tubes = ev('S.links.filter(l=>(l.br|0)===S.ar.bi).length'); + if (!b.tubes) throw new Error(`brief ${i + 1} needs no tube`); + ev(`UI.arWk.def.briefs[${i}].tubes=${b.tubes}`); + if (!passes(ev)) throw new Error(`brief ${i + 1}: the review does not pass`); + } + return { briefs, steps, spend: ev('arSpend()') }; +} + +// Replay a file the way a player would, from its own reference: it must pass every brief and earn three stars. +function verify(g, j, key) { + const { ev } = g, def = J(ev, `arWkValid(${JSON.stringify(j)},'${key}')`); + if (!def) return { ok: false, why: 'the game rejects it' }; + if (!j.ref || !Array.isArray(j.ref.steps) || j.ref.steps.length !== def.briefs.length) return { ok: false, why: 'no reference' }; + try { + ev(`UI.arWk={key:'${key}',def:arWkValid(${JSON.stringify(j)},'${key}'),at:Date.now()}`); + ev(`ACT.pzArStart({id:arWkId('${key}')})`); + for (let i = 0; i < def.briefs.length; i++) { + for (const st of j.ref.steps[i]) if (st[0] === '@rm') ev(`ACT.pzRmPop({city:'${st[1]}'})`); else lay(ev, st[0], st[1], st[2]); + if (!passes(ev)) return { ok: false, why: `brief ${i + 1} does not pass` }; + if (i < def.briefs.length - 1) ev('ACT.pzArNext()'); + } + const sp = ev('arSpend()'), stars = ev(`arStars(${sp})`); + ev('arStop(true)'); + return stars === 3 ? { ok: true, spend: sp } : { ok: false, why: `the reference earns ${stars} stars (spend ${sp}, budget ${j.budget})` }; + } catch (e) { return { ok: false, why: e.message }; } +} + +function generate(g, key, dir) { + const { ev } = g, W = world(ev); + // The regions of the last weeks, so the HQ moves around the world. + const past = list(dir).filter((k) => k < key).map((k) => { try { return JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')).hq; } catch (e) { return null; } }); + const recent = past.slice(-HISTORY).map((c) => W.C[c] && W.C[c].reg), used = past.slice(-12); + for (let attempt = 0; attempt < ATTEMPTS; attempt++) { + const r = rng(hash(`architect|${key}|${attempt}`)); + const hqs = W.cities.filter((c) => !used.includes(c.id) && (!recent.includes(c.reg) || attempt >= ATTEMPTS / 2)); + const hq = pick(r, hqs).id; + const near = W.cities.filter((c) => c.id !== hq && c.reg === W.C[hq].reg && W.km(hq, c.id) < 2500).sort((a, b) => W.km(hq, a.id) - W.km(hq, b.id)).slice(0, 8).map((c) => c.id); + if (near.length < 6) continue; + const mid = shuffle(r, ['lat', 'ring', 'move', 'addgold']).slice(0, r() < 0.5 ? 2 : 3); + const plan = ['add1', 'add2', 'gold', ...mid, 'gold']; + const sites = [...near.slice(0, 3), ...shuffle(r, near.slice(3))]; + try { + const run = play(g, W, key, hq, plan, r, sites); + const jk = pick(r, JOKES), j = { v: SCHEMA, key, hq, budget: ceil10k(run.spend * 1.06), name: { l: pick(r, NAMES), p: { hq } }, joke: { l: jk, p: jk === JOKES[0] ? { hq } : {} }, briefs: run.briefs, ref: { spend: run.spend, steps: run.steps } }; + const v = verify(g, j, key); + if (!v.ok) { if (process.env.DEBUG) console.warn(`${key} #${attempt}: ${v.why}`); continue; } + return j; + } catch (e) { if (process.env.DEBUG) console.warn(`${key} #${attempt} (${hq}): ${e.message}`); } + } + throw new Error(`${key}: no run survived verification`); +} + +// --check: every file is what the game accepts, under its own name, and the weeks still to come earn three stars. +function check(g, dir, now = Date.now()) { + const { ev } = g, bad = [], keys = list(dir); + for (const k of keys) { + let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; } + if (!ev(`!!arWkValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; } + if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); } + } + if (keys.length) { + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* reported below */ } + if (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys)) bad.push('index.json does not list exactly the weekly files'); + } + return bad; +} +// A release can change prices under weeks already out: a week not over yet whose reference no longer earns three stars +// is regenerated with its rev up, so players' stars for that week (only that week) start again. Past weeks stay. +function refresh(g, dir, now = Date.now()) { + const { ev } = g, fixed = [], bad = []; + for (const k of list(dir)) { + let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated below */ } + const valid = !!j && ev(`!!arWkValid(${JSON.stringify(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now; + if (valid && (!live || verify(g, j, k).ok)) continue; + const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1; + try { writeWeek(dir, Object.assign(generate(g, k, dir), { rev })); fixed.push(`${k}: regenerated as rev ${rev}`); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); } + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ } + if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); } + return { fixed, bad }; +} +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); }; +const say = (j) => `${j.key}: HQ ${j.hq}, ${j.briefs.length} briefs (${j.briefs.map((b) => Object.keys(b).filter((k) => k !== 'tubes' && k !== 'dem').join('+')).join(', ')}), budget ${j.budget}, reference ${j.ref.spend}`; + +module.exports = { generate, verify, check, refresh, writeWeek, writeIndex, list, say }; + +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; }; + const dir = path.resolve(ROOT, opt('--dir', 'site/architect/weekly')), g = game(opt('--page') && path.resolve(opt('--page'))); + if (!g.ev("typeof arWkValid==='function'")) { console.log('This game has no weekly Architect runs yet.'); process.exit(0); } + if (args.includes('--check')) { + const r = refresh(g, dir); + for (const x of r.fixed) console.log(`fixed: ${x}`); + const bad = [...r.bad, ...check(g, dir)]; + for (const b of bad) console.error(`error: ${b}`); + console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly Architect run(s) OK`); + process.exit(bad.length ? 1 : 0); + } + const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1); + for (let i = 0; i < n; i++) { + const key = g.ev(`pzKeyAdd('${first}',${i})`); + if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); } + if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; } + const j = generate(g, key, dir); writeWeek(dir, j); console.log(say(j)); + } +} diff --git a/site/architect/weekly/2026-W44.json b/site/architect/weekly/2026-W44.json new file mode 100644 index 0000000..fd5f6ed --- /dev/null +++ b/site/architect/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W44","hq":"cor","budget":1160000,"name":{"l":"architect_weekly.name_all_roads_lead_to_hq","p":{"hq":"cor"}},"joke":{"l":"architect_weekly.joke_hq_signed_the_lease","p":{"hq":"cor"}},"briefs":[{"add":["bue"],"dem":{"bue":20},"tubes":1},{"add":["scl","mvd"],"dem":{"scl":20,"mvd":20},"tubes":2},{"gold":["mvd"],"tubes":2},{"ring":["cor","bue","scl"],"tubes":1},{"add":["cgr"],"dem":{"cgr":20},"gold":["cgr"],"tubes":2},{"lat":["cgr","cor",11.3],"tubes":1}],"ref":{"spend":1090844,"steps":[[["cor","bue","land"]],[["cor","scl","land"],["bue","mvd","land"]],[["bue","cor","land"],["mvd","bue","land"]],[["scl","bue","land"]],[["bue","cgr","land"],["cgr","bue","land"]],[["cgr","cor","land"]]]}} diff --git a/site/architect/weekly/2026-W45.json b/site/architect/weekly/2026-W45.json new file mode 100644 index 0000000..ea2b841 --- /dev/null +++ b/site/architect/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W45","hq":"maa","budget":920000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"maa"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["blr"],"dem":{"blr":20},"tubes":1},{"add":["hyd","cbo"],"dem":{"hyd":20,"cbo":20},"tubes":2},{"gold":["cbo"],"tubes":1},{"ring":["maa","blr","hyd"],"tubes":1},{"drop":["hyd"],"add":["mle"],"dem":{"mle":30},"gold":["mle"],"tubes":2},{"gold":["blr"],"tubes":1}],"ref":{"spend":860936,"steps":[[["maa","blr","land"]],[["blr","hyd","land"],["maa","cbo","smw6"]],[["cbo","maa","smw4"]],[["hyd","maa","land"]],[["@rm","hyd"],["cbo","mle","smw6"],["mle","maa","iax"]],[["blr","maa","land"]]]}} diff --git a/site/architect/weekly/2026-W46.json b/site/architect/weekly/2026-W46.json new file mode 100644 index 0000000..a047c0e --- /dev/null +++ b/site/architect/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W46","hq":"svg","budget":570000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"svg"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["krs"],"dem":{"krs":40},"tubes":1},{"add":["osl","ebj"],"dem":{"osl":20,"ebj":10},"tubes":2},{"gold":["ebj"],"tubes":2},{"lat":["osl","svg",2.2],"tubes":1},{"drop":["krs"],"add":["ams"],"dem":{"ams":20},"gold":["ams"],"tubes":4},{"ring":["svg","osl","ebj"],"tubes":1},{"add":["edi"],"dem":{"edi":10},"gold":["edi"],"tubes":2}],"ref":{"spend":534112,"steps":[[["svg","krs","land"]],[["krs","osl","land"],["krs","ebj","land"]],[["krs","svg","land"],["ebj","krs","land"]],[["osl","svg","land"]],[["@rm","krs"],["ebj","svg","land"],["ebj","ams","land"],["ebj","svg","land"],["ams","ebj","land"]],[["ebj","osl","land"]],[["svg","edi","nouk"],["edi","ebj","havh"]]]}} diff --git a/site/architect/weekly/index.json b/site/architect/weekly/index.json new file mode 100644 index 0000000..8955841 --- /dev/null +++ b/site/architect/weekly/index.json @@ -0,0 +1 @@ +{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} diff --git a/site/i18n/de.js b/site/i18n/de.js index 9715f99..e2c5eae 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -123,6 +123,20 @@ "architect.usa_6":"Ein Cloud-Deal im Silicon Valley. Er ist geschäftskritisch.", "architect.x_paid_for_and_gone":"{x} davon für Dinge, die du wieder entfernt hast", "architect.your_shape":"Deine Form", +"architect_weekly.joke_hq_signed_the_lease":"{hq} hat den Mietvertrag unterschrieben. Alles Weitere ist dein Problem.", +"architect_weekly.joke_one_network_a_handful":"Ein Netz, eine Handvoll Briefings und ein Affe mit Schere.", +"architect_weekly.name_all_roads_lead_to_hq":"Alle Wege führen nach {hq}", +"architect_weekly.name_hq_and_friends":"{hq} und Freunde", +"architect_weekly.name_the_hq_job":"Der {hq}-Job", +"architect_weekly.t_add_gold":"{a} ist neu dabei und von Tag eins an geschäftskritisch: muss jeden einzelnen Schnitt überstehen.", +"architect_weekly.t_add_one":"{a} ist neu dabei: anschließen.", +"architect_weekly.t_add_two":"{a} und {b} sind neu dabei: anschließen.", +"architect_weekly.t_drop":"{a} schließt: zieh aus und bau dort nicht wieder.", +"architect_weekly.t_gold_one":"{a} ist jetzt geschäftskritisch: muss jeden einzelnen Schnitt überstehen.", +"architect_weekly.t_gold_two":"{a} und {b} sind jetzt geschäftskritisch: müssen jeden einzelnen Schnitt überstehen.", +"architect_weekly.t_lat":"{a} ⇄ {b} muss unter {ms} ms bleiben.", +"architect_weekly.t_ring":"{list} wollen auf einem Ring liegen.", +"architect_weekly.weekly_run":"Architect-Run der Woche", "badges.a_petabit_a_second":"Ein Petabit pro Sekunde", "badges.a_secret_badge":"Ein geheimes Abzeichen", "badges.attend_a_conference":"Besuche eine Konferenz.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 605bade..5376911 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -121,6 +121,20 @@ "architect.usa_6":"Un trato de nube en Silicon Valley. Es crítico.", "architect.x_paid_for_and_gone":"{x} de eso pagó cosas que quitaste", "architect.your_shape":"Tu forma", +"architect_weekly.joke_hq_signed_the_lease":"{hq} firmó el contrato. Todo lo demás es problema tuyo.", +"architect_weekly.joke_one_network_a_handful":"Una red, un puñado de encargos y un mono con tijeras.", +"architect_weekly.name_all_roads_lead_to_hq":"Todos los caminos llevan a {hq}", +"architect_weekly.name_hq_and_friends":"{hq} y amigos", +"architect_weekly.name_the_hq_job":"El golpe de {hq}", +"architect_weekly.t_add_gold":"{a} se apunta, crítico desde el primer día: debe sobrevivir a cualquier corte.", +"architect_weekly.t_add_one":"{a} se apunta: conéctalo.", +"architect_weekly.t_add_two":"{a} y {b} se apuntan: conéctalos.", +"architect_weekly.t_drop":"{a} cierra: múdate y no vuelvas a construir allí.", +"architect_weekly.t_gold_one":"{a} es ahora crítico: debe sobrevivir a cualquier corte.", +"architect_weekly.t_gold_two":"{a} y {b} son ahora críticos: deben sobrevivir a cualquier corte.", +"architect_weekly.t_lat":"{a} ⇄ {b} debe quedarse por debajo de {ms} ms.", +"architect_weekly.t_ring":"{list} quieren estar en un mismo anillo.", +"architect_weekly.weekly_run":"La ronda de Arquitecto de la semana", "badges.a_petabit_a_second":"Un petabit por segundo", "badges.a_secret_badge":"Una insignia secreta", "badges.attend_a_conference":"Asiste a una conferencia.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 8ba1aeb..4fbd868 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -121,6 +121,20 @@ "architect.usa_6":"Un contrat cloud dans la Silicon Valley. Il est critique.", "architect.x_paid_for_and_gone":"dont {x} pour des choses que tu as retirées", "architect.your_shape":"Ta forme", +"architect_weekly.joke_hq_signed_the_lease":"{hq} a signé le bail. Tout le reste, c’est ton problème.", +"architect_weekly.joke_one_network_a_handful":"Un réseau, une poignée de briefs et un singe avec des ciseaux.", +"architect_weekly.name_all_roads_lead_to_hq":"Tous les chemins mènent à {hq}", +"architect_weekly.name_hq_and_friends":"{hq} et ses amis", +"architect_weekly.name_the_hq_job":"Le coup de {hq}", +"architect_weekly.t_add_gold":"{a} signe, critique dès le premier jour : il doit survivre à n’importe quelle coupure.", +"architect_weekly.t_add_one":"{a} signe : raccorde-le.", +"architect_weekly.t_add_two":"{a} et {b} signent : raccorde-les.", +"architect_weekly.t_drop":"{a} ferme : déménage et ne construis plus là-bas.", +"architect_weekly.t_gold_one":"{a} est désormais critique : il doit survivre à n’importe quelle coupure.", +"architect_weekly.t_gold_two":"{a} et {b} sont désormais critiques : ils doivent survivre à n’importe quelle coupure.", +"architect_weekly.t_lat":"{a} ⇄ {b} doit rester sous {ms} ms.", +"architect_weekly.t_ring":"{list} veulent être sur un même anneau.", +"architect_weekly.weekly_run":"Le parcours d’architecte de la semaine", "badges.a_petabit_a_second":"Un pétabit par seconde", "badges.a_secret_badge":"Un badge secret", "badges.attend_a_conference":"Participe à une conférence.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 69b9299..c21f57c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -121,6 +121,20 @@ "architect.usa_6":"Un accordo cloud nella Silicon Valley. È critico.", "architect.x_paid_for_and_gone":"{x} di questi per cose che hai tolto", "architect.your_shape":"La tua forma", +"architect_weekly.joke_hq_signed_the_lease":"{hq} ha firmato il contratto. Tutto il resto è un problema tuo.", +"architect_weekly.joke_one_network_a_handful":"Una rete, una manciata di brief e una scimmia con le forbici.", +"architect_weekly.name_all_roads_lead_to_hq":"Tutte le strade portano a {hq}", +"architect_weekly.name_hq_and_friends":"{hq} e amici", +"architect_weekly.name_the_hq_job":"Il colpo di {hq}", +"architect_weekly.t_add_gold":"{a} si iscrive, critico dal primo giorno: deve sopravvivere a qualsiasi taglio.", +"architect_weekly.t_add_one":"{a} si iscrive: collegalo.", +"architect_weekly.t_add_two":"{a} e {b} si iscrivono: collegali.", +"architect_weekly.t_drop":"{a} chiude: trasloca e non costruire più lì.", +"architect_weekly.t_gold_one":"{a} ora è critico: deve sopravvivere a qualsiasi taglio.", +"architect_weekly.t_gold_two":"{a} e {b} ora sono critici: devono sopravvivere a qualsiasi taglio.", +"architect_weekly.t_lat":"{a} ⇄ {b} deve restare sotto {ms} ms.", +"architect_weekly.t_ring":"{list} vogliono stare su un unico anello.", +"architect_weekly.weekly_run":"Il percorso da architetto della settimana", "badges.a_petabit_a_second":"Un petabit al secondo", "badges.a_secret_badge":"Un badge segreto", "badges.attend_a_conference":"Partecipa a una conferenza.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 00c2e32..3782ca0 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -121,6 +121,20 @@ "architect.usa_6":"Um contrato de nuvem no Vale do Silício. É crítico.", "architect.x_paid_for_and_gone":"{x} disso pagou coisas que você removeu", "architect.your_shape":"Seu formato", +"architect_weekly.joke_hq_signed_the_lease":"{hq} assinou o contrato. Todo o resto é problema seu.", +"architect_weekly.joke_one_network_a_handful":"Uma rede, um punhado de briefings e um macaco com uma tesoura.", +"architect_weekly.name_all_roads_lead_to_hq":"Todos os caminhos levam a {hq}", +"architect_weekly.name_hq_and_friends":"{hq} e amigos", +"architect_weekly.name_the_hq_job":"O golpe de {hq}", +"architect_weekly.t_add_gold":"{a} entrou, crítico desde o primeiro dia: precisa sobreviver a qualquer corte.", +"architect_weekly.t_add_one":"{a} entrou: conecte-o.", +"architect_weekly.t_add_two":"{a} e {b} entraram: conecte-os.", +"architect_weekly.t_drop":"{a} vai fechar: saia de lá e não construa lá de novo.", +"architect_weekly.t_gold_one":"{a} agora é crítico: precisa sobreviver a qualquer corte.", +"architect_weekly.t_gold_two":"{a} e {b} agora são críticos: precisam sobreviver a qualquer corte.", +"architect_weekly.t_lat":"{a} ⇄ {b} precisa ficar abaixo de {ms} ms.", +"architect_weekly.t_ring":"{list} querem ficar no mesmo anel.", +"architect_weekly.weekly_run":"A rodada de Arquiteto da semana", "badges.a_petabit_a_second":"Um petabit por segundo", "badges.a_secret_badge":"Um badge secreto", "badges.attend_a_conference":"Participe de uma conferência.", diff --git a/site/sw.js b/site/sw.js index 2e0924c..745bafa 100644 --- a/site/sw.js +++ b/site/sw.js @@ -25,8 +25,8 @@ self.addEventListener('fetch', (e) => { } const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname); if (!local && !fonts) return; - // Weekly puzzles and scenarios are published between releases: ask the network first, and keep a copy for offline. - if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/weekly/'))) { + // Weekly puzzles, scenarios and Architect runs are published between releases: ask the network first, and keep a copy for offline. + if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/weekly/') || url.pathname.startsWith('/architect/weekly/'))) { e.respondWith(fetch(req).then((r) => { if (r.ok) { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); } return r; }) .catch(() => caches.match(req).then((r) => r || Response.error()))); return; diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js index 14ef3f3..ed69701 100644 --- a/src/game/60-features/96-architect.js +++ b/src/game/60-features/96-architect.js @@ -41,17 +41,17 @@ const AR_RUNS=[ ]}, ]; const arOn=()=>pzOn()&&!!S.ar; -const arRunDef=id=>AR_RUNS.find(r=>r.id===id)||null; +const arRunDef=id=>AR_RUNS.find(r=>r.id===id)||arWkRun(id); const arRun=()=>arRunDef(S.ar.id); const arBrief=()=>arRun().briefs[S.ar.bi]; const arLast=()=>S.ar.bi>=arRun().briefs.length-1; // ---------- progress: best stars, spend and briefs cleared per run, under its own key ---------- function arLoad(){let j=null;try{j=JSON.parse(localStorage.getItem(AR_KEY)||'{}');}catch(e){}const o={runs:{}}; - if(j&&j.runs&&typeof j.runs==='object')for(const k of Object.keys(j.runs)){const r=j.runs[k];if(!arRunDef(k)||!r||typeof r!=='object')continue; - o.runs[k]={st:int(r.st,0,3,0),br:int(r.br,0,99,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)};} + if(j&&j.runs&&typeof j.runs==='object')for(const k of Object.keys(j.runs)){const r=j.runs[k];if((!arRunDef(k)&&!AR_WK_ID.test(k))||!r||typeof r!=='object')continue; + o.runs[k]={st:int(r.st,0,3,0),br:int(r.br,0,99,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)};if(AR_WK_ID.test(k))o.runs[k].rv=int(r.rv,1,999,1);} return o;} function arStore(p){try{localStorage.setItem(AR_KEY,JSON.stringify(p));}catch(e){}} -function arRecord(st,br,sp){const p=arLoad(),r=p.runs[S.ar.id]||{st:0,br:0,sp:null}; +function arRecord(st,br,sp){const p=arLoad(),run=arRun(),old=p.runs[S.ar.id],r=old&&(!run.wk||(old.rv||1)===run.rev)?old:{st:0,br:0,sp:null};if(run.wk)r.rv=run.rev; if(st>r.st||(st===r.st&&st>0&&(r.sp==null||sp[...(x.add||[]),...(x.gold||[]),...(x.ring||[])]))].filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); + // Later briefs stay a surprise: their cities do not show until they come (Show all cities shows everything). + P.via=(arRun().via||[]).filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); arDemand();A.start=arSnapStr();UI.pzHist=[];UI.sel=null;UI.arFail=null; compute();pzCam();renderAll(); toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}`,'goal');sfx('click');} diff --git a/src/game/60-features/98-architect-weekly.js b/src/game/60-features/98-architect-weekly.js new file mode 100644 index 0000000..f345fdd --- /dev/null +++ b/src/game/60-features/98-architect-weekly.js @@ -0,0 +1,59 @@ +/* ---------- the published weekly Architect run ---------- + Every Sunday scripts/weekly-architect.js publishes architect/weekly/.json next to the page: an HQ, a budget and + the briefs, as data. Fetched only when Puzzles opens, checked field by field, and played like the handmade runs + (AR_RUNS) under the id 'wk-'. A brief's text is written here from what it asks for, in the player's language, so + the file can never say one thing and want another. When the file is missing, offline or wrong there is simply no + weekly run that week. */ +const AR_WK_V=1,AR_WK_FIELDS=['v','key','hq','budget','name','joke','briefs','ref','rev'],AR_WK_BRIEF=['add','gold','ring','drop','dem','lat','tubes']; +// The labels a file may name (N_: kept whole in the shipped page); their only placeholder is {hq}, a city. +const AR_WK_NAMES=[N_('architect_weekly.name_all_roads_lead_to_hq'),N_('architect_weekly.name_the_hq_job'),N_('architect_weekly.name_hq_and_friends')]; +const AR_WK_JOKES=[N_('architect_weekly.joke_hq_signed_the_lease'),N_('architect_weekly.joke_one_network_a_handful')]; +const arWkId=key=>'wk-'+key,AR_WK_ID=/^wk-\d{4}-W\d{2}$/; +function arWkTxt(o,list){if(!pzObj(o)||!list.includes(o.l))return null;const p=o.p==null?{}:o.p;if(!pzObj(p))return null; + const need=[...new Set([...String(EN[o.l]).matchAll(/\{(\w+)\}/g)].map(m=>m[1]))]; + if(Object.keys(p).length!==need.length||!need.every(k=>k==='hq'&&pzCityOk(p[k])))return null;return {l:o.l,p:Object.assign({},p)};} +const arWkSay1=o=>tr(o.l,o.p.hq?{hq:CITY[o.p.hq].name}:{}); +// What a brief says, built from what it wants. +function arWkSay(b){const n=c=>CITY[c].name,t=[]; + if(b.drop)t.push(tr('architect_weekly.t_drop',{a:n(b.drop[0])})); + const ag=b.add&&b.gold&&b.add.length===1&&b.gold.length===1&&b.add[0]===b.gold[0]; + if(ag)t.push(tr('architect_weekly.t_add_gold',{a:n(b.add[0])})); + else if(b.add)t.push(b.add.length>1?tr('architect_weekly.t_add_two',{a:n(b.add[0]),b:n(b.add[1])}):tr('architect_weekly.t_add_one',{a:n(b.add[0])})); + if(b.gold&&!ag)t.push(b.gold.length>1?tr('architect_weekly.t_gold_two',{a:n(b.gold[0]),b:n(b.gold[1])}):tr('architect_weekly.t_gold_one',{a:n(b.gold[0])})); + if(b.ring)t.push(tr('architect_weekly.t_ring',{list:b.ring.map(n).join(', ')})); + if(b.lat)t.push(tr('architect_weekly.t_lat',{a:n(b.lat[0]),b:n(b.lat[1]),ms:+b.lat[2].toFixed(1)})); + return t.join(' ');} +// The briefs, in order: a site exists from the brief that adds it until one drops it; every brief asks for something. +function arWkBriefs(a,hq){if(!Array.isArray(a)||a.length<3||a.length>7)return null;const sites=new Set([hq]),gone=new Set(),out=[]; + const ids=(x,lo,hi)=>x==null?[]:Array.isArray(x)&&x.length>=lo&&x.length<=hi&&x.every(pzCityOk)&&new Set(x).size===x.length?x.slice():null; + for(const b of a){if(!pzObj(b)||Object.keys(b).some(k=>!AR_WK_BRIEF.includes(k)))return null; + const drop=ids(b.drop,1,1),add=ids(b.add,1,2),gold=ids(b.gold,1,2),ring=b.ring==null?[]:ids(b.ring,3,4);if(!drop||!add||!gold||!ring)return null; + for(const c of drop){if(c===hq||!sites.has(c))return null;sites.delete(c);gone.add(c);} + for(const c of add){if(sites.has(c)||gone.has(c))return null;sites.add(c);} + if(![...gold,...ring].every(c=>sites.has(c))||gold.includes(hq))return null; + const dem={};if(b.dem!=null){if(!pzObj(b.dem))return null;for(const c of Object.keys(b.dem)){const g=b.dem[c];if(!sites.has(c)||c===hq||!Number.isInteger(g)||g<10||g>400)return null;dem[c]=g;}} + let lat=null;if(b.lat!=null){const l=b.lat;if(!Array.isArray(l)||l.length!==3||!sites.has(l[0])||!sites.has(l[1])||l[0]===l[1]||typeof l[2]!=='number'||!isFinite(l[2])||l[2]<1||l[2]>300)return null;lat=l.slice();} + if(!Number.isInteger(b.tubes)||b.tubes<0||b.tubes>9)return null; + if(!add.length&&!gold.length&&!ring.length&&!lat)return null; + const o={tubes:b.tubes};if(add.length)o.add=add;if(gold.length)o.gold=gold;if(ring.length)o.ring=ring;if(drop.length)o.drop=drop;if(Object.keys(dem).length)o.dem=dem;if(lat)o.lat=lat; + o.t=arWkSay(o);out.push(o);} + return out[0].add?out:null;} +// The file, never trusted: a run definition like AR_RUNS's, or null. +function arWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!AR_WK_FIELDS.includes(k))||j.v!==AR_WK_V||j.key!==key||pzWeekStart(key)==null||!pzCityOk(j.hq))return null; + if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>2e7)return null; + if(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null;if(j.ref!==undefined&&!pzObj(j.ref))return null; + const name=arWkTxt(j.name,AR_WK_NAMES),joke=arWkTxt(j.joke,AR_WK_JOKES),briefs=arWkBriefs(j.briefs,j.hq);if(!name||!joke||!briefs)return null; + return {id:arWkId(key),key,wk:true,n:arWkSay1(name),j:arWkSay1(joke),hq:j.hq,via:[],budget:j.budget,briefs,rev:j.rev||1};} +// The run behind an id, when it is this week's. +function arWkRun(id){const w=UI.arWk;return w&&w.def&&w.def.id===id?w.def:null;} +// ---------- fetching it: when Puzzles opens, never on page load ---------- +function arWkEnsure(){const key=pzWeekKey(new Date()),w=UI.arWk;if(w&&w.key===key&&(w.def||Date.now()-w.at<5*60e3))return; + const st=UI.arWk={key,def:null,at:Date.now()};let done=false; + const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.arWk!==st)return;st.def=def;st.at=Date.now();const el=$('arWk');if(el)el.outerHTML=arWkRow();}; + const ac=window.AbortController?new AbortController():null,to=setTimeout(()=>{if(ac)ac.abort();fin(null);},5000); + if(!window.fetch||location.protocol==='file:'){fin(null);return;} + try{fetch(`architect/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>arWkValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +// Its row in the Puzzles menu, above the handmade runs; nothing while there is none. +function arWkRow(){const w=UI.arWk,r=w&&w.key===pzWeekKey(new Date())?w.def:null;if(!r)return '
'; + const x=arLoad().runs[r.id],ok=x&&(x.rv||1)===r.rev?x:null; + return `
🗓️ ${tr('architect_weekly.weekly_run')}
${esc(r.n)} ${pzStarStr(ok?ok.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)} · ${tr('puzzles.budget_x',{x:fmt$(r.budget)})}${ok&&ok.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(ok.sp)}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},ok&&ok.st>=3?'ghost':'pink')}
`;} diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js index 3d9c6f4..1eb9c7c 100644 --- a/src/game/95-modals/96-architect.js +++ b/src/game/95-modals/96-architect.js @@ -65,7 +65,7 @@ function arLinkModal(a,b,keep){const kb=pzKind(b); // ---------- results ---------- const arLine=st=>st>=3?tr('architect.line_3'):st===2?tr('architect.line_2'):tr('architect.line_1'); function arResults(done){const A=S.ar,run=arRun(),sp=arSpend(),br=done?run.briefs.length:A.bi,st=done?arStars(sp):0,sh=arShape();arRecord(st,br,sp); - const nx=AR_RUNS[AR_RUNS.indexOf(run)+1]||null,stars=[0,1,2].map(i=>`⭐`).join(''); + const ri=AR_RUNS.indexOf(run),nx=ri>=0?AR_RUNS[ri+1]||null:null,stars=[0,1,2].map(i=>`⭐`).join(''); openModal(`
${st>=3?pzConfetti():''}
🏗️ ${done?tr('architect.run_complete'):tr('architect.run_over')}

${esc(run.n)}

${stars}

${done?arLine(st):tr('architect.the_cfo_pulled_the_plug')}

${done?'⭐':'☆'} ${tr('architect.briefs_done')}${br} / ${run.briefs.length}
@@ -75,7 +75,7 @@ function arResults(done){const A=S.ar,run=arRun(),sp=arSpend(),br=done?run.brief
${nx&&done?btn(tr('architect.next_run')+' →','pzArStart',{id:nx.id},'pink big'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big')}${btn(tr('architect.try_again'),'pzRetry',{},'')}${done?btn(tr('common.share_2cd9'),'pzShare',{},'ghost'):btn(tr('architect.keep_going'),'closeModal',{},'ghost')}
`); for(let i=0;i{sfx('star');haptic(15);},i*450+150);if(st>=3)setTimeout(()=>sfx('fanfare'),3*450+250);} // ---------- the list ---------- -function arMenuRows(){const p=arLoad();let h=`

🏗️ ${tr('architect.architect_runs')} ${tr('architect.new')}

${tr('architect.runs_lead')}

`; +function arMenuRows(){const p=arLoad();let h=`

🏗️ ${tr('architect.architect_runs')} ${tr('architect.new')}

${tr('architect.runs_lead')}

`;arWkEnsure();h+=arWkRow(); for(const r of AR_RUNS){const x=p.runs[r.id]; h+=`
${esc(r.n)} ${pzStarStr(x?x.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)}${' · '+tr('puzzles.budget_x',{x:fmt$(r.budget)})}${x&&x.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(x.sp)}):x&&x.br?' · '+tr('architect.best_n_briefs',{n:x.br}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},x&&x.st>=3?'ghost':'pink')}
`;} return h;} diff --git a/src/i18n/en.js b/src/i18n/en.js index 3429679..e0a4100 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -122,6 +122,20 @@ "architect.usa_6":"A cloud deal in Silicon Valley. It's mission-critical.", "architect.x_paid_for_and_gone":"{x} of that paid for things you removed", "architect.your_shape":"Your shape", +"architect_weekly.joke_hq_signed_the_lease":"{hq} signed the lease. Everything after that is your problem.", +"architect_weekly.joke_one_network_a_handful":"One network, a handful of briefs and a monkey with scissors.", +"architect_weekly.name_all_roads_lead_to_hq":"All Roads Lead to {hq}", +"architect_weekly.name_hq_and_friends":"{hq} and Friends", +"architect_weekly.name_the_hq_job":"The {hq} Job", +"architect_weekly.t_add_gold":"{a} signs up, mission-critical from day one: it must survive any single cut.", +"architect_weekly.t_add_one":"{a} signs up: connect it.", +"architect_weekly.t_add_two":"{a} and {b} sign up: connect them.", +"architect_weekly.t_drop":"{a} is closing: move out, and don’t build there again.", +"architect_weekly.t_gold_one":"{a} is now mission-critical: it must survive any single cut.", +"architect_weekly.t_gold_two":"{a} and {b} are now mission-critical: they must survive any single cut.", +"architect_weekly.t_lat":"{a} ⇄ {b} must stay under {ms} ms.", +"architect_weekly.t_ring":"{list} want to sit on one ring.", +"architect_weekly.weekly_run":"This week’s Architect run", "badges.a_petabit_a_second":"A Petabit a Second", "badges.a_secret_badge":"A secret badge", "badges.attend_a_conference":"Attend a conference.", diff --git a/tests/architect.test.js b/tests/architect.test.js index a245070..40d4498 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -39,7 +39,7 @@ test('architect runs: the chaos monkey finds a shared trench, edits clear the cu const { ev, errors } = load(); ev("ACT.pzArStart({id:'euro'})"); assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); - assert.equal(ev("arHide('dus')"), false); + assert.equal(ev("arHide('dus')"), true, 'a city a later brief adds stays hidden until then'); // Later briefs stay a surprise: nothing on the map or a city card says where the run goes next. assert.equal(ev("typeof arTags"), 'undefined'); ev("UI.sel={type:'city',id:'fra'};renderPanel()"); diff --git a/tests/weekly-architect.test.js b/tests/weekly-architect.test.js new file mode 100644 index 0000000..42aca52 --- /dev/null +++ b/tests/weekly-architect.test.js @@ -0,0 +1,73 @@ +// The weekly Architect run: generated every Sunday (scripts/weekly-architect.js), checked by the game field by field, +// and played like the handmade runs. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { load } = require('./harness'); +const { game } = require('../scripts/weekly-puzzle'); +const AW = require('../scripts/weekly-architect'); + +const DIR = path.join(__dirname, '..', 'site', 'architect', 'weekly'); +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'sot-arwk-')); + +test('the generator makes the same run for the same week, and its reference earns three stars', () => { + const g = game(), a = AW.generate(g, '2026-W50', tmp()), b = AW.generate(g, '2026-W50', tmp()); + assert.deepEqual(a, b, 'deterministic'); + assert.ok(a.briefs.length >= 6 && a.briefs.length <= 7); + assert.ok(a.briefs.every((x) => x.tubes >= 1), 'every brief asks for at least one tube'); + assert.ok(a.briefs.some((x) => x.gold), 'something is mission-critical'); + assert.ok(a.budget >= a.ref.spend && a.budget <= a.ref.spend * 1.1 + 10000, 'the budget sits just above the reference'); + assert.equal(AW.verify(g, a, '2026-W50').ok, true); +}); + +test('every published week is accepted and its reference still earns three stars', () => { + const keys = AW.list(DIR); + assert.ok(keys.length >= 3); + assert.deepEqual(AW.check(game(), DIR, 0), []); +}); + +test('the game refuses a file that does not add up', () => { + const { ev } = load(); + const j = JSON.parse(fs.readFileSync(path.join(DIR, AW.list(DIR)[0] + '.json'), 'utf8')), k = j.key; + const ok = (o) => ev(`!!arWkValid(${JSON.stringify(o)},'${k}')`); + assert.equal(ok(j), true); + const bad = (f) => { const o = JSON.parse(JSON.stringify(j)); f(o); return ok(o); }; + assert.equal(ev(`!!arWkValid(${JSON.stringify(j)},'2030-W01')`), false, 'under another week'); + assert.equal(bad((o) => { o.extra = 1; }), false, 'an unknown field'); + assert.equal(bad((o) => { o.hq = 'atlantis'; }), false, 'an unknown HQ'); + assert.equal(bad((o) => { o.name.l = 'common.play'; }), false, 'a label it may not name'); + assert.equal(bad((o) => { o.briefs[0] = { tubes: 1 }; }), false, 'a brief that asks for nothing'); + assert.equal(bad((o) => { o.briefs[1].gold = [o.hq]; }), false, 'HQ made mission-critical'); + assert.equal(bad((o) => { o.briefs[1].gold = ['tok']; }), false, 'a site that is not in the run yet'); + assert.equal(bad((o) => { o.briefs.push({ lat: [o.hq, o.briefs[0].add[0], 0.5], tubes: 1 }); }), false, 'a latency cap below 1 ms'); + assert.equal(bad((o) => { o.budget = 1e9; }), false, 'a silly budget'); +}); + +test('this week\'s run shows in Puzzles, plays like a handmade one and keeps its own stars', () => { + const { ev, errors, dom } = load(); + const key = ev('pzWeekKey(new Date())'), j = AW.generate(game(), key, tmp()); + ev(`UI.arWk={key:'${key}',def:arWkValid(${JSON.stringify(j)},'${key}'),at:Date.now()}`); + ev('ACT.puzzleMenu()'); + const row = dom.window.document.getElementById('arWk'); + assert.ok(row && row.querySelector('[data-act=pzArStart]'), 'a row with a Play button'); + assert.match(row.textContent, /This week’s Architect run/); + row.querySelector('[data-act=pzArStart]').click(); + assert.equal(ev('S.ar.id'), 'wk-' + key); + assert.match(ev('arBrief().t'), /signs up: connect it\./, 'the brief is written from what it asks'); + assert.equal(ev(`arHide('${j.briefs[1].add[0]}')`), true, 'the next brief\'s cities stay hidden'); + // The reference, played through: three stars, stored under the week, and no handmade run offered as "next". + j.ref.steps.forEach((st, i) => { + for (const s of st) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else ev(`ACT.pzLinkTo({a:'${s[0]}',b:'${s[1]}'});ACT.pzVia({v:'${s[2]}'});ACT.pzDiv({v:1});ACT.pzLink({tier:AR_TIER});closeModal()`); + ev('arShowStart();arShowSkip()'); + assert.ok(ev('S.ar.passed===pzSig()'), `brief ${i + 1} passes`); + ev('ACT.pzArNext()'); + }); + assert.equal(ev(`arLoad().runs['wk-${key}'].st`), 3); + assert.equal(ev("document.querySelector('#modalCard [data-act=pzArStart]')"), null, 'no "next run" after a weekly one'); + // A regenerated week (rev 2) starts its stars again. + ev(`UI.arWk.def.rev=2;ACT.puzzleMenu()`); + assert.match(dom.window.document.getElementById('arWk').textContent, /⬜⬜⬜/); + assert.deepEqual(errors, []); +});