diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 092aa0f..b8c5146 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -52,7 +52,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | Id | Rule | Why | | --- | --- | --- | -| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0. | A goal must need play. | +| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. | | C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | | C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index 69d4a49..205db5b 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -47,7 +47,9 @@ added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in th 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, and regenerates (in the build, deterministically) any week not over yet that the release's prices no longer fit. 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`. +Puzzles list opens and never trusts; the service worker serves them network-first. The weekly scenario rides along in +the same run: `scripts/weekly-scenario.js` writes `site/scenarios/weekly/.json` (fetched when the Scenarios list +opens), committed and deployed with the puzzle, never by a second workflow. See `docs/ARCHITECTURE.md`. ## Before you hand back a change that touches the build, deploy or loading diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 99f8b4d..509d3fb 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -21,12 +21,16 @@ version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly `gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly file on `main` when it builds. +The weekly scenario (`site/scenarios/weekly/`, `scripts/weekly-scenario.js`) ships in the same run and the same way: +`--key`, `--force` and `--check` work alike. Its `--check` replays each week not over yet with the reference plan in +the file; a new par is just written, a week the reference no longer wins is regenerated with `rev` + 1. + **Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check` -and commit the regenerated files with it. +and commit the regenerated files with it (and `node scripts/weekly-scenario.js --check` for the scenarios). ## Only release when Frederic says so diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fe2070b..0d1ad7a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,15 +70,17 @@ jobs: 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 + - name: Weekly puzzles and scenarios 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 + for d in site/puzzles/weekly site/scenarios/weekly; do + if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then + rm -rf "$d" + git checkout FETCH_HEAD -- "$d" + echo "$d: $(ls "$d" | grep -c '^[0-9].*\.json$')" + fi + done - run: npm ci # This release's prices may no longer fit a week already published: --check regenerates every week not over # yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files), @@ -89,11 +91,12 @@ jobs: # 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 + if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi - run: npm test if: ${{ !inputs.weekly }} - name: Test the weekly puzzles against this release if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} - run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js + run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js 2>/dev/null) - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - uses: actions/upload-pages-artifact@v5 diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml index 0629330..9ac5cfa 100644 --- a/.github/workflows/weekly-puzzle.yml +++ b/.github/workflows/weekly-puzzle.yml @@ -1,8 +1,8 @@ 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. +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js) and scenario (scripts/weekly-scenario.js), +# commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday +# 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts. # # 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 @@ -47,27 +47,29 @@ jobs: - run: npm ci # Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current. - name: Fit the published weeks to main - run: node scripts/weekly-puzzle.js --check - - name: Make the puzzle + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check + - name: Make the puzzle and the scenario 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" + node scripts/weekly-scenario.js --key "$KEY" else node scripts/weekly-puzzle.js + node scripts/weekly-scenario.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 + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js - name: Commit it to main run: | set -euo pipefail - git add site/puzzles/weekly + git add site/puzzles/weekly site/scenarios/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 status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi if git 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 ' ')" + commit -m "Weekly puzzle and scenario $(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 diff --git a/CHANGELOG.md b/CHANGELOG.md index bf31011..5d2a230 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows - A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. - Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. - A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. +- A new weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands in. - Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, never breaks a customer's or a bank's transit requirement, and shows what it adds to your monthly bill. The Ops sheet opens with the intern's mood and a weekly shift report, which is also the one notice a week the intern leaves in the NOC (#98, #100, #102, #181, #185, #192, #177). - Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. - Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips the peering inbox, hardware shortages, sold-out routes and de-peering at exchanges. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ecdacda..7af5613 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -74,6 +74,7 @@ Development runs on `npm run dev` (assembles on every request, reloads on save); | `.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 `.json` per week plus `index.json` (see below) | +| `scripts/weekly-scenario.js`, `scripts/lib/scenario-bot.js`, `site/scenarios/weekly/` | The weekly scenario generator, its reference player and its output (see below) | | `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) | ## Globals @@ -177,6 +178,16 @@ so `auto-release.yml` stays quiet) and starts `release.yml` from the live releas 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. +The weekly scenario is its twin, in the same weeks and the same workflow run: `scripts/weekly-scenario.js` writes +`site/scenarios/weekly/.json`. A template (plain data in the script) picks a theme, a home city, rules from the +scenario vocabulary (`scnRule` keys, `WEEK_MODS`) and a goal type with parameters; each goal type (`WS_GOALS` in +`src/game/60-features/94-scenarios-weekly.js`) is implemented once in the game, with its progress card. A reference +player (`scripts/lib/scenario-bot.js`) plays it through `ACT`, seeded with the scenario's seed; the goal's number is +calibrated from that run, the scenario must not be won on day 0, the reference must win with a tenth of the days to +spare, and its finishing day is the par. The file keeps the reference plan (`ref`), which `--check` replays. The game +fetches the file when the Scenarios list opens, checks it with `wsValid()` (again in `sanitize()` on load), and falls +back to the in-browser `weekly()`. + ## Saves, imports and migration - `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot diff --git a/scripts/lib/scenario-bot.js b/scripts/lib/scenario-bot.js new file mode 100644 index 0000000..bf811ea --- /dev/null +++ b/scripts/lib/scenario-bot.js @@ -0,0 +1,53 @@ +// The reference player for weekly scenarios (scripts/weekly-scenario.js). It plays inside the real game, headless, +// through the game's own actions (ACT.*, openLinkModal + buildLink), as a careful human would: broadband, transit and +// an exchange port at home on day 0, a NOC intern on standing orders for transit and routers, then the generator's +// plan one step at a time whenever the bank allows it, upgrading any wave that runs hot. It never reads the goal, so the +// same seed and plan always play the same game, and the generator can calibrate a goal from what it reached. +const BOT = String.raw`(()=>{ +const B=window.__wsBot={}; +const cheapNet=(c,avoid)=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!avoid.includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0]; +const reserve=()=>Math.max(60000,1.5*(R.costMo||0)); +const can=x=>S.cash>=x+reserve(); +const quiet=f=>{const t=window.toast;window.toast=()=>{};try{f();}finally{window.toast=t;}}; +function link(a,b,tier,via){UI.via=via||null;UI.route=null;openLinkModal(a,b);ACT.buildLink({tier});closeModal();return S.links.some(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));} +function ix(c){if(!S.pops[c])return;for(const x of (B.plan&&B.plan.allIx?ixIdsIn(c):[c])){if(!ixName(x)||S.ixp[x]!==undefined)continue;ACT.buyIx({city:x,tier:1,signed:true});if(S.ixp[x]!==undefined&&!S.rs[x])ACT.rs({city:x});}} +// Before a big event: transit enough for the event on top of the usual peak, and routers that can take it. +function prep(E){const c=E.city,need=(S.stats.peak||R.served||0)*1.2+E.g*1.15;let cap=()=>S.transit.filter(t=>t.city===c).reduce((a,t)=>a+PORT[t.tier].g*(t.n||1),0); + for(let k=0;k<12&&cap()t.city===c).sort((a,b)=>PORT[a.tier].g*(a.n||1)-PORT[b.tier].g*(b.n||1))[0];if(!t)break;const c0=cap(); + if(t.tier=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1});if(cap()===c0)break;} + for(let k=0;k<4;k++){const p=S.pops[c];if(!p||(p.routers||1)>=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}} +B.start=(plan)=>{B.plan=plan;B.i=0;const c=S.scn.home||plan.home;quiet(()=>{ + ACT.launchBB({city:c}); + if(!scnRule('noTransit')){const n=cheapNet(c,plan.avoid||[]);if(n)ACT.buyTransit({city:c,net:n.id,tier:1});if(plan.tr2){const m=cheapNet(c,plan.avoid||[]);if(m)ACT.buyTransit({city:c,net:m.id,tier:1});}} + ix(c);if(plan.scrub)ACT.buildScrub({city:c,tier:plan.scrub});});}; +B.day=()=>{const P=B.plan,d=S.day;if(!P)return;quiet(()=>{ + // A month in, with the first bills paid: the intern keeps transit and routers ahead of the traffic. + if(d===30&&opsCanHire()&&!opsHired()&&rule('clock')){ACT.opsHire({id:'kevin'});closeModal();if(opsHired())for(const k of ['transit','routers','repair'])if(!S.ops.on[k])ACT.opsToggle({k});closeModal();} + if(d%7===0)for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||(R.load[l.id]||0)=P.event.day-21&&d { if (!ev('!!window.__wsBot')) ev(BOT); }; + +// Plays a weekly scenario file from day 0: the plan steps once a day, until the goal is met (when stop) or the days +// run out. Returns the day the goal was first met (or null), what the goal measure read each day, and the end state. +function play(ev, file, plan, { days, stop = true, measure = 'wsMeasure()' } = {}) { + install(ev); + ev(`localStorage.removeItem('sot-wkscn');wsBegin(${JSON.stringify(file)},'Ref');if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`); + if (ev('!!(S.scn&&S.scn.wk)') !== true) throw new Error('the game would not start this scenario'); + ev(`__wsBot.start(${JSON.stringify(plan)})`); + const won0 = ev('wsOk()'), n = days || ev('S.scn.days'); + // Each day: the bot moves, the day ticks (scnTick records a win), and we note the measure. + const out = JSON.parse(ev(`(()=>{const m=[];let won=null;for(let i=0;i<${n};i++){__wsBot.day();dayTick();closeModal();m.push(+(${measure}).toFixed(3));if(won===null&&S.scn.done)won=S.scn.done;if(won!==null&&${stop})break;if(S.lost)break;}return JSON.stringify({won,m,lost:!!S.lost,day:S.day,cash:Math.round(S.cash)});})()`)); + return { won0, ...out }; +} + +module.exports = { BOT, install, play }; diff --git a/scripts/weekly-scenario.js b/scripts/weekly-scenario.js new file mode 100644 index 0000000..a7a45b1 --- /dev/null +++ b/scripts/weekly-scenario.js @@ -0,0 +1,297 @@ +#!/usr/bin/env node +// The weekly scenario generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml +// runs both; this one publishes site/scenarios/weekly/.json, which the game fetches when the Scenarios list opens +// (src/game/60-features/94-scenarios-weekly.js). It loads the real game headless, so it uses the game's own cities, +// cables, prices, week keys, file validator and goal code. +// +// node scripts/weekly-scenario.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing +// node scripts/weekly-scenario.js --key 2026-W45 that week (--force replaces an existing file) +// node scripts/weekly-scenario.js --next 3 this week and the next two +// node scripts/weekly-scenario.js --check re-play every week not over yet with this game; a week its reference +// no longer wins is regenerated with rev + 1 (see refresh()); then +// validate every file. Fails only if that fails. +// --page FILE / --dir DIR another build of the game / where the files live +// +// How a scenario is made: pick a theme the last weeks did not have (TEMPLATES, plain data), a home city from another part +// of the world than the last weeks', its rules and the reference plan (which links to build, in order). Then the +// reference player (scripts/lib/scenario-bot.js) plays it through the game's own actions with the scenario's seed. The +// goal's number is calibrated from that run (what the reference reached about three quarters of the way in), and the +// scenario is verified: not won on day 0, won by the reference with time to spare. Its finishing day is the par. +const fs = require('node:fs'); +const path = require('node:path'); +const BOT = require('./lib/scenario-bot'); + +const ROOT = path.join(__dirname, '..'); +const SCHEMA = 1, HISTORY = 4, THEME_GAP = 4, REG_GAP = 3, ATTEMPTS = 12, AT = 0.8, MARGIN = 0.9; + +// ---------- the templates: data only. `home` names a city pool, `goal` a goal type of the game, `plan` a planner ---------- +const TEMPLATES = { + budget: { goal: 'served', home: 'big', days: [240, 300], cash: [150000, 250000], lvl: 2, mods: ['pricey'], plan: 'spread', hops: 4 }, + spat: { goal: 'reach', home: 'big', days: [240, 300], cash: [500000, 800000], lvl: 2, rules: { spat: true }, plan: 'spread', hops: 3, tr2: true, avoid: ['cog'] }, + region: { goal: 'ix', home: 'ixrich', days: [270, 365], cash: [200000, 350000], lvl: 2, plan: 'exchanges', hops: 14 }, + event: { goal: 'event', home: 'big', days: [180, 240], cash: [500000, 900000], lvl: 2, plan: 'spread', hops: 2, sizes: [1600, 800, 400, 200] }, + flood: { goal: 'floods', home: 'big', days: [240, 300], cash: [1500000, 2500000], lvl: 3, rules: { ddos: true }, plan: 'spread', hops: 2, scrub: 1 }, + island: { goal: 'pops', home: 'island', days: [240, 365], cash: [250000, 500000], lvl: 3, plan: 'islands', hops: 3 }, + cable: { goal: 'path', home: 'landing', days: [270, 365], cash: [200000, 400000], lvl: 3, plan: 'detour', g: [400, 800], n: 45 }, + latency: { goal: 'lat', home: 'fast', days: [180, 270], cash: [300000, 600000], lvl: 3, plan: 'fast', n: 60 }, +}; + +// ---------- the game, headless ---------- +function game(file) { + const { load } = require('../tests/harness'); + let g = load(file ? { file } : {}); + if (file && !g.ev("typeof wsValid==='function'")) { console.warn(`warning: ${file} has no weekly scenarios yet; using src/ instead`); g = load(); } + return g; +} +const J = (ev, s) => JSON.parse(ev(`JSON.stringify(${s})`)); + +// ---------- 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 between = (r, [lo, hi], step) => lo + Math.floor(r() * ((hi - lo) / step + 1)) * step; +// A goal number players can read: two significant digits, rounded down. +const nice = (x) => { if (x < 10) return Math.max(1, Math.floor(x)); const p = 10 ** (Math.floor(Math.log10(x)) - 1); return Math.floor(x / p) * p; }; + +// ---------- the world, as the game sees it ---------- +function world(ev) { + const cities = J(ev, `Object.values(CITY).filter(c=>pzCityOk(c.id)).map(c=>({id:c.id,reg:c.reg,P:c.P,land:lands(c)[0],nl:lands(c).length,ix:ixIdsIn(c.id).length,lon:c.lon,lat:c.lat}))`); + const C = Object.fromEntries(cities.map((c) => [c.id, c])); + const pairs = J(ev, 'CABLE_PAIRS.map(p=>[p.cid,p.a,p.b])').filter(([, a, b]) => C[a] && C[b]); + const byLand = {}; for (const c of cities) (byLand[c.land] = byLand[c.land] || []).push(c.id); + 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)); }; + const cabs = (c) => pairs.filter(([, a, b]) => a === c || b === c); + const pools = { + big: cities.filter((c) => c.P >= 150 && byLand[c.land].length >= 5).map((c) => c.id), + ixrich: cities.filter((c) => c.ix && cities.filter((x) => x.reg === c.reg && x.land === c.land && x.ix && km(c.id, x.id) < 2500).length >= 9).map((c) => c.id), + island: cities.filter((c) => byLand[c.land].length <= 2 && c.nl === 1 && cabs(c.id).length >= 2).map((c) => c.id), + landing: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 3).map((c) => c.id), + fast: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 2).map((c) => c.id), + }; + return { cities, C, pairs, byLand, km, cabs, pools }; +} +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); + +// ---------- drafts: a template, a home, rules, the goal's fixed parameters and the reference plan ---------- +// Plans are lists of steps for the reference player: {k:'hop',v:[a,b,tier,via]} lights a wave a-b (a new POP at b). +function draft(g, W, theme, r, hist) { + const T = TEMPLATES[theme], free = (c) => !hist.cities.has(c) && !hist.regs.includes(W.C[c].reg); + const homes = W.pools[T.home].filter(free); if (!homes.length) return null; + const home = pick(r, homes), H = W.C[home]; + const f = { theme, city: home, cash: between(r, T.cash, 50000), days: between(r, T.days, 10), lvl: T.lvl, rules: { ...(T.rules || {}) }, mods: (T.mods || []).slice() }; + const plan = { home, bb: true, ix: true, steps: [], avoid: T.avoid || [], tr2: !!T.tr2, scrub: T.scrub || 0 }; + const hop = (a, b, t = 1, via = null) => plan.steps.push({ k: 'hop', v: [a, b, t, via] }); + const land = W.byLand[H.land].filter((c) => c !== home && W.km(home, c) < 1500); + let goal = null, words = {}; + if (T.plan === 'spread') { + // Overland to the nearest big cities, each from the closest POP already built. + const to = near(W, home, land.filter((c) => W.C[c].P >= 60), T.hops); if (to.length < Math.min(2, T.hops)) return null; + const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); } + if (theme === 'budget') goal = { t: 'served', p: { g: 0 } }; + if (theme === 'spat') goal = { t: 'reach', p: { r: 99, g: 0 } }; + if (theme === 'flood') goal = { t: 'floods', p: { n: 0, big: 0 } }; + if (theme === 'event') { const day = Math.round(f.days * (0.6 + r() * 0.15)); goal = { t: 'event', p: { city: home, g: 0, day, dur: 3 + Math.floor(r() * 3) } }; plan.event = { city: home, day }; words = { day }; } + } else if (T.plan === 'exchanges') { + const to = near(W, home, W.cities.filter((c) => c.reg === H.reg && c.land === H.land && c.ix).map((c) => c.id), T.hops); if (to.length < T.hops) return null; + const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); } + plan.allIx = true; goal = { t: 'ix', p: { reg: H.reg, n: 0 } }; words = { reg: H.reg }; + } else { + // Cable work: plan inside the game, which knows each pair's cables under this scenario's rules. + let a = home, b = null, cs = null; + if (theme === 'cable') { + // Cut one cable everywhere it lands; the goal is its far end, the long way round. + const mine = W.cabs(home).filter(([, x, y]) => W.C[x].land !== W.C[y].land && W.C[x === home ? y : x].P >= 60); + if (!mine.length) return null; + const [cid, x, y] = pick(r, mine); b = x === home ? y : x; + // The whole cable, and every other cable straight from home to its far end: the corridor is closed. + const cut = new Set([cid, ...W.pairs.filter(([, p, q]) => (p === home && q === b) || (p === b && q === home)).map(([c]) => c)]); + f.rules.banPairs = W.pairs.filter(([c, p, q]) => c === cid || (cut.has(c) && [p, q].includes(home) && [p, q].includes(b))).map(([c, p, q]) => `${c}:${p}-${q}`); + if (f.rules.banPairs.length > 40) return null; + const gb = pick(r, T.g); plan.tier = J(g.ev, `LT.findIndex(x=>x.g>=${gb})`); + goal = { t: 'path', p: { a, b, g: gb, n: T.n } }; words = { cab: cid, a, b }; + } else if (theme === 'island') { + const hops = W.cabs(home).map(([, x, y]) => (x === home ? y : x)).filter((c, i, s) => s.indexOf(c) === i && W.km(home, c) < 6000); + if (hops.length < 2) return null; + // The nearest islands a cable away, and one more island further out. + const isl = W.pools.island.filter((c) => c !== home && W.km(home, c) < 9000 && !hops.includes(c)); + cs = [...near(W, home, hops, 2), ...near(W, home, isl, 1 + Math.floor(r() * 2))]; + if (cs.length < 3) return null; + goal = { t: 'pops', p: { cs } }; + } else if (theme === 'latency') { + // Far enough that the fast way takes more than one cable. + const ok = W.cities.filter((c) => c.P >= 100 && c.land !== H.land && W.km(home, c.id) > 5000 && W.km(home, c.id) < 11000 && W.cabs(c.id).length >= 2).map((c) => c.id); + if (!ok.length) return null; b = pick(r, ok); goal = { t: 'lat', p: { a, b, ms: 0, n: T.n } }; words = { a, b }; + } + plan.targets = cs || [b]; plan.fast = theme === 'latency'; + f.goal = goal; + return { f, plan, words, T }; + } + f.goal = goal; + return { f, plan, words, T }; +} + +// ---------- names and descriptions: labels and their fill-ins ---------- +function texts(ev, d, r) { + const T = J(ev, `WS_THEMES['${d.f.theme}']`), p = d.f.goal.p; + const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], o = {}; + for (const k of need) o[k] = k === 'city' ? d.f.city : k === 'ms' ? p.ms : k === 'g' ? p.g : k === 'n' ? p.n : d.words[k]; + return { l, p: o }; }; + return { name: fill(pick(r, T.names)), desc: fill(pick(r, T.descs)) }; +} + +// ---------- playing a draft ---------- +const fileOf = (key, d, seed, extra) => ({ v: SCHEMA, key, theme: d.f.theme, city: d.f.city, cash: d.f.cash, days: d.f.days, lvl: d.f.lvl, rules: d.f.rules, mods: d.f.mods, goal: d.f.goal, ...extra, seed, ref: d.plan }); +// Cable plans are made in the game, once the scenario's rules are in force: the shortest chain of POPs to each target. +function cablePlan(ev, plan) { + if (!plan.targets) return plan; + const steps = J(ev, `(()=>{const home=S.scn.home,T=${JSON.stringify(plan.targets)},fast=${!!plan.fast},out=[],have=new Set([home]); + const ok=c=>pzCityOk(c)&&cityOn(c)&&!cnCity(c); + const edges=u=>{const o=[];for(const p of CABLE_PAIRS){const v=p.a===u?p.b:p.b===u?p.a:null;if(!v||!ok(v))continue;const cs=cablesOk(u,v);if(!cs.length)continue; + const c=cs.slice().sort((x,y)=>x.km*(CAB[x.cid].lat||1)-y.km*(CAB[y.cid].lat||1))[0];o.push([v,c.km*(CAB[c.cid].lat||1)/200,c.cid]);} + for(const c of CITIES)if(c.id!==u&&ok(c.id)&&!isSub(u,c.id)&&kmBetween(u,c.id)<(fast?4000:1800))o.push([c.id,kmBetween(u,c.id)*1.3/200,null]);return o;}; + for(const t of T){if(have.has(t))continue;const d={},pv={},done=new Set();for(const h of have)d[h]=0; + for(;;){let u=null;for(const k in d)if(!done.has(k)&&(u===null||d[k]=1')) { p.g = size; return { plan: o.plan }; } } + return null; + } + if (t === 'lat') { + const o = run(g, file, d.plan, at); if (!o) return null; + const best = g.ev(`bestLat('${p.a}','${p.b}')`); if (!isFinite(best)) return null; + p.ms = Math.ceil(best * 1.03 + 0.5); return { plan: o.plan }; + } + const o = run(g, file, d.plan, at); if (!o) return null; + const m = o.res.m, v = m[m.length - 1]; + if (t === 'served') p.g = nice(Math.min(...m.slice(-14))); + if (t === 'reach') { if (g.ev('R.reach') < 0.99) return null; p.g = nice(Math.min(...m.slice(-14))); } + if (t === 'ix') p.n = Math.floor(v); + if (t === 'floods') { p.n = Math.floor(v); p.big = Math.min(5, g.ev('S.stats.ddosOkBig||0')); } + if ((p.g !== undefined && p.g < 5) || (p.n !== undefined && p.n < 2)) return null; + return { plan: o.plan }; +} + +// The game's validator decides what a scenario is; then it must need play, and the reference must win with time to spare. +function verify(g, j) { + const { ev } = g; + if (!ev(`!!wsValid(${JSON.stringify(j)},'${j.key}')`)) return { ok: false, why: 'the game rejects the file' }; + // Played with the longest clock the game allows, so a late win still shows its day (the days change nothing else). + const res = BOT.play(ev, { ...j, days: 400 }, j.ref, { stop: true }); + if (res.won0) return { ok: false, why: 'won on day 0' }; + if (!res.won) return { ok: false, why: `the reference does not win in ${j.days} days` }; + if (res.won > j.days * MARGIN) return { ok: false, late: res.won, why: `the reference wins only on day ${res.won} of ${j.days}` }; + if (res.won < 40) return { ok: false, why: `the reference wins already on day ${res.won} of ${j.days}` }; + return { ok: true, par: res.won }; +} + +// ---------- one week ---------- +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() : []); +function history(W, dir, key) { + const files = list(dir).filter((k) => k < key).slice(-HISTORY).map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8'))); + return { themes: files.slice(-THEME_GAP).map((f) => f.theme), regs: files.slice(-REG_GAP).map((f) => W.C[f.city] && W.C[f.city].reg).filter(Boolean), cities: new Set(files.map((f) => f.city)) }; +} +function generate(g, key, dir) { + const { ev } = g, W = world(ev); + if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`); + const hist = history(W, dir, key), free = Object.keys(TEMPLATES).sort().filter((t) => !hist.themes.includes(t)), h = hash('scn|' + key); + const order = free.map((_, i) => free[(h + i) % free.length]); + for (const theme of order) { + for (let at = 0; at < ATTEMPTS; at++) { + const r = rng(hash(`${key}|${theme}|${at}`)), d = draft(g, W, theme, r, hist); + if (!d) continue; + const seed = 1 + (hash(`${key}|seed|${at}`) % 2147483646), c = calibrate(g, d, key, seed); + if (!c) { console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: no goal to calibrate`); continue; } + d.plan = c.plan; + const w = texts(ev, d, r), j = fileOf(key, d, seed, { name: w.name, desc: w.desc, par: 1 }); + let v = verify(g, j); + // A goal with a fixed bar (a path, a set of POPs, a latency) gets the days the reference needed, and a third more. + const day = v.ok ? v.par : v.late; + if (day && ['path', 'pops', 'lat'].includes(j.goal.t)) { j.days = Math.min(365, Math.max(180, Math.ceil(day / 0.7 / 10) * 10)); v = verify(g, j); } + if (v.ok) { j.par = v.par; return order0(j); } + console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: ${v.why}`); + } + } + throw new Error(`${key}: no scenario survived verification`); +} +// Fields in a fixed order, so files diff well. +const order0 = (j) => { const o = {}; for (const k of ['v', 'key', 'rev', 'theme', 'city', 'cash', 'days', 'lvl', 'rules', 'mods', 'goal', 'name', 'desc', 'seed', 'par', 'ref']) if (j[k] !== undefined) o[k] = j[k]; return o; }; + +// --check: every file is what the game accepts, under its own name, listed in the index; weeks not over yet still verify. +function check(g, dir, now = Date.now()) { + const { ev } = g, bad = [], keys = list(dir); + for (const k of keys) { + let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; } + if (!ev(`!!wsValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; } + if (!j.ref || !Array.isArray(j.ref.steps)) { bad.push(`${k}: no reference plan`); continue; } + if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j); if (!v.ok) bad.push(`${k}: ${v.why}`); else if (v.par !== j.par) bad.push(`${k}: par is ${j.par}, the reference wins on day ${v.par}`); } + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* reported below */ } + if (keys.length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys))) bad.push('index.json does not list exactly the weekly files'); + return bad; +} +/* --check, first part: a release can change prices, cables or the simulation under weeks already published. Every week + not over yet is re-played with this game. Still won with time to spare: only its par follows. Not any more: it is + regenerated for the same key, deterministically, with rev + 1, so last week's wins for it no longer show. Past weeks + are only replaced when the game rejects them outright. */ +function refresh(g, dir, now = Date.now()) { + const { ev } = g, fixed = [], bad = []; + for (const k of list(dir)) { + let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated */ } + const valid = !!j && ev(`!!wsValid(${JSON.stringify(j)},'${k}')`) && j.ref && Array.isArray(j.ref.steps), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now; + if (valid && !live) continue; + const v = valid ? verify(g, j) : null; + if (v && v.ok) { if (v.par !== j.par) { j.par = v.par; writeWeek(dir, j); fixed.push(`${k}: new par ${v.par}`); } continue; } + const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1; + let n; try { n = order0({ ...generate(g, k, dir), rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } + writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}, a ${n.theme} scenario in ${n.city}`); + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ } + if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); } + return { fixed, bad }; +} +const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n'); +const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); }; + +module.exports = { game, generate, verify, check, refresh, list, writeWeek, TEMPLATES }; + +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/scenarios/weekly')), g = game(opt('--page') && path.resolve(opt('--page'))); + if (args.includes('--check')) { + const r = refresh(g, dir); + for (const x of r.fixed) console.log(`fixed: ${x}`); + const bad = [...r.bad, ...check(g, dir)]; + for (const b of bad) console.error(`error: ${b}`); + console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly scenario(s) OK`); + process.exit(bad.length ? 1 : 0); + } + const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1); + for (let i = 0; i < n; i++) { + const key = g.ev(`pzKeyAdd('${first}',${i})`); + if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); } + if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; } + const j = generate(g, key, dir); writeWeek(dir, j); + console.log(`${key}: ${j.theme} in ${j.city}, ${j.days} days, goal ${j.goal.t} ${JSON.stringify(j.goal.p)}, par ${j.par}`); + } +} diff --git a/site/i18n/de.js b/site/i18n/de.js index 5a70307..82a1847 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3605,4 +3605,65 @@ "utilities.title":"Werkzeuge", "utilities.two_routers":"Mindestens zwei Router", "utilities.view_pop":"POP ansehen", +"wkscn.copy_my_result":"Mein Ergebnis kopieren", +"wkscn.desc_a_g_event_comes_to":"An Tag {day} kommt ein Event mit {g} nach {city}. Bau das Netz dafür, aus dem Nichts.", +"wkscn.desc_a_ship_dragged_its_anchor":"Ein Schiff hat seinen Anker über {cab} geschleift. Finde einen anderen Weg von {a} nach {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Eine Trading-Firma braucht {a} nach {b} unter {ms} ms, und zwar jeden Tag.", +"wkscn.desc_booters_picked_city_for_their":"Die Booter haben sich {city} für ihren Wochenausflug ausgesucht. Halte die Stellung.", +"wkscn.desc_cab_is_cut_for_the":"{cab} ist die ganze Runde über gekappt. Der Traffic muss trotzdem von {a} nach {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"In {city} steht der Lieblings-Boxsack des Internets. Alle paar Tage kommt eine Flut.", +"wkscn.desc_city_is_just_the_start":"{city} ist nur der Anfang: hol dir Ports an Exchanges in ganz {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} ist von Wasser und Ehrgeiz umgeben. Verbinde die Inseln.", +"wkscn.desc_city_on_a_shoestring":"{city} mit knappem Budget: wenig Geld, und jede Rechnung zählt.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle und Goggle reden schon wieder nicht miteinander. Starte in {city} und erreiche trotzdem alle.", +"wkscn.desc_every_exchange_in_reg_wants":"Jedes Exchange in {reg} will dich kennenlernen. Starte in {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Jede Millisekunde zwischen {a} und {b} kostet einen Trader eine Jacht. Rasier sie weg.", +"wkscn.desc_start_in_city_with_pocket":"Starte in {city} mit Taschengeld und wachse mit dem, was die Kunden zahlen.", +"wkscn.desc_start_on_city_and_string":"Starte in {city} und fädle die Inseln auf, ein Kabel nach dem anderen.", +"wkscn.desc_the_whole_city_is_watching":"An Tag {day} schaut ganz {city} zu. Sei bereit, {g} zu tragen.", +"wkscn.desc_two_giants_de_peered_over":"Zwei Riesen haben sich wegen einer Tabelle depeert. Deine Kunden in {city} wollen trotzdem das ganze Internet.", +"wkscn.event_name_city":"Die große Wochenshow in {city}", +"wkscn.goal_a_connected_pop_in_list":"Ein verbundener POP in {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} nach {b} unter {ms} ms, {n} Tage am Stück", +"wkscn.goal_deliver_the_event_in_city":"Liefere das {g}-Event in {city} voll aus, {dur} Tage ab Tag {day}", +"wkscn.goal_g_on_every_hop_from":"{g} auf jedem Hop von {a} nach {b}, {n} Tage am Stück", +"wkscn.goal_hold_n_floods":"Halte {n} Fluten", +"wkscn.goal_hold_n_floods_big_of":"Halte {n} Fluten, {big} davon ein Terabit oder mehr", +"wkscn.goal_ports_on_n_exchanges_in":"Ports an {n} Exchanges in {reg}", +"wkscn.goal_reach_r_and_serve_g":"Erreiche {r}% des Internets und liefere {g}", +"wkscn.goal_serve_g":"Liefere {g} Traffic", +"wkscn.loading_this_week_s_scenario":"Lade das Szenario dieser Woche…", +"wkscn.name_continental_breakfast":"Kontinentales Frühstück", +"wkscn.name_cut_and_run":"Schnitt und weg", +"wkscn.name_flood_week":"Flutwoche", +"wkscn.name_island_hopper":"Inselhüpfer", +"wkscn.name_light_speed_please":"Lichtgeschwindigkeit, bitte", +"wkscn.name_ludicrous_speed":"Wahnsinnige Geschwindigkeit", +"wkscn.name_not_on_speaking_terms":"Funkstille", +"wkscn.name_packet_monsoon":"Paketmonsun", +"wkscn.name_party_like_its_1999":"Party wie 1999", +"wkscn.name_peering_pressure":"Peering-Druck", +"wkscn.name_planting_flags":"Fahnen hissen", +"wkscn.name_ramen_profitable":"Ramen-Profitabel", +"wkscn.name_sea_you_soon":"Bis zum nächsten Meer", +"wkscn.name_shoestring_backbone":"Backbone für'n Appel und 'n Ei", +"wkscn.name_stream_team":"Stream-Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Nächstes Wochenszenario in {d} T. {h} Std.", +"wkscn.next_weekly_in_h_m":"Nächstes Wochenszenario in {h} Std. {m} Min.", +"wkscn.p_a_b_now":"{a} → {b} jetzt: {ms}", +"wkscn.p_days_in_a_row":"Tage am Stück", +"wkscn.p_event_delivered_in_full":"Event voll ausgeliefert", +"wkscn.p_exchange_ports_in_reg":"Exchange-Ports in {reg}", +"wkscn.p_g_on_day_d":"{g} an Tag {d}", +"wkscn.p_path_g_a_b":"{g}-Pfad {a} → {b}", +"wkscn.par_day_par":"Par: Tag {par}", +"wkscn.par_was_day_par":"Par war Tag {par}. Nächste Woche vielleicht.", +"wkscn.same_scenario_for_everyone_this_week":"Diese Woche dasselbe Szenario für alle", +"wkscn.share_line":"Series of Tubes Wochenszenario {key} „{name}“ gewonnen an Tag {d} (Par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Start in {city} · {d} Tage · {cash}", +"wkscn.under_par_par":"Im Par oder besser (Tag {par}). Schön gemacht.", +"wkscn.weekly_scenario_key":"Wochenszenario {key}", +"wkscn.won_day_d_par_par":"Gewonnen an Tag {d} (Par {par})", +"wkscn.won_on_day_d":"Gewonnen an Tag {d}!", }; diff --git a/site/i18n/es.js b/site/i18n/es.js index ddaaea1..f9f661a 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilidades", "utilities.two_routers":"Al menos dos routers", "utilities.view_pop":"Ver POP", +"wkscn.copy_my_result":"Copiar mi resultado", +"wkscn.desc_a_g_event_comes_to":"El día {day} llega a {city} un evento de {g}. Construye la red que necesita, desde cero.", +"wkscn.desc_a_ship_dragged_its_anchor":"Un barco arrastró el ancla sobre {cab}. Busca otro camino de {a} a {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Una firma de trading necesita {a} a {b} en menos de {ms} ms, y todos los días.", +"wkscn.desc_booters_picked_city_for_their":"Los booters eligieron {city} para su semana libre. Aguanta la línea.", +"wkscn.desc_cab_is_cut_for_the":"{cab} está cortado toda la partida. El tráfico tiene que llegar igual de {a} a {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} aloja el saco de boxeo favorito de internet. Espera una inundación cada pocos días.", +"wkscn.desc_city_is_just_the_start":"{city} es solo el principio: consigue puertos en exchanges por todo {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} está rodeada de agua y de ambición. Conecta las islas.", +"wkscn.desc_city_on_a_shoestring":"{city} con lo justo: poco dinero y cada factura cuenta.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle y Goggle han vuelto a dejar de hablarse. Empieza en {city} y llega a todos igualmente.", +"wkscn.desc_every_exchange_in_reg_wants":"Todos los exchanges de {reg} quieren conocerte. Empieza en {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Cada milisegundo entre {a} y {b} le cuesta un yate a un trader. Recórtalos.", +"wkscn.desc_start_in_city_with_pocket":"Empieza en {city} con calderilla y crece con lo que pagan los clientes.", +"wkscn.desc_start_on_city_and_string":"Empieza en {city} y ensarta las islas, un cable cada vez.", +"wkscn.desc_the_whole_city_is_watching":"El día {day} todo {city} está mirando. Prepárate para llevar {g}.", +"wkscn.desc_two_giants_de_peered_over":"Dos gigantes rompieron el peering por una hoja de cálculo. Tus clientes en {city} siguen queriendo todo internet.", +"wkscn.event_name_city":"El gran show de la semana en {city}", +"wkscn.goal_a_connected_pop_in_list":"Un POP conectado en {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} a {b} en menos de {ms} ms, {n} días seguidos", +"wkscn.goal_deliver_the_event_in_city":"Entrega completo el evento de {g} en {city}, {dur} días desde el día {day}", +"wkscn.goal_g_on_every_hop_from":"{g} en cada salto de {a} a {b}, {n} días seguidos", +"wkscn.goal_hold_n_floods":"Aguanta {n} inundaciones", +"wkscn.goal_hold_n_floods_big_of":"Aguanta {n} inundaciones, {big} de ellas de un terabit o más", +"wkscn.goal_ports_on_n_exchanges_in":"Puertos en {n} exchanges de {reg}", +"wkscn.goal_reach_r_and_serve_g":"Alcanza el {r}% de internet y sirve {g}", +"wkscn.goal_serve_g":"Sirve {g} de tráfico", +"wkscn.loading_this_week_s_scenario":"Cargando el escenario de esta semana…", +"wkscn.name_continental_breakfast":"Desayuno continental", +"wkscn.name_cut_and_run":"Cortar y correr", +"wkscn.name_flood_week":"Semana de inundaciones", +"wkscn.name_island_hopper":"Salta islas", +"wkscn.name_light_speed_please":"A la velocidad de la luz, por favor", +"wkscn.name_ludicrous_speed":"Velocidad absurda", +"wkscn.name_not_on_speaking_terms":"Ni se hablan", +"wkscn.name_packet_monsoon":"Monzón de paquetes", +"wkscn.name_party_like_its_1999":"De fiesta como en 1999", +"wkscn.name_peering_pressure":"Presión de peering", +"wkscn.name_planting_flags":"Plantando banderas", +"wkscn.name_ramen_profitable":"Rentable a base de ramen", +"wkscn.name_sea_you_soon":"Nos vemos en el mar", +"wkscn.name_shoestring_backbone":"Backbone con cuatro duros", +"wkscn.name_stream_team":"Equipo streaming", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Próximo escenario semanal en {d} d {h} h", +"wkscn.next_weekly_in_h_m":"Próximo escenario semanal en {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} ahora: {ms}", +"wkscn.p_days_in_a_row":"Días seguidos", +"wkscn.p_event_delivered_in_full":"Evento entregado completo", +"wkscn.p_exchange_ports_in_reg":"Puertos en exchanges de {reg}", +"wkscn.p_g_on_day_d":"{g} el día {d}", +"wkscn.p_path_g_a_b":"Ruta de {g} {a} → {b}", +"wkscn.par_day_par":"par: día {par}", +"wkscn.par_was_day_par":"El par era el día {par}. Quizá la semana que viene.", +"wkscn.same_scenario_for_everyone_this_week":"El mismo escenario para todos esta semana", +"wkscn.share_line":"Series of Tubes escenario semanal {key} «{name}» ganado el día {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Empieza en {city} · {d} días · {cash}", +"wkscn.under_par_par":"En par o mejor (día {par}). Bien hecho.", +"wkscn.weekly_scenario_key":"Escenario semanal {key}", +"wkscn.won_day_d_par_par":"Ganado el día {d} (par {par})", +"wkscn.won_on_day_d":"¡Ganado el día {d}!", }; diff --git a/site/i18n/fr.js b/site/i18n/fr.js index a45927a..f4056b9 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilitaires", "utilities.two_routers":"Au moins deux routeurs", "utilities.view_pop":"Voir le POP", +"wkscn.copy_my_result":"Copier mon résultat", +"wkscn.desc_a_g_event_comes_to":"Le jour {day}, un événement de {g} arrive à {city}. Construis le réseau qu'il lui faut, à partir de rien.", +"wkscn.desc_a_ship_dragged_its_anchor":"Un navire a traîné son ancre sur {cab}. Trouve un autre chemin de {a} à {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Une société de trading veut {a} à {b} en moins de {ms} ms, et tous les jours.", +"wkscn.desc_booters_picked_city_for_their":"Les booters ont choisi {city} pour leur semaine de sortie. Tiens bon.", +"wkscn.desc_cab_is_cut_for_the":"{cab} est coupé pour toute la partie. Le trafic doit quand même aller de {a} à {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} héberge le punching-ball préféré d'internet. Attends-toi à une crue tous les deux ou trois jours.", +"wkscn.desc_city_is_just_the_start":"{city} n'est que le début : prends des ports sur des exchanges partout en {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} est entourée d'eau et d'ambition. Relie les îles.", +"wkscn.desc_city_on_a_shoestring":"{city} avec des bouts de ficelle : peu d'argent, et chaque facture compte.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle et Goggle ne se parlent plus, encore. Démarre à {city} et touche tout le monde quand même.", +"wkscn.desc_every_exchange_in_reg_wants":"Chaque exchange de {reg} veut te rencontrer. Démarre à {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Chaque milliseconde entre {a} et {b} coûte un yacht à un trader. Rabote-les.", +"wkscn.desc_start_in_city_with_pocket":"Démarre à {city} avec de l'argent de poche et grandis avec ce que paient les clients.", +"wkscn.desc_start_on_city_and_string":"Démarre à {city} et enfile les îles comme des perles, un câble à la fois.", +"wkscn.desc_the_whole_city_is_watching":"Le jour {day}, tout {city} regarde. Sois prêt à porter {g}.", +"wkscn.desc_two_giants_de_peered_over":"Deux géants ont dépeeré pour un tableur. Tes clients à {city} veulent toujours tout internet.", +"wkscn.event_name_city":"Le grand show de la semaine à {city}", +"wkscn.goal_a_connected_pop_in_list":"Un POP relié à {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} à {b} en moins de {ms} ms, {n} jours d'affilée", +"wkscn.goal_deliver_the_event_in_city":"Livrer en entier l'événement de {g} à {city}, {dur} jours à partir du jour {day}", +"wkscn.goal_g_on_every_hop_from":"{g} sur chaque saut de {a} à {b}, {n} jours d'affilée", +"wkscn.goal_hold_n_floods":"Tenir {n} crues", +"wkscn.goal_hold_n_floods_big_of":"Tenir {n} crues, dont {big} d'un térabit ou plus", +"wkscn.goal_ports_on_n_exchanges_in":"Des ports sur {n} exchanges en {reg}", +"wkscn.goal_reach_r_and_serve_g":"Atteindre {r} % d'internet et servir {g}", +"wkscn.goal_serve_g":"Servir {g} de trafic", +"wkscn.loading_this_week_s_scenario":"Chargement du scénario de la semaine…", +"wkscn.name_continental_breakfast":"Petit-déjeuner continental", +"wkscn.name_cut_and_run":"Coupé, décalé", +"wkscn.name_flood_week":"Semaine des crues", +"wkscn.name_island_hopper":"Saute-îles", +"wkscn.name_light_speed_please":"À la vitesse de la lumière, s'il te plaît", +"wkscn.name_ludicrous_speed":"Vitesse grand V", +"wkscn.name_not_on_speaking_terms":"Ils ne se parlent plus", +"wkscn.name_packet_monsoon":"Mousson de paquets", +"wkscn.name_party_like_its_1999":"La fête comme en 1999", +"wkscn.name_peering_pressure":"Pression du peering", +"wkscn.name_planting_flags":"Planter des drapeaux", +"wkscn.name_ramen_profitable":"Rentable aux nouilles", +"wkscn.name_sea_you_soon":"À la mer prochaine", +"wkscn.name_shoestring_backbone":"Backbone à trois francs six sous", +"wkscn.name_stream_team":"Stream Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Prochain scénario de la semaine dans {d} j {h} h", +"wkscn.next_weekly_in_h_m":"Prochain scénario de la semaine dans {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} maintenant : {ms}", +"wkscn.p_days_in_a_row":"Jours d'affilée", +"wkscn.p_event_delivered_in_full":"Événement livré en entier", +"wkscn.p_exchange_ports_in_reg":"Ports d'exchange en {reg}", +"wkscn.p_g_on_day_d":"{g} le jour {d}", +"wkscn.p_path_g_a_b":"Chemin de {g} {a} → {b}", +"wkscn.par_day_par":"par : jour {par}", +"wkscn.par_was_day_par":"Le par était le jour {par}. La semaine prochaine, peut-être.", +"wkscn.same_scenario_for_everyone_this_week":"Le même scénario pour tout le monde cette semaine", +"wkscn.share_line":"Series of Tubes scénario de la semaine {key} « {name} » gagné le jour {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Départ à {city} · {d} jours · {cash}", +"wkscn.under_par_par":"Dans le par ou mieux (jour {par}). Bien joué.", +"wkscn.weekly_scenario_key":"Scénario de la semaine {key}", +"wkscn.won_day_d_par_par":"Gagné le jour {d} (par {par})", +"wkscn.won_on_day_d":"Gagné le jour {d} !", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index 9afaeb6..fe99435 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilità", "utilities.two_routers":"Almeno due router", "utilities.view_pop":"Mostra POP", +"wkscn.copy_my_result":"Copia il mio risultato", +"wkscn.desc_a_g_event_comes_to":"Il giorno {day} arriva a {city} un evento da {g}. Costruisci la rete che serve, da zero.", +"wkscn.desc_a_ship_dragged_its_anchor":"Una nave ha trascinato l'ancora su {cab}. Trova un'altra strada da {a} a {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Una società di trading vuole {a}–{b} sotto i {ms} ms, e tutti i giorni.", +"wkscn.desc_booters_picked_city_for_their":"I booter hanno scelto {city} per la loro settimana di gita. Tieni duro.", +"wkscn.desc_cab_is_cut_for_the":"{cab} è tagliato per tutta la partita. Il traffico deve comunque andare da {a} a {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} ospita il sacco da boxe preferito di internet. Aspettati una piena ogni pochi giorni.", +"wkscn.desc_city_is_just_the_start":"{city} è solo l'inizio: prendi porte sugli exchange in tutta {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} è circondata d'acqua e d'ambizione. Collega le isole.", +"wkscn.desc_city_on_a_shoestring":"{city} con pochi soldi: ogni bolletta conta.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle e Goggle hanno di nuovo smesso di parlarsi. Parti da {city} e raggiungi tutti lo stesso.", +"wkscn.desc_every_exchange_in_reg_wants":"Ogni exchange in {reg} vuole conoscerti. Parti da {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Ogni millisecondo tra {a} e {b} costa uno yacht a un trader. Limali via.", +"wkscn.desc_start_in_city_with_pocket":"Parti da {city} con la paghetta e cresci con quello che pagano i clienti.", +"wkscn.desc_start_on_city_and_string":"Parti da {city} e infila le isole come perle, un cavo alla volta.", +"wkscn.desc_the_whole_city_is_watching":"Il giorno {day} tutta {city} guarda. Preparati a portare {g}.", +"wkscn.desc_two_giants_de_peered_over":"Due giganti hanno chiuso il peering per un foglio di calcolo. I tuoi clienti a {city} vogliono comunque tutto internet.", +"wkscn.event_name_city":"Il grande show della settimana a {city}", +"wkscn.goal_a_connected_pop_in_list":"Un POP collegato a {cs}", +"wkscn.goal_a_to_b_under_ms":"{a}–{b} sotto i {ms} ms, {n} giorni di fila", +"wkscn.goal_deliver_the_event_in_city":"Consegna per intero l'evento da {g} a {city}, {dur} giorni dal giorno {day}", +"wkscn.goal_g_on_every_hop_from":"{g} su ogni hop da {a} a {b}, {n} giorni di fila", +"wkscn.goal_hold_n_floods":"Reggi {n} piene", +"wkscn.goal_hold_n_floods_big_of":"Reggi {n} piene, {big} da un terabit o più", +"wkscn.goal_ports_on_n_exchanges_in":"Porte su {n} exchange in {reg}", +"wkscn.goal_reach_r_and_serve_g":"Raggiungi il {r}% di internet e servi {g}", +"wkscn.goal_serve_g":"Servi {g} di traffico", +"wkscn.loading_this_week_s_scenario":"Carico lo scenario della settimana…", +"wkscn.name_continental_breakfast":"Colazione continentale", +"wkscn.name_cut_and_run":"Taglia e scappa", +"wkscn.name_flood_week":"Settimana delle piene", +"wkscn.name_island_hopper":"Saltaisole", +"wkscn.name_light_speed_please":"Alla velocità della luce, grazie", +"wkscn.name_ludicrous_speed":"Velocità assurda", +"wkscn.name_not_on_speaking_terms":"Non si parlano", +"wkscn.name_packet_monsoon":"Monsone di pacchetti", +"wkscn.name_party_like_its_1999":"Festa come nel 1999", +"wkscn.name_peering_pressure":"Pressione da peering", +"wkscn.name_planting_flags":"Piantare bandierine", +"wkscn.name_ramen_profitable":"In attivo a forza di ramen", +"wkscn.name_sea_you_soon":"Ci vediamo al mare", +"wkscn.name_shoestring_backbone":"Backbone con due spiccioli", +"wkscn.name_stream_team":"Stream Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Prossimo scenario settimanale tra {d} g {h} h", +"wkscn.next_weekly_in_h_m":"Prossimo scenario settimanale tra {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} adesso: {ms}", +"wkscn.p_days_in_a_row":"Giorni di fila", +"wkscn.p_event_delivered_in_full":"Evento consegnato per intero", +"wkscn.p_exchange_ports_in_reg":"Porte su exchange in {reg}", +"wkscn.p_g_on_day_d":"{g} il giorno {d}", +"wkscn.p_path_g_a_b":"Percorso da {g} {a} → {b}", +"wkscn.par_day_par":"par: giorno {par}", +"wkscn.par_was_day_par":"Il par era il giorno {par}. Magari la prossima settimana.", +"wkscn.same_scenario_for_everyone_this_week":"Lo stesso scenario per tutti questa settimana", +"wkscn.share_line":"Series of Tubes scenario settimanale {key} «{name}» vinto il giorno {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Parti da {city} · {d} giorni · {cash}", +"wkscn.under_par_par":"In par o meglio (giorno {par}). Ben fatto.", +"wkscn.weekly_scenario_key":"Scenario della settimana {key}", +"wkscn.won_day_d_par_par":"Vinto il giorno {d} (par {par})", +"wkscn.won_on_day_d":"Vinto il giorno {d}!", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 0dba80c..1eadf43 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilitários", "utilities.two_routers":"Pelo menos dois routers", "utilities.view_pop":"Ver POP", +"wkscn.copy_my_result":"Copiar meu resultado", +"wkscn.desc_a_g_event_comes_to":"No dia {day} chega a {city} um evento de {g}. Construa a rede de que ele precisa, do zero.", +"wkscn.desc_a_ship_dragged_its_anchor":"Um navio arrastou a âncora sobre o {cab}. Encontre outro caminho de {a} a {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Uma firma de trading precisa de {a} a {b} em menos de {ms} ms, todo dia.", +"wkscn.desc_booters_picked_city_for_their":"Os booters escolheram {city} para a semana de folga deles. Segure a linha.", +"wkscn.desc_cab_is_cut_for_the":"{cab} está cortado a partida inteira. O tráfego ainda precisa ir de {a} a {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} hospeda o saco de pancadas favorito da internet. Espere uma enchente a cada poucos dias.", +"wkscn.desc_city_is_just_the_start":"{city} é só o começo: consiga portas em exchanges por toda a {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} está cercada de água e ambição. Conecte as ilhas.", +"wkscn.desc_city_on_a_shoestring":"{city} com o dinheiro contado: cada conta importa.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle e Goggle pararam de se falar de novo. Comece em {city} e alcance todo mundo mesmo assim.", +"wkscn.desc_every_exchange_in_reg_wants":"Todo exchange da {reg} quer conhecer você. Comece em {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Cada milissegundo entre {a} e {b} custa um iate a um trader. Corte-os.", +"wkscn.desc_start_in_city_with_pocket":"Comece em {city} com uns trocados e cresça com o que os clientes pagam.", +"wkscn.desc_start_on_city_and_string":"Comece em {city} e enfie as ilhas num colar, um cabo de cada vez.", +"wkscn.desc_the_whole_city_is_watching":"No dia {day} toda {city} está assistindo. Esteja pronto para levar {g}.", +"wkscn.desc_two_giants_de_peered_over":"Dois gigantes desfizeram o peering por causa de uma planilha. Seus clientes em {city} ainda querem a internet inteira.", +"wkscn.event_name_city":"O grande show da semana em {city}", +"wkscn.goal_a_connected_pop_in_list":"Um POP conectado em {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} a {b} em menos de {ms} ms, {n} dias seguidos", +"wkscn.goal_deliver_the_event_in_city":"Entregue por completo o evento de {g} em {city}, {dur} dias a partir do dia {day}", +"wkscn.goal_g_on_every_hop_from":"{g} em cada salto de {a} a {b}, {n} dias seguidos", +"wkscn.goal_hold_n_floods":"Segure {n} enchentes", +"wkscn.goal_hold_n_floods_big_of":"Segure {n} enchentes, {big} delas de um terabit ou mais", +"wkscn.goal_ports_on_n_exchanges_in":"Portas em {n} exchanges na {reg}", +"wkscn.goal_reach_r_and_serve_g":"Alcance {r}% da internet e entregue {g}", +"wkscn.goal_serve_g":"Entregue {g} de tráfego", +"wkscn.loading_this_week_s_scenario":"Carregando o cenário desta semana…", +"wkscn.name_continental_breakfast":"Café da manhã continental", +"wkscn.name_cut_and_run":"Corta e corre", +"wkscn.name_flood_week":"Semana das enchentes", +"wkscn.name_island_hopper":"Pula-ilhas", +"wkscn.name_light_speed_please":"Na velocidade da luz, por favor", +"wkscn.name_ludicrous_speed":"Velocidade absurda", +"wkscn.name_not_on_speaking_terms":"De mal", +"wkscn.name_packet_monsoon":"Monção de pacotes", +"wkscn.name_party_like_its_1999":"Festa como em 1999", +"wkscn.name_peering_pressure":"Pressão do peering", +"wkscn.name_planting_flags":"Fincando bandeiras", +"wkscn.name_ramen_profitable":"Lucrativo à base de miojo", +"wkscn.name_sea_you_soon":"Até o próximo mar", +"wkscn.name_shoestring_backbone":"Backbone com trocados", +"wkscn.name_stream_team":"Time do streaming", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Próximo cenário semanal em {d} d {h} h", +"wkscn.next_weekly_in_h_m":"Próximo cenário semanal em {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} agora: {ms}", +"wkscn.p_days_in_a_row":"Dias seguidos", +"wkscn.p_event_delivered_in_full":"Evento entregue por completo", +"wkscn.p_exchange_ports_in_reg":"Portas em exchanges na {reg}", +"wkscn.p_g_on_day_d":"{g} no dia {d}", +"wkscn.p_path_g_a_b":"Caminho de {g} {a} → {b}", +"wkscn.par_day_par":"par: dia {par}", +"wkscn.par_was_day_par":"O par era o dia {par}. Quem sabe semana que vem.", +"wkscn.same_scenario_for_everyone_this_week":"O mesmo cenário para todos nesta semana", +"wkscn.share_line":"Series of Tubes cenário semanal {key} “{name}” vencido no dia {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Comece em {city} · {d} dias · {cash}", +"wkscn.under_par_par":"No par ou melhor (dia {par}). Mandou bem.", +"wkscn.weekly_scenario_key":"Cenário semanal {key}", +"wkscn.won_day_d_par_par":"Vencido no dia {d} (par {par})", +"wkscn.won_on_day_d":"Vencido no dia {d}!", }; diff --git a/site/scenarios/weekly/2026-W44.json b/site/scenarios/weekly/2026-W44.json new file mode 100644 index 0000000..8424bfe --- /dev/null +++ b/site/scenarios/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W44","theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":3,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":24,"big":1}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":195,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":1}} diff --git a/site/scenarios/weekly/2026-W45.json b/site/scenarios/weekly/2026-W45.json new file mode 100644 index 0000000..498ff4f --- /dev/null +++ b/site/scenarios/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W45","theme":"event","city":"bog","cash":900000,"days":230,"lvl":2,"rules":{},"mods":[],"goal":{"t":"event","p":{"city":"bog","g":400,"day":159,"dur":3}},"name":{"l":"wkscn.name_party_like_its_1999","p":{}},"desc":{"l":"wkscn.desc_the_whole_city_is_watching","p":{"day":159,"city":"bog","g":400}},"seed":169037385,"par":162,"ref":{"home":"bog","bb":true,"ix":true,"steps":[{"k":"hop","v":["bog","mde",1,null]},{"k":"hop","v":["bog","uio",1,null]}],"avoid":[],"tr2":false,"scrub":0,"event":{"city":"bog","day":159,"g":400}}} diff --git a/site/scenarios/weekly/2026-W46.json b/site/scenarios/weekly/2026-W46.json new file mode 100644 index 0000000..df843d6 --- /dev/null +++ b/site/scenarios/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W46","theme":"spat","city":"fih","cash":750000,"days":250,"lvl":2,"rules":{"spat":true},"mods":[],"goal":{"t":"reach","p":{"r":99,"g":370}},"name":{"l":"wkscn.name_not_on_speaking_terms","p":{}},"desc":{"l":"wkscn.desc_two_giants_de_peered_over","p":{"city":"fih"}},"seed":61791269,"par":183,"ref":{"home":"fih","bb":true,"ix":true,"steps":[{"k":"hop","v":["fih","lad",1,null]},{"k":"hop","v":["fih","dla",1,null]}],"avoid":["cog"],"tr2":true,"scrub":0}} diff --git a/site/scenarios/weekly/index.json b/site/scenarios/weekly/index.json new file mode 100644 index 0000000..8955841 --- /dev/null +++ b/site/scenarios/weekly/index.json @@ -0,0 +1 @@ +{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} diff --git a/site/sw.js b/site/sw.js index 6c895f6..2e0924c 100644 --- a/site/sw.js +++ b/site/sw.js @@ -25,8 +25,8 @@ self.addEventListener('fetch', (e) => { } const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname); if (!local && !fonts) return; - // Weekly puzzles are published between releases: ask the network first, and keep a copy for playing offline. - if (local && url.pathname.startsWith('/puzzles/weekly/')) { + // Weekly puzzles and scenarios are published between releases: ask the network first, and keep a copy for offline. + if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/weekly/'))) { e.respondWith(fetch(req).then((r) => { if (r.ok) { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); } return r; }) .catch(() => caches.match(req).then((r) => r || Response.error()))); return; diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 162138f..a11ca57 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -2,12 +2,11 @@ gives the same world. Free play keeps using the browser's Math.random. */ const _rand=Math.random; Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();}; -function isoWeek(dt){const d=new Date(Date.UTC(dt.getFullYear(),dt.getMonth(),dt.getDate()));const n=d.getUTCDay()||7;d.setUTCDate(d.getUTCDate()+4-n);const y0=new Date(Date.UTC(d.getUTCFullYear(),0,1));return {y:d.getUTCFullYear(),w:Math.ceil(((d-y0)/864e5+1)/7)};} const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name; +const scnName=()=>S.scn.wk?wsTxt(S.scn.wk.name):S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name; const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>l.sub&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size; const brIxN=()=>CITIES.filter(c=>c.br&&S.ixp[c.id]!==undefined).length; const SCN=[ @@ -27,7 +26,8 @@ const SCN=[ ]; const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','scl','hkg']; const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chaos',n:tr('scenarios.twice_the_failures')},{id:'poor',n:tr('scenarios.start_with_only_100k')},{id:'boom',n:tr('scenarios.eyeballs_grow_50_faster')},{id:'dk',n:tr('scenarios.every_ix_is_run_by_de')},{id:'sharks',n:tr('scenarios.shark_season_subsea_cuts_twice_as')}]; -function weekly(){const {y,w}=isoWeek(new Date());let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} +// The in-browser weekly, when no published scenario came: same weeks as the published one (Sunday 06:00 Berlin). +function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);S.mode=o.mode||'normal'; diff --git a/src/game/60-features/70-scenario-progress.js b/src/game/60-features/70-scenario-progress.js index 7ebd962..4436e58 100644 --- a/src/game/60-features/70-scenario-progress.js +++ b/src/game/60-features/70-scenario-progress.js @@ -1,4 +1,5 @@ function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)return; + if(sc.id==='weekly'&&sc.wk){wsTick(d);return;} if(sc.id==='weekly'){if(d>=sc.days){sc.done=d;const score=Math.round(S.stats.peak||0);sc.score=score;let best=null;try{const wk=JSON.parse(localStorage.getItem('sot-weekly')||'{}');best=wk[sc.key];if(!best||score>best){wk[sc.key]=score;localStorage.setItem('sot-weekly',JSON.stringify(wk));}}catch(e){} const h=scnHof();h.weekly=h.weekly||{d:new Date().toISOString().slice(0,10)};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){} openModal(`
${tr('features.weekly_challenge_key',{key:esc(sc.key)})}

