Merge the weekly puzzle generator into v2

This commit is contained in:
Frederic Jung 2026-10-29 07:01:34 +01:00
commit 13376ceb97
No known key found for this signature in database
25 changed files with 1046 additions and 15 deletions

View file

@ -40,6 +40,14 @@ publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 np
`pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the
steps.
**The one exception: the weekly puzzle.** Every Sunday at 03:37 UTC `weekly-puzzle.yml` commits the new
`site/puzzles/weekly/<key>.json` to `main` (data only, no version bump) and starts `release.yml` for the **live
release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main`
added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group.
Players get no update banner (the version does not change). Every release build also copies all weekly files from
`main`, so a release never drops a published week. Weekly files are plain JSON the game fetches only when the
Puzzles list opens and never trusts; the service worker serves them network-first. See `docs/ARCHITECTURE.md`.
## Before you hand back a change that touches the build, deploy or loading
```bash

View file

@ -12,6 +12,15 @@ that version's CHANGELOG section as notes, and dispatches `release.yml`, which b
to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the
`github-pages` skill.
## Weekly puzzles are not releases
`weekly-puzzle.yml` publishes a new puzzle every Sunday morning without a release: it commits the JSON under
`site/puzzles/weekly/` to `main` and redeploys the live tag through `release.yml` (`weekly=true`). Never bump the
version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly-puzzle.js --key 2026-W45 --force`,
`node scripts/weekly-puzzle.js --check`, commit to `main`, then run the "Weekly puzzle" workflow (or
`gh workflow run release.yml --ref <live tag> -f tag=<live tag> -f weekly=true`). A release includes every weekly
file on `main` when it builds.
## Only release when Frederic says so
Never bump the version on your own. Finished work is committed and pushed with its

View file

@ -4,7 +4,8 @@ name: Release to GitHub Pages
# Pushes to main run CI but never deploy. To ship: bump "version" in
# package.json and date its CHANGELOG section; auto-release.yml then tags,
# publishes the release and starts this workflow from the tag. Publishing a
# release by hand works too.
# release by hand works too. Every Sunday weekly-puzzle.yml redeploys the live
# release from its tag with the new weekly puzzle added (input weekly).
on:
release:
# "released" also fires when a pre-release is promoted to a full release.
@ -18,6 +19,10 @@ on:
description: Allow deploying a version older than what is live (rollback)
type: boolean
default: false
weekly:
description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped
type: boolean
default: false
# Least privilege: only the deploy job can write to Pages.
permissions:
@ -63,8 +68,28 @@ jobs:
if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then
echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1
fi
# Weekly puzzles are published on main between releases (weekly-puzzle.yml). Every deploy ships all of them,
# so neither a release nor a weekly redeploy ever drops a week that is already out.
- name: Weekly puzzles from main
run: |
set -euo pipefail
git fetch --no-tags --depth=1 origin main
if git cat-file -e FETCH_HEAD:site/puzzles/weekly 2>/dev/null; then
rm -rf site/puzzles/weekly
git checkout FETCH_HEAD -- site/puzzles/weekly
echo "Weekly puzzles: $(ls site/puzzles/weekly | grep -c '^[0-9].*\.json$')"
fi
- run: npm ci
- run: npm test
if: ${{ !inputs.weekly }}
- name: Check the weekly puzzles against this release
if: ${{ inputs.weekly }}
run: |
set -euo pipefail
# A release from before the weekly puzzles ships the files without reading them: nothing to check.
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
npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js
- name: Build site
run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build
- uses: actions/upload-pages-artifact@v5
@ -88,6 +113,7 @@ jobs:
# the site is live.
indexnow:
needs: deploy
if: ${{ !inputs.weekly }}
runs-on: ubuntu-latest
env:
# IndexNow keys are public by design (also served at /<key>.txt).

80
.github/workflows/weekly-puzzle.yml vendored Normal file
View file

@ -0,0 +1,80 @@
name: Weekly puzzle
# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), commit it to main as a data-only
# change, and redeploy the live release with it. Puzzle weeks start Sunday 06:00 Berlin time; 03:37 UTC is
# 04:37 in winter and 05:37 in summer, so the file is live before the week starts either way.
#
# No version bump, so no release: auto-release.yml only runs when package.json changes (and pushes made with
# the workflow token start no workflows at all). The deploy itself is release.yml, still the only workflow
# that can write to Pages, started from the live release's tag with weekly=true: it rebuilds exactly that
# release with every weekly puzzle from main added, in the same "pages" concurrency group as any release.
on:
schedule:
- cron: '37 3 * * 0'
workflow_dispatch:
inputs:
key:
description: Week to make, e.g. 2026-W45 (default the week starting this Sunday)
required: false
deploy:
description: Redeploy the live release with it
type: boolean
default: true
permissions:
contents: write # commit the puzzle to main
actions: write # start release.yml
concurrency:
group: weekly-puzzle
cancel-in-progress: false
jobs:
puzzle:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
GH_TOKEN: ${{ github.token }}
KEY: ${{ inputs.key }}
steps:
- uses: actions/checkout@v7
with:
ref: main
- uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- run: npm ci
- name: Make the puzzle
run: |
set -euo pipefail
if [ -n "$KEY" ]; then
[[ "$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"
else
node scripts/weekly-puzzle.js
fi
- name: Check every weekly puzzle
run: node scripts/weekly-puzzle.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js
- name: Commit it to main
run: |
set -euo pipefail
git add site/puzzles/weekly
# Data only: anything else changed means something is wrong.
if git status --porcelain | grep -v ' site/puzzles/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 $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')"
git push origin HEAD:main
- name: Redeploy the live release with it
if: github.event_name == 'schedule' || inputs.deploy
run: |
set -euo pipefail
tag=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --exclude-drafts --limit 1 --json tagName -q '.[0].tagName')
[ -n "$tag" ] || { echo "::error::no release to redeploy"; exit 1; }
# Releases from before the weekly puzzles cannot take them (and their game would not read them).
if ! git fetch --no-tags --depth=1 origin "refs/tags/$tag" || ! git show FETCH_HEAD:.github/workflows/release.yml | grep -q '^ weekly:'; then
echo "::notice::$tag predates weekly puzzles; the puzzle is on main and ships with the next release."; exit 0
fi
gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$tag" -f tag="$tag" -f weekly=true
echo "Redeploying $tag with the weekly puzzles."

View file

@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- 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.
- 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.
- 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 and sold-out routes. 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.
- Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy.

View file

@ -29,7 +29,7 @@ hoisted across files, and top-level statements run in path order. Find code by n
| `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) |
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) |
| `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` |
| `60-features/` | Banks and loans, scenarios and the weekly challenge, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) |
| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) |
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering inbox, peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
| `80-simulation/` | Dijkstra, RouteScript, `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service |
| `85-incidents/` | `addInc()`, DDoS and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` |
@ -72,6 +72,8 @@ Development runs on `npm run dev` (assembles on every request, reloads on save);
| `.github/workflows/ci.yml` | Tests and build on every push and PR |
| `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test, tag, GitHub release from the CHANGELOG, start the deploy |
| `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can |
| `.github/workflows/weekly-puzzle.yml` | Sunday 03:37 UTC: makes the week's puzzle, commits it to `main` (data only, no release) and starts `release.yml` for the live release tag with `weekly=true` |
| `scripts/weekly-puzzle.js`, `site/puzzles/weekly/` | The weekly puzzle generator and its output, one `<key>.json` per week plus `index.json` (see below) |
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) |
## Globals
@ -147,6 +149,32 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood.
- The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses
a simplified style; parallel waves are grouped by `linkGroups()`.
## The weekly puzzle
A puzzle week runs from Sunday 06:00 Berlin time to the next Sunday 06:00, and is named after the ISO week of
its Monday (the week starting Sunday 1 November 2026 is `2026-W45`); `pzWeekKey()` and `pzWeekStart()` in
`src/game/60-features/93-puzzles-weekly.js` handle summer time and the year boundary.
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"}`).
`--check` re-validates every file the way the game does.
The game fetches `puzzles/weekly/<key>.json` (relative, same origin) only when the Puzzles list opens, and checks
it field by field (`pzWkValid()`): known fields, playable cities, labels from the theme's own list, sane numbers.
When it is missing, offline or wrong, the seeded weekly (`pzWeekly()`) stands in, so the weekly puzzle always
works. The service worker fetches these files network-first and keeps a copy for offline play.
The weekly ships without a release: the workflow commits only `site/puzzles/weekly/` to `main` (no version bump,
so `auto-release.yml` stays quiet) and starts `release.yml` from the live release's tag with `weekly=true`, which
rebuilds that exact release with every weekly file from `main` and deploys it. Every release build takes the
weekly files from `main` too, so no deploy ever drops a published week.
## Saves, imports and migration
- `save()` writes `S` to localStorage every few seconds and after actions.

341
scripts/weekly-puzzle.js Normal file
View file