${tr('scenario_progress.your_score_score',{score:fmtG(score)})}

${best&&best>score?tr('scenario_progress.peak_traffic_served_in_one_year',{best:fmtG(best)}):best?tr('scenario_progress.peak_traffic_served_in_one_year_c7e5'):tr('scenario_progress.peak_traffic_served_in_one_year_a67b')}

${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);track('weekly_done');}return;} @@ -6,7 +7,7 @@ function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)return; if(ok){sc.done=d;const h=scnHof();if(!h[sc.id]||h[sc.id].days>d)h[sc.id]={d:new Date().toISOString().slice(0,10),days:d};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){}track('scenario_'+sc.id); openModal(`
${tr('common.scenario_complete')}

${tr('scenario_progress.name_done_in_d_days',{name:esc(def.n),d})}

${esc(def.goal)}. ${d

${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}${btn(tr('common.more_scenarios'),'scenarios',{},'ghost')}
`);sfx('coin');} else if(d>=def.days){sc.failed=d;openModal(`
${tr('common.scenario_over')}

${tr('common.time_s_up')}

${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(def.goal),d:def.days})}

${btn(tr('common.try_again'),'startScn',{id:def.id},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);}} -function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){} +function scenarioModal(){wsEnsure();const h=scnHof(); openModal(`
${tr('common.scenarios')}

${tr('scenario_progress.pick_a_challenge')}

-
${tr('features.weekly_challenge_key',{key:esc(wk.key)})}
${tr('scenario_progress.start_in_city_mods_one_year',{city:esc(CITY[wk.city].name),mods:wk.mods.map(m=>esc(m.n)).join(' · ')})}${best?' '+tr('scenario_progress.your_best_best',{best:fmtG(best)}):''}
${btn(tr('common.play'),'startWeekly',{},'pink')}
+ ${wsRow()} ${SCN.map(x=>`
${esc(x.n)} ${h[x.id]?`${tr('features.done_in_d_days',{d:h[x.id].days})}`:''}
${esc(x.d)}
${tr('scenario_progress.goal_goal_time_d_days_start',{goal:esc(x.goal),d:x.days,city:esc(CITY[x.city].name)})}
${btn(tr('common.play'),'startScn',{id:x.id},'')}
`).join('')}`);} diff --git a/src/game/60-features/94-scenarios-weekly.js b/src/game/60-features/94-scenarios-weekly.js new file mode 100644 index 0000000..7d01c02 --- /dev/null +++ b/src/game/60-features/94-scenarios-weekly.js @@ -0,0 +1,125 @@ +/* ================= THE PUBLISHED WEEKLY SCENARIO ================= + The twin of the weekly puzzle: the same weeks (Sunday 06:00 Berlin, pzWeekKey), one themed scenario per week, + published by a GitHub workflow as scenarios/weekly/.json (scripts/weekly-scenario.js) and fetched only when the + Scenarios list opens. The file is data only: a theme, a start, rules from the scenario vocabulary, and a goal TYPE + with its parameters; every goal type is implemented once here, with its progress card. Missing, offline or wrong, + the in-browser weekly() stands in. Like every scenario it runs On-call plus its own rules (M4). */ +// What a {placeholder} holds: c a city, r a region, n a whole number, k a cable id. +const WS_P={a:'c',b:'c',city:'c',reg:'r',n:'n',g:'n',day:'n',ms:'n',cab:'k'}; +const WS_THEMES={ + budget:{i:'🪙',names:[N_('wkscn.name_shoestring_backbone'),N_('wkscn.name_ramen_profitable')],descs:[N_('wkscn.desc_city_on_a_shoestring'),N_('wkscn.desc_start_in_city_with_pocket')]}, + cable:{i:'✂️',names:[N_('wkscn.name_suez_you_later'),N_('wkscn.name_cut_and_run')],descs:[N_('wkscn.desc_cab_is_cut_for_the'),N_('wkscn.desc_a_ship_dragged_its_anchor')]}, + event:{i:'🎉',names:[N_('wkscn.name_party_like_its_1999'),N_('wkscn.name_stream_team')],descs:[N_('wkscn.desc_a_g_event_comes_to'),N_('wkscn.desc_the_whole_city_is_watching')]}, + flood:{i:'🌊',names:[N_('wkscn.name_flood_week'),N_('wkscn.name_packet_monsoon')],descs:[N_('wkscn.desc_city_hosts_the_internets_favourite'),N_('wkscn.desc_booters_picked_city_for_their')]}, + island:{i:'🏝️',names:[N_('wkscn.name_island_hopper'),N_('wkscn.name_sea_you_soon')],descs:[N_('wkscn.desc_start_on_city_and_string'),N_('wkscn.desc_city_is_surrounded_by_water')]}, + latency:{i:'⚡',names:[N_('wkscn.name_ludicrous_speed'),N_('wkscn.name_light_speed_please')],descs:[N_('wkscn.desc_a_trading_firm_needs_a'),N_('wkscn.desc_every_millisecond_between_a_and')]}, + region:{i:'🗺️',names:[N_('wkscn.name_continental_breakfast'),N_('wkscn.name_planting_flags')],descs:[N_('wkscn.desc_city_is_just_the_start'),N_('wkscn.desc_every_exchange_in_reg_wants')]}, + spat:{i:'🙊',names:[N_('wkscn.name_not_on_speaking_terms'),N_('wkscn.name_peering_pressure')],descs:[N_('wkscn.desc_cogentle_and_goggle_stopped_talking'),N_('wkscn.desc_two_giants_de_peered_over')]}, +}; +const wsRun=()=>S.scn.run|0; +const wsIxN=reg=>Object.keys(S.ixp).filter(c=>isIx(c)&&CITY[ixCity(c)]&&CITY[ixCity(c)].reg===reg).length; +const wsCs=p=>p.cs.map(c=>CITY[c].name).join(', '); +// The goal types. p: each parameter's kind and range ([kind,lo,hi]); ok(p) won; m(p) a number the generator calibrates +// against (and the progress bar reads); daily: the goal counts days in a row; prog(p) the card's rows. +const WS_GOALS={ + served:{p:{g:['n',5,50000]},l:N_('wkscn.goal_serve_g'),ok:p=>R.served>=p.g,m:()=>R.served,prog:p=>[pSrv(p.g)]}, + reach:{p:{r:['n',50,99],g:['n',1,50000]},l:N_('wkscn.goal_reach_r_and_serve_g'),ok:p=>R.reach>=p.r/100&&R.served>=p.g,m:()=>R.served,prog:p=>[{l:tr('common.reach'),v:R.reach,max:p.r/100,txt:`${pct(R.reach)} / ${p.r}%`},pSrv(p.g)]}, + path:{p:{a:['c'],b:['c'],g:['n',10,12800],n:['n',1,120]},daily:p=>fastPath(p.a,p.b,p.g),l:N_('wkscn.goal_g_on_every_hop_from'),ok:p=>wsRun()>=p.n,m:()=>wsRun(), + prog:p=>[pChk(tr('wkscn.p_path_g_a_b',{g:fmtG(p.g),a:CITY[p.a].name,b:CITY[p.b].name}),fastPath(p.a,p.b,p.g)),{l:tr('wkscn.p_days_in_a_row'),v:wsRun(),max:p.n,txt:`${wsRun()} / ${p.n}`}]}, + ix:{p:{reg:['r'],n:['n',2,60]},l:N_('wkscn.goal_ports_on_n_exchanges_in'),ok:p=>wsIxN(p.reg)>=p.n,m:p=>wsIxN(p.reg),prog:p=>{const n=wsIxN(p.reg);return [{l:tr('wkscn.p_exchange_ports_in_reg',{reg:WAVE_NAME[p.reg]}),v:n,max:p.n,txt:`${n} / ${p.n}`}];}}, + pops:{p:{cs:['cs',1,8]},l:N_('wkscn.goal_a_connected_pop_in_list'),ok:p=>p.cs.every(c=>pathExists(S.scn.home,c)),m:p=>p.cs.filter(c=>pathExists(S.scn.home,c)).length,prog:p=>p.cs.map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),pathExists(S.scn.home,c)))}, + event:{p:{city:['c'],g:['n',10,6400],day:['n',20,360],dur:['n',1,10]},l:N_('wkscn.goal_deliver_the_event_in_city'),ok:()=>(S.stats.evFull||0)>=1,m:()=>S.stats.evFull||0, + setup:p=>S.biz.push({id:uid(),scripted:true,city:p.city,city2:null,reqs:[],name:tr('wkscn.event_name_city',{city:CITY[p.city].name}),type:'event',bw:p.g,rate:0,mood:100,since:0,start:p.day,dur:p.dur,fee:p.g*p.dur*70}), + prog:p=>[pChk(tr('wkscn.p_event_delivered_in_full'),(S.stats.evFull||0)>=1),{l:tr('common.traffic_served'),v:0,max:0,txt:tr('wkscn.p_g_on_day_d',{g:fmtG(p.g),d:p.day})}]}, + floods:{p:{n:['n',1,60],big:['n',0,20]},l:N_('wkscn.goal_hold_n_floods_big_of'),ok:p=>(S.stats.ddosOk||0)>=p.n&&(S.stats.ddosOkBig||0)>=p.big,m:()=>S.stats.ddosOk||0, + prog:p=>[{l:tr('common.floods_held'),v:S.stats.ddosOk||0,max:p.n,txt:`${S.stats.ddosOk||0} / ${p.n}`},...(p.big?[{l:tr('progress.terabit_floods_held'),v:S.stats.ddosOkBig||0,max:p.big,txt:`${S.stats.ddosOkBig||0} / ${p.big}`}]:[])]}, + lat:{p:{a:['c'],b:['c'],ms:['n',1,400],n:['n',1,120]},daily:p=>bestLat(p.a,p.b)<=p.ms,l:N_('wkscn.goal_a_to_b_under_ms'),ok:p=>wsRun()>=p.n,m:()=>wsRun(), + prog:p=>{const v=bestLat(p.a,p.b);return [pChk(tr('wkscn.p_a_b_now',{a:CITY[p.a].name,b:CITY[p.b].name,ms:isFinite(v)?v.toFixed(1)+' ms':tr('common.no_path')}),v<=p.ms),{l:tr('wkscn.p_days_in_a_row'),v:wsRun(),max:p.n,txt:`${wsRun()} / ${p.n}`}];}}, +}; +// Filled-in text: a label from the file and its typed parameters, in the player's language. +const wsVal=(k,x)=>{const t=WS_P[k];return t==='c'?CITY[x].name:t==='r'?WAVE_NAME[x]:t==='k'?CAB[x].name:k==='g'?fmtG(x):x;}; +const wsTxt=o=>{const v={};for(const k in o.p)v[k]=wsVal(k,o.p[k]);return tr(o.l,v);}; +function wsGoalTxt(j){const G=j.goal,p=G.p,v={};for(const k in p)v[k]=k==='cs'?wsCs(p):WS_P[k]?wsVal(k,p[k]):p[k];return tr(G.t==='floods'&&!p.big?N_('wkscn.goal_hold_n_floods'):WS_GOALS[G.t].l,v);} +// ---------- the file: never trusted ---------- +const WS_FIELDS=['v','key','theme','city','cash','days','lvl','rules','mods','goal','name','desc','seed','par','ref','rev']; +const WS_V=1,WS_RULES=['anchors','banCities','banPairs','ddos','spat']; +const wsPairOk=s=>typeof s==='string'&&CABLE_PAIRS.some(c=>s===`${c.cid}:${c.a}-${c.b}`); +function wsLab(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=WS_P[k],v=own(p,k)?p[k]:undefined; + if(t==='c'&&pzCityOk(v)||t==='r'&&typeof v==='string'&&own(WAVE_NAME,v)||t==='k'&&typeof v==='string'&&own(CAB,v)||t==='n'&&Number.isInteger(v)&&v>0&&v<1e6)out[k]=v;else return null;} + return {l:o.l,p:out};} +function wsGoal(o){if(!pzObj(o)||typeof o.t!=='string'||!own(WS_GOALS,o.t)||!pzObj(o.p))return null;const G=WS_GOALS[o.t],out={}; + if(Object.keys(o.p).length!==Object.keys(G.p).length)return null; + for(const k in G.p){const [t,lo,hi]=G.p[k],v=o.p[k]; + if(t==='c'){if(!pzCityOk(v))return null;}else if(t==='r'){if(typeof v!=='string'||!own(WAVE_NAME,v))return null;} + else if(t==='cs'){if(!Array.isArray(v)||v.lengthhi||!v.every(pzCityOk)||new Set(v).size!==v.length)return null;} + else if(!Number.isInteger(v)||vhi)return null; + out[k]=Array.isArray(v)?v.slice():v;} + if(out.a&&out.a===out.b)return null;return {t:o.t,p:out};} +// A checked copy of the file, or null. The copy is what a game stores and reloads (sanitize() checks it again). +function wsValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!WS_FIELDS.includes(k))||j.v!==WS_V||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(WS_THEMES,j.theme))return null; + const T=WS_THEMES[j.theme],I=(v,lo,hi)=>Number.isInteger(v)&&v>=lo&&v<=hi; + if(!pzCityOk(j.city)||!I(j.cash,50000,2e7)||!I(j.days,60,400)||!I(j.lvl,1,4)||!I(j.seed,1,2**31-1)||!I(j.par,1,j.days))return null; + if(j.rev!==undefined&&!I(j.rev,2,999))return null;if(j.ref!==undefined&&!pzObj(j.ref))return null; + const r=j.rules==null?{}:j.rules;if(!pzObj(r)||Object.keys(r).some(k=>!WS_RULES.includes(k)))return null;const rules={}; + for(const k in r){const v=r[k]; + if(k==='spat'||k==='ddos'){if(v!==true)return null;rules[k]=true;} + else if(k==='anchors'){if(!I(v,1,5))return null;rules[k]=v;} + else if(k==='banCities'){if(!Array.isArray(v)||v.length>6||!v.every(isCity)||v.includes(j.city))return null;rules[k]=v.slice();} + else{if(!Array.isArray(v)||v.length<1||v.length>40||!v.every(wsPairOk))return null;rules[k]=v.slice();}} + const mods=j.mods==null?[]:j.mods;if(!Array.isArray(mods)||mods.length>2||new Set(mods).size!==mods.length||!mods.every(m=>WEEK_MODS.some(x=>x.id===m)))return null; + const goal=wsGoal(j.goal);if(!goal)return null; + // A city the goal needs is never one the rules ban. + if(rules.banCities&&Object.values(goal.p).flat().some(c=>rules.banCities.includes(c)))return null; + if(goal.t==='event'&&goal.p.day+goal.p.dur>=j.days||goal.t==='floods'&&!rules.ddos)return null; + const name=wsLab(j.name,T.names),desc=wsLab(j.desc,T.descs);if(!name||!desc)return null; + const o={v:WS_V,key,theme:j.theme,city:j.city,cash:j.cash,days:j.days,lvl:j.lvl,rules,mods:mods.slice(),goal,name,desc,seed:j.seed,par:j.par};if(j.rev)o.rev=j.rev;return o;} +// ---------- fetching it: when the Scenarios list opens, never on page load ---------- +function wsEnsure(){const key=pzWeekKey(new Date()),w=UI.wsWk; + if(w&&w.key===key&&(w.st!=='fb'||Date.now()-w.at<5*60e3))return; + const st=UI.wsWk={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.wsWk!==st)return;if(def){st.def=def;st.st='ok';}else if(!st.def)st.st='fb';st.at=Date.now();wsRefresh();}; + const ac=window.AbortController?new AbortController():null,to=setTimeout(()=>{if(ac)ac.abort();fin(null);},5000); + if(!window.fetch||location.protocol==='file:'){fin(null);return;} + try{fetch(`scenarios/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>wsValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +const wsDef=()=>{const key=pzWeekKey(new Date()),w=UI.wsWk;return w&&w.key===key&&w.def?w.def:null;}; +const wsLoading=()=>{const w=UI.wsWk;return !!w&&w.st==='load'&&w.key===pzWeekKey(new Date());}; +function wsRefresh(){const el=$('wsRow');if(el)el.outerHTML=wsRow();} +// ---------- the player's record: started weeks (for the badge), wins and the streak ---------- +function wsLoad(){let j=null;try{j=JSON.parse(localStorage.getItem('sot-wkscn')||'null');}catch(e){}const o={go:{},w:{},streak:{last:null,n:0,best:0}};if(!pzObj(j))return o; + const K=/^\d{4}-W\d{2}$/;if(pzObj(j.go))for(const k in j.go)if(K.test(k))o.go[k]=1; + if(pzObj(j.w))for(const k in j.w){const x=j.w[k];if(K.test(k)&&pzObj(x)&&Number.isInteger(x.d)&&x.d>0)o.w[k]={d:x.d,rv:Number.isInteger(x.rv)?x.rv:1};} + const s=j.streak;if(pzObj(s)){o.streak.last=typeof s.last==='string'&&K.test(s.last)?s.last:null;for(const k of ['n','best'])o.streak[k]=Number.isInteger(s[k])&&s[k]>=0?s[k]:0;}return o;} +const wsStore=o=>{try{localStorage.setItem('sot-wkscn',JSON.stringify(o));}catch(e){}}; +// A win counts for its revision: when a week is regenerated (rev), last week's result for it no longer shows. +const wsWin=(o,d)=>{const x=d&&o.w[d.key];return x&&x.rv===(d.rev||1)?x:null;}; +function wsNew(){try{return !wsLoad().go[pzWeekKey(new Date())];}catch(e){return false;}} +const wsStreak=(o,key)=>{const s=o.streak;return s.last===key||s.last===pzPrevKey(key)?s.n:0;}; +// ---------- playing it ---------- +function wsBegin(j,nm){const d=wsValid(j,j&&j.key);if(!d)return false;const G=WS_GOALS[d.goal.t]; + const o=wsLoad();o.go[d.key]=1;wsStore(o); + beginGame(nm||UI.nm||(S&&S.name)||randomNetworkName(),d.city,{seed:d.seed,scn:{id:'weekly',key:d.key,n:wsTxt(d.name),days:d.days,cash:d.cash,rules:JSON.parse(JSON.stringify(d.rules)), + mods:d.mods.map(m=>WEEK_MODS.find(x=>x.id===m)),goal:wsGoalTxt(d),setup:()=>{S.scn.wk=d;S.scn.home=d.city;S.scn.run=0;S.lvl=Math.max(S.lvl||1,d.lvl);if(G.setup)G.setup(d.goal.p);}}}); + return true;} +const wsOk=()=>{const sc=S&&S.scn;if(!sc||!sc.wk)return false;const G=sc.wk.goal;try{return !!WS_GOALS[G.t].ok(G.p);}catch(e){return false;}}; +const wsMeasure=()=>{const G=S.scn.wk.goal;try{return +WS_GOALS[G.t].m(G.p)||0;}catch(e){return 0;}}; +function wsShareText(){const sc=S.scn,d=sc.wk;return tr('wkscn.share_line',{key:sc.key,name:wsTxt(d.name),d:sc.done,par:d.par});} +// Called by scnTick once a day for a published weekly scenario. +function wsTick(d){const sc=S.scn,w=sc.wk,G=WS_GOALS[w.goal.t]; + if(G.daily){let on=false;try{on=!!G.daily(w.goal.p);}catch(e){}sc.run=on?(sc.run|0)+1:0;} + if(wsOk()){sc.done=d;const o=wsLoad(),x=wsWin(o,w);if(!x||x.d>d)o.w[w.key]={d,rv:w.rev||1};const s=o.streak;if(s.last!==w.key){s.n=s.last===pzPrevKey(w.key)?s.n+1:1;s.last=w.key;s.best=Math.max(s.best,s.n);}wsStore(o);track('wkscn_won'); + openModal(`
${T_WS(w)} ${tr('wkscn.weekly_scenario_key',{key:esc(w.key)})}

${tr('wkscn.won_on_day_d',{d})}

${esc(wsGoalTxt(w))}. ${d<=w.par?tr('wkscn.under_par_par',{par:w.par}):tr('wkscn.par_was_day_par',{par:w.par})}

${esc(wsShareText())}

${btn(tr('wkscn.copy_my_result'),'wsShare',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);sfx('coin');} + else if(d>=sc.days){sc.failed=d;openModal(`
${tr('common.scenario_over')}

${tr('common.time_s_up')}

${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(wsGoalTxt(w)),d:sc.days})}

${btn(tr('common.try_again'),'startWeekly',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);}} +const T_WS=w=>(WS_THEMES[w.theme]||{}).i||'📅'; +// The top row of the Scenarios list. +function wsRow(){const d=wsDef(),o=wsLoad(),key=pzWeekKey(new Date()),st=wsStreak(o,key),badge=o.go[key]?'':` ${tr('puzzles.new_this_sunday')}`,cd=`
⏳ ${wsNext(Date.now())}
`; + if(!d){const wk=weekly();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){} + return `
📅 ${tr('wkscn.weekly_scenario_key',{key:esc(wk.key)})}${badge}
${wsLoading()?tr('wkscn.loading_this_week_s_scenario'):tr('features.weekly_challenge_key',{key:esc(wk.key)})}
${tr('scenario_progress.start_in_city_mods_one_year',{city:esc(CITY[wk.city].name),mods:wk.mods.map(m=>esc(m.n)).join(' · ')})}${best?' '+tr('scenario_progress.your_best_best',{best:fmtG(best)}):''}
${cd}
${btn(tr('common.play'),'startWeekly',{},'pink',wsLoading())}
`;} + const x=wsWin(o,d),mods=d.mods.map(m=>esc(WEEK_MODS.find(y=>y.id===m).n)); + return `
📅 ${tr('wkscn.weekly_scenario_key',{key:esc(d.key)})}${badge}
+
${T_WS(d)} ${esc(wsTxt(d.name))} ${x?`${tr('wkscn.won_day_d_par_par',{d:x.d,par:d.par})}`:''}
${esc(wsTxt(d.desc))}
+
🎯 ${esc(wsGoalTxt(d))}
${tr('wkscn.start_in_city_d_days_cash',{city:esc(CITY[d.city].name),d:d.days,cash:fmt$(d.cash)})}${mods.length?' · '+mods.join(' · '):''} · ${tr('wkscn.par_day_par',{par:d.par})}
+
${tr('wkscn.same_scenario_for_everyone_this_week')}${st?' · 🔥 '+trn('puzzles.n_week_streak',st):''}
${cd}
${btn(tr('common.play'),'startWeekly',{},x?'ghost':'pink')}
`;} +function wsNext(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('wkscn.next_weekly_in_d_h',{d,h}):tr('wkscn.next_weekly_in_h_m',{h,m:m%60});} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 3085777..d83a3a8 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -89,7 +89,10 @@ function migrate(s){sanitize(s); // Older saves have one contract per broker sale: fold a carrier's alien waves on one fiber into one contract. {const one=new Map();s.biz=s.biz.filter(b=>{if(b.type!=='wwave')return true;const k=b.link+'|'+b.name,a=one.get(k);if(!a){one.set(k,b);return true;} a.slots=(a.slots||0)+(b.slots||0);a.rate=(a.rate||0)+(b.rate||0);a.since=Math.min(a.since??0,b.since??0);a.mood=Math.min(a.mood??100,b.mood??100);a.folded=true;return false;}); - for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true;for(const b of [...s.biz,...s.offers])if(Array.isArray(b.reqs))b.reqs=b.reqs.filter(k=>!REQS[k]||!REQS[k].can||(isCity(b.city)&&(!b.city2||isCity(b.city2))&&REQS[k].can(b,s)));if(s.ltv!==2){for(const l of s.links)if(l.kind==='wave'&&l.tier>=3)l.tier=Math.min(LT.length-1,l.tier+1);s.ltv=2;}if(s.dk){s.dk.m=s.dk.m||{};s.dk.add=s.dk.add||{};s.dk.ret=s.dk.ret||{};s.dk.retUsed=s.dk.retUsed||{};}s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave'; + for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true; + // A published weekly scenario keeps its file in the save: checked again here; a bad one plays on as the in-browser weekly. + if(s.scn&&typeof s.scn==='object'&&s.scn.wk!==undefined){const d=wsValid(s.scn.wk,s.scn.key);if(d){s.scn.wk=d;s.scn.home=d.city;s.scn.run=Number.isInteger(s.scn.run)&&s.scn.run>=0?s.scn.run:0;}else{delete s.scn.wk;delete s.scn.home;delete s.scn.run;}} + for(const b of [...s.biz,...s.offers])if(Array.isArray(b.reqs))b.reqs=b.reqs.filter(k=>!REQS[k]||!REQS[k].can||(isCity(b.city)&&(!b.city2||isCity(b.city2))&&REQS[k].can(b,s)));if(s.ltv!==2){for(const l of s.links)if(l.kind==='wave'&&l.tier>=3)l.tier=Math.min(LT.length-1,l.tier+1);s.ltv=2;}if(s.dk){s.dk.m=s.dk.m||{};s.dk.add=s.dk.add||{};s.dk.ret=s.dk.ret||{};s.dk.retUsed=s.dk.retUsed||{};}s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave'; for(const c in s.pops){const p=s.pops[c];if(p.rgen===undefined){let g=0;const need=(i,key)=>{const k=RG.findIndex(r=>r[key]>=i);if(k>g)g=k;}; for(const l of s.links||[])if((l.a===c||l.b===c)&&l.kind==='wave')need(l.tier,'maxLT'); for(const t of s.transit||[])if(t.city===c)need(t.tier,'maxP');for(const x of s.pni||[])if(x.city===c)need(x.tier,'maxP');if(s.ixp&&s.ixp[c]!==undefined)need(s.ixp[c],'maxP');p.rgen=g;}}for(const b of s.biz||[])if(!b.reqs)b.reqs=BIZ_T[b.type]&&BIZ_T[b.type].div?['diverse']:[];for(const o of s.offers||[])if(!o.reqs)o.reqs=[];if(!s.lvl)s.lvl=1;s.nni=s.nni||[];s.cnLic=s.cnLic||{state:'none'};s.ev=s.ev||{};for(const l of s.links){if(!l.kind)l.kind='wave';if(l.mo===undefined)l.mo=Math.round(waveMo(l.km,l.sub,l.tier)*(l.mult||1));}for(const c in s.pops){if(!s.pops[c].routers)s.pops[c].routers=1;} diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index d81413e..eb5983f 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -10,7 +10,10 @@ Object.assign(ACT,{ puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');}, scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();}, startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});}, - startWeekly:()=>{const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, + // The published weekly scenario when it came, else the in-browser one. + wsShare:()=>{if(!S||!S.scn||!S.scn.wk||!S.scn.done)return;const t=wsShareText(),copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'); + if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}track('wkscn_share');}, + startWeekly:()=>{const nm=UI.nm||(S&&S.name)||randomNetworkName();if(wsBegin(wsDef(),nm))return;const o=wsLoad();o.go[pzWeekKey(new Date())]=1;wsStore(o);const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;const s=$('homeSel');if(s)s.value=city;const w=$('homeWhat');if(w)w.innerHTML=homeWhat();}, pickHome:({v})=>{if(v)ACT.pickStart({city:v});else ACT.pickStart({city:'fra'});}, // Delete this window's network and go back to the title (the other networks stay). diff --git a/src/game/94-dashboard/10-progress.js b/src/game/94-dashboard/10-progress.js index 111df9b..a400b8e 100644 --- a/src/game/94-dashboard/10-progress.js +++ b/src/game/94-dashboard/10-progress.js @@ -15,6 +15,7 @@ const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.5,txt:`${pct(R.re flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); return [{l:tr('common.floods_held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('progress.terabit_floods_held'),v:big,max:5,txt:`${big} / 5`},{l:tr('progress.floods_that_got_through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('progress.under_attack_now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`})));},baltic:()=>[{l:tr('progress.days_in_a_row_with_99'),v:S.stats.clean||0,max:90,txt:tr('progress.n_of_m',{n:S.stats.clean||0,m:90})}]}; function scnProg(){const sc=S&&S.scn;if(!sc)return null; + if(sc.wk){const G=sc.wk.goal;let items=[];try{items=WS_GOALS[G.t].prog(G.p);}catch(e){}const meas=items.filter(x=>x.max);return {goal:wsGoalTxt(sc.wk),items,f:sc.done?1:meas.length?meas.reduce((a,x)=>a+Math.min(1,x.v/x.max),0)/meas.length:0};} if(sc.id==='weekly')return {goal:tr('common.serve_as_much_traffic_as_you'),items:[{l:tr('progress.your_score_peak_traffic'),v:0,max:0,txt:fmtG(S.stats.peak||0)}],f:Math.min(1,S.day/sc.days)}; const def=SCN.find(x=>x.id===sc.id),fn=SCN_PROG[sc.id];if(!def)return null;let items=[];try{items=fn?fn():[];}catch(e){items=[];} const meas=items.filter(x=>x.max),f=sc.done?1:meas.length?meas.reduce((a,x)=>a+Math.min(1,x.v/x.max),0)/meas.length:0;return {goal:def.goal,items,f};} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index ef1dc02..e1b7c1f 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -40,7 +40,7 @@ const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scena // The chosen preset in one line: its joke, then what actually changes. const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)}`; 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 `
${DOORS.map(([k,i,n,d])=>``).join('')}
+ return `
${DOORS.map(([k,i,n,d])=>``).join('')}
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

${Object.entries(CHAOS).map(([k,C])=>``).join('')}

🔒 ${tr('title.rules_are_picked_once_and_locked')}

`;} diff --git a/src/i18n/en.js b/src/i18n/en.js index c0e470a..cf18cc8 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3604,4 +3604,65 @@ "utilities.title":"Utilities", "utilities.two_routers":"At least two routers", "utilities.view_pop":"View PoP", +"wkscn.copy_my_result":"Copy my result", +"wkscn.desc_a_g_event_comes_to":"A {g} event comes to {city} on day {day}. Build the network it needs, from nothing.", +"wkscn.desc_a_ship_dragged_its_anchor":"A ship dragged its anchor across {cab}. Find another way from {a} to {b}.", +"wkscn.desc_a_trading_firm_needs_a":"A trading firm needs {a} to {b} under {ms} ms, and it needs it every day.", +"wkscn.desc_booters_picked_city_for_their":"The booters picked {city} for their week out. Hold the line.", +"wkscn.desc_cab_is_cut_for_the":"{cab} is cut for the whole run. Traffic still has to get from {a} to {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} hosts the internet's favourite punching bag. Expect a flood every few days.", +"wkscn.desc_city_is_just_the_start":"{city} is just the start: get ports on exchanges all over {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} is surrounded by water and ambition. Connect the islands.", +"wkscn.desc_city_on_a_shoestring":"{city} on a shoestring: little cash, and every bill counts.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle and Goggle have stopped talking again. Start in {city} and reach everyone anyway.", +"wkscn.desc_every_exchange_in_reg_wants":"Every exchange in {reg} wants to meet you. Start in {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Every millisecond between {a} and {b} costs a trader a yacht. Shave them off.", +"wkscn.desc_start_in_city_with_pocket":"Start in {city} with pocket money and grow on what the customers pay.", +"wkscn.desc_start_on_city_and_string":"Start on {city} and string the islands together, one cable at a time.", +"wkscn.desc_the_whole_city_is_watching":"On day {day} all of {city} is watching. Be ready to carry {g}.", +"wkscn.desc_two_giants_de_peered_over":"Two giants de-peered over a spreadsheet. Your customers in {city} still want the whole internet.", +"wkscn.event_name_city":"The Big Weekly Show in {city}", +"wkscn.goal_a_connected_pop_in_list":"A connected POP in {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} to {b} under {ms} ms, {n} days in a row", +"wkscn.goal_deliver_the_event_in_city":"Deliver the {g} event in {city} in full, {dur} days from day {day}", +"wkscn.goal_g_on_every_hop_from":"{g} on every hop from {a} to {b}, {n} days in a row", +"wkscn.goal_hold_n_floods":"Hold {n} floods", +"wkscn.goal_hold_n_floods_big_of":"Hold {n} floods, {big} of them a terabit or more", +"wkscn.goal_ports_on_n_exchanges_in":"Ports on {n} exchanges in {reg}", +"wkscn.goal_reach_r_and_serve_g":"Reach {r}% of the internet and serve {g}", +"wkscn.goal_serve_g":"Serve {g} of traffic", +"wkscn.loading_this_week_s_scenario":"Loading this week's scenario…", +"wkscn.name_continental_breakfast":"Continental Breakfast", +"wkscn.name_cut_and_run":"Cut and Run", +"wkscn.name_flood_week":"Flood Week", +"wkscn.name_island_hopper":"Island Hopper", +"wkscn.name_light_speed_please":"Light Speed, Please", +"wkscn.name_ludicrous_speed":"Ludicrous Speed", +"wkscn.name_not_on_speaking_terms":"Not On Speaking Terms", +"wkscn.name_packet_monsoon":"Packet Monsoon", +"wkscn.name_party_like_its_1999":"Party Like It's 1999", +"wkscn.name_peering_pressure":"Peering Pressure", +"wkscn.name_planting_flags":"Planting Flags", +"wkscn.name_ramen_profitable":"Ramen Profitable", +"wkscn.name_sea_you_soon":"Sea You Soon", +"wkscn.name_shoestring_backbone":"Shoestring Backbone", +"wkscn.name_stream_team":"Stream Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Next weekly scenario in {d} d {h} h", +"wkscn.next_weekly_in_h_m":"Next weekly scenario in {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} now: {ms}", +"wkscn.p_days_in_a_row":"Days in a row", +"wkscn.p_event_delivered_in_full":"Event delivered in full", +"wkscn.p_exchange_ports_in_reg":"Exchange ports in {reg}", +"wkscn.p_g_on_day_d":"{g} on day {d}", +"wkscn.p_path_g_a_b":"{g} path {a} → {b}", +"wkscn.par_day_par":"par: day {par}", +"wkscn.par_was_day_par":"Par was day {par}. Next week, maybe.", +"wkscn.same_scenario_for_everyone_this_week":"Same scenario for everyone this week", +"wkscn.share_line":"Series of Tubes weekly {key} “{name}” won day {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Start in {city} · {d} days · {cash}", +"wkscn.under_par_par":"At or under par (day {par}). Nicely done.", +"wkscn.weekly_scenario_key":"Weekly scenario {key}", +"wkscn.won_day_d_par_par":"Won day {d} (par {par})", +"wkscn.won_on_day_d":"Won on day {d}!", }; diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 3c2c1f7..5123f89 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -282,6 +282,16 @@ test('C1: every scenario has a goal its card checks, and none is won on day 0', if (g.ev(`(()=>{try{return !!${def}.ok();}catch(e){return false;}})()`)) bad.push(id + ': won on day 0'); if (!g.ev(`typeof SCN_PROG['${id}']==='function'&&scnProg().items.length>0`)) bad.push(id + ': no progress card (SCN_PROG)'); } + // The published weekly scenarios too: each committed week starts, has its goal type's card, and needs play. + const wdir = path.join(__dirname, '..', 'site', 'scenarios', 'weekly'); + for (const f of fs.readdirSync(wdir).filter((x) => /^\d{4}-W\d{2}\.json$/.test(x))) { + const j = fs.readFileSync(path.join(wdir, f), 'utf8'), id = 'weekly ' + f.slice(0, -5); + if (!g.ev(`wsBegin(${j},'S')`)) { bad.push(id + ': the game rejects it'); continue; } + g.ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute()'); + if (g.ev('wsOk()')) bad.push(id + ': won on day 0'); + if (!g.ev('scnProg().items.length>0&&!!scnName()&&!!wsGoalTxt(S.scn.wk)')) bad.push(id + ': no progress card or goal'); + if (g.ev('S.rules.preset') !== 'oncall') bad.push(id + ': not On-call (M4)'); + } fail('C1', bad, 'give it n, d, goal, ok(), days, a city and a SCN_PROG entry; its goal must need play'); assert.deepEqual(g.errors, []); }); diff --git a/tests/weekly-scenario.test.js b/tests/weekly-scenario.test.js new file mode 100644 index 0000000..22906f7 --- /dev/null +++ b/tests/weekly-scenario.test.js @@ -0,0 +1,208 @@ +// The published weekly scenario: the generator (scripts/weekly-scenario.js) and its reference player, --check, and the +// game's side: fetched only when the Scenarios list opens, validated strictly, the in-browser weekly as the fallback, +// a goal type and progress card for each kind of week, the win, the streak and the share line. +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-scenario'); + +const DIR = path.join(__dirname, '..', 'site', 'scenarios', 'weekly'); +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-wkscn-')); +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)); +const serveFile = (ev, j) => ev(`UI.wsWk=null;window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(j)})})`); +// One file per goal type, from the committed ones where a week has it: enough to check every card. +const GOALS = { + served: { theme: 'budget', goal: { t: 'served', p: { g: 200 } }, desc: { l: 'wkscn.desc_city_on_a_shoestring', p: { city: 'fra' } } }, + reach: { theme: 'spat', rules: { spat: true }, goal: { t: 'reach', p: { r: 99, g: 150 } }, desc: { l: 'wkscn.desc_two_giants_de_peered_over', p: { city: 'fra' } } }, + path: { theme: 'cable', rules: { banPairs: ['grace:nyc-lon'] }, goal: { t: 'path', p: { a: 'fra', b: 'nyc', g: 400, n: 30 } }, desc: { l: 'wkscn.desc_cab_is_cut_for_the', p: { cab: 'grace', a: 'fra', b: 'nyc' } } }, + ix: { theme: 'region', goal: { t: 'ix', p: { reg: 'EU', n: 8 } }, desc: { l: 'wkscn.desc_every_exchange_in_reg_wants', p: { reg: 'EU', city: 'fra' } } }, + pops: { theme: 'island', goal: { t: 'pops', p: { cs: ['ams', 'par'] } }, desc: { l: 'wkscn.desc_city_is_surrounded_by_water', p: { city: 'fra' } } }, + event: { theme: 'event', goal: { t: 'event', p: { city: 'fra', g: 400, day: 120, dur: 3 } }, desc: { l: 'wkscn.desc_a_g_event_comes_to', p: { g: 400, city: 'fra', day: 120 } } }, + floods: { theme: 'flood', rules: { ddos: true }, goal: { t: 'floods', p: { n: 20, big: 2 } }, desc: { l: 'wkscn.desc_booters_picked_city_for_their', p: { city: 'fra' } } }, + lat: { theme: 'latency', goal: { t: 'lat', p: { a: 'fra', b: 'nyc', ms: 40, n: 30 } }, desc: { l: 'wkscn.desc_a_trading_firm_needs_a', p: { a: 'fra', b: 'nyc', ms: 40 } } }, +}; +const NAME = { budget: 'wkscn.name_shoestring_backbone', spat: 'wkscn.name_peering_pressure', cable: 'wkscn.name_cut_and_run', region: 'wkscn.name_planting_flags', island: 'wkscn.name_island_hopper', event: 'wkscn.name_stream_team', flood: 'wkscn.name_flood_week', latency: 'wkscn.name_ludicrous_speed' }; +const fileFor = (t, key) => { const x = GOALS[t]; return { v: 1, key, theme: x.theme, city: 'fra', cash: 500000, days: 240, lvl: 2, rules: x.rules || {}, mods: [], goal: x.goal, name: { l: NAME[x.theme], p: {} }, desc: x.desc, seed: 42, par: 180, ref: { steps: [] } }; }; + +test('generator: deterministic for a week, and every theme a template the game knows', () => { + const g = G.game(), a = tmp(), b = tmp(); + const j1 = G.generate(g, '2027-W10', a), j2 = G.generate(G.game(), '2027-W10', b); + assert.deepEqual(j1, j2, 'same key, same scenario'); + const themes = JSON.parse(g.ev('JSON.stringify(Object.keys(WS_THEMES))')).sort(), goals = JSON.parse(g.ev('JSON.stringify(Object.keys(WS_GOALS))')); + assert.deepEqual(Object.keys(G.TEMPLATES).sort(), themes, 'a template for each theme'); + for (const T of Object.values(G.TEMPLATES)) assert.ok(goals.includes(T.goal), `${T.goal} is a goal type of the game`); + assert.deepEqual(g.errors, []); +}); + +test('every committed week verifies: not won on day 0, the reference wins on its par with time to spare', () => { + const g = G.game(), files = committed(); + assert.ok(files.length >= 3, 'this week and the next two are committed'); + for (const j of files) { + const v = G.verify(g, j); + assert.ok(v.ok, `${j.key}: ${v.why}`); + assert.equal(v.par, j.par, `${j.key}: par`); + assert.ok(j.days >= 180 && j.days <= 365, `${j.key}: ${j.days} days, playable in a sitting or two`); + } + // Varied: no theme twice in a row, and the weeks start in different parts of the world. + for (let i = 1; i < files.length; i++) assert.notEqual(files[i].theme, files[i - 1].theme); + assert.equal(new Set(files.map((f) => g.ev(`CITY['${f.city}'].reg`))).size, files.length); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(DIR, 'index.json'), 'utf8')), { v: 1, weeks: G.list(DIR) }); + assert.deepEqual(g.errors, []); +}); + +test('the file is checked field by field, and --check rejects a tampered one', () => { + const { ev, errors } = load(), j = committed()[0], ok = (x, key = j.key) => ev(`!!wsValid(${JSON.stringify(x)},'${key}')`); + assert.equal(ok(j), true); + const bad = { + 'another week': [j, '2020-W01'], 'not a week': [{ ...j, key: '2026-W99' }, '2026-W99'], + 'unknown field': [{ ...j, x: 1 }], 'old schema': [{ ...j, v: 0 }], 'unknown theme': [{ ...j, theme: 'pirates' }], + 'unknown city': [{ ...j, city: 'nope' }], 'days': [{ ...j, days: 5000 }], 'cash': [{ ...j, cash: -1 }], 'par after the end': [{ ...j, par: j.days + 1 }], + 'seed': [{ ...j, seed: 1.5 }], 'unknown rule': [{ ...j, rules: { noTransit: true } }], 'rule value': [{ ...j, rules: { spat: 'yes' } }], + 'bogus cable pair': [{ ...j, rules: { banPairs: ['nope:a-b'] } }], 'home banned': [{ ...j, rules: { banCities: [j.city] } }], + 'unknown mod': [{ ...j, mods: ['godmode'] }], 'too many mods': [{ ...j, mods: ['pricey', 'chaos', 'poor'] }], + 'unknown goal type': [{ ...j, goal: { t: 'win', p: {} } }], 'goal number': [{ ...j, goal: { t: 'served', p: { g: 1e9 } } }], + 'goal missing a parameter': [{ ...j, goal: { t: 'path', p: { a: 'fra', b: 'nyc', g: 100 } } }], + 'goal extra parameter': [{ ...j, goal: { t: 'served', p: { g: 100, x: 1 } } }], 'goal city': [{ ...j, goal: { t: 'lat', p: { a: 'fra', b: 'fra', ms: 10, n: 5 } } }], + 'floods without the flood rule': [{ ...j, rules: {}, goal: { t: 'floods', p: { n: 5, big: 0 } } }], + 'event after the end': [{ ...j, goal: { t: 'event', p: { city: j.city, g: 100, day: 360, dur: 5 } }, days: 300 }], + 'name from another theme': [{ ...j, name: { l: 'puzzles_weekly.detour', p: {} } }], 'text with code': [{ ...j, desc: { l: j.desc.l, p: { ...j.desc.p, x: '' } } }], + 'label placeholder': [{ ...j, desc: { l: j.desc.l, p: Object.fromEntries(Object.keys(j.desc.p).map((k) => [k, 'nope'])) } }], + }; + for (const [why, [x, key]] of Object.entries(bad)) assert.equal(ok(x, key || x.key), false, why); + const dir = tmp(); + for (const f of committed()) fs.writeFileSync(path.join(dir, f.key + '.json'), JSON.stringify(f) + '\n'); + fs.copyFileSync(path.join(DIR, 'index.json'), path.join(dir, 'index.json')); + fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'win', p: {} } })); + const g = G.game(); + assert.deepEqual(G.check(g, dir, 0).filter((x) => x.startsWith(j.key)), [`${j.key}: the game rejects it`]); + assert.deepEqual(errors, []); +}); + +test('--check: a week the reference no longer wins is regenerated as a new revision, a new par is just written', () => { + const g = G.game(), dir = tmp(), j = committed()[0]; + fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, par: j.par + 1 }) + '\n'); + const now = g.ev(`pzWeekStart('${j.key}')`); + let r = G.refresh(g, dir, now); + assert.ok(r.fixed.includes(`${j.key}: new par ${j.par}`), r.fixed.join('; ')); + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')).rev, undefined, 'a new par keeps the revision'); + // A goal its reference plan never reaches: as if a release changed the world under the week. + fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'pops', p: { cs: ['scl'] } }, ref: { ...j.ref, steps: [] } }) + '\n'); + r = G.refresh(g, dir, now); + const n = JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')); + assert.equal(n.rev, 2, r.fixed.join('; ') + r.bad.join('; ')); + assert.ok(G.verify(g, n).ok); + // Past weeks keep their files. + assert.deepEqual(G.refresh(g, dir, now + 30 * 864e5).fixed, []); + assert.deepEqual(G.check(g, dir, now), []); + assert.deepEqual(g.errors, []); +}); + +test('the page never asks for a weekly scenario on load, only when the Scenarios list 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=>/scenarios/.test(u)).length"), 0, 'nothing on the title screen'); + ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()"); + assert.equal(ev("__f.filter(u=>/scenarios/.test(u)).length"), 0, 'nothing while playing'); + ev('ACT.scenarios({})'); + const key = ev('pzWeekKey(new Date())'); + assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/scenarios/.test(u)))"), JSON.stringify([`scenarios/weekly/${key}.json`])); + ev('closeModal();ACT.scenarios({})'); + assert.equal(ev("__f.filter(u=>/scenarios/.test(u)).length"), 1, 'once is enough while it is loading'); + await tick(); + assert.deepEqual(errors, []); +}); + +test('the published scenario is played when it is good, the in-browser weekly when it is missing, offline or bad', async () => { + const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())'), good = { ...committed()[1], key }; + 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, city: 'nope' })})})`, 'an unknown city'], + [`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'], + ]) { + ev(`UI.wsWk=null;window.fetch=()=>${how}`); ev('ACT.scenarios({})'); await tick(); + assert.equal(ev('wsDef()'), null, why); + assert.match(dom.window.document.getElementById('wsRow').textContent, new RegExp(ev(`tr('features.weekly_challenge_key',{key:'${key}'})`)), why); + ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev("S.scn.id==='weekly'&&!S.scn.wk&&S.scn.key"), key, `${why}: the in-browser weekly`); + } + serveFile(ev, good); ev('ACT.scenarios({})'); await tick(); + assert.match(dom.window.document.getElementById('wsRow').textContent, new RegExp(ev('wsTxt(wsDef().name)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); + ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('S.scn.wk.key'), key); + assert.equal(ev('S.rules.preset'), 'oncall', 'M4: On-call'); + assert.equal(ev('S.cash'), good.mods.includes('poor') ? 100000 : good.cash); + assert.deepEqual(errors, []); +}); + +test('every goal type has a progress card, needs play, and wins, streaks and shares', () => { + const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())'); + for (const t of Object.keys(GOALS)) { + const f = fileFor(t, key); + assert.equal(ev(`wsBegin(${JSON.stringify(f)},'T')`), true, t); + ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute();renderAll()'); + assert.equal(ev('wsOk()'), false, `${t}: not won on day 0`); + assert.ok(ev('scnProg().items.length') > 0, `${t}: a progress card`); + const card = ev('scnCard()'); + assert.doesNotMatch(card, /wkscn\.|\{\w+\}|undefined|NaN/, `${t}: ${card}`); + if (t === 'event') assert.equal(ev("S.biz.filter(b=>b.type==='event'&&b.start===120&&b.bw===400).length"), 1, 'the event is booked'); + if (t === 'floods') assert.equal(ev("scnRule('ddos')"), true); + } + // A win: a POP goal met on day 1, recorded for the week, with a streak and the share line. + ev("localStorage.removeItem('sot-wkscn')"); + ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`); + // Waves take a few days to light (real lead times), so the goal is met once they are up. + const build = "for(const c of ['ams','par']){UI.via=null;openLinkModal('fra',c);ACT.buildLink({tier:1});closeModal();}for(let i=0;i<90&&!S.scn.done;i++)dayTick()"; + ev(build); + const d = ev('S.scn.done'); + assert.ok(d > 0 && d < 90, `won on day ${d}`); + assert.match(dom.window.document.getElementById('modal').textContent, new RegExp(`Won on day ${d}!`)); + assert.equal(ev('wsShareText()'), `Series of Tubes weekly ${key} “Island Hopper” won day ${d} (par 180) · seriesoftub.es`); + const rec = JSON.parse(ev("localStorage.getItem('sot-wkscn')")); + assert.deepEqual(rec.w[key], { d, rv: 1 }); + assert.equal(rec.streak.n, 1); + // Last week won too: the streak grows; a gap starts it again. + ev(`localStorage.setItem('sot-wkscn',JSON.stringify({go:{},w:{},streak:{last:pzPrevKey('${key}'),n:3,best:3}}))`); + ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`); + ev(build); + assert.equal(JSON.parse(ev("localStorage.getItem('sot-wkscn')")).streak.n, 4); + assert.equal(ev(`wsStreak(wsLoad(),pzKeyAdd('${key}',2))`), 0); + assert.deepEqual(errors, []); +}); + +test('saves keep the scenario, checked again on load; a tampered one plays on as the in-browser weekly', () => { + const { ev, errors } = load(), key = ev('pzWeekKey(new Date())'); + ev(`wsBegin(${JSON.stringify(fileFor('path', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal();S.scn.run=7`); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev("S.scn.wk.goal.t+':'+S.scn.run+':'+S.scn.home"), 'path:7:fra'); + ev("S.scn.wk.goal={t:'win',p:{}};S.scn.run='x';S=migrate(JSON.parse(JSON.stringify(S)));compute();renderAll()"); + assert.equal(ev("S.scn.id+':'+(S.scn.wk===undefined)+':'+(S.scn.run===undefined)"), 'weekly:true:true'); + ev('for(let i=0;i<3;i++)dayTick();scnCard()'); + assert.deepEqual(errors, []); +}); + +test('weekly scenario in every language and on a 360 px phone, with the door badge until started', async () => { + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, dom, errors } = load({ lang }), key = ev('pzWeekKey(new Date())'), doc = dom.window.document; + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()"); + const badge = () => !!doc.querySelector('.door[data-door=scn] .pznew'); + assert.equal(badge(), true, `${lang}: badge before the week is started`); + for (const j of committed()) { + serveFile(ev, { ...j, key }); ev('ACT.scenarios({})'); await tick(); + const row = doc.getElementById('wsRow'); + assert.doesNotMatch(row.textContent, /wkscn\.|\{\w+\}|undefined|NaN/, `${lang} ${j.key}: no raw labels or placeholders`); + assert.notEqual(ev('wsTxt(wsDef().desc)'), ev("(d=>EN[d.l].replace(/\\{(\\w+)\\}/g,(m,k)=>wsVal(k,d.p[k])))(wsDef().desc)"), `${lang}: translated text`); + ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip();closeModal();renderAll()"); + assert.doesNotMatch(ev('scnCard()'), /wkscn\.|\{\w+\}|undefined|NaN/, `${lang} ${j.key}: card`); + } + ev('showTitle()'); + assert.equal(badge(), false, `${lang}: no badge once started`); + assert.deepEqual(errors, [], lang); + } +});