@ -0,0 +1,341 @@
#!/usr/bin/env node
// The weekly puzzle generator. Every Sunday .github/workflows/weekly-puzzle.yml runs it to publish that week's
// puzzle as a static file, site/puzzles/weekly/<key>.json, which the game fetches when Puzzles opens
// (src/game/60-features/93-puzzles-weekly.js). It loads the real game headless (tests/harness.js), so it uses the
// game's own cities, cables, prices, week keys, file validator and star code.
//
// node scripts/weekly-puzzle.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
// node scripts/weekly-puzzle.js --key 2026-W45 that week (--force replaces an existing file)
// node scripts/weekly-puzzle.js --next 3 this week and the next two
// node scripts/weekly-puzzle.js --check validate every file (and re-verify the stars of weeks not over yet)
// --page FILE play another build of the game (the live release), see the workflow
// --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.
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 THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint'];
// ---------- the game, headless ----------
function game(file) {
const { load } = require('../tests/harness');
let g = load(file ? { file } : {});
if (file && !g.ev("typeof pzWkValid==='function'")) {
console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`);
g = load();
}
// 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;
}
// ---------- small helpers ----------
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;
function perms(a) { if (a.length <= 1) return [a]; const out = []; a.forEach((x, i) => { for (const p of perms([...a.slice(0, i), ...a.slice(i + 1)])) out.push([x, ...p]); }); return out; }
function subsets(a) { const out = []; for (let m = 0; m < 1 << a.length; m++) out.push(a.filter((_, i) => m >> i & 1)); return out; }
// ---------- the world, as the game prices it ----------
function world(ev) {
const cities = JSON.parse(ev("JSON.stringify(Object.values(CITY).filter(c=>!c.off&&!c.cn).map(c=>({id:c.id,name:c.name,lands:lands(c),reg:c.reg,P:c.P,lon:c.lon,lat:c.lat,pop:pzPopCost(c.id)})))"));
const C = Object.fromEntries(cities.map((c) => [c.id, c]));
const cablePairs = JSON.parse(ev('JSON.stringify(CABLE_PAIRS.map(p=>[p.cid,p.a,p.b]))')).filter(([, a, b]) => C[a] && C[b]);
const cabs = {}; for (const [cid, a, b] of cablePairs) { (cabs[a] = cabs[a] || new Set()).add(cid); (cabs[b] = cabs[b] || new Set()).add(cid); }
const memo = new Map();
// Every way to join a and b: overland (first wave, and a second one on a diverse route) and each cable.
const opts = (a, b) => {
const k = a < b ? a + '|' + b : b + '|' + a; if (memo.has(k)) return memo.get(k);
const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').filter(r=>!subWaveWhy(0,r.km,r.sub)).map(r=>({via:r.via,cab:r.cab,sub:r.sub,ms:r.ms,c:pzLinkCost(r,0,false),c2:r.sub?0:pzLinkCost(r,0,true)})))`));
const out = [];
for (const r of rs) {
if (r.cab) out.push({ a, b, via: r.via, sub: true, ms: r.ms, cost: r.c, unit: 'cab:' + r.cab });
else { out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c, unit: `land:${k}:1` }); out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c2, unit: `land:${k}:2`, second: true }); }
}
out.sort((x, y) => x.cost - y.cost || (x.unit < y.unit ? -1 : 1));
memo.set(k, out); return out;
};
const km = (a, b) => { const A = C[a], B = C[b], r = Math.PI / 180, h = Math.sin((B.lat - A.lat) * r / 2) ** 2 + Math.cos(A.lat * r) * Math.cos(B.lat * r) * Math.sin((B.lon - A.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(h)); };
return { cities, C, cablePairs, cabs, opts, km };
}
// ---------- judging a build (the game has the last word; this steers the search) ----------
function judge(W, P, links) {
const nodes = new Set(); for (const l of links) { nodes.add(l.a); nodes.add(l.b); }
// A second overland wave on a pair needs the first one.
for (const l of links) if (l.second && !links.some((x) => x !== l && !x.second && x.via === 'land' && x.unit === l.unit.replace(/2$/, '1'))) return null;
if (new Set(links.map((l) => l.unit)).size !== links.length) return null;
const cost = [...nodes].reduce((s, c) => s + W.C[c].pop, 0) + links.reduce((s, l) => s + l.cost, 0);
const comp = (skip) => { const adj = {}; for (const l of links) if (l.unit !== skip) { (adj[l.a] = adj[l.a] || []).push(l.b); (adj[l.b] = adj[l.b] || []).push(l.a); }
const seen = new Set([P.cities[0]]), q = [P.cities[0]]; 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; };
const all = comp(null);
if (!P.cities.every((c) => all.has(c))) return { ok: false, cost };
if (P.avoid.some((c) => nodes.has(c))) return { ok: false, cost };
if (P.noSub && links.some((l) => l.sub)) return { ok: false, cost };
if (P.ring) { const nb = {}; for (const l of links) { (nb[l.a] = nb[l.a] || new Set()).add(l.b); (nb[l.b] = nb[l.b] || new Set()).add(l.a); }
if (links.length !== nodes.size || ![...nodes].every((c) => nb[c].size === 2)) return { ok: false, cost }; }
if (P.lat) { const [a, b, ms] = P.lat, d = { [a]: 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 || u === b) break; done.add(u);
for (const l of links) { const v = l.a === u ? l.b : l.b === u ? l.a : null; if (v && !(d[v] <= d[u] + l.ms)) d[v] = d[u] + l.ms; } }
if (!(d[b] <= ms)) return { ok: false, cost }; }
const weak = [...new Set(links.map((l) => l.unit))].filter((u) => { const g = comp(u); return !P.cities.every((c) => g.has(c)); });
return { ok: true, cost, n1: weak.length === 0, weak };
}
// ---------- the solver ----------
// Cheapest tree over a node set (Kruskal on each pair's cheapest way), with some links forced in.
function tree(W, nodes, forced = []) {
const par = Object.fromEntries(nodes.map((n) => [n, n])), f = (x) => (par[x] === x ? x : (par[x] = f(par[x])));
const out = [];
for (const l of forced) { par[f(l.a)] = f(l.b); out.push(l); }
const es = [];
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) { const o = W.opts(nodes[i], nodes[j]).filter((x) => !x.second); if (o.length) es.push(o[0]); }
es.sort((x, y) => x.cost - y.cost);
for (const e of es) if (f(e.a) !== f(e.b)) { par[f(e.a)] = f(e.b); out.push(e); }
return out.length - forced.length === nodes.length - 1 - forced.length ? out : null;
}
// Add the link that removes the most single points of failure per dollar, until none are left.
function harden(W, P, nodes, links) {
links = links.slice();
for (let guard = 0; guard < 12; guard++) {
const j = judge(W, P, links); if (!j || !j.ok) return null; if (j.n1) return links;
let best = null;
for (let i = 0; i < nodes.length; i++) for (let k = i + 1; k < nodes.length; k++) for (const o of W.opts(nodes[i], nodes[k])) {
if (links.some((l) => l.unit === o.unit)) continue;
const jj = judge(W, P, [...links, o]); if (!jj || !jj.ok) continue;
const gain = j.weak.length - jj.weak.length; if (gain <= 0) continue;
const score = gain / o.cost; if (!best || score > best.score) best = { score, o };
}
if (!best) return null; links.push(best.o);
}
return null;
}
// Every simple cycle through the node set, each hop by one of its three cheapest ways, cheapest first.
function cycles(W, P, nodes, bound) {
let best = null; const [h, ...rest] = nodes;
if (nodes.length < 3) return null;
for (const p of perms(rest)) {
if (p[0] > p[p.length - 1]) continue; // each cycle once
const ring = [h, ...p], hops = ring.map((x, i) => W.opts(x, ring[(i + 1) % ring.length]).filter((o) => !o.second).slice(0, 3));
if (hops.some((o) => !o.length)) continue;
const pop = ring.reduce((s, c) => s + W.C[c].pop, 0);
const go = (i, acc, cost) => {
if (cost >= Math.min(bound, best ? best.cost : Infinity)) return;
if (i === hops.length) { const j = judge(W, P, acc); if (j && j.ok && j.n1) best = { cost: j.cost, links: acc.slice() }; return; }
for (const o of hops[i]) { if (acc.some((l) => l.unit === o.unit)) continue; acc.push(o); go(i + 1, acc, cost + o.cost); acc.pop(); }
};
go(0, [], pop);
}
return best;
}
function solve(W, P) {
const vias = P.via.filter((c) => !P.avoid.includes(c));
let one = null, three = null, naive = null;
const keep = (cur, links) => { if (!links) return cur; const j = judge(W, P, links); if (!j || !j.ok) return cur; return !cur || j.cost < cur.cost ? { cost: j.cost, links, n1: j.n1 } : cur; };
for (const sub of subsets(vias)) {
const nodes = [...P.cities, ...sub];
const forced = P.lat ? [W.opts(P.lat[0], P.lat[1]).filter((o) => !o.second).sort((x, y) => x.ms - y.ms)[0]].filter(Boolean) : [];
const ts = [tree(W, nodes), forced.length ? tree(W, nodes, forced) : null].filter(Boolean)
// A via city left as a leaf is money for nothing.
.filter((t) => sub.every((v) => t.filter((l) => l.a === v || l.b === v).length >= 2));
if (!P.ring) for (const t of ts) {
one = keep(one, t);
// The obvious way to survive a cut: a second, different way along every hop of the tree.
const dbl = t.slice(); let okd = true;
for (const l of t) { const alt = W.opts(l.a, l.b).find((o) => o.unit !== l.unit && !dbl.some((x) => x.unit === o.unit)); if (!alt) { okd = false; break; } dbl.push(alt); }
if (okd) { const j = judge(W, P, dbl); if (j && j.ok && j.n1 && (!naive || j.cost < naive.cost)) naive = { cost: j.cost, links: dbl }; if (j && j.ok && j.n1) three = keep(three, dbl); }
const hd = harden(W, P, nodes, t); if (hd) three = keep(three, hd);
}
if (nodes.length <= 7) { const c = cycles(W, P, nodes, three ? three.cost : Infinity); if (c) { three = keep(three, c.links); if (P.ring) one = keep(one, c.links); } }
}
return { one, three, naive };
}
// ---------- themes: which cities, which twist ----------
function pools(W) {
const byLand = {};
for (const c of W.cities) { const k = c.lands[0] + '/' + c.reg; (byLand[k] = byLand[k] || []).push(c.id); }
const big = Object.values(byLand).map((g) => g.filter((c) => W.C[c].P >= 100)).filter((g) => g.length >= 6);
const isl = W.cities.filter((c) => byLand[c.lands[0] + '/' + c.reg].length === 1 && c.lands.length === 1 && (W.cabs[c.id] || new Set()).size >= 2).map((c) => c.id);
return { big, isl };
}
const near = (W, c, from, n) => from.filter((x) => x !== c).sort((a, b) => W.km(c, a) - W.km(c, b)).slice(0, n);
function draft(W, theme, r, banned) {
const { big, isl } = pools(W), free = (c) => !banned.has(c);
const P = { theme, cities: [], via: [], avoid: [], noSub: false, ring: false, lat: null };
if (theme === 'tour' || theme === 'ring' || theme === 'detour') {
const g = pick(r, big).filter(free);
if (g.length < 6) return null;
if (theme === 'detour') {
const hub = pick(r, g.slice().sort((a, b) => W.C[b].P - W.C[a].P).slice(0, 4)), around = near(W, hub, g, 8);
if (around.length < 6) return null;
const sh = shuffle(r, around); P.cities = sh.slice(0, 4); P.via = sh.slice(4, 6); P.avoid = [hub];
} else {
const seed = pick(r, g), n = theme === 'ring' ? 4 + Math.floor(r() * 2) : 4 + Math.floor(r() * 3);
P.cities = [seed, ...shuffle(r, near(W, seed, g, n + 2)).slice(0, n - 1)];
if (theme === 'tour') P.via = near(W, seed, g, n + 4).filter((c) => !P.cities.includes(c)).slice(0, 1);
P.ring = theme === 'ring';
}
} else if (theme === 'ocean') {
const land = (c) => W.C[c].lands[0], ok = W.cablePairs.filter(([, a, b]) => land(a) !== land(b) && free(a) && free(b) && big.some((g) => g.includes(a)) && big.some((g) => g.includes(b)));
if (!ok.length) return null;
const [, a, b] = pick(r, ok), ga = big.find((g) => g.includes(a)).filter(free), gb = big.find((g) => g.includes(b)).filter(free);
const a2 = pick(r, near(W, a, ga, 3)), b2 = pick(r, near(W, b, gb, 3));
if (!a2 || !b2) return null;
P.cities = [a, a2, b, b2];
// Other landing points on either shore that cross the same ocean: the stepping stones to a second crossing.
const shores = W.cablePairs.filter(([, x, y]) => (land(x) === land(a) && land(y) === land(b)) || (land(x) === land(b) && land(y) === land(a))).flatMap(([, x, y]) => [x, y]);
P.via = shuffle(r, [...new Set(shores)].filter((c) => free(c) && !P.cities.includes(c))).slice(0, 2);
} else if (theme === 'islands') {
const i0 = pick(r, isl.filter(free)); if (!i0) return null;
const hops = W.cablePairs.filter(([, x, y]) => x === i0 || y === i0).map(([, x, y]) => (x === i0 ? y : x));
const islN = near(W, i0, isl.filter((c) => free(c) && W.km(i0, c) < 4500), 3), main = near(W, i0, [...new Set(hops)].filter((c) => free(c) && !isl.includes(c)), 2);
if (!islN.length || !main.length) return null;
P.cities = [i0, ...shuffle(r, islN).slice(0, 1 + Math.floor(r() * 2)), main[0]];
P.via = [...new Set([...islN, ...main, ...hops])].filter((c) => !P.cities.includes(c) && free(c)).sort((x, y) => W.km(i0, x) - W.km(i0, y)).slice(0, 3);
} else if (theme === 'sprint') {
const ok = [];
for (const [, a, b] of W.cablePairs) { if (!free(a) || !free(b) || W.C[a].P < 100 || W.C[b].P < 100) continue;
const o = W.opts(a, b).filter((x) => !x.second); if (o.length < 2) continue;
const fast = o.slice().sort((x, y) => x.ms - y.ms)[0], cheap = o[0];
if (fast.unit !== cheap.unit && fast.ms < cheap.ms * 0.94 && fast.ms >= 5) ok.push([a, b, fast.ms, cheap.ms]); }
if (!ok.length) return null;
const [a, b, fms, cms] = pick(r, ok.sort((x, y) => (x[0] + x[1] < y[0] + y[1] ? -1 : 1)));
const ms = Math.ceil(fms * 1.04 + 0.5); if (ms >= cms) return null;
const ga = big.find((g) => g.includes(a)) || [], gb = big.find((g) => g.includes(b)) || [];
const extra = [...near(W, a, ga.filter(free), 2), ...near(W, b, gb.filter(free), 2)];
P.cities = [a, b, ...shuffle(r, extra).slice(0, 1 + Math.floor(r() * 2))];
P.via = W.cablePairs.filter(([, x, y]) => [x, y].includes(a) || [x, y].includes(b)).flatMap(([, x, y]) => [x, y]).filter((c, i, s) => s.indexOf(c) === i && free(c) && !P.cities.includes(c)).sort((x, y) => W.km(a, x) - W.km(a, y)).slice(0, 2);
P.lat = [a, b, ms];
}
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;
return P;
}
// ---------- names and jokes: labels and their fill-ins ----------
function words(ev, W, P, r) {
const T = JSON.parse(ev(`JSON.stringify(PZ_WK_THEMES['${P.theme}'])`)), c = P.cities, last = c[c.length - 1];
const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], p = {};
for (const k of need) p[k] = k === 'hub' ? P.avoid[0] : k === 'reg' ? W.C[c[0]].reg : k === 'ms' ? P.lat[2] : k === 'n' ? c.length : k === 'a' ? (P.lat ? P.lat[0] : P.theme === 'tour' ? last : c[0]) : k === 'b' ? (P.lat ? P.lat[1] : c[2] || last) : null;
return { l, p }; };
return { name: fill(pick(r, T.names)), joke: fill(pick(r, T.jokes)) };
}
// ---------- one week ----------
function history(dir, key) {
const keys = list(dir).filter((k) => k < key).slice(-HISTORY);
const files = keys.map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')));
return { cities: new Set(files.flatMap((f) => [...(f.cities || []), ...(f.via || []), ...(f.avoid || [])])), themes: files.slice(-THEME_GAP).map((f) => f.theme),
regs: files.slice(-REG_GAP).map((f) => f.cities && f.cities[0]).filter(Boolean) };
}
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})`);
}
ev('closeModal()');
return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))'));
}
const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, via: P.via, avoid: P.avoid, budget,
twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}, P.lat ? { lat: P.lat } : {}),
name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } });
// The game's own validator decides what a puzzle is; then both references must earn their stars.
function verify(g, W, j, key) {
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' };
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` };
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 };
}
function generate(g, key, dir) {
const { ev } = g, W = world(ev);
if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`);
// Themes take turns (none of the last weeks' again); the week's own theme first, the others only if it finds nothing.
const hist = history(dir, key), free = THEMES.filter((t) => !hist.themes.includes(t)), h = hash(key);
const order = free.map((_, i) => free[(h + i) % free.length]);
for (const theme of order) {
const cands = [];
for (let at = 0; at < ATTEMPTS && cands.length < KEEP; at++) {
const r = rng(hash(`${key}|${theme}|${at}`)), P = draft(W, theme, r, hist.cities);
// Not the same part of the world as the last two weeks.
if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue;
const sol = solve(W, P);
if (!sol.one || !sol.three) continue;
// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the
// obvious one (a second way along every hop) whenever there is room.
let budget = ceil10k(sol.three.cost * 1.05);
if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000);
const smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost;
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.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);
if (v.ok) return j;
console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`);
}
}
throw new Error(`${key}: no puzzle survived verification`);
}
// --check: every file is what the game accepts, under its own name, and the weeks still to come are solvable.
function check(g, dir, now = Date.now()) {
const { ev } = g, W = world(ev), 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(`!!pzWkValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
if (!j.ref || !Number.isInteger(j.ref.one) || !Number.isInteger(j.ref.three) || j.ref.one > j.ref.three || j.ref.three > j.budget) { bad.push(`${k}: bad ref`); continue; }
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, W, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
}
const ip = path.join(dir, 'index.json');
if (keys.length) {
let idx = null; try { idx = JSON.parse(fs.readFileSync(ip, '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;
}
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, solve, 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; };
const dir = path.resolve(ROOT, opt('--dir', 'site/puzzles/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
if (args.includes('--check')) {
const 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 puzzle(s) OK`);
process.exit(bad.length ? 1 : 0);
}
// By default the week that holds "12 hours from now": run early on Sunday, that is the week starting that morning.
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(`${key}: ${j.theme}, ${j.cities.join(' ')}${j.via.length ? ' via ' + j.via.join(' ') : ''}${j.avoid.length ? ' avoid ' + j.avoid.join(' ') : ''}, budget ${j.budget} (1★ ${j.ref.one}, 3★ ${j.ref.three})`);
}
}

View file

@ -2896,15 +2896,19 @@
"puzzles.keep_building":"Weiterbauen",
"puzzles.kiwi_fruit_salad":"Kiwi-Obstsalat",
"puzzles.lease_a_wave_to":"Wave mieten nach",
"puzzles.loading_this_week_s_puzzle":"Lade das Puzzle dieser Woche…",
"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_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.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}⭐",
"puzzles.next_puzzle":"Nächstes Puzzle",
"puzzles.next_weekly_in_d_h":"Nächstes Wochenpuzzle in {d} T. {h} Std.",
"puzzles.next_weekly_in_h_m":"Nächstes Wochenpuzzle in {h} Std. {m} Min.",
"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.",
@ -2971,6 +2975,36 @@
"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_stars":"Deine Sterne",
"puzzles_weekly.detour":"Umleitung",
"puzzles_weekly.island_hopping":"Inselhüpfen",
"puzzles_weekly.joke_a_ring_survives_one_cut":"Ein Ring übersteht jeden einzelnen Schnitt. Genau dafür ist er ein Ring.",
"puzzles_weekly.joke_a_road_trip_for_photons":"Ein Roadtrip für Photonen. Proviant nicht inbegriffen.",
"puzzles_weekly.joke_a_to_b_under_ms":"{a} nach {b} in unter {ms} ms. Die Börsenhändler schauen zu.",
"puzzles_weekly.joke_every_hop_is_a_cable":"Jeder Hop ist ein Kabel, und jedes Kabel ist eine lange Bootsfahrt.",
"puzzles_weekly.joke_hub_is_having_a_very":"{hub} hat eine sehr teure Woche. Fahr drumherum.",
"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} Städte, ein Kontinent und jede Menge Gräben zu buddeln.",
"puzzles_weekly.joke_one_ring_through_every_pop":"Ein Ring durch jeden POP: je zwei Links, keine Abkürzungen, keine Stichleitungen.",
"puzzles_weekly.joke_somewhere_between_a_and_b":"Irgendwo zwischen {a} und {b} wartet schon ein Reparaturschiff. Plan es ein.",
"puzzles_weekly.joke_the_cheapest_way_between_two":"Der billigste Weg zwischen zwei Inseln ist selten eine Gerade.",
"puzzles_weekly.joke_the_obvious_path_goes_through":"Der naheliegende Weg führt durch {hub}. Der naheliegende Weg ist gesperrt.",
"puzzles_weekly.joke_the_ocean_is_big_and":"Der Ozean ist groß, und Anker gibt es viele. Nimm ein Ersatzkabel mit.",
"puzzles_weekly.joke_the_speed_of_light_is":"Die Lichtgeschwindigkeit ist kein Vorschlag. Nimm das geradeste Glas.",
"puzzles_weekly.latency_sprint":"Latenz-Sprint",
"puzzles_weekly.name_across_the_big_blue":"Übers große Blau",
"puzzles_weekly.name_anywhere_but_hub":"Überall, nur nicht {hub}",
"puzzles_weekly.name_are_we_there_yet_a":"Sind wir schon da, {a}?",
"puzzles_weekly.name_hop_skip_and_a_cable":"Hopp, Hopp, Seekabel",
"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms oder nichts",
"puzzles_weekly.name_one_ring_to_rule_reg":"Ein Ring, sie alle zu knechten: {reg}",
"puzzles_weekly.name_race_to_b":"Wettrennen nach {b}",
"puzzles_weekly.name_ring_around_reg":"Ringelreihen durch {reg}",
"puzzles_weekly.name_sea_you_in_b":"Wir sehen uns in {b}",
"puzzles_weekly.name_sun_sea_and_subsea":"Sonne, Strand und Seekabel",
"puzzles_weekly.name_tour_de_reg":"Tour de {reg}",
"puzzles_weekly.name_who_needs_hub":"Wer braucht schon {hub}?",
"puzzles_weekly.ocean_crossing":"Ozeanüberquerung",
"puzzles_weekly.region_tour":"Rundreise",
"puzzles_weekly.ring":"Ring",
"reach_and_subsea.premium_submarine_terminals":"Premium-Seekabel-Terminals",
"release_notes.and_n_more_change":{"one":"… und {n} weitere Änderung","other":"… und {n} weitere Änderungen"},
"release_notes.read_the_full_notes_on_github":"Alle Hinweise auf GitHub lesen",

View file

@ -2894,15 +2894,19 @@
"puzzles.keep_building":"Seguir construyendo",
"puzzles.kiwi_fruit_salad":"Macedonia de kiwi",
"puzzles.lease_a_wave_to":"Alquilar una onda hasta",
"puzzles.loading_this_week_s_puzzle":"Cargando el puzle de esta semana…",
"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_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.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}⭐",
"puzzles.next_puzzle":"Siguiente puzle",
"puzzles.next_weekly_in_d_h":"Próximo puzle semanal en {d} d {h} h",
"puzzles.next_weekly_in_h_m":"Próximo puzle semanal en {h} h {m} min",
"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.",
@ -2969,6 +2973,36 @@
"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_stars":"Tus estrellas",
"puzzles_weekly.detour":"Desvío",
"puzzles_weekly.island_hopping":"De isla en isla",
"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anillo sobrevive a cualquier corte. Para eso es un anillo.",
"puzzles_weekly.joke_a_road_trip_for_photons":"Un viaje por carretera para fotones. Bocadillos no incluidos.",
"puzzles_weekly.joke_a_to_b_under_ms":"De {a} a {b} en menos de {ms} ms. Los traders están mirando.",
"puzzles_weekly.joke_every_hop_is_a_cable":"Cada salto es un cable, y cada cable es un largo viaje en barco.",
"puzzles_weekly.joke_hub_is_having_a_very":"{hub} tiene una semana carísima. Rodéalo.",
"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} ciudades, un continente y muchas zanjas por cavar.",
"puzzles_weekly.joke_one_ring_through_every_pop":"Un anillo por cada POP: dos enlaces cada uno, sin atajos ni ramales.",
"puzzles_weekly.joke_somewhere_between_a_and_b":"En algún punto entre {a} y {b} ya espera un barco de reparación. Tenlo en cuenta.",
"puzzles_weekly.joke_the_cheapest_way_between_two":"El camino más barato entre dos islas casi nunca es una línea recta.",
"puzzles_weekly.joke_the_obvious_path_goes_through":"El camino obvio pasa por {hub}. El camino obvio está cerrado.",
"puzzles_weekly.joke_the_ocean_is_big_and":"El océano es grande y las anclas son muchas. Lleva un cable de repuesto.",
"puzzles_weekly.joke_the_speed_of_light_is":"La velocidad de la luz no es una sugerencia. Elige el vidrio más recto.",
"puzzles_weekly.latency_sprint":"Sprint de latencia",
"puzzles_weekly.name_across_the_big_blue":"A través del gran azul",
"puzzles_weekly.name_anywhere_but_hub":"Cualquier sitio menos {hub}",
"puzzles_weekly.name_are_we_there_yet_a":"¿Falta mucho, {a}?",
"puzzles_weekly.name_hop_skip_and_a_cable":"Salto, brinco y cable",
"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms o nada",
"puzzles_weekly.name_one_ring_to_rule_reg":"Un anillo para gobernar {reg}",
"puzzles_weekly.name_race_to_b":"Carrera a {b}",
"puzzles_weekly.name_ring_around_reg":"Anillo por {reg}",
"puzzles_weekly.name_sea_you_in_b":"Nos vemos en {b}",
"puzzles_weekly.name_sun_sea_and_subsea":"Sol, playa y cable submarino",
"puzzles_weekly.name_tour_de_reg":"Tour de {reg}",
"puzzles_weekly.name_who_needs_hub":"¿Quién necesita {hub}?",
"puzzles_weekly.ocean_crossing":"Cruzar el océano",
"puzzles_weekly.region_tour":"Gira regional",
"puzzles_weekly.ring":"Anillo",
"reach_and_subsea.premium_submarine_terminals":"Terminales submarinas premium",
"release_notes.and_n_more_change":{"one":"…y {n} cambio más","other":"…y {n} cambios más"},
"release_notes.read_the_full_notes_on_github":"Lee las notas completas en GitHub",

View file

@ -2894,15 +2894,19 @@
"puzzles.keep_building":"Continuer à construire",
"puzzles.kiwi_fruit_salad":"Salade de kiwis",
"puzzles.lease_a_wave_to":"Louer une longueur d’onde vers",
"puzzles.loading_this_week_s_puzzle":"Chargement du puzzle de la semaine…",
"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_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.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}⭐",
"puzzles.next_puzzle":"Puzzle suivant",
"puzzles.next_weekly_in_d_h":"Prochain puzzle de la semaine dans {d} j {h} h",
"puzzles.next_weekly_in_h_m":"Prochain puzzle de la semaine dans {h} h {m} min",
"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.",
@ -2969,6 +2973,36 @@
"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_stars":"Tes étoiles",
"puzzles_weekly.detour":"Détour",
"puzzles_weekly.island_hopping":"Saut d’île en île",
"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anneau survit à n’importe quelle coupure. C’est tout l’intérêt d’un anneau.",
"puzzles_weekly.joke_a_road_trip_for_photons":"Un road trip pour photons. Casse-croûte non compris.",
"puzzles_weekly.joke_a_to_b_under_ms":"De {a} à {b} en moins de {ms} ms. Les traders regardent.",
"puzzles_weekly.joke_every_hop_is_a_cable":"Chaque saut est un câble, et chaque câble est une longue traversée en bateau.",
"puzzles_weekly.joke_hub_is_having_a_very":"{hub} passe une semaine très chère. Contourne-le.",
"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} villes, un continent et beaucoup de tranchées à creuser.",
"puzzles_weekly.joke_one_ring_through_every_pop":"Un anneau par chaque POP : deux liens chacun, pas de raccourci, pas d’antenne.",
"puzzles_weekly.joke_somewhere_between_a_and_b":"Quelque part entre {a} et {b}, un navire câblier attend déjà. Prévois-le.",
"puzzles_weekly.joke_the_cheapest_way_between_two":"Le chemin le moins cher entre deux îles est rarement une ligne droite.",
"puzzles_weekly.joke_the_obvious_path_goes_through":"Le chemin évident passe par {hub}. Le chemin évident est fermé.",
"puzzles_weekly.joke_the_ocean_is_big_and":"L’océan est grand et les ancres sont nombreuses. Prévois un câble de secours.",
"puzzles_weekly.joke_the_speed_of_light_is":"La vitesse de la lumière n’est pas une suggestion. Prends la fibre la plus droite.",
"puzzles_weekly.latency_sprint":"Sprint de latence",
"puzzles_weekly.name_across_the_big_blue":"Le Grand Bleu",
"puzzles_weekly.name_anywhere_but_hub":"Partout sauf {hub}",
"puzzles_weekly.name_are_we_there_yet_a":"On arrive quand, {a} ?",
"puzzles_weekly.name_hop_skip_and_a_cable":"Un saut, deux sauts, un câble",
"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms ou rien",
"puzzles_weekly.name_one_ring_to_rule_reg":"Un anneau pour gouverner {reg}",
"puzzles_weekly.name_race_to_b":"Course vers {b}",
"puzzles_weekly.name_ring_around_reg":"La ronde de {reg}",
"puzzles_weekly.name_sea_you_in_b":"Rendez-vous à {b}",
"puzzles_weekly.name_sun_sea_and_subsea":"Soleil, plage et câble sous-marin",
"puzzles_weekly.name_tour_de_reg":"Tour de {reg}",
"puzzles_weekly.name_who_needs_hub":"Qui a besoin de {hub} ?",
"puzzles_weekly.ocean_crossing":"Traversée de l’océan",
"puzzles_weekly.region_tour":"Tour de la région",
"puzzles_weekly.ring":"Anneau",
"reach_and_subsea.premium_submarine_terminals":"Terminaux sous-marins premium",
"release_notes.and_n_more_change":{"one":"…et {n} autre changement","other":"…et {n} autres changements"},
"release_notes.read_the_full_notes_on_github":"Lire les notes complètes sur GitHub",

View file

@ -2894,15 +2894,19 @@
"puzzles.keep_building":"Continua a costruire",
"puzzles.kiwi_fruit_salad":"Macedonia di kiwi",
"puzzles.lease_a_wave_to":"Noleggia una wave verso",
"puzzles.loading_this_week_s_puzzle":"Carico il puzzle della settimana…",
"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_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.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}⭐",
"puzzles.next_puzzle":"Prossimo puzzle",
"puzzles.next_weekly_in_d_h":"Prossimo puzzle settimanale tra {d} g {h} h",
"puzzles.next_weekly_in_h_m":"Prossimo puzzle settimanale tra {h} h {m} min",
"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.",
@ -2969,6 +2973,36 @@
"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_stars":"Le tue stelle",
"puzzles_weekly.detour":"Deviazione",
"puzzles_weekly.island_hopping":"Di isola in isola",
"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anello sopravvive a qualsiasi taglio. È proprio il bello dell’anello.",
"puzzles_weekly.joke_a_road_trip_for_photons":"Un viaggio on the road per fotoni. Panini non inclusi.",
"puzzles_weekly.joke_a_to_b_under_ms":"Da {a} a {b} in meno di {ms} ms. I trader ti guardano.",
"puzzles_weekly.joke_every_hop_is_a_cable":"Ogni salto è un cavo, e ogni cavo è un lungo viaggio in barca.",
"puzzles_weekly.joke_hub_is_having_a_very":"{hub} ha una settimana carissima. Giraci intorno.",
"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} città, un continente e un sacco di scavi da fare.",
"puzzles_weekly.joke_one_ring_through_every_pop":"Un anello per ogni POP: due link ciascuno, niente scorciatoie, niente diramazioni.",
"puzzles_weekly.joke_somewhere_between_a_and_b":"Da qualche parte tra {a} e {b} una nave posacavi sta già aspettando. Tienine conto.",
"puzzles_weekly.joke_the_cheapest_way_between_two":"La strada più economica tra due isole raramente è una linea retta.",
"puzzles_weekly.joke_the_obvious_path_goes_through":"La strada ovvia passa da {hub}. La strada ovvia è chiusa.",
"puzzles_weekly.joke_the_ocean_is_big_and":"L’oceano è grande e le ancore sono tante. Porta un cavo di scorta.",
"puzzles_weekly.joke_the_speed_of_light_is":"La velocità della luce non è un suggerimento. Scegli il vetro più dritto.",
"puzzles_weekly.latency_sprint":"Sprint di latenza",
"puzzles_weekly.name_across_the_big_blue":"Oltre il grande blu",
"puzzles_weekly.name_anywhere_but_hub":"Ovunque tranne {hub}",
"puzzles_weekly.name_are_we_there_yet_a":"Quanto manca, {a}?",
"puzzles_weekly.name_hop_skip_and_a_cable":"Un salto, un balzo e un cavo",
"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms o niente",
"puzzles_weekly.name_one_ring_to_rule_reg":"Un anello per domare {reg}",
"puzzles_weekly.name_race_to_b":"Corsa verso {b}",
"puzzles_weekly.name_ring_around_reg":"Girotondo in {reg}",
"puzzles_weekly.name_sea_you_in_b":"Ci vediamo a {b}",
"puzzles_weekly.name_sun_sea_and_subsea":"Sole, mare e cavo sottomarino",
"puzzles_weekly.name_tour_de_reg":"Tour de {reg}",
"puzzles_weekly.name_who_needs_hub":"Chi ha bisogno di {hub}?",
"puzzles_weekly.ocean_crossing":"Traversata oceanica",
"puzzles_weekly.region_tour":"Giro della regione",
"puzzles_weekly.ring":"Anello",
"reach_and_subsea.premium_submarine_terminals":"Terminali sottomarini avanzati",
"release_notes.and_n_more_change":{"one":"…e {n} altra modifica","other":"…e altre {n} modifiche"},
"release_notes.read_the_full_notes_on_github":"Leggi le note complete su GitHub",

View file

@ -2894,15 +2894,19 @@
"puzzles.keep_building":"Continuar construindo",
"puzzles.kiwi_fruit_salad":"Salada de kiwi",
"puzzles.lease_a_wave_to":"Alugar uma wave até",
"puzzles.loading_this_week_s_puzzle":"Carregando o puzzle da semana…",
"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_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.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}⭐",
"puzzles.next_puzzle":"Próximo puzzle",
"puzzles.next_weekly_in_d_h":"Próximo puzzle semanal em {d} d {h} h",
"puzzles.next_weekly_in_h_m":"Próximo puzzle semanal em {h} h {m} min",
"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.",
@ -2969,6 +2973,36 @@
"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_stars":"Suas estrelas",
"puzzles_weekly.detour":"Desvio",
"puzzles_weekly.island_hopping":"De ilha em ilha",
"puzzles_weekly.joke_a_ring_survives_one_cut":"Um anel sobrevive a qualquer corte. É para isso que serve um anel.",
"puzzles_weekly.joke_a_road_trip_for_photons":"Uma viagem de carro para fótons. Lanche não incluído.",
"puzzles_weekly.joke_a_to_b_under_ms":"De {a} a {b} em menos de {ms} ms. Os traders estão de olho.",
"puzzles_weekly.joke_every_hop_is_a_cable":"Cada salto é um cabo, e cada cabo é uma longa viagem de barco.",
"puzzles_weekly.joke_hub_is_having_a_very":"{hub} está numa semana caríssima. Dê a volta.",
"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} cidades, um continente e muitas valas para cavar.",
"puzzles_weekly.joke_one_ring_through_every_pop":"Um anel por cada POP: dois links cada, sem atalhos, sem ramais.",
"puzzles_weekly.joke_somewhere_between_a_and_b":"Em algum lugar entre {a} e {b} um navio de reparo já está esperando. Planeje para isso.",
"puzzles_weekly.joke_the_cheapest_way_between_two":"O caminho mais barato entre duas ilhas raramente é uma linha reta.",
"puzzles_weekly.joke_the_obvious_path_goes_through":"O caminho óbvio passa por {hub}. O caminho óbvio está fechado.",
"puzzles_weekly.joke_the_ocean_is_big_and":"O oceano é grande e as âncoras são muitas. Leve um cabo reserva.",
"puzzles_weekly.joke_the_speed_of_light_is":"A velocidade da luz não é uma sugestão. Escolha o vidro mais reto.",
"puzzles_weekly.latency_sprint":"Corrida de latência",
"puzzles_weekly.name_across_the_big_blue":"Através do grande azul",
"puzzles_weekly.name_anywhere_but_hub":"Qualquer lugar menos {hub}",
"puzzles_weekly.name_are_we_there_yet_a":"Já chegamos, {a}?",
"puzzles_weekly.name_hop_skip_and_a_cable":"Um pulo, um salto e um cabo",
"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms ou nada",
"puzzles_weekly.name_one_ring_to_rule_reg":"Um anel para governar {reg}",
"puzzles_weekly.name_race_to_b":"Corrida até {b}",
"puzzles_weekly.name_ring_around_reg":"Ciranda por {reg}",
"puzzles_weekly.name_sea_you_in_b":"Te vejo em {b}",
"puzzles_weekly.name_sun_sea_and_subsea":"Sol, mar e cabo submarino",
"puzzles_weekly.name_tour_de_reg":"Tour de {reg}",
"puzzles_weekly.name_who_needs_hub":"Quem precisa de {hub}?",
"puzzles_weekly.ocean_crossing":"Travessia do oceano",
"puzzles_weekly.region_tour":"Volta pela região",
"puzzles_weekly.ring":"Anel",
"reach_and_subsea.premium_submarine_terminals":"Terminais submarinos premium",
"release_notes.and_n_more_change":{"one":"…e mais {n} mudança","other":"…e mais {n} mudanças"},
"release_notes.read_the_full_notes_on_github":"Leia as notas completas no GitHub",

View file

@ -0,0 +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}}

View file

@ -0,0 +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}}

View file

@ -0,0 +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}}

View file

@ -0,0 +1 @@
{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]}

View file

@ -25,6 +25,12 @@ self.addEventListener('fetch', (e) => {
}
const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname);
if (!local && !fonts) return;
// Weekly puzzles are published between releases: ask the network first, and keep a copy for playing offline.
if (local && url.pathname.startsWith('/puzzles/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;
}
e.respondWith(caches.open(CACHE).then((c) => c.match(req).then((hit) => {
const net = fetch(req).then((r) => { if (r && (r.ok || r.type === 'opaque')) c.put(req, r.clone()); return r; }).catch(() => hit);
return hit || net;

View file

@ -6,7 +6,7 @@ const PZ_KEY='sot-puzzles',PZ_YEAR=12;
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;
const pzName=d=>d.id==='weekly'?tr('puzzles.weekly_puzzle_key',{key:d.key}):d.n;
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);
// ---------- 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;
@ -64,9 +64,7 @@ function pzOneMore(e){const P=S.pz;if(e.stars!==2||!e.cheap||e.n1)return false;c
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;}
// ---------- the weekly puzzle: the same for everyone, seeded by the ISO week like the weekly challenge ----------
function pzWeekKey(dt){const {y,w}=isoWeek(dt);return `${y}-W${String(w).padStart(2,'0')}`;}
function pzPrevKey(key){const m=/^(\d{4})-W(\d{2})$/.exec(key);if(!m)return null;return pzWeekKey(new Date(+m[1],0,4+(+m[2]-2)*7));}
// ---------- 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.length<n&&pool.length)cities.push(pool.splice(Math.floor(nx()*pool.length),1)[0]);
@ -88,7 +86,7 @@ const pzToastsClear=()=>{$('toasts').textContent='';};
function pzFlush(){save(true);UI.pzKeep=UI.gzBusy||saveFailing()?S:null;}
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};
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};
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;
$('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz');
compute();pzCam();renderAll();track('puzzle_'+def.id);

View file

@ -0,0 +1,75 @@
/* ================= THE PUBLISHED WEEKLY PUZZLE =================
A puzzle week runs from Sunday 06:00 Berlin time to the next Sunday 06:00. Its key is the ISO week of its Monday
(the week starting Sunday 1 Nov 2026 is 2026-W45), so keys look like the old ISO-week keys and old streaks carry on.
Every Sunday a GitHub workflow publishes puzzles/weekly/<key>.json (scripts/weekly-puzzle.js): a static file next to
the page, fetched only when the player opens Puzzles. It is checked field by field; when it is missing, offline or
wrong, the seeded weekly in 92-puzzles.js stands in, so the weekly puzzle never breaks. */
// Europe/Berlin is UTC+1, and UTC+2 from the last Sunday of March to the last Sunday of October, 01:00 UTC both times.
const pzLastSun=(y,m)=>{const d=new Date(Date.UTC(y,m+1,0));return Date.UTC(y,m,d.getUTCDate()-d.getUTCDay(),1);};
const pzBerlinOff=t=>{const y=new Date(t).getUTCFullYear();return t>=pzLastSun(y,2)&&t<pzLastSun(y,9)?2:1;};
// 06:00 Berlin on the Sunday at UTC midnight `sun`; the clocks change at 01:00 UTC, well before.
const pzSunStart=sun=>sun+(6-pzBerlinOff(sun+4*3600e3))*3600e3;
function pzIso(t){const d=new Date(t);d.setUTCHours(0,0,0,0);d.setUTCDate(d.getUTCDate()+4-(d.getUTCDay()||7));const y=d.getUTCFullYear();return `${y}-W${String(Math.ceil(((d-Date.UTC(y,0,1))/864e5+1)/7)).padStart(2,'0')}`;}
// The key of the puzzle week holding this moment.
function pzWeekKey(dt){const t=+dt,d=new Date(t);let sun=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate())-d.getUTCDay()*864e5;
if(t<pzSunStart(sun))sun-=7*864e5;return pzIso(sun+864e5);}
// When a week starts (UTC ms), or null for a key that is not a real week.
function pzWeekStart(key){const m=/^(\d{4})-W(\d{2})$/.exec(String(key));if(!m)return null;const j4=Date.UTC(+m[1],0,4),mon=j4-((new Date(j4).getUTCDay()+6)%7)*864e5+(+m[2]-1)*7*864e5;
const t=pzSunStart(mon-864e5);return pzWeekKey(t)===key?t:null;}
// n weeks on (or back). Weeks are 7 days plus or minus the hour the clocks change, so aim 3 hours into the week.
const pzKeyAdd=(key,n)=>{const t=pzWeekStart(key);return t==null?null:pzWeekKey(t+n*7*864e5+3*3600e3);};
const pzPrevKey=key=>pzKeyAdd(key,-1);
// ---------- themes and their text: labels, so the file names a label and the player reads their language ----------
// A file may only use these labels (N_: kept whole in the shipped page, since the file names them in full).
const PZ_WK_THEMES={
detour:{i:'🚧',t:N_('puzzles_weekly.detour'),names:[N_('puzzles_weekly.name_anywhere_but_hub'),N_('puzzles_weekly.name_who_needs_hub')],jokes:[N_('puzzles_weekly.joke_hub_is_having_a_very'),N_('puzzles_weekly.joke_the_obvious_path_goes_through')]},
islands:{i:'🏝️',t:N_('puzzles_weekly.island_hopping'),names:[N_('puzzles_weekly.name_hop_skip_and_a_cable'),N_('puzzles_weekly.name_sun_sea_and_subsea')],jokes:[N_('puzzles_weekly.joke_every_hop_is_a_cable'),N_('puzzles_weekly.joke_the_cheapest_way_between_two')]},
ocean:{i:'🌊',t:N_('puzzles_weekly.ocean_crossing'),names:[N_('puzzles_weekly.name_sea_you_in_b'),N_('puzzles_weekly.name_across_the_big_blue')],jokes:[N_('puzzles_weekly.joke_the_ocean_is_big_and'),N_('puzzles_weekly.joke_somewhere_between_a_and_b')]},
ring:{i:'💍',t:N_('puzzles_weekly.ring'),names:[N_('puzzles_weekly.name_one_ring_to_rule_reg'),N_('puzzles_weekly.name_ring_around_reg')],jokes:[N_('puzzles_weekly.joke_one_ring_through_every_pop'),N_('puzzles_weekly.joke_a_ring_survives_one_cut')]},
sprint:{i:'⚡',t:N_('puzzles_weekly.latency_sprint'),names:[N_('puzzles_weekly.name_race_to_b'),N_('puzzles_weekly.name_ms_ms_or_bust')],jokes:[N_('puzzles_weekly.joke_a_to_b_under_ms'),N_('puzzles_weekly.joke_the_speed_of_light_is')]},
tour:{i:'🗺️',t:N_('puzzles_weekly.region_tour'),names:[N_('puzzles_weekly.name_tour_de_reg'),N_('puzzles_weekly.name_are_we_there_yet_a')],jokes:[N_('puzzles_weekly.joke_n_cities_one_landmass_and'),N_('puzzles_weekly.joke_a_road_trip_for_photons')]},
};
// What each {placeholder} in those labels holds: c a city id, r a region code, n a whole number.
const PZ_WK_P={a:'c',b:'c',hub:'c',reg:'r',ms:'n',n:'n'};
const pzCityOk=c=>isCity(c)&&!CITY[c].off&&!CITY[c].cn;
const pzTxt=o=>{const v={};for(const k in o.p){const x=o.p[k],t=PZ_WK_P[k];v[k]=t==='c'?CITY[x].name:t==='r'?WAVE_NAME[x]:x;}return tr(o.l,v);};
// ---------- the file: never trusted. Only known fields, known cities, known labels and sane numbers get through ----------
const pzObj=o=>!!o&&typeof o==='object'&&!Array.isArray(o);
function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!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]))],out={};
if(Object.keys(p).length!==need.length)return null;
for(const k of need){const t=PZ_WK_P[k],v=own(p,k)?p[k]:undefined;
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};}
const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref'];
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 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 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;
const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null};
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 ----------
function pzWkEnsure(){const key=pzWeekKey(new Date()),w=UI.pzWk;
if(w&&w.key===key&&(w.st!=='fb'||Date.now()-w.at<5*60e3))return;
const st=UI.pzWk={key,st:w&&w.key===key&&w.def?'ok':'load',def:w&&w.key===key?w.def:null,at:Date.now()};
let done=false;const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.pzWk!==st)return;if(def){st.def=def;st.st='ok';}else if(!st.def)st.st='fb';st.at=Date.now();pzWkRefresh();};
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;}
// Relative and same origin; each week has its own file name, so caches never serve last week's.
try{fetch(`puzzles/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>pzWkValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}}
// This week's puzzle: the published one when it came, else the seeded one.
function pzWkDef(){const key=pzWeekKey(new Date()),w=UI.pzWk;return w&&w.key===key&&w.def?w.def:pzWeekly();}
const pzWkLoading=()=>{const w=UI.pzWk;return !!w&&w.st==='load'&&w.key===pzWeekKey(new Date());};
function pzWkRefresh(){const el=$('pzWk');if(el)el.outerHTML=pzWkRow();}
// "Next weekly puzzle in 2 d 14 h".
function pzWkNext(now){const key=pzWeekKey(now),t=pzWeekStart(pzKeyAdd(key,1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60);
return d?tr('puzzles.next_weekly_in_d_h',{d,h}):tr('puzzles.next_weekly_in_h_m',{h,m:m%60});}
// The Puzzles door says so when this week's puzzle has not been played yet.
function pzWkNew(){try{return !pzLoad().wk[pzWeekKey(new Date())];}catch(e){return false;}}

View file

@ -2,8 +2,8 @@ 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();},
pzStart:({id})=>{const d=pzDef(id);if(!d||!pzPackOpen(d.pack))return;pzBegin(d);},
pzWeekly:()=>pzBegin(pzWeekly()),
pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWeekly():pzDef(S.pz.id));},
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();},

View file

@ -38,7 +38,7 @@ function whatsNew(returning,force){
const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot_no_clock')],['sandbox','🏖️',tr('common.sandbox'),tr('title.a_billion_dollars_and_every_toy')],['normal','📟',tr('common.normal'),tr('title.the_real_game_climb_from_tier')],['scn','🏆',tr('title.scenarios_amp_weekly'),tr('title.hand_built_crises_and_one_world')]];
const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'};
function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none';
return `<label class="f">${tr('title.pick_a_door')}</label><div class="doors">${DOORS.map(([k,i,n,d])=>`<button class="door${k===m?' on':''}" data-door="${k}" data-act="${doorAct[k]}" data-args='${k==='sandbox'||k==='normal'?`{"m":"${k}"}`:'{}'}'><i aria-hidden="true">${i}</i><b>${n}</b><span>${d}</span></button>`).join('')}</div>
return `<label class="f">${tr('title.pick_a_door')}</label><div class="doors">${DOORS.map(([k,i,n,d])=>`<button class="door${k===m?' on':''}" data-door="${k}" data-act="${doorAct[k]}" data-args='${k==='sandbox'||k==='normal'?`{"m":"${k}"}`:'{}'}'><i aria-hidden="true">${i}</i><b>${n}</b><span>${d}</span>${k==='puzzle'&&pzWkNew()?`<em class="pznew">${tr('puzzles.new_this_sunday')}</em>`:''}</button>`).join('')}</div>
<div id="doorNormal"${m==='normal'?'':' hidden'}><label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}'><i aria-hidden="true">${P.i}</i><b>${P.n}</b><span>${P.d}</span><small>${P.x}</small></button>`;}).join('')}</div></div>
<div id="doorSandbox"${m==='sandbox'?'':' hidden'}><label class="f">${tr('title.chaos_in_your_sandbox')}</label><div class="chaos">${Object.entries(CHAOS).map(([k,C])=>`<button class="chs${k===ch?' on':''}" data-chaos="${k}" data-act="chaosSet" data-args='{"c":"${k}"}'><i aria-hidden="true">${C.i}</i><b>${C.n}</b><span>${C.d}</span></button>`).join('')}</div></div>
<p class="note lockn">🔒 ${tr('title.rules_are_picked_once_and_locked')}</p>`;}

View file

@ -6,14 +6,14 @@ function pzTwistTxt(t){const P=S.pz;
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)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;}
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;}
// 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)+')':''}`;};
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)=>`<span class="${on?'on':''}">⭐<small>${l}</small></span>`;
let h=`<div class="grab" data-grab="pz" aria-hidden="true"></div><div class="pzh"><div class="grow"><div class="eyebrow">${pk?esc(pk.n):tr('puzzles.weekly_puzzle')}</div><h3>${esc(pzName(d||P))}</h3></div>${btn('☰','puzzleMenu',{},'ghost sm')}</div>`;
if(d)h+=`<p class="pzj">${esc(d.j)}</p>`;
let h=`<div class="grab" data-grab="pz" aria-hidden="true"></div><div class="pzh"><div class="grow"><div class="eyebrow">${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')}</div><h3>${esc(pzName(d||P))}</h3></div>${btn('☰','puzzleMenu',{},'ghost sm')}</div>`;
if(d)h+=`<p class="pzj">${esc(d.j)}</p>`;else if(P.wj)h+=`<p class="pzj">${esc(pzTxt(P.wj))}</p>`;
h+=`<div class="pzs">${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')}</div>`;
// ○ still to reach, ◐ has a POP, ✓ joined up. A leading mark, so nothing looks cut off.
h+=`<div class="pzck">${e.marks.map(m=>`<span class="pzc s${m.st}"><i aria-hidden="true">${m.st===2?'✓':m.st===1?'◐':'○'}</i> ${esc(CITY[m.c].name)}</span>`).join('')}</div>`;
@ -74,12 +74,18 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left
for(let i=prev;i<e.stars;i++)setTimeout(()=>{sfx('star');haptic(15);},Math.max(0,i-prev)*450+150);
if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);}
// ---------- the list ----------
function pzMenu(){const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot),w=pzWeekly(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0;
// 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=p.wk[w.key],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);
return `<div class="scn wk" id="pzWk"><div class="grow"><div class="eyebrow">📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` <span class="pznew">${tr('puzzles.new_this_sunday')}</span>`}</div>
<div class="nm">${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`<span class="pzst">${pzStarStr(wr.st)}</span>`:''}</div>${w.wj?`<div class="meta">${esc(pzTxt(w.wj))}</div>`:''}
<div class="meta">${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · <b>'+tg.join(' · ')+'</b>':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}</div>
<div class="meta">${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}</div><div class="meta pzcd">⏳ ${pzWkNext(Date.now())}</div></div>${btn(tr('common.play'),'pzWeekly',{},wr&&wr.st>=3?'ghost':'pink',load)}</div>`;}
function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot);
let h=`<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">${tr('puzzles.puzzles')}</div><h2 style="font-size:28px">${tr('puzzles.small_calm_network_builds')}</h2></div><button class="x" data-act="helpClose" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('puzzles.no_clock_no_bills_nothing_breaks')}</p>
<div class="pzprog"><div class="kv"><span>${tr('puzzles.your_stars')}</span><b>⭐ ${tot} / ${max}</b></div><div class="bar me"><i style="width:${(tot/max*100).toFixed(1)}%"></i></div>${nxP?`<div class="meta">${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}</div>`:''}</div>`;
if(pzOn())h+=`<div class="btns" style="margin:8px 0">${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}</div>`;
h+=`<div class="scn wk"><div class="grow"><div class="nm">${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})} ${wr?`<span class="pzst">${pzStarStr(wr.st)}</span>`:''}</div><div class="meta">${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}</div><div class="meta">${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}</div></div>${btn(tr('common.play'),'pzWeekly',{},'pink')}</div>`;
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+=`<h3 class="pzpack">${open?'':'🔒 '}${esc(pk.n)} <span class="meta">⭐ ${got}/${n*3}</span></h3><p class="meta" style="margin:0 0 2px">${open?esc(pk.d):tr('puzzles.unlocks_at_n_stars',{n:pk.need})}</p>`;
for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzTwistTag(d);

View file

@ -2895,15 +2895,19 @@
"puzzles.keep_building":"Keep building",
"puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad",
"puzzles.lease_a_wave_to":"Lease a wave to",
"puzzles.loading_this_week_s_puzzle":"Loading this week's puzzle…",
"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_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.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}⭐",
"puzzles.next_puzzle":"Next puzzle",
"puzzles.next_weekly_in_d_h":"Next weekly puzzle in {d} d {h} h",
"puzzles.next_weekly_in_h_m":"Next weekly puzzle in {h} h {m} min",
"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.",
@ -2970,6 +2974,36 @@
"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_stars":"Your stars",
"puzzles_weekly.detour":"Detour",
"puzzles_weekly.island_hopping":"Island hopping",
"puzzles_weekly.joke_a_ring_survives_one_cut":"A ring survives any one cut. That is the whole point of a ring.",
"puzzles_weekly.joke_a_road_trip_for_photons":"A road trip for photons. Snacks not included.",
"puzzles_weekly.joke_a_to_b_under_ms":"{a} to {b} in under {ms} ms. The traders are watching.",
"puzzles_weekly.joke_every_hop_is_a_cable":"Every hop is a cable, and every cable is a long boat trip.",
"puzzles_weekly.joke_hub_is_having_a_very":"{hub} is having a very expensive week. Route around it.",
"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} cities, one landmass and a lot of trenches to dig.",
"puzzles_weekly.joke_one_ring_through_every_pop":"One ring through every POP: two links each, no shortcuts, no spurs.",
"puzzles_weekly.joke_somewhere_between_a_and_b":"Somewhere between {a} and {b} a repair ship is already waiting. Plan for it.",
"puzzles_weekly.joke_the_cheapest_way_between_two":"The cheapest way between two islands is rarely a straight line.",
"puzzles_weekly.joke_the_obvious_path_goes_through":"The obvious path goes through {hub}. The obvious path is closed.",
"puzzles_weekly.joke_the_ocean_is_big_and":"The ocean is big and the anchors are many. Bring a spare cable.",
"puzzles_weekly.joke_the_speed_of_light_is":"The speed of light is not a suggestion. Pick the straightest glass.",
"puzzles_weekly.latency_sprint":"Latency sprint",
"puzzles_weekly.name_across_the_big_blue":"Across the Big Blue",
"puzzles_weekly.name_anywhere_but_hub":"Anywhere but {hub}",
"puzzles_weekly.name_are_we_there_yet_a":"Are We There Yet, {a}?",
"puzzles_weekly.name_hop_skip_and_a_cable":"Hop, Skip and a Cable",
"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms or Bust",
"puzzles_weekly.name_one_ring_to_rule_reg":"One Ring to Rule {reg}",
"puzzles_weekly.name_race_to_b":"Race to {b}",
"puzzles_weekly.name_ring_around_reg":"Ring Around {reg}",
"puzzles_weekly.name_sea_you_in_b":"Sea You in {b}",
"puzzles_weekly.name_sun_sea_and_subsea":"Sun, Sea and Subsea",
"puzzles_weekly.name_tour_de_reg":"Tour de {reg}",
"puzzles_weekly.name_who_needs_hub":"Who Needs {hub}?",
"puzzles_weekly.ocean_crossing":"Ocean crossing",
"puzzles_weekly.region_tour":"Region tour",
"puzzles_weekly.ring":"Ring",
"reach_and_subsea.premium_submarine_terminals":"Premium submarine terminals",
"release_notes.and_n_more_change":{"one":"…and {n} more change","other":"…and {n} more changes"},
"release_notes.read_the_full_notes_on_github":"Read the full notes on GitHub",

View file

@ -47,3 +47,8 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB
body.pz #hint{bottom:12px !important;left:30% !important}
body.pz #toasts{left:8px !important;transform:none !important;width:calc(48% - 16px) !important}
}
/* The weekly puzzle: a badge on the Puzzles door and in the list while this week's puzzle is unplayed. */
.pznew{display:inline-block;font:900 10.5px/1.2 var(--body);font-style:normal;text-transform:uppercase;letter-spacing:.04em;background:var(--me);color:#fff;border:2px solid var(--ink);border-radius:999px;padding:1px 7px;white-space:nowrap;vertical-align:1px}
.door .pznew{position:absolute;top:-9px;right:8px;transform:rotate(4deg);animation:pznew 2.4s ease-in-out infinite}
@keyframes pznew{50%{transform:rotate(-3deg) scale(1.08)}}
.scn.wk{flex-wrap:wrap}.scn.wk .grow{min-width:0;flex:1 1 200px}.pzcd{font-weight:800;color:var(--ink)}

240
tests/weekly-puzzle.test.js Normal file
View file

@ -0,0 +1,240 @@
// The published weekly puzzle: Sunday 06:00 Berlin weeks, the generator (scripts/weekly-puzzle.js), its --check,
// and the game's fetch: only when Puzzles opens, validated strictly, with the seeded weekly as the fallback.
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 G = require('../scripts/weekly-puzzle');
const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly');
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-'));
const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8')));
const tick = () => new Promise((r) => setTimeout(r, 30));
test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run across New Year', () => {
const { ev, errors } = load();
const key = (iso) => ev(`pzWeekKey(new Date('${iso}'))`), start = (k) => ev(`new Date(pzWeekStart('${k}')).toISOString()`);
// Winter (CET, UTC+1): 06:00 Berlin is 05:00 UTC.
assert.equal(key('2026-11-01T04:59:59Z'), '2026-W44');
assert.equal(key('2026-11-01T05:00:00Z'), '2026-W45', 'the week starting Sunday 1 Nov is named after its Monday');
assert.equal(key('2026-11-07T23:00:00Z'), '2026-W45', 'Saturday night is still the same week');
assert.equal(start('2026-W45'), '2026-11-01T05:00:00.000Z');
// Summer (CEST, UTC+2): 06:00 Berlin is 04:00 UTC.
assert.equal(key('2026-07-05T03:59:00Z'), '2026-W27');
assert.equal(key('2026-07-05T04:00:00Z'), '2026-W28');
// The weekends the clocks change: the change is at 01:00 UTC that same Sunday, before the week starts.
assert.equal(start('2026-W14'), '2026-03-29T04:00:00.000Z', 'spring forward: first CEST Sunday');
assert.equal(start('2026-W13'), '2026-03-22T05:00:00.000Z');
assert.equal(start('2026-W44'), '2026-10-25T05:00:00.000Z', 'fall back: first CET Sunday');
assert.equal(start('2026-W43'), '2026-10-18T04:00:00.000Z');
assert.equal(key('2026-03-29T03:59:00Z'), '2026-W13');
assert.equal(key('2026-03-29T04:00:00Z'), '2026-W14');
assert.equal(key('2026-10-25T04:59:00Z'), '2026-W43');
assert.equal(key('2026-10-25T05:00:00Z'), '2026-W44');
// New Year: 2026 has 53 ISO weeks, 2027 has 52.
assert.equal(key('2026-12-27T05:00:00Z'), '2026-W53');
assert.equal(key('2027-01-03T04:59:00Z'), '2026-W53');
assert.equal(key('2027-01-03T05:00:00Z'), '2027-W01');
assert.equal(key('2027-12-26T05:00:00Z'), '2027-W52');
assert.equal(key('2028-01-02T05:00:00Z'), '2028-W01');
assert.equal(ev("pzKeyAdd('2026-W53',1)"), '2027-W01');
assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53');
assert.equal(ev("pzPrevKey('2028-W01')"), '2027-W52');
assert.equal(ev("pzWeekStart('2027-W53')"), null, '2027 has no week 53');
assert.equal(ev("pzWeekStart('2026-W00')"), null);
assert.equal(ev("pzWeekStart('nope')"), null);
// Every week of ten years: 7 days apart (give or take the DST hour), keys round-trip, never two Sundays the same key.
let k = '2026-W01', seen = new Set();
for (let i = 0; i < 522; i++) {
const t = ev(`pzWeekStart('${k}')`), n = ev(`pzKeyAdd('${k}',1)`), tn = ev(`pzWeekStart('${n}')`);
assert.equal(new Date(t).getUTCDay(), 0, `${k} starts on a Sunday`);
assert.ok([7 * 864e5, 7 * 864e5 - 3600e3, 7 * 864e5 + 3600e3].includes(tn - t), `${k} → ${n}`);
assert.equal(ev(`pzWeekKey(${t})`), k);
assert.equal(ev(`pzWeekKey(${t - 1})`), ev(`pzPrevKey('${k}')`));
assert.ok(!seen.has(k)); seen.add(k); k = n;
}
// The countdown.
assert.equal(ev("pzWkNext(Date.parse('2026-10-29T14:00:00Z'))"), 'Next weekly puzzle in 2 d 15 h');
assert.equal(ev("pzWkNext(Date.parse('2026-11-01T03:20:00Z'))"), 'Next weekly puzzle in 1 h 40 min');
assert.deepEqual(errors, []);
});
// Weeks already out are not compared with a fresh run: a later release may change prices, and a published week stays as
// it was (--check still makes sure the weeks not over yet can be solved).
test('generator: deterministic for a week', () => {
const g = G.game(), a = tmp(), b = tmp();
const first = G.list(DIR).slice(-3)[0];
const keys = Math.min(3, G.list(DIR).length);
for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d));
for (const k of G.list(a)) {
assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`);
}
assert.ok(G.list(DIR).length >= 3, 'the release ships with weeklies in place');
});
test('generator: a quarter of weeks, all verified, varied, small and in the schema', () => {
const g = G.game(), d = tmp();
let k = '2027-W10';
const out = [];
for (let i = 0; i < 12; i++, k = g.ev(`pzKeyAdd('${k}',1)`)) { const j = G.generate(g, k, d); G.writeWeek(d, j); out.push(j); }
assert.deepEqual(G.check(g, d, 0), [], 'every week verifies: both references earn their stars in the game');
for (let i = 1; i < out.length; i++) {
assert.notEqual(out[i].theme, out[i - 1].theme, `${out[i].key}: not last week's theme`);
for (const c of out[i].cities) assert.ok(!out[i - 1].cities.includes(c), `${out[i].key}: ${c} was a city last week too`);
}
assert.ok(new Set(out.map((j) => j.theme)).size >= 5, 'most themes come round in a quarter');
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.deepEqual(JSON.parse(fs.readFileSync(path.join(d, 'index.json'), 'utf8')).weeks, out.map((j) => j.key));
});
test('--check passes on the committed files and rejects tampered ones', () => {
const g = G.game();
// Weeks still to come are re-solved; past ones are checked the way the game reads them.
assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify');
const bad = (edit, why) => {
const d = tmp();
for (const k of G.list(DIR).slice(-3)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json'));
G.writeIndex(d);
const k = G.list(d)[0], f = path.join(d, k + '.json'), j = JSON.parse(fs.readFileSync(f, 'utf8'));
const r = edit(j, d, k); fs.writeFileSync(f, typeof r === 'string' ? r : JSON.stringify(j));
assert.notDeepEqual(G.check(g, d, 0), [], why);
};
bad((j) => { j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; }, 'a budget nobody can earn three stars under');
bad((j) => { j.cities[0] = 'xxx'; }, 'an unknown city');
bad((j) => { j.name.l = 'puzzles.hello_world'; }, 'a label that is not a weekly name');
bad((j) => { j.joke.p = { hub: 'fra' }; }, 'parameters the label does not take');
bad((j) => { j.extra = '<img src=x onerror=alert(1)>'; }, '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(() => '{nope', 'not JSON');
bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks');
});
test('the page never asks for a weekly puzzle on load, only when Puzzles opens', async () => {
const { ev, errors } = load();
ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}");
ev("showTitle();for(let i=0;i<5;i++)frame(performance.now()+i*1000);renderAll()");
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing on the title screen');
assert.equal(ev("UI.pzWk===undefined"), true);
ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()");
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing while playing');
ev('ACT.puzzleMenu({})');
const key = ev('pzWeekKey(new Date())');
assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/puzzles/.test(u)))"), JSON.stringify([`puzzles/weekly/${key}.json`]), 'one relative, same-origin request');
ev('closeModal();ACT.puzzleMenu({})');
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 1, 'once is enough while it is loading');
await tick();
assert.deepEqual(errors, []);
});
test('the published puzzle is played when it is good, the seeded one when it is missing, offline or bad', async () => {
const src = committed()[1], { ev, dom, errors } = load();
const key = ev('pzWeekKey(new Date())'), good = { ...src, key };
const serve = (how) => { ev(`UI.pzWk=null;window.fetch=()=>${how}`); ev('ACT.puzzleMenu({})'); };
const seeded = JSON.parse(ev('JSON.stringify(pzWeekly())'));
for (const [how, why] of [
["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'],
["Promise.reject(new TypeError('offline'))", 'offline'],
["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'],
]) {
serve(how);
await tick();
assert.equal(ev('UI.pzWk.st'), 'fb', why);
assert.deepEqual(JSON.parse(ev('JSON.stringify(pzWkDef().cities)')), seeded.cities, `${why}: the seeded weekly stands in`);
assert.match(ev("document.getElementById('pzWk').textContent"), new RegExp(`Weekly puzzle ${key}`));
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), false);
}
// While it loads, the button waits a moment.
ev("UI.pzWk=null;window.fetch=()=>new Promise(()=>{})");
ev('ACT.puzzleMenu({})');
assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/);
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true);
// The good one.
serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(good)})})`);
await tick();
assert.equal(ev('UI.pzWk.st'), 'ok');
const row = ev("document.getElementById('pzWk').textContent");
assert.ok(row.includes(ev('pzName(pzWkDef())')), 'its pun name');
assert.ok(row.includes(ev('pzTxt(pzWkDef().wj)')), 'its joke');
assert.match(row, /New this Sunday!/);
assert.match(row, /Next weekly puzzle in \d+ (d \d+ h|h \d+ min)/);
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
assert.equal(ev('S.pz.key'), key);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.pz.cities)')), good.cities);
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})`);
}
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')"));
assert.equal(p.wk[key].st, 3);
assert.equal(p.streak.last, key);
ev('ACT.pzLeave({})');
assert.doesNotMatch(ev("document.querySelector('.door[data-door=puzzle]').textContent"), /New this Sunday/, 'played: no badge');
void dom;
assert.deepEqual(errors, []);
});
test('the file is checked field by field', () => {
const { ev, errors } = load();
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.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');
no((o) => { o.via = [o.cities[0]]; }, 'a goal city as a stepping stone');
no((o) => { o.cities[0] = 'pek'; }, 'a city that needs a licence');
no((o) => { o.budget = '240000'; }, 'a budget as text');
no((o) => { o.budget = 1e9; }, 'a silly budget');
no((o) => { o.twist = { ring: 'yes' }; }, 'a twist that is not true');
no((o) => { o.twist = { avoidAll: true }; }, 'an unknown twist');
no((o) => { o.name = { l: 'puzzles_weekly.name_tour_de_reg', p: { reg: 'XX' } }; }, 'an unknown region');
no((o) => { o.name = { l: 'puzzles_weekly.name_race_to_b', p: { b: '<b>' } }; }, 'markup as a city');
no((o) => { o.joke = 'Ha ha'; }, 'raw English');
no((o) => { o.__proto__ = { budget: 1 }; o.extra = 1; }, 'extra fields');
assert.equal(ev(`pzWkValid(null,'${k}')`), null);
assert.equal(ev(`pzWkValid([],'${k}')`), null);
// Every label a theme may use exists in English, and every file names its text in the player's language.
assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))"));
for (const f of committed()) {
const d = ev(`JSON.stringify(pzWkValid(${JSON.stringify(f)},'${f.key}'))`);
assert.ok(d, f.key);
assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`);
}
assert.deepEqual(errors, []);
});
test('weekly puzzle in every language and on a 360 px phone', async () => {
const f = committed()[0];
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
const { ev, errors } = load({ lang });
const key = ev('pzWeekKey(new Date())');
ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...f, key })})})`);
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()");
ev('ACT.puzzleMenu({})');
await tick();
const row = ev("document.getElementById('pzWk').textContent");
assert.doesNotMatch(row, /puzzles(_weekly)?\.|\{/, `${lang}: no raw labels or placeholders`);
assert.notEqual(ev('pzName(pzWkDef())'), ev("EN[pzWkDef().wn.l]"), `${lang}: translated name`);
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
assert.doesNotMatch(ev("document.getElementById('pzBox').textContent"), /puzzles(_weekly)?\./);
assert.deepEqual(errors, [], lang);
}
});