diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index 3eafcfb..f57d959 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -40,6 +40,14 @@ publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 np `pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the steps. +**The one exception: the weekly puzzle.** Every Sunday at 03:37 UTC `weekly-puzzle.yml` commits the new +`site/puzzles/weekly/.json` to `main` (data only, no version bump) and starts `release.yml` for the **live +release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main` +added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group. +Players get no update banner (the version does not change). Every release build also copies all weekly files from +`main`, so a release never drops a published week. Weekly files are plain JSON the game fetches only when the +Puzzles list opens and never trusts; the service worker serves them network-first. See `docs/ARCHITECTURE.md`. + ## Before you hand back a change that touches the build, deploy or loading ```bash diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 79087df..0378f48 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -12,6 +12,15 @@ that version's CHANGELOG section as notes, and dispatches `release.yml`, which b to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the `github-pages` skill. +## Weekly puzzles are not releases + +`weekly-puzzle.yml` publishes a new puzzle every Sunday morning without a release: it commits the JSON under +`site/puzzles/weekly/` to `main` and redeploys the live tag through `release.yml` (`weekly=true`). Never bump the +version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly-puzzle.js --key 2026-W45 --force`, +`node scripts/weekly-puzzle.js --check`, commit to `main`, then run the "Weekly puzzle" workflow (or +`gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly +file on `main` when it builds. + ## Only release when Frederic says so Never bump the version on your own. Finished work is committed and pushed with its diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index da224da..801aee4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,7 +4,8 @@ name: Release to GitHub Pages # Pushes to main run CI but never deploy. To ship: bump "version" in # package.json and date its CHANGELOG section; auto-release.yml then tags, # publishes the release and starts this workflow from the tag. Publishing a -# release by hand works too. +# release by hand works too. Every Sunday weekly-puzzle.yml redeploys the live +# release from its tag with the new weekly puzzle added (input weekly). on: release: # "released" also fires when a pre-release is promoted to a full release. @@ -18,6 +19,10 @@ on: description: Allow deploying a version older than what is live (rollback) type: boolean default: false + weekly: + description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped + type: boolean + default: false # Least privilege: only the deploy job can write to Pages. permissions: @@ -63,8 +68,28 @@ jobs: if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1 fi + # Weekly puzzles are published on main between releases (weekly-puzzle.yml). Every deploy ships all of them, + # so neither a release nor a weekly redeploy ever drops a week that is already out. + - name: Weekly puzzles from main + run: | + set -euo pipefail + git fetch --no-tags --depth=1 origin main + if git cat-file -e FETCH_HEAD:site/puzzles/weekly 2>/dev/null; then + rm -rf site/puzzles/weekly + git checkout FETCH_HEAD -- site/puzzles/weekly + echo "Weekly puzzles: $(ls site/puzzles/weekly | grep -c '^[0-9].*\.json$')" + fi - run: npm ci - run: npm test + if: ${{ !inputs.weekly }} + - name: Check the weekly puzzles against this release + if: ${{ inputs.weekly }} + run: | + set -euo pipefail + # A release from before the weekly puzzles ships the files without reading them: nothing to check. + if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi + node scripts/weekly-puzzle.js --check + npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - uses: actions/upload-pages-artifact@v5 @@ -88,6 +113,7 @@ jobs: # the site is live. indexnow: needs: deploy + if: ${{ !inputs.weekly }} runs-on: ubuntu-latest env: # IndexNow keys are public by design (also served at /.txt). diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml new file mode 100644 index 0000000..09cf814 --- /dev/null +++ b/.github/workflows/weekly-puzzle.yml @@ -0,0 +1,80 @@ +name: Weekly puzzle + +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), commit it to main as a data-only +# change, and redeploy the live release with it. Puzzle weeks start Sunday 06:00 Berlin time; 03:37 UTC is +# 04:37 in winter and 05:37 in summer, so the file is live before the week starts either way. +# +# No version bump, so no release: auto-release.yml only runs when package.json changes (and pushes made with +# the workflow token start no workflows at all). The deploy itself is release.yml, still the only workflow +# that can write to Pages, started from the live release's tag with weekly=true: it rebuilds exactly that +# release with every weekly puzzle from main added, in the same "pages" concurrency group as any release. +on: + schedule: + - cron: '37 3 * * 0' + workflow_dispatch: + inputs: + key: + description: Week to make, e.g. 2026-W45 (default the week starting this Sunday) + required: false + deploy: + description: Redeploy the live release with it + type: boolean + default: true + +permissions: + contents: write # commit the puzzle to main + actions: write # start release.yml + +concurrency: + group: weekly-puzzle + cancel-in-progress: false + +jobs: + puzzle: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + GH_TOKEN: ${{ github.token }} + KEY: ${{ inputs.key }} + steps: + - uses: actions/checkout@v7 + with: + ref: main + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Make the puzzle + run: | + set -euo pipefail + if [ -n "$KEY" ]; then + [[ "$KEY" =~ ^[0-9]{4}-W[0-9]{2}$ ]] || { echo "::error::$KEY is not a week key"; exit 1; } + node scripts/weekly-puzzle.js --key "$KEY" + else + node scripts/weekly-puzzle.js + fi + - name: Check every weekly puzzle + run: node scripts/weekly-puzzle.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js + - name: Commit it to main + run: | + set -euo pipefail + git add site/puzzles/weekly + # Data only: anything else changed means something is wrong. + if git status --porcelain | grep -v ' site/puzzles/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi + if git diff --cached --quiet; then echo "Nothing new to commit."; exit 0; fi + git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -m "Weekly puzzle $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')" + git push origin HEAD:main + - name: Redeploy the live release with it + if: github.event_name == 'schedule' || inputs.deploy + run: | + set -euo pipefail + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --exclude-drafts --limit 1 --json tagName -q '.[0].tagName') + [ -n "$tag" ] || { echo "::error::no release to redeploy"; exit 1; } + # Releases from before the weekly puzzles cannot take them (and their game would not read them). + if ! git fetch --no-tags --depth=1 origin "refs/tags/$tag" || ! git show FETCH_HEAD:.github/workflows/release.yml | grep -q '^ weekly:'; then + echo "::notice::$tag predates weekly puzzles; the puzzle is on main and ships with the next release."; exit 0 + fi + gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$tag" -f tag="$tag" -f weekly=true + echo "Redeploying $tag with the weekly puzzles." diff --git a/CHANGELOG.md b/CHANGELOG.md index e4abd57..6663165 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,18 +6,17 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. - A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. - Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips the peering inbox, hardware shortages and sold-out routes. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. - Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. -- Puzzles: small, calm network builds you can finish in a coffee break (#190). Connect a few cities on the real map with POPs and leased waves, with no clock, no bills and nothing breaking, and earn up to three stars: one for the goal, one for staying under budget, and one if the network survives any single cut. Eighteen puzzles in four packs (more stars open the next pack), some with a twist like a latency target, no subsea cables or a ring, plus a weekly puzzle that is the same for everyone, with a streak and a result to share. Puzzles never touch your saved network; only your stars are kept. +- Puzzles: small, calm network builds you can finish in a coffee break (#190). Connect a few cities on the real map with POPs and leased waves, with no clock, no bills and nothing breaking, and earn up to three stars: one for the goal, one for staying under budget, and one if the network survives any single cut (a trench, or a whole cable). Eighteen puzzles in four packs, with roomy budgets at first and tighter ones as you go (more stars open the next pack), some with a twist like a latency target, no subsea cables or a ring, plus a weekly puzzle that is the same for everyone, with a streak and a result to share. Puzzles never touch your saved network; only your stars are kept. - 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. -- Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge again under harder rules upgrades its look, and the badge list counts your collection of each kind on this device. On-call games earn the standard badges; Sandbox and puzzles earn none. -- China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. -- Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them. -- Glowball Sakura Lager joins the map: a Tier 2 carrier in the big hubs of the US, Europe and Asia-Pacific that sells transit, takes PNIs and peers openly wherever it is. It is not a Tier 1, so it buys its own transit from three of them, while 13 smaller networks in its regions buy theirs from it, and one PNI with it reaches about 3% of all traffic. Far from home, in Asia and New Zealand, it charges more than the locals, and it sells no transit in Australia. +- Only Spätzle-IX now asks for 50% reach instead of 45%, since peering with the Tier 1 club brings their customers along. Two Tier 1 PNIs and the exchange are no longer quite enough (#114). +- Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge under harder rules than before upgrades it in your collection on this device, and the badge list counts how many of each kind you have. On-call games earn the standard badges; Sandbox and puzzles earn none. - Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network. - Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link. -- Prices now follow how connected each city really is, based on PeeringDB and Hurricane Electric data. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. +- Prices now follow how connected each city really is, based on public peering and routing data. Every city on the map now has it, from Düsseldorf and Riga to Malé, the Caribbean and the Russian Arctic. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. - Attacks are more varied: sizes, lengths and ingress ports change from one attack to the next, and several can hit at once. Hosting game servers or cloud gaming makes attacks more frequent, as it does in real life. - The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels. - Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. @@ -29,13 +28,20 @@ All notable changes to this project are documented here. The project follows - DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center. - Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation. - Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. -- Order PNIs with one network or every network at all shared POPs from the NOC Traffic tab: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. -- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. -- 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, and the intern writes one line a day in the NOC (#98, #100, #102, #181, #185, #192, #177). +- Order PNIs with one network or every network at all shared POPs from the Ops sheet: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. +- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. A POP's Infra tab shows the redundancy kit as one line with its price, above the rows it fills 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). - Open a new city from a template in one tap: POP, broadband, transit, an IX port and the redundancy kit, priced up front, with your standing orders taking it from there (#98, #192). - Auto-accept and auto-pay repairs are now the intern's sales and repair orders and run once a game day; saved games keep both switched on, and they start working once you hire an intern. The bulk peering and PNI batches moved into the Ops sheet, next to the orders that repeat them (#185, #181, #192). - Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. - Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. +- The intern only signs a customer after a trial run shows the network can carry them without hurting anyone else, and rushes every repair that has a price, while the budget lasts (#185). The bulk peering and PNI batches live in the Ops sheet, next to the orders that repeat them (#181, #192). + +## [1.37.0] — 2026-10-28 + +- Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them. +- Glowball Sakura Lager joins the map: a Tier 2 carrier in the big hubs of the US, Europe and Asia-Pacific that sells transit, takes PNIs and peers openly wherever it is. It is not a Tier 1, so it buys its own transit from three of them, while 13 smaller networks in its regions buy theirs from it, and one PNI with it reaches about 3% of all traffic. Far from home, in Asia and New Zealand, it charges more than the locals, and it sells no transit in Australia. +- China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. ## [1.36.0] — 2026-10-28 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1e23b3b..c25fdae 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -29,7 +29,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) | | `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) | | `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` | -| `60-features/` | Banks and loans, scenarios and the weekly challenge, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) | +| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) | | `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering inbox, peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | | `80-simulation/` | Dijkstra, RouteScript, `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service | | `85-incidents/` | `addInc()`, DDoS and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` | @@ -72,6 +72,8 @@ Development runs on `npm run dev` (assembles on every request, reloads on save); | `.github/workflows/ci.yml` | Tests and build on every push and PR | | `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test, tag, GitHub release from the CHANGELOG, start the deploy | | `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can | +| `.github/workflows/weekly-puzzle.yml` | Sunday 03:37 UTC: makes the week's puzzle, commits it to `main` (data only, no release) and starts `release.yml` for the live release tag with `weekly=true` | +| `scripts/weekly-puzzle.js`, `site/puzzles/weekly/` | The weekly puzzle generator and its output, one `.json` per week plus `index.json` (see below) | | `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) | ## Globals @@ -100,7 +102,8 @@ never freezes the game. 4. Rolls failures (`fireFailure()`) and events (`fireEvent()`) when their timers run out, and expires incidents. Then the NOC intern's standing orders (`opsDay()`), if one is hired: each order clicks the same `ACT` - actions a player would, muted, within its monthly budget, and the shift recomputes once at the end. + actions a player would, muted, within its monthly budget, and the shift recomputes once at the end, only if + a job changed the network. An order that throws is paused; the day goes on. The NOC gets one notice a week. 5. Updates customer mood, churn and new offers; IX members join; loans tick. 6. Every 30 days: bills the month (revenue minus costs) and checks for bankruptcy. 7. Checks goals, level, badges and scenario end conditions. @@ -146,6 +149,32 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood. - The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses a simplified style; parallel waves are grouped by `linkGroups()`. +## The weekly puzzle + +A puzzle week runs from Sunday 06:00 Berlin time to the next Sunday 06:00, and is named after the ISO week of +its Monday (the week starting Sunday 1 November 2026 is `2026-W45`); `pzWeekKey()` and `pzWeekStart()` in +`src/game/60-features/93-puzzles-weekly.js` handle summer time and the year boundary. + +Every Sunday `weekly-puzzle.yml` runs `scripts/weekly-puzzle.js`, which loads the real game headless, picks a +theme the last three weeks did not have (region tour, ring, detour around a hub, ocean crossing, island hopping, +latency sprint) and cities the last four weeks did not use, and searches for the cheapest build that connects +them and the cheapest one that survives any single cut (a whole cable, or a trench). The budget sits just above +that N-1 build and, where there is room, below the obvious "second path along every hop", so three stars take +some thought. Both reference builds are then played through the game's own actions and must earn one and three +stars, or the puzzle is thrown away. The file holds only ids, numbers and translation labels with their fill-ins +(`{"v":1,"key","theme","cities","via","avoid","budget","twist","name":{"l","p"},"joke":{"l","p"},"ref"}`). +`--check` re-validates every file the way the game does. + +The game fetches `puzzles/weekly/.json` (relative, same origin) only when the Puzzles list opens, and checks +it field by field (`pzWkValid()`): known fields, playable cities, labels from the theme's own list, sane numbers. +When it is missing, offline or wrong, the seeded weekly (`pzWeekly()`) stands in, so the weekly puzzle always +works. The service worker fetches these files network-first and keeps a copy for offline play. + +The weekly ships without a release: the workflow commits only `site/puzzles/weekly/` to `main` (no version bump, +so `auto-release.yml` stays quiet) and starts `release.yml` from the live release's tag with `weekly=true`, which +rebuilds that exact release with every weekly file from `main` and deploys it. Every release build takes the +weekly files from `main` too, so no deploy ever drops a published week. + ## Saves, imports and migration - `save()` writes `S` to localStorage every few seconds and after actions. diff --git a/package-lock.json b/package-lock.json index b0b4c4d..a378772 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "1.36.0", + "version": "1.37.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "1.36.0", + "version": "1.37.0", "license": "MIT", "devDependencies": { "jsdom": "24.1.3", diff --git a/package.json b/package.json index e9dff8b..55062b1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "1.36.0", + "version": "1.37.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js new file mode 100644 index 0000000..93b6edd --- /dev/null +++ b/scripts/weekly-puzzle.js @@ -0,0 +1,341 @@ +#!/usr/bin/env node +// The weekly puzzle generator. Every Sunday .github/workflows/weekly-puzzle.yml runs it to publish that week's +// puzzle as a static file, site/puzzles/weekly/.json, which the game fetches when Puzzles opens +// (src/game/60-features/93-puzzles-weekly.js). It loads the real game headless (tests/harness.js), so it uses the +// game's own cities, cables, prices, week keys, file validator and star code. +// +// node scripts/weekly-puzzle.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing +// node scripts/weekly-puzzle.js --key 2026-W45 that week (--force replaces an existing file) +// node scripts/weekly-puzzle.js --next 3 this week and the next two +// node scripts/weekly-puzzle.js --check validate every file (and re-verify the stars of weeks not over yet) +// --page FILE play another build of the game (the live release), see the workflow +// --dir DIR where the files live (default site/puzzles/weekly) +// +// How a puzzle is made: pick a theme the last weeks did not have, choose 4-6 cities for it (avoiding last weeks' +// cities), then search for the cheapest build that connects them and the cheapest build that survives any single cut +// (a whole cable or a trench). The budget is that N-1 build plus a little, so three stars need the smart design, not +// the obvious "double everything". Both reference builds are then played through the game's own actions and must earn +// their stars, or the candidate is thrown away and another one tried. +const fs = require('node:fs'); +const path = require('node:path'); + +const ROOT = path.join(__dirname, '..'); +const SCHEMA = 1, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6; +const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint']; + +// ---------- the game, headless ---------- +function game(file) { + const { load } = require('../tests/harness'); + let g = load(file ? { file } : {}); + if (file && !g.ev("typeof pzWkValid==='function'")) { + console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`); + g = load(); + } + // N-1 counts a whole cable as one failure (every segment of a cable shares its risk), as the solver does. + if (g.ev("pzUnit({cable:'x',a:'a',b:'b'})") !== 'cab:x') throw new Error('this game counts cable segments separately; the solver would not match its N-1 check'); + return g; +} + +// ---------- small helpers ---------- +const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }; +function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } +const pick = (r, a) => a[Math.floor(r() * a.length)]; +const shuffle = (r, a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }; +const ceil10k = (x) => Math.ceil(x / 10000) * 10000; +function perms(a) { if (a.length <= 1) return [a]; const out = []; a.forEach((x, i) => { for (const p of perms([...a.slice(0, i), ...a.slice(i + 1)])) out.push([x, ...p]); }); return out; } +function subsets(a) { const out = []; for (let m = 0; m < 1 << a.length; m++) out.push(a.filter((_, i) => m >> i & 1)); return out; } + +// ---------- the world, as the game prices it ---------- +function world(ev) { + const cities = JSON.parse(ev("JSON.stringify(Object.values(CITY).filter(c=>!c.off&&!c.cn).map(c=>({id:c.id,name:c.name,lands:lands(c),reg:c.reg,P:c.P,lon:c.lon,lat:c.lat,pop:pzPopCost(c.id)})))")); + const C = Object.fromEntries(cities.map((c) => [c.id, c])); + const cablePairs = JSON.parse(ev('JSON.stringify(CABLE_PAIRS.map(p=>[p.cid,p.a,p.b]))')).filter(([, a, b]) => C[a] && C[b]); + const cabs = {}; for (const [cid, a, b] of cablePairs) { (cabs[a] = cabs[a] || new Set()).add(cid); (cabs[b] = cabs[b] || new Set()).add(cid); } + const memo = new Map(); + // Every way to join a and b: overland (first wave, and a second one on a diverse route) and each cable. + const opts = (a, b) => { + const k = a < b ? a + '|' + b : b + '|' + a; if (memo.has(k)) return memo.get(k); + const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').filter(r=>!subWaveWhy(0,r.km,r.sub)).map(r=>({via:r.via,cab:r.cab,sub:r.sub,ms:r.ms,c:pzLinkCost(r,0,false),c2:r.sub?0:pzLinkCost(r,0,true)})))`)); + const out = []; + for (const r of rs) { + if (r.cab) out.push({ a, b, via: r.via, sub: true, ms: r.ms, cost: r.c, unit: 'cab:' + r.cab }); + else { out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c, unit: `land:${k}:1` }); out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c2, unit: `land:${k}:2`, second: true }); } + } + out.sort((x, y) => x.cost - y.cost || (x.unit < y.unit ? -1 : 1)); + memo.set(k, out); return out; + }; + const km = (a, b) => { const A = C[a], B = C[b], r = Math.PI / 180, h = Math.sin((B.lat - A.lat) * r / 2) ** 2 + Math.cos(A.lat * r) * Math.cos(B.lat * r) * Math.sin((B.lon - A.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(h)); }; + return { cities, C, cablePairs, cabs, opts, km }; +} + +// ---------- judging a build (the game has the last word; this steers the search) ---------- +function judge(W, P, links) { + const nodes = new Set(); for (const l of links) { nodes.add(l.a); nodes.add(l.b); } + // A second overland wave on a pair needs the first one. + for (const l of links) if (l.second && !links.some((x) => x !== l && !x.second && x.via === 'land' && x.unit === l.unit.replace(/2$/, '1'))) return null; + if (new Set(links.map((l) => l.unit)).size !== links.length) return null; + const cost = [...nodes].reduce((s, c) => s + W.C[c].pop, 0) + links.reduce((s, l) => s + l.cost, 0); + const comp = (skip) => { const adj = {}; for (const l of links) if (l.unit !== skip) { (adj[l.a] = adj[l.a] || []).push(l.b); (adj[l.b] = adj[l.b] || []).push(l.a); } + const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) { const u = q.pop(); for (const v of adj[u] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } } return seen; }; + const all = comp(null); + if (!P.cities.every((c) => all.has(c))) return { ok: false, cost }; + if (P.avoid.some((c) => nodes.has(c))) return { ok: false, cost }; + if (P.noSub && links.some((l) => l.sub)) return { ok: false, cost }; + if (P.ring) { const nb = {}; for (const l of links) { (nb[l.a] = nb[l.a] || new Set()).add(l.b); (nb[l.b] = nb[l.b] || new Set()).add(l.a); } + if (links.length !== nodes.size || ![...nodes].every((c) => nb[c].size === 2)) return { ok: false, cost }; } + if (P.lat) { const [a, b, ms] = P.lat, d = { [a]: 0 }, done = new Set(); + for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null || u === b) break; done.add(u); + for (const l of links) { const v = l.a === u ? l.b : l.b === u ? l.a : null; if (v && !(d[v] <= d[u] + l.ms)) d[v] = d[u] + l.ms; } } + if (!(d[b] <= ms)) return { ok: false, cost }; } + const weak = [...new Set(links.map((l) => l.unit))].filter((u) => { const g = comp(u); return !P.cities.every((c) => g.has(c)); }); + return { ok: true, cost, n1: weak.length === 0, weak }; +} + +// ---------- the solver ---------- +// Cheapest tree over a node set (Kruskal on each pair's cheapest way), with some links forced in. +function tree(W, nodes, forced = []) { + const par = Object.fromEntries(nodes.map((n) => [n, n])), f = (x) => (par[x] === x ? x : (par[x] = f(par[x]))); + const out = []; + for (const l of forced) { par[f(l.a)] = f(l.b); out.push(l); } + const es = []; + for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) { const o = W.opts(nodes[i], nodes[j]).filter((x) => !x.second); if (o.length) es.push(o[0]); } + es.sort((x, y) => x.cost - y.cost); + for (const e of es) if (f(e.a) !== f(e.b)) { par[f(e.a)] = f(e.b); out.push(e); } + return out.length - forced.length === nodes.length - 1 - forced.length ? out : null; +} +// Add the link that removes the most single points of failure per dollar, until none are left. +function harden(W, P, nodes, links) { + links = links.slice(); + for (let guard = 0; guard < 12; guard++) { + const j = judge(W, P, links); if (!j || !j.ok) return null; if (j.n1) return links; + let best = null; + for (let i = 0; i < nodes.length; i++) for (let k = i + 1; k < nodes.length; k++) for (const o of W.opts(nodes[i], nodes[k])) { + if (links.some((l) => l.unit === o.unit)) continue; + const jj = judge(W, P, [...links, o]); if (!jj || !jj.ok) continue; + const gain = j.weak.length - jj.weak.length; if (gain <= 0) continue; + const score = gain / o.cost; if (!best || score > best.score) best = { score, o }; + } + if (!best) return null; links.push(best.o); + } + return null; +} +// Every simple cycle through the node set, each hop by one of its three cheapest ways, cheapest first. +function cycles(W, P, nodes, bound) { + let best = null; const [h, ...rest] = nodes; + if (nodes.length < 3) return null; + for (const p of perms(rest)) { + if (p[0] > p[p.length - 1]) continue; // each cycle once + const ring = [h, ...p], hops = ring.map((x, i) => W.opts(x, ring[(i + 1) % ring.length]).filter((o) => !o.second).slice(0, 3)); + if (hops.some((o) => !o.length)) continue; + const pop = ring.reduce((s, c) => s + W.C[c].pop, 0); + const go = (i, acc, cost) => { + if (cost >= Math.min(bound, best ? best.cost : Infinity)) return; + if (i === hops.length) { const j = judge(W, P, acc); if (j && j.ok && j.n1) best = { cost: j.cost, links: acc.slice() }; return; } + for (const o of hops[i]) { if (acc.some((l) => l.unit === o.unit)) continue; acc.push(o); go(i + 1, acc, cost + o.cost); acc.pop(); } + }; + go(0, [], pop); + } + return best; +} +function solve(W, P) { + const vias = P.via.filter((c) => !P.avoid.includes(c)); + let one = null, three = null, naive = null; + const keep = (cur, links) => { if (!links) return cur; const j = judge(W, P, links); if (!j || !j.ok) return cur; return !cur || j.cost < cur.cost ? { cost: j.cost, links, n1: j.n1 } : cur; }; + for (const sub of subsets(vias)) { + const nodes = [...P.cities, ...sub]; + const forced = P.lat ? [W.opts(P.lat[0], P.lat[1]).filter((o) => !o.second).sort((x, y) => x.ms - y.ms)[0]].filter(Boolean) : []; + const ts = [tree(W, nodes), forced.length ? tree(W, nodes, forced) : null].filter(Boolean) + // A via city left as a leaf is money for nothing. + .filter((t) => sub.every((v) => t.filter((l) => l.a === v || l.b === v).length >= 2)); + if (!P.ring) for (const t of ts) { + one = keep(one, t); + // The obvious way to survive a cut: a second, different way along every hop of the tree. + const dbl = t.slice(); let okd = true; + for (const l of t) { const alt = W.opts(l.a, l.b).find((o) => o.unit !== l.unit && !dbl.some((x) => x.unit === o.unit)); if (!alt) { okd = false; break; } dbl.push(alt); } + if (okd) { const j = judge(W, P, dbl); if (j && j.ok && j.n1 && (!naive || j.cost < naive.cost)) naive = { cost: j.cost, links: dbl }; if (j && j.ok && j.n1) three = keep(three, dbl); } + const hd = harden(W, P, nodes, t); if (hd) three = keep(three, hd); + } + if (nodes.length <= 7) { const c = cycles(W, P, nodes, three ? three.cost : Infinity); if (c) { three = keep(three, c.links); if (P.ring) one = keep(one, c.links); } } + } + return { one, three, naive }; +} + +// ---------- themes: which cities, which twist ---------- +function pools(W) { + const byLand = {}; + for (const c of W.cities) { const k = c.lands[0] + '/' + c.reg; (byLand[k] = byLand[k] || []).push(c.id); } + const big = Object.values(byLand).map((g) => g.filter((c) => W.C[c].P >= 100)).filter((g) => g.length >= 6); + const isl = W.cities.filter((c) => byLand[c.lands[0] + '/' + c.reg].length === 1 && c.lands.length === 1 && (W.cabs[c.id] || new Set()).size >= 2).map((c) => c.id); + return { big, isl }; +} +const near = (W, c, from, n) => from.filter((x) => x !== c).sort((a, b) => W.km(c, a) - W.km(c, b)).slice(0, n); +function draft(W, theme, r, banned) { + const { big, isl } = pools(W), free = (c) => !banned.has(c); + const P = { theme, cities: [], via: [], avoid: [], noSub: false, ring: false, lat: null }; + if (theme === 'tour' || theme === 'ring' || theme === 'detour') { + const g = pick(r, big).filter(free); + if (g.length < 6) return null; + if (theme === 'detour') { + const hub = pick(r, g.slice().sort((a, b) => W.C[b].P - W.C[a].P).slice(0, 4)), around = near(W, hub, g, 8); + if (around.length < 6) return null; + const sh = shuffle(r, around); P.cities = sh.slice(0, 4); P.via = sh.slice(4, 6); P.avoid = [hub]; + } else { + const seed = pick(r, g), n = theme === 'ring' ? 4 + Math.floor(r() * 2) : 4 + Math.floor(r() * 3); + P.cities = [seed, ...shuffle(r, near(W, seed, g, n + 2)).slice(0, n - 1)]; + if (theme === 'tour') P.via = near(W, seed, g, n + 4).filter((c) => !P.cities.includes(c)).slice(0, 1); + P.ring = theme === 'ring'; + } + } else if (theme === 'ocean') { + const land = (c) => W.C[c].lands[0], ok = W.cablePairs.filter(([, a, b]) => land(a) !== land(b) && free(a) && free(b) && big.some((g) => g.includes(a)) && big.some((g) => g.includes(b))); + if (!ok.length) return null; + const [, a, b] = pick(r, ok), ga = big.find((g) => g.includes(a)).filter(free), gb = big.find((g) => g.includes(b)).filter(free); + const a2 = pick(r, near(W, a, ga, 3)), b2 = pick(r, near(W, b, gb, 3)); + if (!a2 || !b2) return null; + P.cities = [a, a2, b, b2]; + // Other landing points on either shore that cross the same ocean: the stepping stones to a second crossing. + const shores = W.cablePairs.filter(([, x, y]) => (land(x) === land(a) && land(y) === land(b)) || (land(x) === land(b) && land(y) === land(a))).flatMap(([, x, y]) => [x, y]); + P.via = shuffle(r, [...new Set(shores)].filter((c) => free(c) && !P.cities.includes(c))).slice(0, 2); + } else if (theme === 'islands') { + const i0 = pick(r, isl.filter(free)); if (!i0) return null; + const hops = W.cablePairs.filter(([, x, y]) => x === i0 || y === i0).map(([, x, y]) => (x === i0 ? y : x)); + const islN = near(W, i0, isl.filter((c) => free(c) && W.km(i0, c) < 4500), 3), main = near(W, i0, [...new Set(hops)].filter((c) => free(c) && !isl.includes(c)), 2); + if (!islN.length || !main.length) return null; + P.cities = [i0, ...shuffle(r, islN).slice(0, 1 + Math.floor(r() * 2)), main[0]]; + P.via = [...new Set([...islN, ...main, ...hops])].filter((c) => !P.cities.includes(c) && free(c)).sort((x, y) => W.km(i0, x) - W.km(i0, y)).slice(0, 3); + } else if (theme === 'sprint') { + const ok = []; + for (const [, a, b] of W.cablePairs) { if (!free(a) || !free(b) || W.C[a].P < 100 || W.C[b].P < 100) continue; + const o = W.opts(a, b).filter((x) => !x.second); if (o.length < 2) continue; + const fast = o.slice().sort((x, y) => x.ms - y.ms)[0], cheap = o[0]; + if (fast.unit !== cheap.unit && fast.ms < cheap.ms * 0.94 && fast.ms >= 5) ok.push([a, b, fast.ms, cheap.ms]); } + if (!ok.length) return null; + const [a, b, fms, cms] = pick(r, ok.sort((x, y) => (x[0] + x[1] < y[0] + y[1] ? -1 : 1))); + const ms = Math.ceil(fms * 1.04 + 0.5); if (ms >= cms) return null; + const ga = big.find((g) => g.includes(a)) || [], gb = big.find((g) => g.includes(b)) || []; + const extra = [...near(W, a, ga.filter(free), 2), ...near(W, b, gb.filter(free), 2)]; + P.cities = [a, b, ...shuffle(r, extra).slice(0, 1 + Math.floor(r() * 2))]; + P.via = W.cablePairs.filter(([, x, y]) => [x, y].includes(a) || [x, y].includes(b)).flatMap(([, x, y]) => [x, y]).filter((c, i, s) => s.indexOf(c) === i && free(c) && !P.cities.includes(c)).sort((x, y) => W.km(a, x) - W.km(a, y)).slice(0, 2); + P.lat = [a, b, ms]; + } + if (new Set([...P.cities, ...P.via, ...P.avoid]).size !== P.cities.length + P.via.length + P.avoid.length) return null; + if (P.cities.length < 3 || P.cities.length > 6) return null; + return P; +} + +// ---------- names and jokes: labels and their fill-ins ---------- +function words(ev, W, P, r) { + const T = JSON.parse(ev(`JSON.stringify(PZ_WK_THEMES['${P.theme}'])`)), c = P.cities, last = c[c.length - 1]; + const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], p = {}; + for (const k of need) p[k] = k === 'hub' ? P.avoid[0] : k === 'reg' ? W.C[c[0]].reg : k === 'ms' ? P.lat[2] : k === 'n' ? c.length : k === 'a' ? (P.lat ? P.lat[0] : P.theme === 'tour' ? last : c[0]) : k === 'b' ? (P.lat ? P.lat[1] : c[2] || last) : null; + return { l, p }; }; + return { name: fill(pick(r, T.names)), joke: fill(pick(r, T.jokes)) }; +} + +// ---------- one week ---------- +function history(dir, key) { + const keys = list(dir).filter((k) => k < key).slice(-HISTORY); + const files = keys.map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8'))); + return { cities: new Set(files.flatMap((f) => [...(f.cities || []), ...(f.via || []), ...(f.avoid || [])])), themes: files.slice(-THEME_GAP).map((f) => f.theme), + regs: files.slice(-REG_GAP).map((f) => f.cities && f.cities[0]).filter(Boolean) }; +} +const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []); + +// Plays a build through the game's own actions and returns the stars it earns. +function play(ev, def, links) { + ev(`localStorage.removeItem('sot-puzzles');pzBegin(${JSON.stringify(def)})`); + for (const l of links) { + if (!ev(`!!S.pops['${l.a}']`)) ev(`ACT.pzPop({city:'${l.a}'})`); + ev(`ACT.pzLinkTo({a:'${l.a}',b:'${l.b}'});ACT.pzVia({v:'${l.via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:0})`); + } + ev('closeModal()'); + return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))')); +} +const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, via: P.via, avoid: P.avoid, budget, + twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}, P.lat ? { lat: P.lat } : {}), + name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } }); +// The game's own validator decides what a puzzle is; then both references must earn their stars. +function verify(g, W, j, key) { + const { ev } = g, def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${key}'))`)); + if (!def) return { ok: false, why: 'the game rejects the file' }; + const P = { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: def.lat }; + const sol = solve(W, P); + if (!sol.one || !sol.three) return { ok: false, why: 'no build reaches the goal and survives a cut' }; + if (sol.three.cost > def.budget) return { ok: false, why: `the cheapest N-1 build found costs ${sol.three.cost}, over the budget ${def.budget}` }; + const s1 = play(ev, def, sol.one.links), s3 = play(ev, def, sol.three.links); + if (s1.stars < 1 || (!P.ring && s1.stars !== 2)) return { ok: false, why: `the one-star reference earns ${s1.stars} stars` }; + if (s3.stars !== 3) return { ok: false, why: `the three-star reference earns ${s3.stars} stars (${JSON.stringify(s3)})` }; + return { ok: true, sol, s1, s3 }; +} + +function generate(g, key, dir) { + const { ev } = g, W = world(ev); + if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`); + // Themes take turns (none of the last weeks' again); the week's own theme first, the others only if it finds nothing. + const hist = history(dir, key), free = THEMES.filter((t) => !hist.themes.includes(t)), h = hash(key); + const order = free.map((_, i) => free[(h + i) % free.length]); + for (const theme of order) { + const cands = []; + for (let at = 0; at < ATTEMPTS && cands.length < KEEP; at++) { + const r = rng(hash(`${key}|${theme}|${at}`)), P = draft(W, theme, r, hist.cities); + // Not the same part of the world as the last two weeks. + if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue; + const sol = solve(W, P); + if (!sol.one || !sol.three) continue; + // Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the + // obvious one (a second way along every hop) whenever there is room. + let budget = ceil10k(sol.three.cost * 1.05); + if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000); + const smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost; + const score = Math.min(smart, 1.6) + Math.min(slack, 2) * 0.2 + r() * 0.05; + cands.push({ P, sol, budget, score, w: words(ev, W, P, r) }); + } + cands.sort((a, b) => b.score - a.score); + for (const c of cands) { + const j = fileOf(key, c.P, c.budget, c.w, c.sol), v = verify(g, W, j, key); + if (v.ok) return j; + console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`); + } + } + throw new Error(`${key}: no puzzle survived verification`); +} + +// --check: every file is what the game accepts, under its own name, and the weeks still to come are solvable. +function check(g, dir, now = Date.now()) { + const { ev } = g, W = world(ev), bad = [], keys = list(dir); + for (const k of keys) { + let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; } + if (!ev(`!!pzWkValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; } + if (!j.ref || !Number.isInteger(j.ref.one) || !Number.isInteger(j.ref.three) || j.ref.one > j.ref.three || j.ref.three > j.budget) { bad.push(`${k}: bad ref`); continue; } + if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, W, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); } + } + const ip = path.join(dir, 'index.json'); + if (keys.length) { + let idx = null; try { idx = JSON.parse(fs.readFileSync(ip, 'utf8')); } catch (e) { /* reported below */ } + if (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys)) bad.push('index.json does not list exactly the weekly files'); + } + return bad; +} +const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n'); +const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); }; + +module.exports = { game, generate, check, solve, world, writeWeek, writeIndex, list }; + +if (require.main === module) { + const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; }; + const dir = path.resolve(ROOT, opt('--dir', 'site/puzzles/weekly')), g = game(opt('--page') && path.resolve(opt('--page'))); + if (args.includes('--check')) { + const bad = check(g, dir); + for (const b of bad) console.error(`error: ${b}`); + console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly puzzle(s) OK`); + process.exit(bad.length ? 1 : 0); + } + // By default the week that holds "12 hours from now": run early on Sunday, that is the week starting that morning. + const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1); + for (let i = 0; i < n; i++) { + const key = g.ev(`pzKeyAdd('${first}',${i})`); + if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); } + if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; } + const j = generate(g, key, dir); writeWeek(dir, j); + console.log(`${key}: ${j.theme}, ${j.cities.join(' ')}${j.via.length ? ' via ' + j.via.join(' ') : ''}${j.avoid.length ? ' avoid ' + j.avoid.join(' ') : ''}, budget ${j.budget} (1★ ${j.ref.one}, 3★ ${j.ref.three})`); + } +} diff --git a/site/i18n/de.js b/site/i18n/de.js index 5cb729b..7ba2e24 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2596,8 +2596,10 @@ "ops.anycast_annie":"Anycast-Annie", "ops.at_least_port":"mindestens {port}", "ops.budget":"Budget", +"ops.budget_running":"Höchstens dazu", "ops.by_hand":"Einmal alles", "ops.by_hand_note":"Für den Moment, in dem alles sofort erledigt sein soll: jeder Peer an jedem Exchange, ein Redundanz-Kit, PNIs mit allen.", +"ops.caches_rent":"Kostenlos ins Rack, aber jede Box kostet {price}/Monat für Platz und Strom.", "ops.cheapest":"Günstigster", "ops.ff_desc":"hat einen Port in {city} „TODO: später fixen (nicht fixen)“ beschriftet", "ops.ff_hostname":"hat den Router in {city} in router-final-FINAL-v2 umbenannt", @@ -2610,8 +2612,8 @@ "ops.floor":"Mindestens behalten", "ops.hire_an_intern":"NOC-Praktikant einstellen", "ops.hire_mo":"Einstellen · {price}/Monat", -"ops.hire_pitch":"Keine Lust mehr, in jeder Stadt dieselben fünfzehn Buttons zu klicken? Stell einen NOC-Praktikanten ein. Du schreibst die Daueraufträge einmal; er arbeitet sie jeden Tag ab, zahlt genau das, was deine Klicks kosten würden, und hinterlässt eine Zeile im Log.", "ops.hire_pitch_short":"Regeln einmal festlegen, und ein Praktikant klickt jeden Tag die Buttons.", +"ops.hire_pitch_weekly":"Keine Lust mehr, in jeder Stadt dieselben fünfzehn Buttons zu klicken? Stell einen NOC-Praktikanten ein. Du schreibst die Daueraufträge einmal; er arbeitet sie jeden Tag ab, zahlt genau das, was deine Klicks kosten würden, und gibt dir jede Woche einen Schichtbericht.", "ops.hired":"{name} ist im NOC. Schreib ein paar Daueraufträge, morgen geht es los.", "ops.how_add":"Router dazu", "ops.how_auto":"erst dazu, dann tauschen", @@ -2626,6 +2628,7 @@ "ops.l_decom":{"one":"hat eine kleine Wave auf {where} zurückgegeben","other":"hat {n} kleine Waves zurückgegeben ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"hat einen Kanal auf {where} aufgeschaltet","other":"hat {n} Kanäle aufgeschaltet ({where})"}, +"ops.l_paid":"Kosten: {cost} einmalig, {mo}/Monat.", "ops.l_peer":{"one":"hat mit einem Netz an {where} gepeert","other":"hat mit {n} Netzen an {where} gepeert"}, "ops.l_pni":{"one":"hat einen PNI in {where} bestellt","other":"hat {n} PNIs bestellt ({where})"}, "ops.l_quiet":"{name} hat auf die Graphen geschaut. Nichts zu tun.", @@ -2633,10 +2636,22 @@ "ops.l_routers":{"one":"hat Router in {where} aufgerüstet","other":"hat Router an {n} Orten aufgerüstet ({where})"}, "ops.l_rs":{"one":"hat sich einem Route Server angeschlossen","other":"hat sich {n} Route Servern angeschlossen"}, "ops.l_sales":{"one":"hat einen Kunden unterschrieben","other":"hat {n} Kunden unterschrieben"}, +"ops.l_snag":{"one":"ist bei {where} hängen geblieben und hat den Auftrag pausiert, bis du draufschaust","other":"ist bei {n} Aufträgen hängen geblieben ({where}) und hat sie pausiert, bis du draufschaust"}, "ops.l_transit":{"one":"hat Transit in {where} aufgestockt","other":"hat {n}-mal Transit aufgestockt ({where})"}, "ops.locked":"Das NOC stellt ab Kundenlevel {lv} Praktikanten ein.", "ops.lpm_off":"Die Peering-Inbox bleibt deine Sache. Dafür gibt es das Large Peering Model; {name} macht keine E-Mails.", "ops.lpm_on":"Das Large Peering Model beantwortet die Peering-Inbox. {name} geht ihm aus dem Weg.", +"ops.mood_annie":"Annie hat drei Fragen beantwortet, bevor du sie gestellt hast, vom nächstgelegenen Schreibtisch aus.", +"ops.mood_broke":"{name} hat schon eine Einkaufsliste für das Budget des nächsten Monats.", +"ops.mood_busy":"{name} hatte eine volle Woche und ist beim dritten Energydrink.", +"ops.mood_kevin":"Kevin sagt, 2001 war es ruhiger. War es nicht.", +"ops.mood_new":"{name} hat die Kaffeemaschine und die CLI gefunden, in dieser Reihenfolge. Bereit, wenn du es bist.", +"ops.mood_oops":"{name} ist heute sehr vorsichtig. Bitte niemand die Interface-Beschreibungen erwähnen.", +"ops.mood_outage":"{name} beobachtet die Störungsgraphen und lädt die Statusseite neu. Sehr oft.", +"ops.mood_quiet":"{name} liest in Ruhe RFCs. Die Graphen sind flach, genau wie es sein soll.", +"ops.mood_sales":"{name} läuft heute etwas aufrechter: In der eigenen Schicht hat jemand unterschrieben.", +"ops.mood_snag":"{name} ist auf etwas Seltsames gestoßen, hat den Auftrag pausiert und dir einen Zettel hingeklebt.", +"ops.mood_tracy":"Tracy ist drei Hops tief in einem Traceroute, bisher mit nur einem Sternchen.", "ops.never":"nie", "ops.no_cap":"kein Limit", "ops.no_clock":"Keine Uhr, keine Schichten: Bei diesen Regeln gibt es keine Tage, an denen ein Praktikant arbeiten könnte.", @@ -2674,9 +2689,11 @@ "ops.per_pop":"Pro POP", "ops.per_pop_note":"Grüne Aufträge laufen in diesem POP. Schalte einen aus, um hier selbst zu entscheiden.", "ops.really_fire":"Wirklich entlassen?", +"ops.report_last":"Schichtbericht der letzten Woche", +"ops.report_now":"Diese Woche bisher", "ops.salary":"Gehalt {price}/Monat · seit {d}", -"ops.shift":"Schicht von {name}", -"ops.spent_this_month":"Diesen Monat ausgegeben: {price}", +"ops.shift_report":"{name}s Woche", +"ops.spent_and_mo":"Diesen Monat: {price} einmalig, {mo}/Monat auf der Rechnung", "ops.standing_orders":"Daueraufträge", "ops.template":"Neuer POP aus der Vorlage", "ops.template_note":"Wähle, was {name} einrichtet, wenn du eine Stadt aus der Vorlage eröffnest. Den Rest übernehmen die Daueraufträge.", @@ -2692,6 +2709,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Verfolgt jedes Paket Hop für Hop. Kommt am Ende an, mit ein, zwei Sternchen unterwegs.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Woche gesamt: {cost} einmalig, {mo}/Monat.", +"ops.w_oops":{"one":"hat sich einmal kurz vertippt","other":"hat sich {n}-mal kurz vertippt"}, +"ops.w_sales":{"one":"hat einen Kunden gewonnen ({rev}/Monat)","other":"hat {n} Kunden gewonnen ({rev}/Monat)"}, "optic_counts.apply_price":"Übernehmen · {price}", "optic_counts.count_for_model":"Anzahl der {model}-Kanäle", "optic_counts.only_n_channels_free":"Auf dieser Glasfaser sind nur {n} Kanäle frei.", @@ -2919,6 +2940,7 @@ "puzzles.euro_trip":"Euro-Trip", "puzzles.every_internet_starts_with_one_tube":"Jedes Internet beginnt mit einer Röhre.", "puzzles.every_link_n_g_or_more":"Jeder Link {n}G oder mehr", +"puzzles.every_star_in_this_pack_is":"Alle Sterne in diesem Paket gehören dir.", "puzzles.fat_pipes_only":"Nur dicke Rohre", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Für Architekten, die die Baggersaison verschlafen.", @@ -2937,19 +2959,23 @@ "puzzles.keep_building":"Weiterbauen", "puzzles.kiwi_fruit_salad":"Kiwi-Obstsalat", "puzzles.lease_a_wave_to":"Wave mieten nach", +"puzzles.loading_this_week_s_puzzle":"Lade das Puzzle dieser Woche…", "puzzles.more_puzzles":"Mehr Puzzles", "puzzles.n_1_club":"N-1-Club", "puzzles.n_1_connect_everything_first":"N-1: erst alles verbinden", "puzzles.n_g_links":"{n}G-Links", +"puzzles.n_stars_left_in_this_pack":{"one":"Noch {n} ⭐ in diesem Paket","other":"Noch {n} ⭐ in diesem Paket"}, "puzzles.n_week_streak":{"one":"{n} Woche in Folge","other":"{n} Wochen in Folge"}, +"puzzles.new_this_sunday":"Neu diesen Sonntag!", "puzzles.new_zealand_is_far_from_everything":"Neuseeland ist weit weg von allem. Genau das ist der Witz, und das Problem.", "puzzles.next_pack_unlocks_at_n":"Nächstes Paket, {pack}, ab {n}⭐", "puzzles.next_puzzle":"Nächstes Puzzle", +"puzzles.next_weekly_in_d_h":"Nächstes Wochenpuzzle in {d} T. {h} Std.", +"puzzles.next_weekly_in_h_m":"Nächstes Wochenpuzzle in {h} Std. {m} Min.", "puzzles.no_budget":"kein Budget", "puzzles.no_budget_star_on_the_house":"kein Budget: ⭐ geht aufs Haus", "puzzles.no_cable_lands_in_both_try":"Kein Kabel landet in {a} und {b}. Versuch es mit einem Trittstein dazwischen.", "puzzles.no_clock_no_bills_nothing_breaks":"Keine Uhr, keine Rechnungen, nichts geht kaputt. Verbinde die Städte und hol dir drei Sterne: unter Budget, und noch verbunden, wenn irgendein Link durchtrennt wird.", -"puzzles.no_pop_in_list":"Kein POP in {list}", "puzzles.no_subsea":"kein Seekabel", "puzzles.no_subsea_cables":"Keine Seekabel", "puzzles.nobody_ever_got_fired_for_buying":"Für 100G ist noch nie jemand gefeuert worden.", @@ -2976,6 +3002,7 @@ "puzzles.ring":"Ring", "puzzles.ring_of_fire":"Ring of Fire", "puzzles.rock_solid_and_gold_plated_the":"Felsenfest und vergoldet. Der CFO hat Fragen.", +"puzzles.rule_not_via_list":"Regel: nicht über {list}", "puzzles.samba_sprint":"Samba-Sprint", "puzzles.same_puzzle_for_everyone_this_week":"Diese Woche für alle dasselbe Puzzle", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Gleicher Graben (billiger, ein Bagger kappt beide)", @@ -2986,6 +3013,7 @@ "puzzles.size":"Größe", "puzzles.small_calm_network_builds":"Kleine, entspannte Netzbauten", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Fast: noch ein Link, und kein Bagger kann dir was.", "puzzles.speed_runs":"Speedruns", "puzzles.spent_x":"Ausgegeben {x}", "puzzles.spent_x_of_y":"Ausgegeben {x} / {y}", @@ -3008,8 +3036,38 @@ "puzzles.weekly_puzzle":"Wochenpuzzle", "puzzles.weekly_puzzle_key":"Wochenpuzzle {key}", "puzzles.with_the_pop_price":"mit POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Deine ersten Röhren. Kein Druck, kein Budget.", +"puzzles.your_first_tubes_roomy_budgets":"Deine ersten Röhren. Großzügige Budgets, und die ersten zwei gehen aufs Haus.", "puzzles.your_stars":"Deine Sterne", +"puzzles_weekly.detour":"Umleitung", +"puzzles_weekly.island_hopping":"Inselhüpfen", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Ein Ring übersteht jeden einzelnen Schnitt. Genau dafür ist er ein Ring.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Ein Roadtrip für Photonen. Proviant nicht inbegriffen.", +"puzzles_weekly.joke_a_to_b_under_ms":"{a} nach {b} in unter {ms} ms. Die Börsenhändler schauen zu.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Jeder Hop ist ein Kabel, und jedes Kabel ist eine lange Bootsfahrt.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} hat eine sehr teure Woche. Fahr drumherum.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} Städte, ein Kontinent und jede Menge Gräben zu buddeln.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Ein Ring durch jeden POP: je zwei Links, keine Abkürzungen, keine Stichleitungen.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Irgendwo zwischen {a} und {b} wartet schon ein Reparaturschiff. Plan es ein.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"Der billigste Weg zwischen zwei Inseln ist selten eine Gerade.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"Der naheliegende Weg führt durch {hub}. Der naheliegende Weg ist gesperrt.", +"puzzles_weekly.joke_the_ocean_is_big_and":"Der Ozean ist groß, und Anker gibt es viele. Nimm ein Ersatzkabel mit.", +"puzzles_weekly.joke_the_speed_of_light_is":"Die Lichtgeschwindigkeit ist kein Vorschlag. Nimm das geradeste Glas.", +"puzzles_weekly.latency_sprint":"Latenz-Sprint", +"puzzles_weekly.name_across_the_big_blue":"Übers große Blau", +"puzzles_weekly.name_anywhere_but_hub":"Überall, nur nicht {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Sind wir schon da, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Hopp, Hopp, Seekabel", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms oder nichts", +"puzzles_weekly.name_one_ring_to_rule_reg":"Ein Ring, sie alle zu knechten: {reg}", +"puzzles_weekly.name_race_to_b":"Wettrennen nach {b}", +"puzzles_weekly.name_ring_around_reg":"Ringelreihen durch {reg}", +"puzzles_weekly.name_sea_you_in_b":"Wir sehen uns in {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sonne, Strand und Seekabel", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Wer braucht schon {hub}?", +"puzzles_weekly.ocean_crossing":"Ozeanüberquerung", +"puzzles_weekly.region_tour":"Rundreise", +"puzzles_weekly.ring":"Ring", "reach_and_subsea.premium_submarine_terminals":"Premium-Seekabel-Terminals", "release_notes.and_n_more_change":{"one":"… und {n} weitere Änderung","other":"… und {n} weitere Änderungen"}, "release_notes.read_the_full_notes_on_github":"Alle Hinweise auf GitHub lesen", @@ -3268,7 +3326,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada auf den Azoren, mitten im Atlantik. Florida–Spanien und Lissabon–Lagos sind einfach zu lang für eine 1.6T-Wave: direkt hinüber trägt jede nur 1.2T. Lande auf den Inseln dazwischen, starte das Licht neu, und jeder Hop läuft mit 1.6T oder besser. Du startest mit freigeschalteter 1.6T-Hardware.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs in Bogotá, Lima, Santiago und São Paulo, und 150 Gbps bedient", "scenarios.ports_on_15_ix_brrr_exchanges":"Ports an 15 IX.brrr-Exchanges, einer davon in Manaus, und 200 Gbps bedient", -"scenarios.reach_45_of_the_internet_and":"Erreiche 45 % des Internets und bediene 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Erreiche 50 % des Internets und bediene 300 Gbps", "scenarios.red_sea_crisis":"Krise im Roten Meer", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio, ganz von vorn. Der Karneval beginnt in 90 Tagen und will fünf Tage am Stück 400 Gbps. Die ganze Welt schaut zu.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Sandbox-Modus
Eine Milliarde Dollar und alles freigeschaltet. Chaos: {chaos}. Bau das Internet, das du immer wolltest, und halt einen Ersatzbagger bereit.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 3af769b..a5e8117 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2594,8 +2594,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"al menos {port}", "ops.budget":"Presupuesto", +"ops.budget_running":"Añade como máximo", "ops.by_hand":"Lotes puntuales", "ops.by_hand_note":"Para cuando lo quieres todo hecho ya: cada peer en cada exchange, un kit de redundancia, PNIs con todos.", +"ops.caches_rent":"Instalarla es gratis, pero cada caja cuesta {price}/mes en espacio y energía.", "ops.cheapest":"El más barato", "ops.ff_desc":"etiquetó un puerto en {city} como «TODO: arreglar luego (no arreglar)»", "ops.ff_hostname":"renombró el router de {city} a router-final-FINAL-v2", @@ -2608,8 +2610,8 @@ "ops.floor":"Conservar al menos", "ops.hire_an_intern":"Contratar a un becario del NOC", "ops.hire_mo":"Contratar · {price}/mes", -"ops.hire_pitch":"¿Harto de pulsar los mismos quince botones en cada ciudad? Contrata a un becario del NOC. Escribes las órdenes permanentes una vez; las ejecuta cada día, paga exactamente lo que costarían tus clics y deja una línea en el registro.", "ops.hire_pitch_short":"Fija las reglas una vez y un becario pulsa los botones cada día.", +"ops.hire_pitch_weekly":"¿Harto de pulsar los mismos quince botones en cada ciudad? Contrata a un becario del NOC. Escribes las órdenes permanentes una vez; las ejecuta cada día, paga exactamente lo que costarían tus clics y te entrega un informe de turno cada semana.", "ops.hired":"{name} se ha unido al NOC. Escribe unas órdenes permanentes y mañana se pone a trabajar.", "ops.how_add":"añadir router", "ops.how_auto":"añadir y luego cambiar", @@ -2624,6 +2626,7 @@ "ops.l_decom":{"one":"devolvió una wave pequeña en {where}","other":"devolvió {n} waves pequeñas ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"encendió un canal en {where}","other":"encendió {n} canales ({where})"}, +"ops.l_paid":"Coste: {cost} de entrada, {mo}/mes.", "ops.l_peer":{"one":"hizo peering con una red en {where}","other":"hizo peering con {n} redes en {where}"}, "ops.l_pni":{"one":"pidió un PNI en {where}","other":"pidió {n} PNIs ({where})"}, "ops.l_quiet":"{name} miró las gráficas. No había nada que hacer.", @@ -2631,10 +2634,22 @@ "ops.l_routers":{"one":"mejoró los routers en {where}","other":"mejoró los routers en {n} sitios ({where})"}, "ops.l_rs":{"one":"se unió a un route server","other":"se unió a {n} route servers"}, "ops.l_sales":{"one":"firmó un cliente","other":"firmó {n} clientes"}, +"ops.l_snag":{"one":"se atascó con {where} y la pausó hasta que le eches un vistazo","other":"se atascó con {n} órdenes ({where}) y las pausó hasta que les eches un vistazo"}, "ops.l_transit":{"one":"amplió el tránsito en {where}","other":"amplió el tránsito {n} veces ({where})"}, "ops.locked":"El NOC contrata becarios a partir del nivel de clientes {lv}.", "ops.lpm_off":"La bandeja de peering sigue siendo cosa tuya. Para eso está el Large Peering Model; {name} no contesta correos.", "ops.lpm_on":"El Large Peering Model contesta la bandeja de peering. {name} no se mete en su camino.", +"ops.mood_annie":"Annie respondió tres preguntas antes de que las hicieras, desde la mesa más cercana.", +"ops.mood_broke":"{name} ya tiene la lista de la compra para cuando llegue el presupuesto del mes que viene.", +"ops.mood_busy":"{name} ha tenido una semana movida y va por la tercera bebida energética.", +"ops.mood_kevin":"Kevin dice que en 2001 todo estaba más tranquilo. No lo estaba.", +"ops.mood_new":"{name} ha encontrado la cafetera y la CLI, en ese orden. Cuando quieras.", +"ops.mood_oops":"{name} va con mucho cuidado hoy. Que nadie mencione las descripciones de las interfaces.", +"ops.mood_outage":"{name} está mirando las gráficas de la avería y recargando la página de estado. Mucho.", +"ops.mood_quiet":"{name} lee RFCs tranquilamente. Las gráficas están planas, como debe ser.", +"ops.mood_sales":"{name} camina un poco más erguido hoy: alguien firmó en su turno.", +"ops.mood_snag":"{name} se topó con algo raro, pausó esa orden y te dejó un pósit.", +"ops.mood_tracy":"Tracy va por el tercer salto de un traceroute, con solo un asterisco de momento.", "ops.never":"nunca", "ops.no_cap":"sin límite", "ops.no_clock":"Sin reloj no hay turnos: con estas reglas no hay días en los que un becario pueda trabajar.", @@ -2672,9 +2687,11 @@ "ops.per_pop":"Por POP", "ops.per_pop_note":"Las órdenes en verde se ejecutan en este POP. Apaga una para decidir aquí a mano.", "ops.really_fire":"¿Despedir de verdad?", +"ops.report_last":"Informe del turno de la semana pasada", +"ops.report_now":"Esta semana, hasta ahora", "ops.salary":"Sueldo {price}/mes · desde {d}", -"ops.shift":"Turno de {name}", -"ops.spent_this_month":"Gastado este mes: {price}", +"ops.shift_report":"La semana de {name}", +"ops.spent_and_mo":"Este mes: {price} de entrada, {mo}/mes en la factura", "ops.standing_orders":"Órdenes permanentes", "ops.template":"POP nuevo desde plantilla", "ops.template_note":"Elige lo que monta {name} cuando abres una ciudad desde la plantilla. Las órdenes permanentes se encargan del resto.", @@ -2690,6 +2707,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Sigue cada paquete salto a salto. Al final llega, con alguna estrellita por el camino.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Total de la semana: {cost} de entrada, {mo}/mes.", +"ops.w_oops":{"one":"tuvo un pequeño despiste","other":"tuvo {n} pequeños despistes"}, +"ops.w_sales":{"one":"firmó un cliente ({rev}/mes)","other":"firmó {n} clientes ({rev}/mes)"}, "optic_counts.apply_price":"Aplicar · {price}", "optic_counts.count_for_model":"Número de canales {model}", "optic_counts.only_n_channels_free":"Solo quedan {n} canales libres en esta fibra.", @@ -2917,6 +2938,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Todo internet empieza con un tubo.", "puzzles.every_link_n_g_or_more":"Cada enlace de {n}G o más", +"puzzles.every_star_in_this_pack_is":"Todas las estrellas de este paquete son tuyas.", "puzzles.fat_pipes_only":"Solo tuberías gordas", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Para arquitectos que duermen tranquilos en temporada de retroexcavadoras.", @@ -2935,19 +2957,23 @@ "puzzles.keep_building":"Seguir construyendo", "puzzles.kiwi_fruit_salad":"Macedonia de kiwi", "puzzles.lease_a_wave_to":"Alquilar una onda hasta", +"puzzles.loading_this_week_s_puzzle":"Cargando el puzle de esta semana…", "puzzles.more_puzzles":"Más puzles", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1: primero conéctalo todo", "puzzles.n_g_links":"enlaces de {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Queda {n} ⭐ en este paquete","other":"Quedan {n} ⭐ en este paquete"}, "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, +"puzzles.new_this_sunday":"¡Nuevo este domingo!", "puzzles.new_zealand_is_far_from_everything":"Nueva Zelanda está lejos de todo. Esa es la gracia, y el problema.", "puzzles.next_pack_unlocks_at_n":"El siguiente pack, {pack}, se desbloquea con {n}⭐", "puzzles.next_puzzle":"Siguiente puzle", +"puzzles.next_weekly_in_d_h":"Próximo puzle semanal en {d} d {h} h", +"puzzles.next_weekly_in_h_m":"Próximo puzle semanal en {h} h {m} min", "puzzles.no_budget":"sin presupuesto", "puzzles.no_budget_star_on_the_house":"sin presupuesto: ⭐ invita la casa", "puzzles.no_cable_lands_in_both_try":"Ningún cable llega a {a} y a {b}. Prueba con una escala entre medias.", "puzzles.no_clock_no_bills_nothing_breaks":"Sin reloj, sin facturas, nada se rompe. Conecta las ciudades y ve a por tres estrellas: bajo presupuesto, y aún conectado si se corta cualquier enlace.", -"puzzles.no_pop_in_list":"Ningún POP en {list}", "puzzles.no_subsea":"sin submarinos", "puzzles.no_subsea_cables":"Sin cables submarinos", "puzzles.nobody_ever_got_fired_for_buying":"A nadie lo han despedido nunca por comprar 100G.", @@ -2974,6 +3000,7 @@ "puzzles.ring":"anillo", "puzzles.ring_of_fire":"Anillo de fuego", "puzzles.rock_solid_and_gold_plated_the":"A prueba de bombas, y bañado en oro. El director financiero tiene preguntas.", +"puzzles.rule_not_via_list":"Regla: sin pasar por {list}", "puzzles.samba_sprint":"Sprint de samba", "puzzles.same_puzzle_for_everyone_this_week":"El mismo puzle para todos esta semana", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Misma zanja (más barata, una retroexcavadora corta las dos)", @@ -2984,6 +3011,7 @@ "puzzles.size":"Tamaño", "puzzles.small_calm_network_builds":"Redes pequeñas y tranquilas", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Casi: un enlace más y ninguna retroexcavadora podrá contigo.", "puzzles.speed_runs":"Contrarreloj", "puzzles.spent_x":"Gastado {x}", "puzzles.spent_x_of_y":"Gastado {x} / {y}", @@ -3006,8 +3034,38 @@ "puzzles.weekly_puzzle":"Puzle semanal", "puzzles.weekly_puzzle_key":"Puzle semanal {key}", "puzzles.with_the_pop_price":"con el POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Tus primeros tubos. Sin presión, sin presupuesto.", +"puzzles.your_first_tubes_roomy_budgets":"Tus primeros tubos. Presupuestos holgados, y los dos primeros invita la casa.", "puzzles.your_stars":"Tus estrellas", +"puzzles_weekly.detour":"Desvío", +"puzzles_weekly.island_hopping":"De isla en isla", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anillo sobrevive a cualquier corte. Para eso es un anillo.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Un viaje por carretera para fotones. Bocadillos no incluidos.", +"puzzles_weekly.joke_a_to_b_under_ms":"De {a} a {b} en menos de {ms} ms. Los traders están mirando.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Cada salto es un cable, y cada cable es un largo viaje en barco.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} tiene una semana carísima. Rodéalo.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} ciudades, un continente y muchas zanjas por cavar.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Un anillo por cada POP: dos enlaces cada uno, sin atajos ni ramales.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"En algún punto entre {a} y {b} ya espera un barco de reparación. Tenlo en cuenta.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"El camino más barato entre dos islas casi nunca es una línea recta.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"El camino obvio pasa por {hub}. El camino obvio está cerrado.", +"puzzles_weekly.joke_the_ocean_is_big_and":"El océano es grande y las anclas son muchas. Lleva un cable de repuesto.", +"puzzles_weekly.joke_the_speed_of_light_is":"La velocidad de la luz no es una sugerencia. Elige el vidrio más recto.", +"puzzles_weekly.latency_sprint":"Sprint de latencia", +"puzzles_weekly.name_across_the_big_blue":"A través del gran azul", +"puzzles_weekly.name_anywhere_but_hub":"Cualquier sitio menos {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"¿Falta mucho, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Salto, brinco y cable", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms o nada", +"puzzles_weekly.name_one_ring_to_rule_reg":"Un anillo para gobernar {reg}", +"puzzles_weekly.name_race_to_b":"Carrera a {b}", +"puzzles_weekly.name_ring_around_reg":"Anillo por {reg}", +"puzzles_weekly.name_sea_you_in_b":"Nos vemos en {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sol, playa y cable submarino", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"¿Quién necesita {hub}?", +"puzzles_weekly.ocean_crossing":"Cruzar el océano", +"puzzles_weekly.region_tour":"Gira regional", +"puzzles_weekly.ring":"Anillo", "reach_and_subsea.premium_submarine_terminals":"Terminales submarinas premium", "release_notes.and_n_more_change":{"one":"…y {n} cambio más","other":"…y {n} cambios más"}, "release_notes.read_the_full_notes_on_github":"Lee las notas completas en GitHub", @@ -3266,7 +3324,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, en las Azores, a medio camino por el Atlántico. De Florida a España y de Lisboa a Lagos es demasiado largo para una onda de 1.6T: en línea recta, cada una lleva 1.2T. Aterriza en las islas intermedias, empieza la luz de nuevo, y cada salto va a 1.6T o más. Empiezas con equipo de 1.6T desbloqueado.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs en Bogotá, Lima, Santiago y São Paulo, y 150 Gbps servidos", "scenarios.ports_on_15_ix_brrr_exchanges":"Puertos en 15 intercambios IX.brrr, uno de ellos en Manaos, y 200 Gbps servidos", -"scenarios.reach_45_of_the_internet_and":"Llega al 45 % de internet y sirve 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Llega al 50 % de internet y sirve 300 Gbps", "scenarios.red_sea_crisis":"Crisis del Mar Rojo", "scenarios.rio_from_scratch_carnaval_starts_in":"Río desde cero. El Carnaval empieza en 90 días y quiere 400 Gbps durante cinco días seguidos. Todo el mundo está mirando.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Modo sandbox
Mil millones de dólares y todo desbloqueado. Caos: {chaos}. Construye el internet que siempre quisiste, y ten a mano una excavadora de repuesto.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b3104f0..25ce2ec 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2594,8 +2594,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"au moins {port}", "ops.budget":"Budget", +"ops.budget_running":"Ajoute au plus", "ops.by_hand":"Lots ponctuels", "ops.by_hand_note":"Pour quand tu veux tout, tout de suite : chaque peer sur chaque exchange, un kit de redondance, des PNI avec tout le monde.", +"ops.caches_rent":"Gratuit à installer, mais chaque boîtier coûte {price}/mois en espace et en électricité.", "ops.cheapest":"Le moins cher", "ops.ff_desc":"a étiqueté un port à {city} « TODO : corriger plus tard (ne pas corriger) »", "ops.ff_hostname":"a renommé le routeur de {city} en router-final-FINAL-v2", @@ -2608,8 +2610,8 @@ "ops.floor":"Garder au moins", "ops.hire_an_intern":"Recruter un stagiaire NOC", "ops.hire_mo":"Recruter · {price}/mois", -"ops.hire_pitch":"Marre de cliquer sur les mêmes quinze boutons dans chaque ville ? Recrute un stagiaire NOC. Tu écris les ordres permanents une fois ; il les exécute chaque jour, paie exactement ce que coûteraient tes clics et laisse une ligne dans le journal.", "ops.hire_pitch_short":"Fixe les règles une fois, un stagiaire clique sur les boutons chaque jour.", +"ops.hire_pitch_weekly":"Marre de cliquer sur les mêmes quinze boutons dans chaque ville ? Recrute un stagiaire NOC. Tu écris les ordres permanents une fois ; il les exécute chaque jour, paie exactement ce que coûteraient tes clics et te remet un rapport de garde chaque semaine.", "ops.hired":"{name} a rejoint le NOC. Écris quelques ordres permanents, et au travail dès demain.", "ops.how_add":"ajouter un routeur", "ops.how_auto":"ajouter, puis changer", @@ -2624,6 +2626,7 @@ "ops.l_decom":{"one":"a rendu une petite wave sur {where}","other":"a rendu {n} petites waves ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"a allumé un canal sur {where}","other":"a allumé {n} canaux ({where})"}, +"ops.l_paid":"Coût : {cost} d'entrée, {mo}/mois.", "ops.l_peer":{"one":"a peeré avec un réseau à {where}","other":"a peeré avec {n} réseaux à {where}"}, "ops.l_pni":{"one":"a commandé un PNI à {where}","other":"a commandé {n} PNI ({where})"}, "ops.l_quiet":"{name} a surveillé les graphes. Rien à faire.", @@ -2631,10 +2634,22 @@ "ops.l_routers":{"one":"a mis à niveau les routeurs à {where}","other":"a mis à niveau les routeurs à {n} endroits ({where})"}, "ops.l_rs":{"one":"a rejoint un route server","other":"a rejoint {n} route servers"}, "ops.l_sales":{"one":"a signé un client","other":"a signé {n} clients"}, +"ops.l_snag":{"one":"a calé sur {where} et l'a mis en pause en attendant que tu jettes un œil","other":"a calé sur {n} ordres ({where}) et les a mis en pause en attendant que tu jettes un œil"}, "ops.l_transit":{"one":"a renforcé le transit à {where}","other":"a renforcé le transit {n} fois ({where})"}, "ops.locked":"Le NOC recrute des stagiaires à partir du niveau clients {lv}.", "ops.lpm_off":"La boîte de peering reste à toi. Pour ça, il y a le Large Peering Model ; {name} ne fait pas les mails.", "ops.lpm_on":"Le Large Peering Model répond à la boîte de peering. {name} reste hors de son chemin.", +"ops.mood_annie":"Annie a répondu à trois questions avant que tu les poses, depuis le bureau le plus proche.", +"ops.mood_broke":"{name} a déjà sa liste de courses pour le budget du mois prochain.", +"ops.mood_busy":"{name} a eu une semaine chargée et en est à sa troisième boisson énergisante.", +"ops.mood_kevin":"Kevin dit que c'était plus calme en 2001. Ce n'était pas le cas.", +"ops.mood_new":"{name} a trouvé la machine à café et la CLI, dans cet ordre. Prêt quand tu veux.", +"ops.mood_oops":"{name} fait très attention aujourd'hui. Personne ne parle des descriptions d'interface.", +"ops.mood_outage":"{name} surveille les graphes de la panne et rafraîchit la page de statut. Beaucoup.", +"ops.mood_quiet":"{name} lit tranquillement des RFC. Les graphes sont plats, comme il se doit.", +"ops.mood_sales":"{name} marche un peu plus droit aujourd'hui : quelqu'un a signé pendant sa garde.", +"ops.mood_snag":"{name} est tombé sur un truc bizarre, a mis cet ordre en pause et t'a laissé un post-it.", +"ops.mood_tracy":"Tracy en est au troisième saut d'un traceroute, avec une seule étoile pour l'instant.", "ops.never":"jamais", "ops.no_cap":"sans limite", "ops.no_clock":"Pas d'horloge, pas de service : avec ces règles, il n'y a pas de jours où un stagiaire pourrait travailler.", @@ -2672,9 +2687,11 @@ "ops.per_pop":"Par POP", "ops.per_pop_note":"Les ordres en vert s'appliquent à ce POP. Désactive-en un pour décider ici à la main.", "ops.really_fire":"Vraiment remercier ?", +"ops.report_last":"Rapport de garde de la semaine dernière", +"ops.report_now":"Cette semaine, jusqu'ici", "ops.salary":"Salaire {price}/mois · depuis {d}", -"ops.shift":"Le service de {name}", -"ops.spent_this_month":"Dépensé ce mois-ci : {price}", +"ops.shift_report":"La semaine de {name}", +"ops.spent_and_mo":"Ce mois-ci : {price} d'entrée, {mo}/mois sur la facture", "ops.standing_orders":"Ordres permanents", "ops.template":"Nouveau POP depuis le modèle", "ops.template_note":"Choisis ce que {name} installe quand tu ouvres une ville depuis le modèle. Les ordres permanents s'occupent du reste.", @@ -2690,6 +2707,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Suit chaque paquet saut par saut. Arrive au bout, avec une ou deux étoiles en chemin.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Total de la semaine : {cost} d'entrée, {mo}/mois.", +"ops.w_oops":{"one":"a fait une petite bourde","other":"a fait {n} petites bourdes"}, +"ops.w_sales":{"one":"a signé un client ({rev}/mois)","other":"a signé {n} clients ({rev}/mois)"}, "optic_counts.apply_price":"Appliquer · {price}", "optic_counts.count_for_model":"Nombre de canaux {model}", "optic_counts.only_n_channels_free":"Il ne reste que {n} canaux libres sur cette fibre.", @@ -2917,6 +2938,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Tout internet commence par un tube.", "puzzles.every_link_n_g_or_more":"Chaque lien à {n}G ou plus", +"puzzles.every_star_in_this_pack_is":"Toutes les étoiles de ce pack sont à toi.", "puzzles.fat_pipes_only":"Gros tuyaux uniquement", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Pour les architectes qui dorment pendant la saison des pelleteuses.", @@ -2935,19 +2957,23 @@ "puzzles.keep_building":"Continuer à construire", "puzzles.kiwi_fruit_salad":"Salade de kiwis", "puzzles.lease_a_wave_to":"Louer une longueur d’onde vers", +"puzzles.loading_this_week_s_puzzle":"Chargement du puzzle de la semaine…", "puzzles.more_puzzles":"Plus de puzzles", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1 : relie d’abord tout", "puzzles.n_g_links":"liens {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Encore {n} ⭐ dans ce pack","other":"Encore {n} ⭐ dans ce pack"}, "puzzles.n_week_streak":{"one":"{n} semaine d’affilée","other":"{n} semaines d’affilée"}, +"puzzles.new_this_sunday":"Nouveau ce dimanche !", "puzzles.new_zealand_is_far_from_everything":"La Nouvelle-Zélande est loin de tout. C’est tout l’intérêt, et tout le problème.", "puzzles.next_pack_unlocks_at_n":"Prochain pack, {pack}, à {n}⭐", "puzzles.next_puzzle":"Puzzle suivant", +"puzzles.next_weekly_in_d_h":"Prochain puzzle de la semaine dans {d} j {h} h", +"puzzles.next_weekly_in_h_m":"Prochain puzzle de la semaine dans {h} h {m} min", "puzzles.no_budget":"sans budget", "puzzles.no_budget_star_on_the_house":"sans budget : ⭐ offerte par la maison", "puzzles.no_cable_lands_in_both_try":"Aucun câble n’atterrit à la fois à {a} et à {b}. Essaie une escale entre les deux.", "puzzles.no_clock_no_bills_nothing_breaks":"Pas d’horloge, pas de factures, rien ne casse. Relie les villes, puis vise trois étoiles : sous le budget, et toujours relié si n’importe quel lien est coupé.", -"puzzles.no_pop_in_list":"Aucun POP à {list}", "puzzles.no_subsea":"pas de sous-marin", "puzzles.no_subsea_cables":"Pas de câbles sous-marins", "puzzles.nobody_ever_got_fired_for_buying":"Personne ne s’est jamais fait virer pour avoir acheté du 100G.", @@ -2974,6 +3000,7 @@ "puzzles.ring":"anneau", "puzzles.ring_of_fire":"Ceinture de feu", "puzzles.rock_solid_and_gold_plated_the":"Solide comme un roc, et plaqué or. Le DAF a des questions.", +"puzzles.rule_not_via_list":"Règle : pas par {list}", "puzzles.samba_sprint":"Sprint samba", "puzzles.same_puzzle_for_everyone_this_week":"Le même puzzle pour tout le monde cette semaine", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Même tranchée (moins cher, une pelleteuse coupe les deux)", @@ -2984,6 +3011,7 @@ "puzzles.size":"Taille", "puzzles.small_calm_network_builds":"Petits réseaux, tranquillement", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Presque : encore un lien et aucune pelleteuse ne pourra rien contre toi.", "puzzles.speed_runs":"Contre la montre", "puzzles.spent_x":"Dépensé {x}", "puzzles.spent_x_of_y":"Dépensé {x} / {y}", @@ -3006,8 +3034,38 @@ "puzzles.weekly_puzzle":"Puzzle de la semaine", "puzzles.weekly_puzzle_key":"Puzzle de la semaine {key}", "puzzles.with_the_pop_price":"avec le POP : {price}", -"puzzles.your_first_tubes_no_pressure":"Tes premiers tubes. Pas de pression, pas de budget.", +"puzzles.your_first_tubes_roomy_budgets":"Tes premiers tubes. Des budgets confortables, et les deux premiers sont offerts par la maison.", "puzzles.your_stars":"Tes étoiles", +"puzzles_weekly.detour":"Détour", +"puzzles_weekly.island_hopping":"Saut d’île en île", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anneau survit à n’importe quelle coupure. C’est tout l’intérêt d’un anneau.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Un road trip pour photons. Casse-croûte non compris.", +"puzzles_weekly.joke_a_to_b_under_ms":"De {a} à {b} en moins de {ms} ms. Les traders regardent.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Chaque saut est un câble, et chaque câble est une longue traversée en bateau.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} passe une semaine très chère. Contourne-le.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} villes, un continent et beaucoup de tranchées à creuser.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Un anneau par chaque POP : deux liens chacun, pas de raccourci, pas d’antenne.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Quelque part entre {a} et {b}, un navire câblier attend déjà. Prévois-le.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"Le chemin le moins cher entre deux îles est rarement une ligne droite.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"Le chemin évident passe par {hub}. Le chemin évident est fermé.", +"puzzles_weekly.joke_the_ocean_is_big_and":"L’océan est grand et les ancres sont nombreuses. Prévois un câble de secours.", +"puzzles_weekly.joke_the_speed_of_light_is":"La vitesse de la lumière n’est pas une suggestion. Prends la fibre la plus droite.", +"puzzles_weekly.latency_sprint":"Sprint de latence", +"puzzles_weekly.name_across_the_big_blue":"Le Grand Bleu", +"puzzles_weekly.name_anywhere_but_hub":"Partout sauf {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"On arrive quand, {a} ?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Un saut, deux sauts, un câble", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms ou rien", +"puzzles_weekly.name_one_ring_to_rule_reg":"Un anneau pour gouverner {reg}", +"puzzles_weekly.name_race_to_b":"Course vers {b}", +"puzzles_weekly.name_ring_around_reg":"La ronde de {reg}", +"puzzles_weekly.name_sea_you_in_b":"Rendez-vous à {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Soleil, plage et câble sous-marin", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Qui a besoin de {hub} ?", +"puzzles_weekly.ocean_crossing":"Traversée de l’océan", +"puzzles_weekly.region_tour":"Tour de la région", +"puzzles_weekly.ring":"Anneau", "reach_and_subsea.premium_submarine_terminals":"Terminaux sous-marins premium", "release_notes.and_n_more_change":{"one":"…et {n} autre changement","other":"…et {n} autres changements"}, "release_notes.read_the_full_notes_on_github":"Lire les notes complètes sur GitHub", @@ -3266,7 +3324,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, aux Açores, à mi-chemin de l’Atlantique. De la Floride à l’Espagne et de Lisbonne à Lagos, c’est juste trop long pour une onde de 1.6T : en ligne droite, chacune transporte 1.2T. Atterrissez sur les îles entre les deux, relancez la lumière, et chaque saut passe à 1.6T ou mieux. Vous commencez avec l’équipement 1.6T débloqué.", "scenarios.pops_in_bogota_lima_santiago_and":"Des POP à Bogotá, Lima, Santiago et São Paulo, et 150 Gbps servis", "scenarios.ports_on_15_ix_brrr_exchanges":"Des ports sur 15 IX.brrr, dont un à Manaus, et 200 Gbps servis", -"scenarios.reach_45_of_the_internet_and":"Couvre 45 % d’internet et sers 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Couvre 50 % d’internet et sers 300 Gbps", "scenarios.red_sea_crisis":"Crise en mer Rouge", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio en partant de zéro. Le Carnaval commence dans 90 jours et veut 400 Gbps pendant cinq jours d’affilée. Le monde entier regarde.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Mode bac à sable
Un milliard de dollars et tout débloqué. Chaos : {chaos}. Construis l’internet dont tu as toujours rêvé, et garde une pelleteuse de rechange sous la main.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 7de3959..d665790 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2594,8 +2594,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"almeno {port}", "ops.budget":"Budget", +"ops.budget_running":"Aggiunge al massimo", "ops.by_hand":"Lotti una tantum", "ops.by_hand_note":"Per quando vuoi tutto fatto subito: ogni peer su ogni exchange, un kit di ridondanza, PNI con tutti.", +"ops.caches_rent":"Gratis da montare, ma ogni box costa {price}/mese di spazio e corrente.", "ops.cheapest":"Il più economico", "ops.ff_desc":"ha etichettato una porta a {city} «TODO: sistemare dopo (non sistemare)»", "ops.ff_hostname":"ha rinominato il router di {city} in router-final-FINAL-v2", @@ -2608,8 +2610,8 @@ "ops.floor":"Tieni almeno", "ops.hire_an_intern":"Assumi uno stagista NOC", "ops.hire_mo":"Assumi · {price}/mese", -"ops.hire_pitch":"Stufo di cliccare gli stessi quindici pulsanti in ogni città? Assumi uno stagista NOC. Scrivi gli ordini permanenti una volta sola; lui li esegue ogni giorno, paga esattamente quanto costerebbero i tuoi clic e lascia una riga nel registro.", "ops.hire_pitch_short":"Fissa le regole una volta, e uno stagista clicca i pulsanti ogni giorno.", +"ops.hire_pitch_weekly":"Stufo di cliccare gli stessi quindici pulsanti in ogni città? Assumi uno stagista NOC. Scrivi gli ordini permanenti una volta sola; lui li esegue ogni giorno, paga esattamente quanto costerebbero i tuoi clic e ti consegna un rapporto del turno ogni settimana.", "ops.hired":"{name} è entrato nel NOC. Scrivi qualche ordine permanente e domani si comincia.", "ops.how_add":"aggiungi router", "ops.how_auto":"aggiungi, poi cambia", @@ -2624,6 +2626,7 @@ "ops.l_decom":{"one":"ha restituito una wave piccola su {where}","other":"ha restituito {n} wave piccole ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"ha acceso un canale su {where}","other":"ha acceso {n} canali ({where})"}, +"ops.l_paid":"Costo: {cost} subito, {mo}/mese.", "ops.l_peer":{"one":"ha fatto peering con una rete a {where}","other":"ha fatto peering con {n} reti a {where}"}, "ops.l_pni":{"one":"ha ordinato un PNI a {where}","other":"ha ordinato {n} PNI ({where})"}, "ops.l_quiet":"{name} ha guardato i grafici. Niente da fare.", @@ -2631,10 +2634,22 @@ "ops.l_routers":{"one":"ha potenziato i router a {where}","other":"ha potenziato i router in {n} posti ({where})"}, "ops.l_rs":{"one":"si è unito a un route server","other":"si è unito a {n} route server"}, "ops.l_sales":{"one":"ha firmato un cliente","other":"ha firmato {n} clienti"}, +"ops.l_snag":{"one":"si è bloccato su {where} e l'ha messo in pausa finché non dai un'occhiata","other":"si è bloccato su {n} ordini ({where}) e li ha messi in pausa finché non dai un'occhiata"}, "ops.l_transit":{"one":"ha aumentato il transit a {where}","other":"ha aumentato il transit {n} volte ({where})"}, "ops.locked":"Il NOC assume stagisti dal livello clienti {lv}.", "ops.lpm_off":"La casella del peering resta tua. Per quella c'è il Large Peering Model; {name} non risponde alle email.", "ops.lpm_on":"Il Large Peering Model risponde alla casella del peering. {name} gli sta alla larga.", +"ops.mood_annie":"Annie ha risposto a tre domande prima che tu le facessi, dalla scrivania più vicina.", +"ops.mood_broke":"{name} ha già la lista della spesa per quando arriva il budget del mese prossimo.", +"ops.mood_busy":"{name} ha avuto una settimana piena ed è alla terza bevanda energetica.", +"ops.mood_kevin":"Kevin dice che nel 2001 era più tranquillo. Non lo era.", +"ops.mood_new":"{name} ha trovato la macchinetta del caffè e la CLI, in quest'ordine. Pronto quando vuoi.", +"ops.mood_oops":"{name} oggi va con i piedi di piombo. Nessuno nomini le descrizioni delle interfacce.", +"ops.mood_outage":"{name} guarda i grafici del guasto e ricarica la pagina di stato. Parecchio.", +"ops.mood_quiet":"{name} legge RFC in santa pace. I grafici sono piatti, come devono essere.", +"ops.mood_sales":"{name} cammina un po' più dritto oggi: qualcuno ha firmato nel suo turno.", +"ops.mood_snag":"{name} ha trovato qualcosa di strano, ha messo in pausa quell'ordine e ti ha lasciato un post-it.", +"ops.mood_tracy":"Tracy è al terzo hop di un traceroute, con un solo asterisco per ora.", "ops.never":"mai", "ops.no_cap":"nessun limite", "ops.no_clock":"Niente orologio, niente turni: con queste regole non ci sono giorni in cui uno stagista possa lavorare.", @@ -2672,9 +2687,11 @@ "ops.per_pop":"Per POP", "ops.per_pop_note":"Gli ordini in verde valgono per questo POP. Spegnine uno per decidere qui a mano.", "ops.really_fire":"Licenziare davvero?", +"ops.report_last":"Rapporto del turno della settimana scorsa", +"ops.report_now":"Questa settimana, finora", "ops.salary":"Stipendio {price}/mese · dal {d}", -"ops.shift":"Il turno di {name}", -"ops.spent_this_month":"Speso questo mese: {price}", +"ops.shift_report":"La settimana di {name}", +"ops.spent_and_mo":"Questo mese: {price} subito, {mo}/mese in bolletta", "ops.standing_orders":"Ordini permanenti", "ops.template":"Nuovo POP da modello", "ops.template_note":"Scegli cosa monta {name} quando apri una città dal modello. Al resto pensano gli ordini permanenti.", @@ -2690,6 +2707,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Segue ogni pacchetto hop per hop. Alla fine arriva, con qualche asterisco per strada.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Totale della settimana: {cost} subito, {mo}/mese.", +"ops.w_oops":{"one":"ha fatto un piccolo pasticcio","other":"ha fatto {n} piccoli pasticci"}, +"ops.w_sales":{"one":"ha firmato un cliente ({rev}/mese)","other":"ha firmato {n} clienti ({rev}/mese)"}, "optic_counts.apply_price":"Applica · {price}", "optic_counts.count_for_model":"Numero di canali {model}", "optic_counts.only_n_channels_free":"Su questa fibra sono liberi solo {n} canali.", @@ -2917,6 +2938,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Ogni internet comincia con un tubo.", "puzzles.every_link_n_g_or_more":"Ogni link da {n}G o più", +"puzzles.every_star_in_this_pack_is":"Tutte le stelle di questo pacchetto sono tue.", "puzzles.fat_pipes_only":"Solo tubi grossi", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Per architetti che dormono sonni tranquilli nella stagione delle ruspe.", @@ -2935,19 +2957,23 @@ "puzzles.keep_building":"Continua a costruire", "puzzles.kiwi_fruit_salad":"Macedonia di kiwi", "puzzles.lease_a_wave_to":"Noleggia una wave verso", +"puzzles.loading_this_week_s_puzzle":"Carico il puzzle della settimana…", "puzzles.more_puzzles":"Altri puzzle", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1: prima collega tutto", "puzzles.n_g_links":"link da {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Ancora {n} ⭐ in questo pacchetto","other":"Ancora {n} ⭐ in questo pacchetto"}, "puzzles.n_week_streak":{"one":"{n} settimana di fila","other":"{n} settimane di fila"}, +"puzzles.new_this_sunday":"Nuovo questa domenica!", "puzzles.new_zealand_is_far_from_everything":"La Nuova Zelanda è lontana da tutto. È proprio questo il bello, e il problema.", "puzzles.next_pack_unlocks_at_n":"Il prossimo pacchetto, {pack}, si sblocca a {n}⭐", "puzzles.next_puzzle":"Prossimo puzzle", +"puzzles.next_weekly_in_d_h":"Prossimo puzzle settimanale tra {d} g {h} h", +"puzzles.next_weekly_in_h_m":"Prossimo puzzle settimanale tra {h} h {m} min", "puzzles.no_budget":"senza budget", "puzzles.no_budget_star_on_the_house":"senza budget: ⭐ offerta dalla casa", "puzzles.no_cable_lands_in_both_try":"Nessun cavo approda sia a {a} che a {b}. Prova con una tappa in mezzo.", "puzzles.no_clock_no_bills_nothing_breaks":"Niente orologio, niente bollette, non si rompe niente. Collega le città, poi punta alle tre stelle: sotto budget, e ancora collegato se si taglia un link qualsiasi.", -"puzzles.no_pop_in_list":"Nessun POP a {list}", "puzzles.no_subsea":"niente sottomarini", "puzzles.no_subsea_cables":"Niente cavi sottomarini", "puzzles.nobody_ever_got_fired_for_buying":"Nessuno è mai stato licenziato per aver comprato 100G.", @@ -2974,6 +3000,7 @@ "puzzles.ring":"anello", "puzzles.ring_of_fire":"Cintura di fuoco", "puzzles.rock_solid_and_gold_plated_the":"Solida come una roccia, e placcata d’oro. Il CFO ha delle domande.", +"puzzles.rule_not_via_list":"Regola: niente passaggi da {list}", "puzzles.samba_sprint":"Sprint di samba", "puzzles.same_puzzle_for_everyone_this_week":"Lo stesso puzzle per tutti questa settimana", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Stesso scavo (più economico, una ruspa li taglia tutti e due)", @@ -2984,6 +3011,7 @@ "puzzles.size":"Taglia", "puzzles.small_calm_network_builds":"Piccole reti, con calma", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Ci sei quasi: ancora un link e nessuna ruspa può toccarti.", "puzzles.speed_runs":"Corse contro il tempo", "puzzles.spent_x":"Speso {x}", "puzzles.spent_x_of_y":"Speso {x} / {y}", @@ -3006,8 +3034,38 @@ "puzzles.weekly_puzzle":"Puzzle della settimana", "puzzles.weekly_puzzle_key":"Puzzle della settimana {key}", "puzzles.with_the_pop_price":"con il POP: {price}", -"puzzles.your_first_tubes_no_pressure":"I tuoi primi tubi. Niente pressione, niente budget.", +"puzzles.your_first_tubes_roomy_budgets":"I tuoi primi tubi. Budget comodi, e i primi due li offre la casa.", "puzzles.your_stars":"Le tue stelle", +"puzzles_weekly.detour":"Deviazione", +"puzzles_weekly.island_hopping":"Di isola in isola", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anello sopravvive a qualsiasi taglio. È proprio il bello dell’anello.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Un viaggio on the road per fotoni. Panini non inclusi.", +"puzzles_weekly.joke_a_to_b_under_ms":"Da {a} a {b} in meno di {ms} ms. I trader ti guardano.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Ogni salto è un cavo, e ogni cavo è un lungo viaggio in barca.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} ha una settimana carissima. Giraci intorno.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} città, un continente e un sacco di scavi da fare.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Un anello per ogni POP: due link ciascuno, niente scorciatoie, niente diramazioni.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Da qualche parte tra {a} e {b} una nave posacavi sta già aspettando. Tienine conto.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"La strada più economica tra due isole raramente è una linea retta.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"La strada ovvia passa da {hub}. La strada ovvia è chiusa.", +"puzzles_weekly.joke_the_ocean_is_big_and":"L’oceano è grande e le ancore sono tante. Porta un cavo di scorta.", +"puzzles_weekly.joke_the_speed_of_light_is":"La velocità della luce non è un suggerimento. Scegli il vetro più dritto.", +"puzzles_weekly.latency_sprint":"Sprint di latenza", +"puzzles_weekly.name_across_the_big_blue":"Oltre il grande blu", +"puzzles_weekly.name_anywhere_but_hub":"Ovunque tranne {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Quanto manca, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Un salto, un balzo e un cavo", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms o niente", +"puzzles_weekly.name_one_ring_to_rule_reg":"Un anello per domare {reg}", +"puzzles_weekly.name_race_to_b":"Corsa verso {b}", +"puzzles_weekly.name_ring_around_reg":"Girotondo in {reg}", +"puzzles_weekly.name_sea_you_in_b":"Ci vediamo a {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sole, mare e cavo sottomarino", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Chi ha bisogno di {hub}?", +"puzzles_weekly.ocean_crossing":"Traversata oceanica", +"puzzles_weekly.region_tour":"Giro della regione", +"puzzles_weekly.ring":"Anello", "reach_and_subsea.premium_submarine_terminals":"Terminali sottomarini avanzati", "release_notes.and_n_more_change":{"one":"…e {n} altra modifica","other":"…e altre {n} modifiche"}, "release_notes.read_the_full_notes_on_github":"Leggi le note complete su GitHub", @@ -3266,7 +3324,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, nelle Azzorre, a metà dell’Atlantico. Dalla Florida alla Spagna e da Lisbona a Lagos è appena troppo lungo per un’onda da 1.6T: in linea diretta ognuna porta 1.2T. Approda sulle isole in mezzo, fai ripartire la luce e ogni tratto va a 1.6T o più. Parti con l’attrezzatura da 1.6T sbloccata.", "scenarios.pops_in_bogota_lima_santiago_and":"POP a Bogotá, Lima, Santiago e São Paulo, e 150 Gbps serviti", "scenarios.ports_on_15_ix_brrr_exchanges":"Porte su 15 exchange IX.brrr, una delle quali a Manaus, e 200 Gbps serviti", -"scenarios.reach_45_of_the_internet_and":"Raggiungi il 45% di internet e servi 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Raggiungi il 50% di internet e servi 300 Gbps", "scenarios.red_sea_crisis":"Crisi nel Mar Rosso", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio da zero. Il Carnaval comincia tra 90 giorni e vuole 400 Gbps per cinque giorni di fila. Il mondo intero sta guardando.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Modalità sandbox
Un miliardo di dollari e tutto sbloccato. Caos: {chaos}. Costruisci l’internet che hai sempre sognato, e tieni una ruspa di scorta a portata di mano.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index dc6b6e9..8c4e54e 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2594,8 +2594,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"pelo menos {port}", "ops.budget":"Orçamento", +"ops.budget_running":"Adiciona no máximo", "ops.by_hand":"Lotes avulsos", "ops.by_hand_note":"Para quando você quer tudo feito agora: cada peer em cada exchange, um kit de redundância, PNIs com todo mundo.", +"ops.caches_rent":"Instalar é grátis, mas cada caixa custa {price}/mês em espaço e energia.", "ops.cheapest":"O mais barato", "ops.ff_desc":"etiquetou uma porta em {city} como “TODO: corrigir depois (não corrigir)”", "ops.ff_hostname":"renomeou o roteador de {city} para router-final-FINAL-v2", @@ -2608,8 +2610,8 @@ "ops.floor":"Manter pelo menos", "ops.hire_an_intern":"Contratar um estagiário de NOC", "ops.hire_mo":"Contratar · {price}/mês", -"ops.hire_pitch":"Cansado de clicar nos mesmos quinze botões em cada cidade? Contrate um estagiário de NOC. Você escreve as ordens permanentes uma vez; ele as executa todo dia, paga exatamente o que seus cliques custariam e deixa uma linha no registro.", "ops.hire_pitch_short":"Defina as regras uma vez, e um estagiário clica nos botões todo dia.", +"ops.hire_pitch_weekly":"Cansado de clicar nos mesmos quinze botões em cada cidade? Contrate um estagiário de NOC. Você escreve as ordens permanentes uma vez; ele as executa todo dia, paga exatamente o que seus cliques custariam e entrega um relatório de turno toda semana.", "ops.hired":"{name} entrou no NOC. Escreva algumas ordens permanentes e amanhã começa o trabalho.", "ops.how_add":"adicionar roteador", "ops.how_auto":"adicionar, depois trocar", @@ -2624,6 +2626,7 @@ "ops.l_decom":{"one":"devolveu uma wave pequena em {where}","other":"devolveu {n} waves pequenas ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"acendeu um canal em {where}","other":"acendeu {n} canais ({where})"}, +"ops.l_paid":"Custo: {cost} de entrada, {mo}/mês.", "ops.l_peer":{"one":"fez peering com uma rede em {where}","other":"fez peering com {n} redes em {where}"}, "ops.l_pni":{"one":"pediu um PNI em {where}","other":"pediu {n} PNIs ({where})"}, "ops.l_quiet":"{name} ficou olhando os gráficos. Nada a fazer.", @@ -2631,10 +2634,22 @@ "ops.l_routers":{"one":"melhorou os roteadores em {where}","other":"melhorou os roteadores em {n} lugares ({where})"}, "ops.l_rs":{"one":"entrou em um route server","other":"entrou em {n} route servers"}, "ops.l_sales":{"one":"fechou com um cliente","other":"fechou com {n} clientes"}, +"ops.l_snag":{"one":"travou em {where} e pausou a ordem até você dar uma olhada","other":"travou em {n} ordens ({where}) e pausou-as até você dar uma olhada"}, "ops.l_transit":{"one":"reforçou o trânsito em {where}","other":"reforçou o trânsito {n} vezes ({where})"}, "ops.locked":"O NOC contrata estagiários a partir do nível de clientes {lv}.", "ops.lpm_off":"A caixa de peering continua com você. Para isso existe o Large Peering Model; {name} não responde e-mail.", "ops.lpm_on":"O Large Peering Model responde a caixa de peering. {name} fica fora do caminho dele.", +"ops.mood_annie":"Annie respondeu três perguntas antes de você fazê-las, da mesa mais próxima.", +"ops.mood_broke":"{name} já tem a lista de compras para quando chegar o orçamento do mês que vem.", +"ops.mood_busy":"{name} teve uma semana cheia e está na terceira bebida energética.", +"ops.mood_kevin":"Kevin diz que em 2001 era mais tranquilo. Não era.", +"ops.mood_new":"{name} encontrou a máquina de café e a CLI, nessa ordem. Pronto quando você estiver.", +"ops.mood_oops":"{name} está tomando muito cuidado hoje. Ninguém fale das descrições das interfaces.", +"ops.mood_outage":"{name} está olhando os gráficos da pane e recarregando a página de status. Muito.", +"ops.mood_quiet":"{name} lê RFCs em paz. Os gráficos estão planos, como deve ser.", +"ops.mood_sales":"{name} está andando um pouco mais ereto hoje: alguém assinou no seu turno.", +"ops.mood_snag":"{name} encontrou algo estranho, pausou essa ordem e deixou um post-it para você.", +"ops.mood_tracy":"Tracy está no terceiro salto de um traceroute, com só um asterisco até agora.", "ops.never":"nunca", "ops.no_cap":"sem limite", "ops.no_clock":"Sem relógio, sem turnos: com estas regras não há dias para um estagiário trabalhar.", @@ -2672,9 +2687,11 @@ "ops.per_pop":"Por POP", "ops.per_pop_note":"As ordens em verde valem neste POP. Desligue uma para decidir aqui na mão.", "ops.really_fire":"Dispensar mesmo?", +"ops.report_last":"Relatório do turno da semana passada", +"ops.report_now":"Esta semana, até agora", "ops.salary":"Salário {price}/mês · desde {d}", -"ops.shift":"Turno de {name}", -"ops.spent_this_month":"Gasto este mês: {price}", +"ops.shift_report":"A semana de {name}", +"ops.spent_and_mo":"Este mês: {price} de entrada, {mo}/mês na fatura", "ops.standing_orders":"Ordens permanentes", "ops.template":"Novo POP por modelo", "ops.template_note":"Escolha o que {name} monta quando você abre uma cidade pelo modelo. As ordens permanentes cuidam do resto.", @@ -2690,6 +2707,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Segue cada pacote salto a salto. Chega no fim, com uma ou duas estrelinhas no caminho.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Total da semana: {cost} de entrada, {mo}/mês.", +"ops.w_oops":{"one":"cometeu um pequeno deslize","other":"cometeu {n} pequenos deslizes"}, +"ops.w_sales":{"one":"assinou um cliente ({rev}/mês)","other":"assinou {n} clientes ({rev}/mês)"}, "optic_counts.apply_price":"Aplicar · {price}", "optic_counts.count_for_model":"Número de canais {model}", "optic_counts.only_n_channels_free":"Só há {n} canais livres nesta fibra.", @@ -2917,6 +2938,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Toda internet começa com um tubo.", "puzzles.every_link_n_g_or_more":"Todo link com {n}G ou mais", +"puzzles.every_star_in_this_pack_is":"Todas as estrelas deste pacote são suas.", "puzzles.fat_pipes_only":"Só tubos grossos", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Para arquitetos que dormem tranquilos na temporada das retroescavadeiras.", @@ -2935,19 +2957,23 @@ "puzzles.keep_building":"Continuar construindo", "puzzles.kiwi_fruit_salad":"Salada de kiwi", "puzzles.lease_a_wave_to":"Alugar uma wave até", +"puzzles.loading_this_week_s_puzzle":"Carregando o puzzle da semana…", "puzzles.more_puzzles":"Mais puzzles", "puzzles.n_1_club":"Clube N-1", "puzzles.n_1_connect_everything_first":"N-1: conecte tudo primeiro", "puzzles.n_g_links":"links de {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Falta {n} ⭐ neste pacote","other":"Faltam {n} ⭐ neste pacote"}, "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, +"puzzles.new_this_sunday":"Novo neste domingo!", "puzzles.new_zealand_is_far_from_everything":"A Nova Zelândia fica longe de tudo. Essa é a graça, e o problema.", "puzzles.next_pack_unlocks_at_n":"O próximo pacote, {pack}, abre com {n}⭐", "puzzles.next_puzzle":"Próximo puzzle", +"puzzles.next_weekly_in_d_h":"Próximo puzzle semanal em {d} d {h} h", +"puzzles.next_weekly_in_h_m":"Próximo puzzle semanal em {h} h {m} min", "puzzles.no_budget":"sem orçamento", "puzzles.no_budget_star_on_the_house":"sem orçamento: ⭐ por conta da casa", "puzzles.no_cable_lands_in_both_try":"Nenhum cabo chega a {a} e a {b}. Tente uma escala no meio.", "puzzles.no_clock_no_bills_nothing_breaks":"Sem relógio, sem contas, nada quebra. Conecte as cidades e busque três estrelas: dentro do orçamento, e ainda conectado se qualquer link for cortado.", -"puzzles.no_pop_in_list":"Nenhum POP em {list}", "puzzles.no_subsea":"sem submarino", "puzzles.no_subsea_cables":"Sem cabos submarinos", "puzzles.nobody_ever_got_fired_for_buying":"Ninguém nunca foi demitido por comprar 100G.", @@ -2974,6 +3000,7 @@ "puzzles.ring":"anel", "puzzles.ring_of_fire":"Anel de Fogo", "puzzles.rock_solid_and_gold_plated_the":"Sólida como rocha, e banhada a ouro. O CFO tem perguntas.", +"puzzles.rule_not_via_list":"Regra: sem passar por {list}", "puzzles.samba_sprint":"Corrida de samba", "puzzles.same_puzzle_for_everyone_this_week":"O mesmo puzzle para todo mundo nesta semana", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Mesma vala (mais barata, uma retroescavadeira corta as duas)", @@ -2984,6 +3011,7 @@ "puzzles.size":"Tamanho", "puzzles.small_calm_network_builds":"Redes pequenas, com calma", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Quase lá: mais um link e nenhuma retroescavadeira te alcança.", "puzzles.speed_runs":"Contra o relógio", "puzzles.spent_x":"Gasto {x}", "puzzles.spent_x_of_y":"Gasto {x} / {y}", @@ -3006,8 +3034,38 @@ "puzzles.weekly_puzzle":"Puzzle da semana", "puzzles.weekly_puzzle_key":"Puzzle da semana {key}", "puzzles.with_the_pop_price":"com o POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Seus primeiros tubos. Sem pressão, sem orçamento.", +"puzzles.your_first_tubes_roomy_budgets":"Seus primeiros tubos. Orçamentos folgados, e os dois primeiros são por conta da casa.", "puzzles.your_stars":"Suas estrelas", +"puzzles_weekly.detour":"Desvio", +"puzzles_weekly.island_hopping":"De ilha em ilha", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Um anel sobrevive a qualquer corte. É para isso que serve um anel.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Uma viagem de carro para fótons. Lanche não incluído.", +"puzzles_weekly.joke_a_to_b_under_ms":"De {a} a {b} em menos de {ms} ms. Os traders estão de olho.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Cada salto é um cabo, e cada cabo é uma longa viagem de barco.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} está numa semana caríssima. Dê a volta.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} cidades, um continente e muitas valas para cavar.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Um anel por cada POP: dois links cada, sem atalhos, sem ramais.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Em algum lugar entre {a} e {b} um navio de reparo já está esperando. Planeje para isso.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"O caminho mais barato entre duas ilhas raramente é uma linha reta.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"O caminho óbvio passa por {hub}. O caminho óbvio está fechado.", +"puzzles_weekly.joke_the_ocean_is_big_and":"O oceano é grande e as âncoras são muitas. Leve um cabo reserva.", +"puzzles_weekly.joke_the_speed_of_light_is":"A velocidade da luz não é uma sugestão. Escolha o vidro mais reto.", +"puzzles_weekly.latency_sprint":"Corrida de latência", +"puzzles_weekly.name_across_the_big_blue":"Através do grande azul", +"puzzles_weekly.name_anywhere_but_hub":"Qualquer lugar menos {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Já chegamos, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Um pulo, um salto e um cabo", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms ou nada", +"puzzles_weekly.name_one_ring_to_rule_reg":"Um anel para governar {reg}", +"puzzles_weekly.name_race_to_b":"Corrida até {b}", +"puzzles_weekly.name_ring_around_reg":"Ciranda por {reg}", +"puzzles_weekly.name_sea_you_in_b":"Te vejo em {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sol, mar e cabo submarino", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Quem precisa de {hub}?", +"puzzles_weekly.ocean_crossing":"Travessia do oceano", +"puzzles_weekly.region_tour":"Volta pela região", +"puzzles_weekly.ring":"Anel", "reach_and_subsea.premium_submarine_terminals":"Terminais submarinos premium", "release_notes.and_n_more_change":{"one":"…e mais {n} mudança","other":"…e mais {n} mudanças"}, "release_notes.read_the_full_notes_on_github":"Leia as notas completas no GitHub", @@ -3266,7 +3324,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, nos Açores, no meio do Atlântico. Da Flórida à Espanha e de Lisboa a Lagos é um pouco longo demais para uma onda de 1.6T: em linha direta, cada uma leva 1.2T. Pouse nas ilhas no meio, recomece a luz, e cada trecho roda a 1.6T ou mais. Você começa com equipamento de 1.6T desbloqueado.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs em Bogotá, Lima, Santiago e São Paulo, e 150 Gbps servidos", "scenarios.ports_on_15_ix_brrr_exchanges":"Portas em 15 exchanges IX.brrr, uma delas em Manaus, e 200 Gbps servidos", -"scenarios.reach_45_of_the_internet_and":"Alcance 45% da internet e atenda 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Alcance 50% da internet e atenda 300 Gbps", "scenarios.red_sea_crisis":"Crise no Mar Vermelho", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio do zero. O Carnaval começa em 90 dias e quer 400 Gbps por cinco dias seguidos. O mundo inteiro está assistindo.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Modo sandbox
Um bilhão de dólares e tudo desbloqueado. Caos: {chaos}. Construa a internet que você sempre quis, e deixe uma retroescavadeira reserva à mão.", diff --git a/site/puzzles/weekly/2026-W44.json b/site/puzzles/weekly/2026-W44.json new file mode 100644 index 0000000..128937c --- /dev/null +++ b/site/puzzles/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W44","theme":"ring","cities":["mil","vie","rom","mrs","stg"],"via":[],"avoid":[],"budget":240000,"twist":{"ring":true},"name":{"l":"puzzles_weekly.name_ring_around_reg","p":{"reg":"EU"}},"joke":{"l":"puzzles_weekly.joke_one_ring_through_every_pop","p":{}},"ref":{"one":226300,"three":226300}} diff --git a/site/puzzles/weekly/2026-W45.json b/site/puzzles/weekly/2026-W45.json new file mode 100644 index 0000000..413d8ac --- /dev/null +++ b/site/puzzles/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"via":["lag"],"avoid":[],"budget":740000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":457084,"three":695668}} diff --git a/site/puzzles/weekly/2026-W46.json b/site/puzzles/weekly/2026-W46.json new file mode 100644 index 0000000..d7b9f26 --- /dev/null +++ b/site/puzzles/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W46","theme":"ocean","cities":["for","ssa","lad","lun"],"via":["dla","sao"],"avoid":[],"budget":2060000,"twist":{},"name":{"l":"puzzles_weekly.name_across_the_big_blue","p":{}},"joke":{"l":"puzzles_weekly.joke_somewhere_between_a_and_b","p":{"a":"for","b":"lad"}},"ref":{"one":943664,"three":1959268}} diff --git a/site/puzzles/weekly/index.json b/site/puzzles/weekly/index.json new file mode 100644 index 0000000..8955841 --- /dev/null +++ b/site/puzzles/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 3febeef..6c895f6 100644 --- a/site/sw.js +++ b/site/sw.js @@ -25,6 +25,12 @@ self.addEventListener('fetch', (e) => { } const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname); if (!local && !fonts) return; + // Weekly puzzles are published between releases: ask the network first, and keep a copy for playing offline. + if (local && url.pathname.startsWith('/puzzles/weekly/')) { + e.respondWith(fetch(req).then((r) => { if (r.ok) { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); } return r; }) + .catch(() => caches.match(req).then((r) => r || Response.error()))); + return; + } e.respondWith(caches.open(CACHE).then((c) => c.match(req).then((hit) => { const net = fetch(req).then((r) => { if (r && (r.ok || r.type === 'opaque')) c.put(req, r.clone()); return r; }).catch(() => hit); return hit || net; diff --git a/src/game/20-world/55-city-pdb.js b/src/game/20-world/55-city-pdb.js index 2233152..1b6d62f 100644 --- a/src/game/20-world/55-city-pdb.js +++ b/src/game/20-world/55-city-pdb.js @@ -1,15 +1,18 @@ /* Real-world calibration, pulled 2026-10-25 (Pacific islands 2026-10-26). Per city: [carrier-neutral facilities, network presences across them, ASNs registered in its country]. Facilities and presences are PeeringDB facilities within 50 km or in the same city (peeringdb.com/api/fac, net_count summed); ASNs per country are from bgp.he.net/report/world. - A city missing here keeps the plain regional price. One entry per line, sorted by id. */ + Cities PeeringDB barely knows (added 2026-10-28) are marked: est. is an estimate from what is known to be there, with + the country's ASN count. A city missing here keeps the plain regional price. One entry per line, sorted by id. */ const CITY_PDB={ abj:[5,11,32], acc:[7,78,124], add:[2,3,10], + adl:[6,70,3196], // est. aju:[4,3,9693], akl:[27,398,755], alg:[0,0,16], ams:[69,2731,1827], + anc:[3,12,33300], // est. apw:[0,0,11], ash:[86,1010,33300], asu:[3,8,124], @@ -17,11 +20,13 @@ const CITY_PDB={ atn:[42,589,33300], auh:[4,1,231], bcn:[13,159,1341], + bda:[2,8,25], // est. bde:[0,0,4027], beg:[7,49,227], bel:[3,7,9693], ber:[22,351,3705], bet:[16,174,152], + bgi:[1,5,20], // est. bhz:[13,40,9693], bkk:[32,397,675], blr:[14,104,6412], @@ -30,6 +35,7 @@ const CITY_PDB={ bom:[59,1050,6412], bos:[31,209,33300], bru:[33,328,443], + brw:[0,0,33300], // est. bsb:[14,108,9693], bud:[6,146,369], bue:[28,372,1357], @@ -41,15 +47,18 @@ const CITY_PDB={ cas:[2,2,39], cau:[2,2,9693], cbo:[1,0,33], + cbr:[5,60,3196], // est. ccs:[6,32,296], cgb:[4,5,9693], cgr:[4,4,9693], + chc:[4,30,755], // est. chi:[64,809,33300], cor:[2,29,1357], cph:[30,290,529], cpq:[19,65,9693], cpt:[6,267,879], cpv:[4,12,9693], + cur:[3,20,25], // est. cwb:[11,79,9693], cxj:[2,3,9693], dac:[30,107,2105], @@ -58,26 +67,37 @@ const CITY_PDB={ del:[31,479,6412], den:[28,310,33300], dkr:[2,4,23], + dks:[0,0,6683], // est. dla:[3,14,34], doh:[6,29,31], drw:[3,15,3196], dub:[21,277,350], dur:[4,137,879], + dus:[13,350,3705], // 14 listed, one closed; Digital Realty DUS1-3 alone has 141 networks + dut:[0,0,33300], // est. dxb:[8,135,231], + dyr:[0,0,6683], // est. + ebj:[1,5,529], // est. edi:[4,46,4027], + fdf:[1,5,10], // est. fec:[5,4,9693], fih:[7,19,57], fln:[5,23,9693], for:[16,362,9693], fra:[56,2450,3705], fuj:[1,49,231], + fuk:[5,50,1330], // QTnet QD3 has 14 networks, BBIX Fukuoka is there; the rest est. gbe:[1,2,39], gdl:[4,22,814], + gdx:[1,2,6683], // est. gua:[5,16,103], gum:[6,28,11], gyn:[5,28,9693], ham:[26,228,3705], + hav:[0,0,8], // est.: no neutral data center + hba:[2,10,3196], // est. hel:[23,232,427], + hfx:[3,20,2595], // est. hir:[1,0,11], hkg:[57,1107,1514], hnl:[7,33,33300], @@ -87,15 +107,20 @@ const CITY_PDB={ icn:[37,201,1197], igu:[5,26,124], ist:[28,334,1290], + ivc:[1,2,755], // est. + jam:[0,0,2], // est. jed:[5,25,220], jib:[3,19,5], jkt:[98,3015,4108], jnb:[14,561,879], + jnu:[1,2,33300], // est. jpa:[4,18,9693], kcy:[22,313,33300], kgl:[5,14,34], khi:[7,15,488], + kin:[2,10,30], // est. kla:[2,18,71], + krs:[3,15,448], // est. kul:[20,210,434], kyv:[33,506,2342], lad:[8,27,79], @@ -115,6 +140,7 @@ const CITY_PDB={ mao:[7,15,9693], mba:[4,176,274], mcp:[2,0,9693], + mct:[3,25,45], // Equinix MC1 and WCS; presences est. mcz:[1,5,9693], mde:[2,18,598], mel:[20,395,3196], @@ -122,54 +148,71 @@ const CITY_PDB={ mgf:[4,9,9693], mia:[27,553,33300], mil:[29,728,1534], + mle:[1,3,15], // est. + mmk:[2,4,6683], // est. mnl:[17,352,750], mos:[49,632,6683], mpm:[7,20,36], mrs:[8,273,2249], + mru:[3,20,60], // est. mtl:[35,283,2595], mty:[5,27,814], muc:[22,230,3705], mvd:[1,2,53], + nas:[1,4,20], // est. nat:[1,3,9693], nbo:[9,283,274], nou:[2,2,19], nyc:[96,1322,33300], + ome:[0,0,33300], // est. oos:[5,22,443], osa:[19,229,1330], osl:[20,209,448], ott:[6,21,2595], pan:[8,26,158], par:[77,1528,2249], + pcn:[0,0,0], // est.: no network of its own + pdl:[1,3,187], // est. pek:[10,15,6717], per:[12,248,3196], phx:[26,279,33300], + pkc:[1,2,6683], // est. pmo:[3,46,1534], pmw:[3,8,9693], poa:[22,120,9693], pom:[2,0,46], + pos:[2,10,35], // est. ppg:[0,0,2], ppt:[0,0,6], prg:[24,336,775], + prr:[0,0,2595], // est. pvh:[3,4,9693], + pvs:[0,0,6683], // est. qro:[11,144,814], + rai:[1,3,8], // est. rao:[6,3,9693], rbr:[0,0,9693], rec:[6,31,9693], rek:[15,51,93], ria:[2,2,9693], rio:[33,577,9693], + rix:[8,60,330], // 8 listed, Perses 2 has 19 networks; presences est. rom:[12,213,1534], ror:[0,0,4], ruh:[8,29,220], + run:[3,15,15], // est. sao:[70,1875,9693], scl:[36,274,450], + sdq:[4,25,90], // est. sea:[37,539,33300], + sez:[1,4,20], // est. sgn:[6,36,1068], sha:[11,27,6717], sin:[58,1271,782], sjc:[57,1048,33300], sjo:[8,6,128], sjp:[2,4,9693], + sju:[5,40,60], // est. slc:[22,202,33300], slz:[1,6,9693], sof:[15,451,889], @@ -180,16 +223,21 @@ const CITY_PDB={ svg:[2,14,448], syd:[40,979,3196], tbu:[0,0,5], + tci:[3,30,1341], // est. the:[2,1,9693], + tik:[0,0,6683], // est. tll:[7,80,256], + tnr:[1,4,25], // est. tok:[58,917,1330], tor:[46,509,2595], tpe:[15,274,500], tun:[2,0,30], uio:[9,16,287], + uus:[1,3,6683], // est. van:[13,214,2595], vie:[30,377,860], vix:[6,30,9693], + vvo:[5,25,6683], // est. waw:[25,855,2743], wdh:[1,2,22], zrh:[38,535,1209], diff --git a/src/game/30-networks/40-traffic-shares.js b/src/game/30-networks/40-traffic-shares.js index 67a0c3b..8883887 100644 --- a/src/game/30-networks/40-traffic-shares.js +++ b/src/game/30-networks/40-traffic-shares.js @@ -8,7 +8,9 @@ const NET=Object.fromEntries(NETS.map(n=>[n.id,n])),NET_IDS=NETS.map(n=>n.id); PLDTea Time (Not That, Ta-Ta), TIM-Tam (its sibling Sparkly Seabone), Floptus (its parent SingTell), Sky-High and Tele-Nor-Way (Tell-Ya, Level Tree), Virgin Mediocre (Level Tree, Not That), and the long tail (tailUp()). The rest stay islands because they are too: the content giants, the transit-free incumbents (Doitsche, Comecast, Jio-graphy, Bee-Tee), - China and Korea, and Australians, who buy only from Australian carriers. */ + China and Korea, and Australia's big ISPs, which buy only from Australian carriers. Smaller Australians do sit in Tier 1 + cones: Kangaroo Courier buys from Cogentle, Doodoo and Spin2wintel from Hocus Pocus (Not That, Tell-Ya), Lintel from + Speedyloop (Tell-Ya). */ const CONE={},CONE_S={},DOWN={}; {const dn={};for(const n of NETS)for(const u of n.up||[])(dn[u]||(dn[u]=[])).push(n.id); for(const n of NETS){const s=new Set([n.id]),q=[n.id];while(q.length){for(const y of dn[q.pop()]||[])if(!s.has(y)){s.add(y);q.push(y);}} diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index abd4507..d8854ce 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -11,7 +11,7 @@ const scnName=()=>S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}) 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=[ - {id:'stg',n:tr('scenarios.only_spatzle_ix'),city:'stg',cash:400000,days:730,rules:{noTransit:true,local:true},d:tr('scenarios.start_in_stuttgart_where_nobody'),goal:tr('scenarios.reach_45_of_the_internet_and'),ok:()=>R.reach>=0.45&&R.served>=300}, + {id:'stg',n:tr('scenarios.only_spatzle_ix'),city:'stg',cash:400000,days:730,rules:{noTransit:true,local:true},d:tr('scenarios.start_in_stuttgart_where_nobody'),goal:tr('scenarios.reach_50_of_the_internet_and'),ok:()=>R.reach>=0.5&&R.served>=300}, {id:'redsea',n:tr('scenarios.red_sea_crisis'),city:'mrs',cash:2500000,days:540,rules:{banCities:['cai','jed'],banPairs:['eig:dxb-mrs','gbi:fuj-mrs','smw4:khi-mrs','smw6:mrs-bom','smw6:mrs-sin','peace:mrs-sin','aae:mrs-hkg','twoaf:mrs-bom','medn:cai-mrs','medn:ist-mrs','twoaf:jnb-mrs','eassy:nbo-mrs']},d:tr('scenarios.every_cable_through_the_red_sea'),goal:tr('scenarios.a_path_from_marseille_to_singapore'),ok:()=>pathExists('mrs','sin')&&(S.stats.asiaRun||0)>=RS_DAYS}, {id:'spat',n:tr('scenarios.the_cogentle_spat'),city:'nyc',cash:700000,days:540,rules:{spat:true},d:tr('scenarios.cogentle_and_goggle_are_not_speaking'),goal:tr('scenarios.99_reach_and_150_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=150}, {id:'carnaval',n:tr('common.carnaval'),city:'rio',cash:600000,days:100,rules:{},setup:()=>{S.biz.push({id:uid(),scripted:true,city:'rio',city2:null,reqs:[],name:'Carnaval Parade in Rio de Janeiro',type:'event',bw:400,rate:0,mood:100,since:0,start:90,dur:5,fee:400*5*70});},d:tr('scenarios.rio_from_scratch_carnaval_starts_in'),goal:tr('scenarios.deliver_carnaval_in_full'),ok:()=>(S.stats.evFull||0)>=1}, diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js index 250e9b5..8f4618a 100644 --- a/src/game/60-features/50-traceroute.js +++ b/src/game/60-features/50-traceroute.js @@ -10,9 +10,12 @@ function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev for(const x of S.caches)if(x.net===net&&popUp(x.city)&&!siteDown(x.city,'a'))out.push({k:'c',rank:0,city:x.city,pref:'normal',lab:tr('common.name_cache',{name:NET[net].cache.name}),used:R.useCache[x.id]||0,cap:CACHE_CAP}); // A peer's customer cone (#85): one AS hop more, so tried after direct peering and before transit, as in compute(). for(const p of S.pni)if(CONE_S[p.net].has(net)&&pniOn(p)&&popUp(p.city)&&liveN(p.city,p.site,p.n))out.push({k:'p',rank:p.net===net?1:CONE_RANK,via:p.net===net?null:p.net,city:p.city,pref:p.pref||'normal',lab:tr('common.pni_with_net',{net:NET[p.net].name}),used:R.usePni[p.id]||0,cap:liveCap(pniG(p),p.city,p.site,p.n)}); - for(const c in S.ixp){const ses=ixSessions(c),via=ses.has(net)?null:[...ses].find(id=>CONE_S[id].has(net));if((ses.has(net)||via)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:via?CONE_RANK:2,via,city:ixCity(c),id:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('common.ix_peering',{ix:ixName(c)}),used:R.useIx[c]||0,cap:ixCap(c)});} + for(const c in S.ixp){const ses=ixSessions(c),via=ses.has(net)?null:ANC[net].find(u=>ses.has(u))||null;if((ses.has(net)||via)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:via?CONE_RANK:2,via,city:ixCity(c),id:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('common.ix_peering',{ix:ixName(c)}),used:R.useIx[c]||0,cap:ixCap(c)});} for(const t of S.transit)if(popUp(t.city)&&!(t.down>day)&&liveN(t.city,t.site,t.n)&&net!==leak&&!((ev.depeer>day||scnRule('spat'))&&t.net==='cog'&&net==='ggl'))out.push({k:'t',rank:3,city:t.city,pref:t.pref||'normal',lab:tr('traceroute.name_transit',{name:NET[t.net].name}),tnet:t.net,used:R.useT[t.id]||0,cap:liveCap(PORT[t.tier].g,t.city,t.site,t.n)}); return out;} +// coneChain(peer,net): [peer, …, net], the shortest walk down customer links (the network's up lists, read backwards). +function coneChain(top,id){const prev={[id]:null},q=[id];while(q.length){const x=q.shift();if(x===top)break;for(const u of NET[x].up||[])if(NET[u]&&!(u in prev)){prev[u]=x;q.push(u);}} + if(!(top in prev))return [top,id];const out=[];for(let x=top;x!==null;x=prev[x])out.push(x);return out;} function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1; const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);}; hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,tr('traceroute.city_your_router',{city:CITY[src].name})); @@ -30,7 +33,8 @@ function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[] hop(`${slug(N.name)}-peer.${far}.${slug(T.name)}.net`,`198.51.100.${hstr(N.id)%250}`,0.4,tr('traceroute.net_hands_it_to_to',{net:T.name,to:N.name}));}} else if(e.k==='ix'){hop(`${slug(ixName(e.city))}.peering.${e.city}`,`185.0.${hstr(e.city)%250}.${hstr(N.id)%250}`,0.3,tr('traceroute.across_the_ix_switch',{ix:ixName(e.city)}));} else if(e.k==='p'){hop(`pni-${slug(NET[e.via||N.id].name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,tr('traceroute.private_cross_connect'));} - if(e.via){const V=NET[e.via];asPath.push(V.asn);hop(`${slug(N.name)}-cust.${e.city}.${slug(V.name)}.net`,`198.51.100.${(hstr(V.id)+3)%250}`,1.2,tr('traceroute.net_hands_it_to_its_customer',{net:V.name,to:N.name}));} + // Down the cone one customer at a time: the shortest chain of upstreams from the peer to the network, each AS on the path. + if(e.via){const ch=coneChain(e.via,N.id);for(let i=0;i{const v=S.achP&&S.achP[b.id];if(v&&v!=='oncall'&&BVAR[v]){g.strokeStyle=BVAR[v].col;g.lineWidth=4;g.beginPath();g.arc(60+i*48,537,22,0,7);g.stroke();}}); + top.forEach((b,i)=>{const v=S.achP&&S.achP[b.id];if(v&&v!=='oncall'&&own(BVAR,v)){g.strokeStyle=BVAR[v].col;g.lineWidth=4;g.beginPath();g.arc(60+i*48,537,22,0,7);g.stroke();}}); g.font='34px sans-serif';top.forEach((b,i)=>g.fillText(b.i,40+i*48,520)); {const n=v=>got.filter(b=>(S.achP&&S.achP[b.id]||'oncall')===v).length,f=n('freeze'),h=n('bgp');if(f||h){g.fillStyle='#1E2640';g.font='800 18px Nunito, sans-serif';g.fillText([h?`🔥 ${h}`:'',f?`🧊 ${f}`:''].filter(Boolean).join(' '),40+Math.max(1,top.length)*48+8,526);}} g.fillStyle='#1E2640';g.font='900 30px "Baloo 2", sans-serif';g.fillText('seriesoftub.es',40,572);g.font='700 20px Nunito, sans-serif';g.fillText(tr('share_card.build_the_internet_one_tube_at'),300,580); diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js index aa4a274..528c15a 100644 --- a/src/game/60-features/90-automation.js +++ b/src/game/60-features/90-automation.js @@ -11,7 +11,14 @@ function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.ra // Trial the added demand before signing; failed trials leave the live game untouched. try{S={...S,biz:S.biz}; // shortcut: future events reserve capacity together; use per-date trials if separate bookings must share capacity. - if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();} + if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x); + /* Signed if the offer works and nobody who works without it breaks. compute() reads the last result only for + scenic circuits, so without them the pass with the offer can go first: when the offer fails, or nobody is + unhappy with it, the pass without it cannot change the answer and is skipped. */ + const fut=S.biz,all=fut.concat(b); + if(!all.some(x=>x.route==='scenic')){if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=all;compute();if(bizWhy(b).length)return null; + const bad=fut.filter(x=>bizWhy(x).length);if(!bad.length)return b;S.biz=fut;compute();return bad.every(x=>bizWhy(x).length)?b:null;} + compute();} const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}} diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js index 1d7ede6..a6b7bba 100644 --- a/src/game/60-features/90-puzzles-data.js +++ b/src/game/60-features/90-puzzles-data.js @@ -4,7 +4,7 @@ noSub (no subsea cables), ring (one ring through every POP), lat:[a,b,ms] (best path under ms), minG (every link at least this many Gbps), avoid (cities shown on the map that you may not build in). */ const PZ_PACKS=[ - {id:'hello',n:tr('puzzles.hello_world'),d:tr('puzzles.your_first_tubes_no_pressure'),need:0}, + {id:'hello',n:tr('puzzles.hello_world'),d:tr('puzzles.your_first_tubes_roomy_budgets'),need:0}, {id:'fire',n:tr('puzzles.ring_of_fire'),d:tr('puzzles.the_pacific_rim_where_every_hop'),need:6}, {id:'speed',n:tr('puzzles.speed_runs'),d:tr('puzzles.beat_the_clock_light_in_glass'),need:14}, {id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.for_architects_who_sleep_through_backhoes'),need:22}, @@ -12,22 +12,22 @@ const PZ_PACKS=[ const PZ=[ {id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),cities:['lon','nyc'],budget:0}, {id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),cities:['lon','ams','fra'],budget:0}, - {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),cities:['nyc','chi','dal','sjc'],budget:300000}, - {id:'smorgas',pack:'hello',n:tr('puzzles.smorgasbord'),j:tr('puzzles.four_capitals_one_very_long_winter'),cities:['osl','sto','cph','hel'],budget:190000}, - {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),cities:['syd','mel','bne','adl'],budget:300000}, - {id:'aloha',pack:'fire',n:tr('puzzles.aloha_latency'),j:tr('puzzles.honolulu_the_world_s_most_scenic'),cities:['sjc','hnl','syd'],budget:1750000}, - {id:'rimshot',pack:'fire',n:tr('puzzles.pacific_rim_shot'),j:tr('puzzles.seattle_to_singapore_with_a_stop'),cities:['sea','tok','hkg','sin'],budget:1200000}, - {id:'fire',pack:'fire',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),cities:['tok','hkg','sin','syd'],ring:true,budget:1600000}, - {id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv'],budget:1400000}, - {id:'guam',pack:'fire',n:tr('puzzles.guam_slam'),j:tr('puzzles.a_tiny_island_where_half_the'),cities:['tok','mnl','syd'],via:['gum'],budget:1600000}, - {id:'flash',pack:'speed',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),cities:['nyc','lon'],lat:['nyc','lon',27],budget:450000}, - {id:'pingpong',pack:'speed',n:tr('puzzles.ping_pong_to_tokyo'),j:tr('puzzles.the_pacific_is_big_light_is'),cities:['lax','tok'],via:['sea','sjc'],lat:['lax','tok',47],budget:850000}, - {id:'suez',pack:'speed',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),cities:['fra','sin'],via:['mrs','bom'],lat:['fra','sin',68],budget:1000000}, - {id:'samba',pack:'speed',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),cities:['sao','mia'],via:['for','rio'],lat:['sao','mia',45],budget:950000}, + {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),cities:['nyc','chi','dal','sjc'],budget:340000}, + {id:'smorgas',pack:'hello',n:tr('puzzles.smorgasbord'),j:tr('puzzles.four_capitals_one_very_long_winter'),cities:['osl','sto','cph','hel'],budget:210000}, + {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),cities:['syd','mel','bne','adl'],budget:320000}, + {id:'aloha',pack:'fire',n:tr('puzzles.aloha_latency'),j:tr('puzzles.honolulu_the_world_s_most_scenic'),cities:['sjc','hnl','syd'],budget:1830000}, + {id:'rimshot',pack:'fire',n:tr('puzzles.pacific_rim_shot'),j:tr('puzzles.seattle_to_singapore_with_a_stop'),cities:['sea','tok','hkg','sin'],budget:1240000}, + {id:'fire',pack:'fire',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),cities:['tok','hkg','sin','syd'],ring:true,budget:1610000}, + {id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv','lax'],budget:1450000}, + {id:'guam',pack:'fire',n:tr('puzzles.guam_slam'),j:tr('puzzles.a_tiny_island_where_half_the'),cities:['tok','mnl','syd'],via:['gum'],budget:1700000}, + {id:'flash',pack:'speed',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),cities:['nyc','lon'],lat:['nyc','lon',27],budget:465000}, + {id:'pingpong',pack:'speed',n:tr('puzzles.ping_pong_to_tokyo'),j:tr('puzzles.the_pacific_is_big_light_is'),cities:['lax','tok'],via:['sea','sjc'],lat:['lax','tok',47],budget:880000}, + {id:'suez',pack:'speed',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),cities:['fra','sin'],via:['mrs','bom'],lat:['fra','sin',68],budget:1010000}, + {id:'samba',pack:'speed',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),cities:['sao','mia'],via:['for','rio'],lat:['sao','mia',45],budget:1060000}, {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),cities:['lis','mad','par','mil'],via:['bcn','mrs'],noSub:true,budget:210000}, {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),cities:['nyc','lon','dub'],budget:380000}, - {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),cities:['ams','ber','muc','zrh'],via:['ham','dus'],avoid:['fra'],budget:200000}, - {id:'fatpipes',pack:'n1',n:tr('puzzles.fat_pipes_only'),j:tr('puzzles.nobody_ever_got_fired_for_buying'),cities:['par','mrs','mil','zrh'],minG:100,budget:240000}, + {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),cities:['ams','ber','muc','zrh'],via:['ham','dus'],avoid:['fra'],budget:192000}, + {id:'fatpipes',pack:'n1',n:tr('puzzles.fat_pipes_only'),j:tr('puzzles.nobody_ever_got_fired_for_buying'),cities:['par','mrs','mil','zrh'],minG:100,budget:235000}, ]; // Weekly puzzle pools: each is one landmass and one region, so every pair has an overland route. const PZ_WEEK_POOLS=[ diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index b0ca38e..ed43683 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -6,7 +6,7 @@ const PZ_KEY='sot-puzzles',PZ_YEAR=12; const pzOn=()=>!!(S&&S.mode==='puzzle'&&S.pz); const pzDef=id=>PZ.find(p=>p.id===id)||null; const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':null; -const pzName=d=>d.id==='weekly'?tr('puzzles.weekly_puzzle_key',{key:d.key}):d.n; +const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key',{key:d.key})):d.n; const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n); // ---------- progress (localStorage, never trusted) ---------- function pzClean(j){const o={s:{},wk:{},streak:{last:null,n:0,best:0}};if(!j||typeof j!=='object')return o; @@ -28,11 +28,12 @@ function pzRoutes(a,b){const out=[],sub=isSub(a,b); return out;} const pzMo=(r,tier,div)=>Math.round(waveMo(r.km,r.sub,tier)*r.f*(div?DIVERSE:1)); const pzLinkCost=(r,tier,div)=>pzMo(r,tier,div)*PZ_YEAR;// leased waves have no setup fee: a year of rent -const pzPopCost=c=>popCost(c)+PZ_YEAR*POP_MO; +const pzPopCost=c=>popCost(c)+PZ_YEAR*popMo(c);// thin markets cost more every month too (#94) const PZ_TIERS=[0,1,2]; function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c);for(const l of S.links)s+=l.mo*PZ_YEAR;return s;} -// What one backhoe or one anchor takes out: waves in the same trench, or on the same cable between the same cities. -const pzUnit=l=>l.cable?'cab:'+l.cable+':'+edgeKey(l):String(l.trench||l.id); +// What one backhoe or one anchor takes out: waves in the same trench, or every wave on the same cable (a cable fails +// as a whole, as in the main game's diversity checks). +const pzUnit=l=>l.cable?'cab:'+l.cable:String(l.trench||l.id); // ---------- checks ---------- function pzComp(ls,skip,from){const adj={};for(const l of ls){if(skip&&pzUnit(l)===skip)continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);} const seen=new Set([from]),q=[from];while(q.length){const u=q.pop();for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return seen;} @@ -51,38 +52,49 @@ function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend(); if(P.minG)tw.push({k:'g',ok:ls.every(l=>LT[l.tier].g>=P.minG)}); if(P.avoid.length)tw.push({k:'avoid',ok:P.avoid.every(c=>!S.pops[c])}); const goal=conn&&tw.every(t=>t.ok),units=[...new Set(ls.map(pzUnit))]; - // N-1: the goal cities stay joined whichever single trench or cable segment is cut. + // N-1: the goal cities stay joined whichever single trench or cable is cut. const weak=conn?units.filter(u=>{const g=pzComp(ls,u,cs[0]);return !cs.every(c=>g.has(c));}):[]; const n1=conn&&units.length>0&&!weak.length,cheap=!P.budget||spend<=P.budget; return {marks,conn,tw,goal,spend,cheap,n1,weak,stars:goal?1+(cheap?1:0)+(n1?1:0):0};} -// ---------- the weekly puzzle: the same for everyone, seeded by the ISO week like the weekly challenge ---------- -function pzWeekKey(dt){const {y,w}=isoWeek(dt);return `${y}-W${String(w).padStart(2,'0')}`;} -function pzPrevKey(key){const m=/^(\d{4})-W(\d{2})$/.exec(key);if(!m)return null;return pzWeekKey(new Date(+m[1],0,4+(+m[2]-2)*7));} +// Two stars, and one more link within budget would survive any cut? Then the third star is close. Tries every route +// between the puzzle's cities at the smallest allowed size, so the nudge is true, not a guess. +function pzOneMore(e){const P=S.pz;if(e.stars!==2||!e.cheap||e.n1)return false;const cs=[...P.cities,...P.via],tier=P.minG?1:0,cs0=P.cities[0]; + for(const a of cs)for(const b of cs){if(a>=b)continue;for(const r of pzRoutes(a,b)){if((P.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))continue; + const div=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),cost=pzLinkCost(r,tier,div)+(S.pops[a]?0:pzPopCost(a))+(S.pops[b]?0:pzPopCost(b)); + if(e.spend+cost>P.budget)continue;const ls=[...S.links,{id:'pz?',a,b,cable:r.cab,trench:r.cab?'cab:'+r.cab:'pz?'}];if(P.ring&&!pzRingOk(ls))continue; + if([...new Set(ls.map(pzUnit))].every(u=>{const g=pzComp(ls,u,cs0);return P.cities.every(c=>g.has(c));}))return true;}} + return false;} +// ---------- the seeded weekly puzzle: the same for everyone, and the stand-in when the published one (93-puzzles-weekly.js) is not there ---------- function pzWeekly(dt){const key=pzWeekKey(dt||new Date());let r=hstr('puzzle|'+key)||1;const nx=()=>{r=(Math.imul(r,1103515245)+12345)>>>0;return r/4294967296;}; const pool=PZ_WEEK_POOLS[Math.floor(nx()*PZ_WEEK_POOLS.length)].slice(),n=4+Math.floor(nx()*2),cities=[]; while(cities.lengthkmBetween(u,a)-kmBetween(u,b));ring.push(left.shift());} - let cost=cities.reduce((a,c)=>a+pzPopCost(c),0);for(let i=0;ipzLinkCost(x,0,false))); - return {id:'weekly',key,cities,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring};} + let cost=cities.reduce((a,c)=>a+pzPopCost(c),0);const used=new Set(),via=[]; + for(let i=0;i!x.cab||!used.has(x.cab)).sort((x,y)=>pzLinkCost(x,0,false)-pzLinkCost(y,0,false))[0]; + if(r.cab)used.add(r.cab);via.push(r.via);cost+=pzLinkCost(r,0,false);} + return {id:'weekly',key,cities,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring,refVia:via};} function pzStreak(p,key){const st=p.streak;if(st.last===key)return;st.n=st.last&&st.last===pzPrevKey(key)?st.n+1:1;st.last=key;st.best=Math.max(st.best,st.n);} function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==='weekly'?P.key:pzName(pzDef(P.id)),stars:pzStarStr(e.stars),spend:fmt$(e.spend)});} // ---------- entering and leaving ---------- +// Toasts from one world never carry over into the other (their buttons act on the S they came from). +const pzToastsClear=()=>{$('toasts').textContent='';}; // The running game gets its usual save first, so leaving the puzzle can load it back exactly as booting does. A huge // save is compressed in the background and may not have landed yet, so the game object is kept in memory too. function pzFlush(){save(true);UI.pzKeep=UI.gzBusy||saveFailing()?S:null;} function pzBegin(def){if(!def)return; const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null; - S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null}; + S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null}; UI.pzHist=[];UI.pzTop=0;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null; - $('dash').hidden=true;$('bankBox').hidden=true;closeModal();document.body.classList.add('pz'); + $('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz'); compute();pzCam();renderAll();track('puzzle_'+def.id); toast(`${esc(pzName(def))}
${tr('puzzles.connect_list',{list:def.cities.map(c=>CITY[c].name).join(', ')})}`,'goal');}; if(pzOn()){go();return;} const live=!!(S&&UI.started&&!S.lost);UI.pzFrom=live?'game':'title'; if(live)pzFlush();go();} -function pzLeave(){const from=UI.pzFrom;document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; +function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){S=null;UI.started=false;}}} renderAll();showTitle();} @@ -97,8 +109,11 @@ const pzNewPop=()=>({day:0,bb:null,boost:0,down:0,routers:1,gen:false}); function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null; compute();renderAll();pzCheck();} // Stars count the moment they are earned: a better result than this attempt has had opens the results card. -function pzCheck(){const e=pzEval();if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;pzRecord(e);pzResults(e,prev);return e;} +// Every solved state is recorded, so a cheaper build at the same stars counts too. +function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;pzResults(e,prev);return e;} +// The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend. function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=bag[k]||{st:0,sp:null}; - r.st=Math.max(r.st,e.stars);r.sp=r.sp==null?e.spend:Math.min(r.sp,e.spend);bag[k]=r;if(P.id==='weekly')pzStreak(p,P.key);pzStore(p);} + if(e.starsx.id===S.pz.id);for(let j=i+1;j.json (scripts/weekly-puzzle.js): a static file next to + the page, fetched only when the player opens Puzzles. It is checked field by field; when it is missing, offline or + wrong, the seeded weekly in 92-puzzles.js stands in, so the weekly puzzle never breaks. */ +// Europe/Berlin is UTC+1, and UTC+2 from the last Sunday of March to the last Sunday of October, 01:00 UTC both times. +const pzLastSun=(y,m)=>{const d=new Date(Date.UTC(y,m+1,0));return Date.UTC(y,m,d.getUTCDate()-d.getUTCDay(),1);}; +const pzBerlinOff=t=>{const y=new Date(t).getUTCFullYear();return t>=pzLastSun(y,2)&&tsun+(6-pzBerlinOff(sun+4*3600e3))*3600e3; +function pzIso(t){const d=new Date(t);d.setUTCHours(0,0,0,0);d.setUTCDate(d.getUTCDate()+4-(d.getUTCDay()||7));const y=d.getUTCFullYear();return `${y}-W${String(Math.ceil(((d-Date.UTC(y,0,1))/864e5+1)/7)).padStart(2,'0')}`;} +// The key of the puzzle week holding this moment. +function pzWeekKey(dt){const t=+dt,d=new Date(t);let sun=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate())-d.getUTCDay()*864e5; + if(t{const t=pzWeekStart(key);return t==null?null:pzWeekKey(t+n*7*864e5+3*3600e3);}; +const pzPrevKey=key=>pzKeyAdd(key,-1); +// ---------- themes and their text: labels, so the file names a label and the player reads their language ---------- +// A file may only use these labels (N_: kept whole in the shipped page, since the file names them in full). +const PZ_WK_THEMES={ + detour:{i:'🚧',t:N_('puzzles_weekly.detour'),names:[N_('puzzles_weekly.name_anywhere_but_hub'),N_('puzzles_weekly.name_who_needs_hub')],jokes:[N_('puzzles_weekly.joke_hub_is_having_a_very'),N_('puzzles_weekly.joke_the_obvious_path_goes_through')]}, + islands:{i:'🏝️',t:N_('puzzles_weekly.island_hopping'),names:[N_('puzzles_weekly.name_hop_skip_and_a_cable'),N_('puzzles_weekly.name_sun_sea_and_subsea')],jokes:[N_('puzzles_weekly.joke_every_hop_is_a_cable'),N_('puzzles_weekly.joke_the_cheapest_way_between_two')]}, + ocean:{i:'🌊',t:N_('puzzles_weekly.ocean_crossing'),names:[N_('puzzles_weekly.name_sea_you_in_b'),N_('puzzles_weekly.name_across_the_big_blue')],jokes:[N_('puzzles_weekly.joke_the_ocean_is_big_and'),N_('puzzles_weekly.joke_somewhere_between_a_and_b')]}, + ring:{i:'💍',t:N_('puzzles_weekly.ring'),names:[N_('puzzles_weekly.name_one_ring_to_rule_reg'),N_('puzzles_weekly.name_ring_around_reg')],jokes:[N_('puzzles_weekly.joke_one_ring_through_every_pop'),N_('puzzles_weekly.joke_a_ring_survives_one_cut')]}, + sprint:{i:'⚡',t:N_('puzzles_weekly.latency_sprint'),names:[N_('puzzles_weekly.name_race_to_b'),N_('puzzles_weekly.name_ms_ms_or_bust')],jokes:[N_('puzzles_weekly.joke_a_to_b_under_ms'),N_('puzzles_weekly.joke_the_speed_of_light_is')]}, + tour:{i:'🗺️',t:N_('puzzles_weekly.region_tour'),names:[N_('puzzles_weekly.name_tour_de_reg'),N_('puzzles_weekly.name_are_we_there_yet_a')],jokes:[N_('puzzles_weekly.joke_n_cities_one_landmass_and'),N_('puzzles_weekly.joke_a_road_trip_for_photons')]}, +}; +// What each {placeholder} in those labels holds: c a city id, r a region code, n a whole number. +const PZ_WK_P={a:'c',b:'c',hub:'c',reg:'r',ms:'n',n:'n'}; +const pzCityOk=c=>isCity(c)&&!CITY[c].off&&!CITY[c].cn; +const pzTxt=o=>{const v={};for(const k in o.p){const x=o.p[k],t=PZ_WK_P[k];v[k]=t==='c'?CITY[x].name:t==='r'?WAVE_NAME[x]:x;}return tr(o.l,v);}; +// ---------- the file: never trusted. Only known fields, known cities, known labels and sane numbers get through ---------- +const pzObj=o=>!!o&&typeof o==='object'&&!Array.isArray(o); +function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l))return null;const p=o.p==null?{}:o.p;if(!pzObj(p))return null; + const need=[...new Set([...String(EN[o.l]).matchAll(/\{(\w+)\}/g)].map(m=>m[1]))],out={}; + if(Object.keys(p).length!==need.length)return null; + for(const k of need){const t=PZ_WK_P[k],v=own(p,k)?p[k]:undefined; + if(t==='c'&&pzCityOk(v))out[k]=v;else if(t==='r'&&typeof v==='string'&&own(WAVE_NAME,v))out[k]=v;else if(t==='n'&&Number.isInteger(v)&&v>0&&v<1000)out[k]=v;else return null;} + return {l:o.l,p:out};} +const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref']; +function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==1||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null; + const T=PZ_WK_THEMES[j.theme],ids=(a,lo,hi)=>Array.isArray(a)&&a.length>=lo&&a.length<=hi&&a.every(pzCityOk)&&new Set(a).size===a.length?a.slice():null; + const cities=ids(j.cities,3,6),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2);if(!cities||!via||!avoid)return null; + const all=[...cities,...via,...avoid];if(new Set(all).size!==all.length)return null; + if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>1e7)return null; + const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['lat','ring','noSub','minG'].includes(k)))return null; + const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null}; + if(own(tw,'ring')){if(tw.ring!==true)return null;d.ring=true;} + if(own(tw,'noSub')){if(tw.noSub!==true)return null;d.noSub=true;} + if(own(tw,'minG')){if(![100,400].includes(tw.minG))return null;d.minG=tw.minG;} + if(own(tw,'lat')){const l=tw.lat;if(!Array.isArray(l)||l.length!==3||!cities.includes(l[0])||!cities.includes(l[1])||l[0]===l[1]||!Number.isInteger(l[2])||l[2]<1||l[2]>500)return null;d.lat=l.slice();} + d.wn=pzWkTxt(j.name,T.names);d.wj=pzWkTxt(j.joke,T.jokes);if(!d.wn||!d.wj)return null; + return d;} +// ---------- fetching it: when Puzzles opens, never on page load ---------- +function pzWkEnsure(){const key=pzWeekKey(new Date()),w=UI.pzWk; + if(w&&w.key===key&&(w.st!=='fb'||Date.now()-w.at<5*60e3))return; + const st=UI.pzWk={key,st:w&&w.key===key&&w.def?'ok':'load',def:w&&w.key===key?w.def:null,at:Date.now()}; + let done=false;const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.pzWk!==st)return;if(def){st.def=def;st.st='ok';}else if(!st.def)st.st='fb';st.at=Date.now();pzWkRefresh();}; + const ac=window.AbortController?new AbortController():null,to=setTimeout(()=>{if(ac)ac.abort();fin(null);},5000); + if(!window.fetch||location.protocol==='file:'){fin(null);return;} + // Relative and same origin; each week has its own file name, so caches never serve last week's. + try{fetch(`puzzles/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>pzWkValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +// This week's puzzle: the published one when it came, else the seeded one. +function pzWkDef(){const key=pzWeekKey(new Date()),w=UI.pzWk;return w&&w.key===key&&w.def?w.def:pzWeekly();} +const pzWkLoading=()=>{const w=UI.pzWk;return !!w&&w.st==='load'&&w.key===pzWeekKey(new Date());}; +function pzWkRefresh(){const el=$('pzWk');if(el)el.outerHTML=pzWkRow();} +// "Next weekly puzzle in 2 d 14 h". +function pzWkNext(now){const key=pzWeekKey(now),t=pzWeekStart(pzKeyAdd(key,1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60); + return d?tr('puzzles.next_weekly_in_d_h',{d,h}):tr('puzzles.next_weekly_in_h_m',{h,m:m%60});} +// The Puzzles door says so when this week's puzzle has not been played yet. +function pzWkNew(){try{return !pzLoad().wk[pzWeekKey(new Date())];}catch(e){return false;}} diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 9aa65be..fa6cb2e 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -2,17 +2,18 @@ A NOC intern runs the player's standing orders once per game day. Every job goes through the same action a click would (ACT.*, pniPlace, the #185/#192 planners), so it costs exactly what the click costs, with toasts and redraws muted and one recompute at the end. Without an intern nothing here runs and no random numbers are drawn. */ -const INTERN_MO=6000,OPS_LOG=12,OPS_CAPS=[10000,50000,250000,1e6,5e6,0],OPS_FLOORS=[0,50000,250000,1e6,5e6]; +const INTERN_MO=6000,OPS_LOG=12,OPS_CAPS=[10000,50000,250000,1e6,5e6,0],OPS_CAPS_MO=[1000,2500,5000,10000,25000,0],OPS_FLOORS=[0,50000,250000,1e6,5e6]; const INTERNS={ annie:{i:'📡',n:N_('ops.anycast_annie'),s:N_('ops.annie'),d:N_('ops.annie_d')}, kevin:{i:'🌙',n:N_('ops.kevin_from_the_night_shift'),s:N_('ops.kevin'),d:N_('ops.kevin_d')}, tracy:{i:'🧭',n:N_('ops.tracy_route'),s:N_('ops.tracy'),d:N_('ops.tracy_d')}, }; -// The orders, in the order the panel shows them. pop: can be switched off per POP. cap: default monthly budget. +// The orders, in the order the panel shows them. pop: can be switched off per POP. cap: default monthly budget, of setup +// fees, or (mo) of the running costs the order adds, for caches, which are free to rack but cost rent every month. const OPS=[ {k:'transit',i:'📈',pop:1,cap:50000,t:N_('ops.o_transit'),d:N_('ops.o_transit_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}}, {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}}}, - {k:'caches',i:'📦',pop:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, + {k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, {k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}}, {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>tr(v?'common.on':'common.off')}}}, {k:'sales',i:'💼',t:N_('ops.o_sales'),d:N_('ops.o_sales_d'),p:{acc:{d:true,v:[true,false],l:N_('ops.p_acc'),f:v=>tr(v?'common.on':'common.off')},min:{d:0,v:[0,2000,5000,10000,25000,50000],l:N_('ops.p_min'),f:v=>v?tr('common.price_mo',{price:fmt$(v)}):tr('ops.never')}}}, @@ -23,20 +24,22 @@ const OPS=[ const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); const OPS_TPL=['bb','transit','ix','kit']; // What the shift log can say. One line per day: "{name} did this, that and the other." -const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke')}; +const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')}; // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; const OPS_TRIALS=1,OPS_FF_RATE={oncall:1/150,bgp:1/60}; -function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} +function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),addMo:{},mon:0,skip:{},log:[],wk:null,rep:null,floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} const opsO=()=>S.ops||(S.ops=opsNew()); const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern)); const opsCanHire=()=>lvl()>=2; const opsName=(long)=>{const I=INTERNS[S.ops.intern];return I?tr(long?I.n:I.s):'';}; function opsP(k,p){const P=OPSK[k].p[p],v=S.ops.p[k]&&S.ops.p[k][p];return v!==undefined&&(P.ok?P.ok(v):P.v.includes(v))?v:P.d;} -function opsCap(k){const c=S.ops.cap[k];return OPS_CAPS.includes(c)?c:OPSK[k].cap||0;} +const opsCaps=k=>OPSK[k].mo?OPS_CAPS_MO:OPS_CAPS; +function opsCap(k){const c=S.ops.cap[k];return opsCaps(k).includes(c)?c:OPSK[k].cap||0;} const opsHere=(k,c)=>!(S.ops.skip[c]||[]).includes(k); const opsPops=k=>Object.keys(S.pops).filter(c=>opsHere(k,c)); -// Saves are untrusted: rebuild ops from known orders, params, cities and log shapes. Old saves get no intern, +// Saves are untrusted: rebuild ops from known orders, params, cities and log shapes. Runs after the POPs are repaired, +// so exceptions only survive for POPs that still exist. Old saves get no intern, // and the two #185 toggles (auto-accept, auto-pay repairs) become the sales and repair orders. function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s.ops)?s.ops:{},n=opsNew(),ob=x=>x&&typeof x==='object'&&!Array.isArray(x)?x:{}; n.intern=typeof o.intern==='string'&&own(INTERNS,o.intern)?o.intern:null;n.hired=int(o.hired,0,1e7,0);n.mon=int(o.mon,0,1e6,0); @@ -44,31 +47,73 @@ function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s const on=ob(o.on),p=ob(o.p),cap=ob(o.cap),sp=ob(o.spent); for(const d of OPS){const k=d.k;n.on[k]=on[k]===true;const q=ob(p[k]),r={}; for(const pk of Object.keys(d.p)){const P=d.p[pk];if(own(q,pk)&&(P.ok?P.ok(q[pk]):P.v.includes(q[pk])))r[pk]=q[pk];}n.p[k]=r; - if(d.cap&&OPS_CAPS.includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0));} + if(d.cap&&opsCaps(k).includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0)); + {const v=num(ob(o.addMo)[k],0);if(v)n.addMo[k]=Math.max(-1e9,Math.min(1e9,v));}} {const t=ob(o.tpl);for(const k of OPS_TPL)if(typeof t[k]==='boolean')n.tpl[k]=t[k];} - {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} + {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&own(s.pops,c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} if(Array.isArray(o.log))n.log=o.log.map(opsLogOk).filter(Boolean).slice(0,OPS_LOG); + n.wk=opsWkOk(o.wk);n.rep=opsWkOk(o.rep); if(s.autoSales===true)n.on.sales=true;if(s.autoRepair===true)n.on.repair=true;delete s.autoSales;delete s.autoRepair; s.ops=n;} -// A log entry: {d, i: intern, r: [[kind, n, [where…]]], f: fat-finger index, c: its city}. +// A log entry: {d, i: intern, r: [[kind, n, [where…]]], f: fat-finger index, c: its city, up: paid up front, mo: running costs added}. const opsWhereOk=w=>typeof w==='string'&&w.length<=48&&/^[a-z0-9~|]+( [+\w.×→⇧]+)?$/i.test(w)&&w.split(' ')[0].split('|').every(x=>isIx(x)||own(OPSK,x)||isNet(x)); function opsLogOk(e){if(!e||typeof e!=='object'||!own(INTERNS,e.i))return null;const r=Array.isArray(e.r)?e.r.filter(x=>Array.isArray(x)&&own(OPS_SAY,x[0])&&Array.isArray(x[2])).map(x=>[x[0],int(x[1],1,1e6,1),x[2].filter(opsWhereOk).slice(0,3)]).slice(0,16):[]; - const f=Number.isInteger(e.f)&&OPS_FF[e.f]?e.f:undefined;return {d:int(e.d,0,1e7,0),i:e.i,r,...(f!==undefined&&isCity(e.c)?{f,c:e.c}:{})};} + const f=Number.isInteger(e.f)&&OPS_FF[e.f]?e.f:undefined,up=int(e.up,0,1e12,0),mo=int(e.mo,-1e9,1e9,0); + return {d:int(e.d,0,1e7,0),i:e.i,r,...(f!==undefined&&isCity(e.c)?{f,c:e.c}:{}),...(up?{up}:{}),...(mo?{mo}:{})};} +// A week's tally, for the shift report and the one NOC notice a week: {w: week, i: intern, n: {kind: count}, wh: {kind: [where…]}, up, mo, rev, ff}. +function opsWkOk(x){if(!x||typeof x!=='object'||Array.isArray(x)||!own(INTERNS,x.i))return null;const n={},wh={},xn=x.n&&typeof x.n==='object'?x.n:{},xw=x.wh&&typeof x.wh==='object'?x.wh:{}; + for(const k of Object.keys(OPS_SAY)){if(own(xn,k)){const v=int(xn[k],0,1e6,0);if(v)n[k]=v;}if(own(xw,k)&&Array.isArray(xw[k])){const w=xw[k].filter(opsWhereOk).slice(0,3);if(w.length)wh[k]=w;}} + return {w:int(x.w,0,1e6,0),i:x.i,n,wh,up:int(x.up,0,1e12,0),mo:int(x.mo,-1e9,1e9,0),rev:int(x.rev,0,1e9,0),ff:int(x.ff,0,7,0)};} +const opsWkNew=w=>({w,i:S.ops.intern,n:{},wh:{},up:0,mo:0,rev:0,ff:0}); +const opsWkAny=x=>!!x&&(Object.keys(x.n).length>0||x.ff>0); +// "Kevin's week: signed 3 customers (+$41k/mo), topped up transit 2 times (Frankfurt +1×100G), declined 17 tiny offers. Week total: …" +function opsWeekLine(x){const I=INTERNS[x.i],name=I?tr(I.s):'',ks=Object.keys(x.n).sort((a,b)=>(a==='sales'?-1:b==='sales'?1:0)||(a==='broke')-(b==='broke')); + const parts=ks.map(k=>k==='sales'?trn('ops.w_sales',x.n[k],{rev:opsMo$(x.rev)}):trn(OPS_SAY[k],x.n[k],{where:(x.wh[k]||[]).map(opsWhere).join(', ')})); + if(x.ff)parts.push(trn('ops.w_oops',x.ff)); + return tr('ops.w_line',{name,list:parts.join(', ')})+(x.up||x.mo?' '+tr('ops.w_money',{cost:fmt$(x.up),mo:opsMo$(x.mo)}):'');} +// The intern's mood, from what the week has been like. No dice: the same day always reads the same. +function opsMood(){const O=S.ops,x=O.wk&&O.wk.w===Math.floor(S.day/7)?O.wk:null,n=x?x.n:{},jobs=Object.keys(n).filter(k=>k!=='broke'&&k!=='decline').reduce((a,k)=>a+n[k],0); + const k=S.day-O.hired<7?'new':x&&x.ff?'oops':n.snag?'snag':S.inc.some(i=>i.until>S.day&&i.type!=='ddos')?'outage':n.sales?'sales':n.broke?'broke':jobs>=5?'busy':S.day%2?'quiet':O.intern; + return tr({new:N_('ops.mood_new'),oops:N_('ops.mood_oops'),snag:N_('ops.mood_snag'),outage:N_('ops.mood_outage'),sales:N_('ops.mood_sales'),broke:N_('ops.mood_broke'),busy:N_('ops.mood_busy'),quiet:N_('ops.mood_quiet'), + annie:N_('ops.mood_annie'),kevin:N_('ops.mood_kevin'),tracy:N_('ops.mood_tracy')}[k],{name:opsName()});} // "fra +1×100G", "fra|ams", "ams~3", "transit" (an order, for the budget line) or "ggl" (a network). function opsWhere(w){const [a,x]=w.split(' '),nm=a.split('|').map(p=>own(OPSK,p)?tr(OPSK[p].t):isCity(p)?CITY[p].name:isNet(p)?NET[p].name:ixName(p)).join('–');return x?nm+' '+(isNet(x)?NET[x].name:x):nm;} function opsLine(e){const I=INTERNS[e.i],name=I?tr(I.s):'',parts=e.r.map(([k,n,w])=>trn(OPS_SAY[k],n,{where:w.map(opsWhere).join(', ')})); - return parts.length?tr('ops.l_line',{name,list:parts.join(', ')}):tr('ops.l_quiet',{name});} + return (parts.length?tr('ops.l_line',{name,list:parts.join(', ')}):tr('ops.l_quiet',{name}))+opsPaid(e);} +const opsMo$=v=>(v>0?'+':'')+fmt$(v); +const opsPaid=e=>e.up||e.mo?' '+tr('ops.l_paid',{cost:fmt$(e.up||0),mo:opsMo$(e.mo||0)}):''; +// What the network costs every month before traffic: what a job adds to the bill (ports, routers, rent, links, cache boxes). +// PNIs count from the day they are ordered, at the size they are going to be. +function opsMoNow(){let m=S.caches.length*CACHE_MO; + for(const c in S.pops){const p=S.pops[c],rt=p.routers||1;m+=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[p.rgen||0].mo;} + for(const l of S.links)m+=(l.mo||0)+(l.kind==='df'?(l.spares?Math.round(150+(l.ch||[]).length*80):0)+(l.regen|0)*REGEN_MO:0); + for(const t of S.transit)m+=transitMo(t,0); + for(const p of S.pni){const q=p.up||p,N=NET[p.net];m+=(q.g1?Math.round(PORT[0].pni/2):PORT[q.tier].pni)*(q.n||1)+(N.pol==='paid'&&!paidFree(N)?N.paidFee:0);} + return m;} const opsFFLine=e=>tr('ops.ff_line',{name:tr(INTERNS[e.i].s),what:tr(OPS_FF[e.f],{city:CITY[e.c].name})}); // Mute what a click would show (toasts, sounds, floaters, the full redraw) and keep the player's selection. function opsQuiet(fn){const a=after,t=toast,s=sfx,f=floater,sel=UI.sel,cf=UI.confirm,tab=UI.tab;after=()=>{};toast=()=>{};sfx=()=>{};floater=()=>{}; try{return fn();}finally{after=a;toast=t;sfx=s;floater=f;UI.confirm=cf;UI.tab=tab;UI.sel=sel&&(sel.type!=='link'||S.links.some(l=>l.id===sel.id))&&(sel.type!=='city'||isCity(sel.id))?sel:null;}} // One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget. +// dirty: a job changed the network, so R (loads, routing) is out of date until the next compute(). +// up/mo/rev: what this shift paid up front, added to the monthly bill, and signed in monthly revenue. function opsShift(){const r=new Map(),broke=new Set(); - return {r,broke,did(k,w){const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, - can(k,cost){const O=S.ops,cap=opsCap(k);if(cost<=0)return true;if(S.cash-costcap)){broke.add(k);return false;}return true;}, + return {r,broke,dirty:false,up:0,mo:0,rev:0,did(k,w){if(k!=='decline')this.dirty=true;const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, + // A job that costs nothing up front still has to pass the cash floor if it adds to the monthly bill. + can(k,cost,mo=0){const O=S.ops,cap=opsCap(k);if(cost<=0&&!(mo>0))return true; + if(S.cash-Math.max(0,cost)cap)){broke.add(k);return false;}return true;}, + book(k,d,dm){const O=S.ops;if(d>0){this.up+=d;if(OPSK[k].cap)O.spent[k]=(O.spent[k]||0)+d;}if(dm){this.mo+=dm;O.addMo[k]=(O.addMo[k]||0)+dm;}}, // Run a click and book what it really cost; false when the action refused (no ports, no cash, a quote changed). - pay(k,fn){const c0=S.cash,x=fn();const d=c0-S.cash;if(d>0&&OPSK[k].cap)S.ops.spent[k]=(S.ops.spent[k]||0)+d;return x===undefined?d>0:x;}};} -const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; + pay(k,fn){const c0=S.cash,m0=opsMoNow(),x=fn();this.book(k,c0-S.cash,opsMoNow()-m0);return x===undefined?c0-S.cash>0:x;}};} +// Never buy from a provider that breaks a promise: a customer's "no Cogentle" or "two upstreams", a bank's covenant, +// or Cogentle while it is not speaking to Goggle (the Spat scenario, a de-peering). Only met → failed counts. +const OPS_TREQ=['nocog','twoup']; +function opsTransitOk(n,c){if(n.id==='cog'&&(scnRule('spat')||S.ev.depeer>S.day))return false; + const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>OPS_TREQ.includes(k))),ls=(S.loans||[]).filter(l=>(l.covs||[]).includes('nocog'));if(!bz.length&&!ls.length)return true; + const chk=()=>bz.map(b=>b.reqs.every(k=>!OPS_TREQ.includes(k)||REQS[k].ok(b))).concat(ls.map(l=>COVS.nocog.ok(l))); + const was=chk(),all=S.transit;S.transit=all.concat({net:n.id,city:c});try{const now=chk();return was.every((v,i)=>!v||now[i]);}finally{S.transit=all;}} +const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; +const opsProv=c=>{const pv=opsP('transit','prov');return pv!=='cheap'&&sellsAt(NET[pv],c)&&opsTransitOk(NET[pv],c)?NET[pv]:cheapestTransit(c);}; // The orders. Each takes the shift and does its jobs through the player's own actions. const OPS_RUN={ repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');}, @@ -77,7 +122,7 @@ const OPS_RUN={ if(min&&vx!==o);X.did('decline');continue;} // Each trial is a full routing pass: at most one a shift, and an offer that did not fit waits a week. if(acc&&o.exp>S.day&&bCities(o).every(popUp)&&reqOk(o)&&triesS.day-7)){tries++;ACT.accept({id:o.id,auto:true}); - if(!S.offers.includes(o))X.did('sales');else{if(!UI.opsTried||UI.opsTried.s!==S)UI.opsTried={s:S,m:new Map()};UI.opsTried.m.set(o.id,S.day);}}}}, + if(!S.offers.includes(o)){X.did('sales');X.rev+=bizMo(o);}else{if(!UI.opsTried||UI.opsTried.s!==S)UI.opsTried={s:S,m:new Map()};UI.opsTried.m.set(o.id,S.day);}}}}, routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'); for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; const ld=Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));if(ld=4||!add);if(!doSwap&&(how==='swap'||!add))continue; const cost=doSwap?swapCost(c,nx):routerCost(g,rt);if(!X.can('routers',cost))continue; if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));}}, - transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'),pv=opsP('transit','prov'); + transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'); for(const c of opsPops('transit')){let ts=S.transit.filter(t=>t.city===c);if(!ts.length)continue; // Thirty days of 95th-percentile-ish history per port; their peaks summed is a safe (high) estimate of the POP's peak. const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0);if(!(peak>0))continue; - const n=pv!=='cheap'&&sellsAt(NET[pv],c)?NET[pv]:cheapestTransit(c);if(!n)continue; + const n=opsProv(c);if(!n)continue; for(let step=0;step<4;step++){const cap=ts.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0);if(cap>=N*peak)break; const t=ts.find(x=>x.net===n.id);let job=null; if(t){const k=t.n||1,up=t.tier+1; @@ -116,7 +161,7 @@ const OPS_RUN={ caches(X){const g=opsP('caches','g'); for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue; const want=q.add.filter(x=>(R.cityDem[c]||0)*(NSH[x.net]||0)>=g),free=Math.floor(portsMax(c)-portsUsed(c)+1e-9); - for(const x of want.slice(0,Math.max(0,free))){S.caches.push({id:uid(),city:c,net:x.net,site:x.site});X.did('caches',c);}}}, + for(const x of want.slice(0,Math.max(0,free))){if(!X.can('caches',0,CACHE_MO))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site});X.book('caches',0,CACHE_MO);X.did('caches',c);}}}, // Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192). ix(X){if(S.day%7)return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');} for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}}, @@ -127,11 +172,14 @@ const OPS_RUN={ if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}}, // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). decom(X){const keep=opsP('decom','keep'),by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} + // Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go. + if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;} for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue; let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a)); - if(keep)small.shift(); - for(const l of small.reverse()){if(cap-capOf(l)l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} + for(const l of small.reverse()){if(cap-capOf(l)ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}}, }; // A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first. function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; @@ -139,20 +187,28 @@ function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='dive const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}} const OPS_ORDER=['repair','sales','routers','transit','optics','caches','ix','pni','decom']; // The shift: once per game day from dayTick, after outages and events have had their turn. -function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;} - const X=opsShift(),cash=S.cash; - opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])OPS_RUN[k](X);}); +function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} + // A new week: last week's tally becomes the shift report, and the one NOC notice of the week. + const w=Math.floor(d/7);if(!O.wk||O.wk.w!==w){if(opsWkAny(O.wk)&&O.wk.w${esc(tr('ops.shift_report',{name:opsName()}))} ${esc(opsWeekLine(O.rep))}`,O.rep.rev>0?'good':'',[],{a:'tab',v:'noc'});}O.wk=opsWkNew(w);} + const X=opsShift(); + // One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen. + opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])try{OPS_RUN[k](X);}catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);}}); const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]); // Very rarely, and never under Change Freeze, the intern fat-fingers something harmless. const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;} + if(f===3){const t=O.on.transit&&opsHere('transit',c)&&!scnRule('noTransit')&&S.transit.find(t=>t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;else X.dirty=true;} e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);} - if(e.r.length||e.f!==undefined){compute();O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} - if(e.r.length)logNote(`${esc(tr('ops.shift',{name:opsName()}))} ${esc(opsLine(e))}`,cash>S.cash?'':'good',[],{a:'tab',v:'noc'});} + if(X.up)e.up=Math.round(X.up);if(Math.round(X.mo))e.mo=Math.round(X.mo); + // Declining an offer or stopping at a budget changes nothing a route depends on: no recompute for those. + if(X.dirty)compute(); + if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} + // The day's detail stays in the Ops sheet; the NOC gets one notice a week (above). + const W=O.wk;for(const [k,n,ws] of e.r){W.n[k]=(W.n[k]||0)+n;const a=W.wh[k]||(W.wh[k]=[]);for(const x of ws)if(a.length<3&&!a.includes(x))a.push(x);} + W.up+=e.up||0;W.mo+=e.mo||0;W.rev+=Math.round(X.rev);if(e.f!==undefined)W.ff=Math.min(7,W.ff+1);} // New POP from the template: price the whole bundle first, then click through it in one go. function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; if(T.bb){cost+=bbCost(c);parts.push(tr('ops.tpl_bb'));} - if(T.transit&&!scnRule('noTransit')){const pv=opsP('transit','prov');net=pv!=='cheap'&&sellsAt(NET[pv],c)?NET[pv]:cheapestTransit(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} + if(T.transit&&!scnRule('noTransit')){net=opsProv(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} // Priced as if the POP were already there (an IX port is dearer from afar). DE-KICKS wants a sales call first, so not those. S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false}; try{if(T.ix&&CITY[c].ix&&!isDk(c)&&S.ixp[c]===undefined){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 9b35c84..ea34fc6 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -1,5 +1,7 @@ // tr() with one placeholder, remembered: compute() labels every port, PNI and cache on every run. const LABS=new Map();function labOf(s,k,v){const key=s+'|'+v;let o=LABS.get(key);if(o===undefined)LABS.set(key,o=tr(s,{[k]:v}));return o;} +// Who carries a network reached only through a cone (kept out of compute(), whose size the JIT is sensitive to). +function coneBy(L,id){let by=null;for(const e of L){if(e.k==='p')return e.net;if(!by&&e.k==='ix'&&e.dir)by=ANC[id].find(u=>e.dir.has(u))||null;}return by||1;} function compute(){ const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length; // The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order. @@ -14,6 +16,8 @@ function compute(){ // ALONE[i]: no other city lies within 1e-6 of POP i (so only its own exits can be at distance 0 from it). const SPD={},SPP={},SDi=[],SPi=[],ALONE=new Uint8Array(NC),wW=e=>e.w,wLat=e=>e.lat+0.05; for(const s of pops){const i=CIDX[s],r=dijkstra(adj,i,wW);SDi[i]=SPD[s]=r.D;SPi[i]=SPP[s]=r.P;ALONE[i]=1;for(let x=0;x=0)continue;const D=SDi[i],k=NCOMP++;for(let x=0;xday||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null; for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue; @@ -41,8 +45,9 @@ function compute(){ // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}} for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id]; - // Reached without transit only through the customers of networks you peer with (#85). - if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id)))R2.cone[n.id]=1;}} + // Reached without transit only through the customers of networks you peer with (#85). R.cone[id]: the peer that + // carries it, the first PNI's network or else the nearest upstream that is a member of an exchange you are on. + if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id)))R2.cone[n.id]=coneBy(okBy[n.id],n.id);}} const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); // Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index). @@ -165,8 +170,15 @@ function compute(){ const PASSES=TR&&TR.protect?[x=>x.bz,x=>!x.bz]:null; // Each network's exits by the rank they route at (RouteScript can move an exit per network), in E's order. // Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order. + // With several islands (POPs no backbone joins), each list is split by island: a flow only scans exits it can reach. + const idx=L=>{L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}; + // Networks with the same exits at a rank share one list (LIST, by content), so what one flow learns serves them all. + const LIST=new Map();for(let i=0;ie.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}} + for(const r in m){const L=m[r],key=L.map(e=>e.xi).join(','),o=LIST.get(key);if(o){m[r]=o;continue;} + let V=L;if(NCOMP>1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);V={cs};}else idx(L);LIST.set(key,V);m[r]=V;}} + // Attack flows pinned to their entry port route at its plain rank, which RouteScript may have left with no list. + for(const f of flows)if(f.pin)for(const e of ingressE[f.pin]||[])RSET.add(base(e)); // The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index. let f=null,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],REST=[],NEG=[]; // An exit the flow can still try: not visited yet, not full when the flow started, and reachable from the POP. @@ -216,7 +228,7 @@ function compute(){ if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue; Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++; if(f.pin){for(const e of ingressE[f.pin]||[])if(base(e)===rank&&e.usede.used=e.cap){full++;continue;}const d=Dv[e.ci];if(d===Infinity)continue;const h=e.hp; if(h=lst.length&&full){let k=0;for(let li=0;li1)continue; - if(G.length>1)sortD(G);} + if(bh>1){gc[f.ci]=[];continue;} + if(G.length>1)sortD(G);gc[f.ci]=G.slice();}} sendGroup(G,0,G.length); if(f.rem<=1e-6)continue; REST.length=0;for(let li=0;liint(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);return l;}); for(const l of s.links)repairSubUpgradeDates(l,s.day); @@ -75,7 +75,7 @@ function sanitize(s){ s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; // Badges: S.ach[id] is the day it was earned (any save); S.achP[id] the variant (2.0). A missing variant is the standard one. for(const k of Object.keys(s.ach))s.ach[k]=num(s.ach[k],0); - {const p=s.achP&&typeof s.achP==='object'&&!Array.isArray(s.achP)?s.achP:{};s.achP={};for(const k of Object.keys(s.ach))s.achP[k]=BVAR[p[k]]?p[k]:'oncall';} + {const p=s.achP&&typeof s.achP==='object'&&!Array.isArray(s.achP)?s.achP:{};s.achP={};for(const k of Object.keys(s.ach))s.achP[k]=typeof p[k]==='string'&&own(BVAR,p[k])?p[k]:'oncall';} if(s.merged){const o={};if(typeof s.merged==='object')for(const m of MERGERS)if(isFinite(s.merged[m.id]))o[m.id]=+s.merged[m.id];s.merged=Object.keys(o).length?o:undefined;} // The rules (2.0): a save without them is the classic game, On-call (or a sandbox or puzzle, if it was one). Locked after the start. {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{},p=s.mode==='sandbox'?'sandbox':s.mode==='puzzle'?'puzzle':own(PRESETS,r.preset)?r.preset:'oncall';s.rules=makeRules(p,own(PRESETS,r.preset)?r:{});} diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 39cd21a..0de9fa4 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -74,10 +74,10 @@ const BADGES=[ fiery one; Sandbox and the puzzles earn none (puzzles have stars). Earning a badge again under a harder preset upgrades its look, here and in the hall of fame. S.ach[id] stays the day it was earned; S.achP[id] is its variant. */ const BVAR={freeze:{k:'freeze',lv:1,i:'🧊',n:N_('badges.variant_freeze_dried'),col:'#5BC0EB'},oncall:{k:'oncall',lv:2,i:'⭐',n:N_('badges.variant_on_call'),col:'#FFD23F'},bgp:{k:'bgp',lv:3,i:'🔥',n:N_('badges.variant_forged_at_3_a_m'),col:'#FF5A1F'}}; -const BVAR_IDS=['freeze','oncall','bgp'],bvar=k=>BVAR[k]||BVAR.oncall; +const BVAR_IDS=['freeze','oncall','bgp'],bvar=k=>own(BVAR,k)?BVAR[k]:BVAR.oncall; // The preset this save plays under ('oncall' for every save from before rulesets), and the variant it earns (null: none). const rulePre=()=>(typeof rulePreset==='function'?rulePreset():(S&&S.rules&&S.rules.preset))||'oncall'; -function badgeVar(){if(!S||S.mode==='sandbox')return null;const p=rulePre();return p==='sandbox'||p==='puzzle'?null:BVAR[p]?p:'oncall';} +function badgeVar(){if(!S||S.mode==='sandbox')return null;const p=rulePre();return p==='sandbox'||p==='puzzle'?null:own(BVAR,p)?p:'oncall';} // The hall of fame is this device's localStorage, so it is checked like a save: unknown variants count as standard. function hof(){let h;try{h=JSON.parse(localStorage.getItem('sot-badges')||'{}');}catch(e){h=null;}if(!h||typeof h!=='object'||Array.isArray(h))return {}; for(const k of Object.keys(h)){const x=h[k];if(!x||typeof x!=='object'){delete h[k];continue;}const vs=x.vs&&typeof x.vs==='object'&&!Array.isArray(x.vs)?x.vs:{}; @@ -87,8 +87,9 @@ function hof(){let h;try{h=JSON.parse(localStorage.getItem('sot-badges')||'{}'); function checkBadges(){S.ach=S.ach||{};S.achP=S.achP||{};const v=badgeVar();if(!v)return;let h=null;const V=BVAR[v]; for(const b of BADGES){const had=S.ach[b.id]!==undefined;if(had&&bvar(S.achP[b.id]).lv>=V.lv)continue;let ok=false;try{ok=b.ok();}catch(e){} if(!ok)continue;if(!had)S.ach[b.id]=S.day;S.achP[b.id]=v;const R0=RARITY[b.r]; - if(!h)h=hof();const today=new Date().toISOString().slice(0,10),x=h[b.id]||(h[b.id]={d:today,n:S.name,vs:{}});if(x.vs[v]===undefined)x.vs[v]=today;if(bvar(x.v).lv${b.i} ${had?tr('badges.badge_upgraded_name',{name:esc(b.t)}):tr('badges.badge_unlocked_name',{name:esc(b.t)})}
${R0.n}${v==='oncall'?'':` · ${V.i} ${tr(V.n)}`} · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id+(v==='oncall'?'':'_'+v));} + // "Upgraded" is about this device's collection: the hall of fame already held the badge, only in a lower variant. + if(!h)h=hof();const today=new Date().toISOString().slice(0,10),up=!!h[b.id]&&bvar(h[b.id].v).lv${b.i} ${up?tr('badges.badge_upgraded_name',{name:esc(b.t)}):tr('badges.badge_unlocked_name',{name:esc(b.t)})}
${R0.n}${v==='oncall'?'':` · ${V.i} ${tr(V.n)}`} · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id+(v==='oncall'?'':'_'+v));} if(h)try{localStorage.setItem('sot-badges',JSON.stringify(h));}catch(e){}} // How many badges this device has ever earned in each variant: the collection. function badgeShelf(h){const o={freeze:0,oncall:0,bgp:0};for(const b of BADGES){const x=h[b.id];if(x)for(const v of BVAR_IDS)if(x.vs[v]!==undefined)o[v]++;}return o;} diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index d9b1000..7c046d0 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -30,10 +30,10 @@ Object.assign(ACT,{ setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();}, setMetric:({id,v})=>{if(v!=='custom'&&!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;const m=S.pairMet||(S.pairMet={}),k=edgeKey(l); // Switching to custom starts from the current preset's factor, so nothing moves until the player edits it. - if(v==='custom'){if(!pairCm(k))m[k]={k:'f',v:MET[pairMet(k)].f};}else if(v==='normal')delete m[k];else m[k]=v;sfx('click');after();}, + if(v==='custom'){if(!pairCm(k))m[k]={k:'f',v:MET[pairMet(k)].f};}else if(v==='normal')delete m[k];else m[k]=v;metBlur();sfx('click');after();}, metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l)return;const key=edgeKey(l),c=pairCm(key);if(!c||c.k===k)return; // The cost stays what it was on this link, written the other way. - const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};sfx('click');after();}, + const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};metBlur();sfx('click');after();}, metricSet:({id})=>{const l=S.links.find(x=>x.id===id),t=$('metIn');if(!l||!t)return;const key=edgeKey(l),c=pairCm(key);if(!c)return;const v=parseFloat(String(t.value).replace(',','.'));if(!Number.isFinite(v)){sfx('err');return;} t.blur();S.pairMet[key]={k:c.k,v:clampM(c.k,v)};sfx('click');after();}, setStandby:({id,on})=>{const l=S.links.find(x=>x.id===id);if(!l)return;if(on)l.standby=true;else delete l.standby;sfx('click');after();}, diff --git a/src/game/90-actions/88-ops.js b/src/game/90-actions/88-ops.js index 121e7a8..3d8115a 100644 --- a/src/game/90-actions/88-ops.js +++ b/src/game/90-actions/88-ops.js @@ -2,7 +2,9 @@ const opsCycle=(a,v)=>a[(a.indexOf(v)+1)%a.length]; Object.assign(ACT,{ opsOpen:()=>{if(S)opsModal();}, - opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO();O.intern=id;O.hired=S.day;O.mon=Math.floor(S.day/30); + opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=Math.floor(S.day/30);O.intern=id;O.hired=S.day;O.wk=null; + // A new hire starts on a fresh month's budget, whatever the last one spent. + if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();}, opsFire:()=>{if(!opsHired())return;if(UI.confirm!=='opsFire'){UI.confirm='opsFire';opsModal();return;}UI.confirm=null;const nm=opsName();S.ops.intern=null; toast(esc(tr('ops.fired',{name:nm})),'');after();opsModal();}, @@ -10,7 +12,7 @@ Object.assign(ACT,{ opsParam:({k,p})=>{if(!opsHired()||!own(OPSK,k)||!own(OPSK[k].p,p))return;const P=OPSK[k].p[p];let v; if(p==='prov'){const ids=['cheap',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)];v=opsCycle(ids,opsP(k,p));}else v=opsCycle(P.v,opsP(k,p)); (S.ops.p[k]||(S.ops.p[k]={}))[p]=v;sfx('click');after();opsModal();}, - opsCap:({k})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;S.ops.cap[k]=opsCycle(OPS_CAPS,opsCap(k));sfx('click');after();opsModal();}, + opsCap:({k})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;S.ops.cap[k]=opsCycle(opsCaps(k),opsCap(k));sfx('click');after();opsModal();}, opsFloor:()=>{if(!opsHired())return;S.ops.floor=opsCycle(OPS_FLOORS,S.ops.floor);sfx('click');after();opsModal();}, opsCity:({v})=>{if(!S||!S.pops[v])return;UI.opsCity=v;opsModal();}, opsPop:({k,city})=>{if(!opsHired()||!OPS_POP.includes(k)||!S.pops[city])return;const sk=S.ops.skip,a=sk[city]||[];sk[city]=a.includes(k)?a.filter(x=>x!==k):[...a,k];if(!sk[city].length)delete sk[city]; diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 41667e0..26f158e 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -2,8 +2,8 @@ Object.assign(ACT,{ // The puzzle list. The ruleset's title-screen door calls this. puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();}, pzStart:({id})=>{const d=pzDef(id);if(!d||!pzPackOpen(d.pack))return;pzBegin(d);}, - pzWeekly:()=>pzBegin(pzWeekly()), - pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWeekly():pzDef(S.pz.id));}, + pzWeekly:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());}, + pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, pzLeave:()=>{if(pzOn())pzLeave();}, pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop();sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();}, pzRmPop:({city})=>{if(!pzOn()||!S.pops[city])return;pzSnap();delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);sfx('click');UI.sel=null;pzAfter();}, @@ -24,3 +24,8 @@ Object.assign(ACT,{ const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'),copy=()=>{try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}; if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}copy();track('puzzle_share');}, }); +// A puzzle is its own S: a leftover main-game button (an old toast, a stale panel, a shortcut) must not build, buy or +// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. This file is the +// last of the actions, so every one is here to wrap. +const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','menu','mute','prefSet','puzzleDoor','puzzleMenu','selLink','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); +for(const k of Object.keys(ACT))if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k)){const f=ACT[k];ACT[k]=a=>pzOn()?undefined:f(a);} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index b1e0470..90ccb82 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -80,7 +80,7 @@ function renderLeft(){checkLayer(); h+=`
${btn(tr('common.all_networks'),'netFilter',{f:'all'},!foc&&!out?'sm':'ghost sm')}${btn(tr('hud_and_panels.out_of_reach_without_transit_n',{n:lostN}),'netFilter',{f:'out'},out?'sm':'ghost sm')}
`; if(out&&!lostN)h+=`

${tr('hud_and_panels.nothing_every_network_is_reachable')}

`; for(const n of foc?[foc]:out?ntLost():NETS){if(n.tail&&!UI.tailOpen&&!foc&&!out)continue; - h+=`
${logo(n)}
${esc(n.name)} AS${n.asn}
${TYPE_L[n.type]} ${n.pol} · ${tr('hud_and_panels.p_of_traffic',{p:(NSH[n.id]*100).toFixed(1)})}${n.price?` · ${tr('hud_and_panels.transit_price_gbps',{price:(n.price*S.priceMul).toFixed(2)})}`:''}
${esc(n.blurb)}
${netWhere(n,where)}${(foc||out)&&!R.nt[n.id]?`

${esc(offTransitHint(n.id))}

`:''}${(foc||out)&&coneVia(n.id)&&(R.cone[n.id]||!R.nt[n.id])?`

${R.cone[n.id]?tr('hud_and_panels.reached_through_the_customer_cone_of',{net:esc(coneVia(n.id).name)}):tr('hud_and_panels.buys_transit_from_net_peer_with',{net:esc(coneVia(n.id).name)})}

`:''}${foc||out&&!R.nt[n.id]?meetLine(n,foc?24:4):''}
`;} + h+=`
${logo(n)}
${esc(n.name)} AS${n.asn}
${TYPE_L[n.type]} ${n.pol} · ${tr('hud_and_panels.p_of_traffic',{p:(NSH[n.id]*100).toFixed(1)})}${n.price?` · ${tr('hud_and_panels.transit_price_gbps',{price:(n.price*S.priceMul).toFixed(2)})}`:''}
${esc(n.blurb)}
${netWhere(n,where)}${(foc||out)&&!R.nt[n.id]?`

${esc(offTransitHint(n.id))}

`:''}${(foc||out)&&coneVia(n.id)&&(R.cone[n.id]||!R.nt[n.id])?`

${R.cone[n.id]?tr('hud_and_panels.reached_through_the_customer_cone_of',{net:esc((NET[R.cone[n.id]]||coneVia(n.id)).name)}):tr('hud_and_panels.buys_transit_from_net_peer_with',{net:esc(coneVia(n.id).name)})}

`:''}${foc||out&&!R.nt[n.id]?meetLine(n,foc?24:4):''}
`;} if(!foc&&!out)h+=`
${tr('hud_and_panels.the_long_tail')} ${tr('hud_and_panels.n_small_networks',{n:tl.length})}
${tr('hud_and_panels.p_of_traffic_between_them_scattered',{p:(tl.reduce((a,n)=>a+NSH[n.id],0)*100).toFixed(1),n:tlOn})}
${btn(UI.tailOpen?tr('common.hide'):tr('common.show'),'tailTog',{},'ghost sm')}
`; } if(h!==UI._lh){UI._lh=h;morph($('leftBody'),h);} diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 4c068b7..b816232 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -67,7 +67,7 @@ function cityPanel(c){ ${have.length?btn(tr('common.remove'),'rmCache',{id:(have.find(x=>x.site==='b')||have[0]).id},'ghost sm'):''}${btn(have.length?tr('common.box'):tr('common.request'),'cache',{city:c,net:n.id},'sm',!ok)}${S.pops[c].site2&&have.length?(()=>{const nb=have.filter(x=>x.site==='b').length,na=have.length-nb;return `
${tr('city_panel.boxes_a_in_a_b_in',{a:na,b:nb})}${na?btn(tr('city_panel.move_one_to_b'),'cacheSite',{city:c,net:n.id,s:'b'},'ghost sm'):''}${nb?btn(tr('city_panel.move_one_to_a'),'cacheSite',{city:c,net:n.id,s:'a'},'ghost sm'):''}
`;})():''}`;} h+=``; }else{ - h+=utilityKitHtml(c); + h+=utilityKitLine(c); const ls=S.links.filter(l=>l.a===c||l.b===c); const rt=p.routers||1,g=p.rgen||0,G=RG[g],nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||nodeCap(c),Ni=g===mainRG(G.cls)?mainRG(G.cls+1):-1,N=Ni>=0?RG[Ni]:null,pu=portsUsed(c),pm=portsMax(c); h+=`

${tr('common.routers')}

${tr('city_panel.the_model_sets_your_fastest')}

diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js index 2d50105..3398392 100644 --- a/src/game/93-ui/55-utilities.js +++ b/src/game/93-ui/55-utilities.js @@ -5,6 +5,11 @@ function utilityKitHtml(city,modal=false){const q=utilityKit(city);if(!q)return

${tr('utilities.cache_moves',{n:q.moves.length})}

${q.cost||q.moves.length?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost,modal},'pink',q.cost>0&&S.cash`:`

${tr('utilities.kit_balanced')}

`}

${tr('utilities.redundancy_note')}

${utilityCachesHtml(city,modal)}`;} +// In the Infra tab (#192): one line and the button, since the generator, second site, routers and caches each have +// their own rows below; the full kit with its caches is in Utilities. +function utilityKitLine(city){const q=utilityKit(city);if(!q)return '';const todo=q.cost||q.moves.length; + return `

${tr('utilities.redundancy_kit')} · ${todo?tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})+(q.moves.length?' · '+tr('utilities.cache_moves',{n:q.moves.length}):''):tr('utilities.kit_balanced')}

+
${todo?btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost},'pink sm',q.cost>0&&S.cash
`;} function utilityCachesHtml(city,modal=false){const q=utilityCaches(city);if(!q)return ''; return `

${tr('common.embedded_caches')}

${tr('utilities.cache_note')}

${tr('utilities.cache_quote',{n:q.add.length,mo:fmt$(q.mo)})}

diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js index b0bf525..711c913 100644 --- a/src/game/93-ui/57-ops-panel.js +++ b/src/game/93-ui/57-ops-panel.js @@ -6,15 +6,15 @@ function opsCard(){if(!S)return '';const last=opsHired()&&S.ops.log[0];
${btn(opsHired()?tr('ops.standing_orders'):tr('ops.hire_an_intern'),'opsOpen',{},opsHired()?'sm':'pink sm',!opsHired()&&!opsCanHire())}
`;} const opsEntry=e=>(e.f!==undefined?opsFFLine(e)+' ':'')+(e.r.length||e.f===undefined?opsLine(e):''); function opsVal(k,p){const P=OPSK[k].p[p],v=opsP(k,p);return p==='prov'?(v==='cheap'?tr('ops.cheapest'):NET[v].name):P.f(v);} -function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0; - return `
${tr(d.t)}
${tr(d.d)}
+function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.ops.spent[k]||0,am=Math.round(S.ops.addMo[k]||0); + return `
${tr(d.t)}
${tr(d.d)}${k==='caches'?' '+tr('ops.caches_rent',{price:fmt$(CACHE_MO)}):''}
${on?`
${Object.keys(d.p).map(p=>btn(`${tr(d.p[p].l)}: ${esc(opsVal(k,p))}`,'opsParam',{k,p},'ghost sm')).join('')} - ${d.cap?btn(`${tr('ops.budget')}: ${cap?tr('common.price_mo',{price:fmt$(cap)}):tr('ops.no_cap')}`,'opsCap',{k},'ghost sm'):''}
- ${d.cap&&S.ops.spent[k]?`
${tr('ops.spent_this_month',{price:fmt$(S.ops.spent[k])})}
`:''} + ${d.cap?btn(`${d.mo?tr('ops.budget_running'):tr('ops.budget')}: ${cap?tr('common.price_mo',{price:(d.mo?'+':'')+fmt$(cap)}):tr('ops.no_cap')}`,'opsCap',{k},'ghost sm'):''}
+ ${sp||am?`
${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}
`:''} ${k==='ix'&&ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

`:''}`:''}
`;} function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr('ops.ops')}

${tr('ops.standing_orders')}

`; - if(!hired){h+=`

${tr('ops.hire_pitch')}

`; + if(!hired){h+=`

${tr('ops.hire_pitch_weekly')}

`; if(!rule('clock'))h+=`

${tr('ops.no_clock')}

`;else if(!opsCanHire())h+=`

${tr('ops.locked',{lv:2})}

`; else h+=Object.entries(INTERNS).map(([id,I])=>`
${tr(I.n)}
${tr(I.d)}
${btn(tr('ops.hire_mo',{price:fmt$(INTERN_MO)}),'opsHire',{id},'pink sm',S.cash
`).join(''); @@ -22,6 +22,7 @@ function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr(I.n)}
${tr('ops.salary',{price:fmt$(INTERN_MO),d:dateStr(O.hired)})}
${btn(UI.confirm==='opsFire'?tr('ops.really_fire'):tr('ops.fire'),'opsFire',{},'ghost sm')}
+

${esc(opsMood())}

${opsReportHtml()} ${O.log.length?`
${O.log.slice(0,6).map(e=>esc(tr('peering_inbox.day_d',{d:e.d})+': '+opsEntry(e))).join('\n')}
`:''}

${ibx().bot?tr('ops.lpm_on',{name:opsName()}):tr('ops.lpm_off',{name:opsName()})}

${btn(`${tr('ops.floor')}: ${O.floor?fmt$(O.floor):tr('ops.no_cap')}`,'opsFloor',{},'ghost sm')}
`; @@ -33,6 +34,10 @@ function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr('ops.per_pop_note')}

`; h+=`

${tr('ops.template')}

${tr('ops.template_note',{name:opsName()})}

${OPS_TPL.map(k=>``).join('')}
`; h+=opsOnceHtml();openModal(h,'ops');} +// The shift report: last week in one paragraph, and this week so far. The daily lines below are the detail. +function opsReportHtml(){const O=S.ops,w=Math.floor(S.day/7),cur=O.wk&&O.wk.w===w&&opsWkAny(O.wk)?O.wk:null,rep=O.rep&&O.rep.w===w-1?O.rep:null;if(!cur&&!rep)return ''; + const row=(t,x)=>`
${t}
${esc(opsWeekLine(x))}
`; + return (rep?row(tr('ops.report_last'),rep):'')+(cur?row(tr('ops.report_now'),cur):'');} // The big one-off batches (#181, #192) live here now, next to the orders that run them every week. const opsOnceHtml=()=>`

${tr('ops.by_hand')}

${tr('ops.by_hand_note')}

${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}
`; // On a city without a POP: open it from the template in one tap. diff --git a/src/game/93-ui/60-decommission.js b/src/game/93-ui/60-decommission.js index 4386098..e2db4cf 100644 --- a/src/game/93-ui/60-decommission.js +++ b/src/game/93-ui/60-decommission.js @@ -15,7 +15,7 @@ function decomModal(){const sel=[...(UI.decom||[])],im=decomImpact(sel),all=Obje function decommission(cities){const set=new Set(cities),im=decomImpact(cities),lids=new Set(im.links.map(l=>l.id)),bids=new Set(im.biz.map(b=>b.id)); S.links=S.links.filter(l=>!lids.has(l.id));prunePairMet();S.biz=S.biz.filter(b=>!bids.has(b.id));S.offers=S.offers.filter(o=>!bCities(o).some(c=>set.has(c))); S.transit=S.transit.filter(t=>!set.has(t.city));S.pni=S.pni.filter(x=>!set.has(x.city));S.caches=S.caches.filter(x=>!set.has(x.city));S.nni=(S.nni||[]).filter(x=>!set.has(x.city)); - for(const c of cities){for(const x of ixIdsIn(c)){delete S.ixp[x];delete S.rs[x];if(S.ixn)delete S.ixn[x];if(S.ixSite)delete S.ixSite[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}delete S.myIx[c];S.scrubs=S.scrubs.filter(x=>x.city!==c);delete S.pops[c];} + for(const c of cities){for(const x of ixIdsIn(c)){delete S.ixp[x];delete S.rs[x];if(S.ixn)delete S.ixn[x];if(S.ixSite)delete S.ixSite[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}delete S.myIx[c];S.scrubs=S.scrubs.filter(x=>x.city!==c);if(S.ops)delete S.ops.skip[c];delete S.pops[c];} const rem=remoteCities();for(const x in S.ixp){const c=ixCity(x);if(!S.pops[c]&&!rem.includes(c)){delete S.ixp[x];delete S.rs[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}} if(set.has(S.home))S.home=Object.keys(S.pops)[0]; purgeInc();S.cash-=im.fee;S.stats.decom=(S.stats.decom||0)+cities.length; diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 4633d68..9167cb4 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -34,10 +34,11 @@ function vxcPanel(l){ return h; } function prefCtl(kind,id,cur){cur=cur||'normal';return `
${tr('common.egress')}${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}
`;} -// Trial routing is isolated from the live save, counters and scenic-route memory. +// Trial routing is isolated from the live save, counters and scenic-route memory. "Before" is the live routing, which +// after() keeps current, so a check costs one compute() on a big network, not two. function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE; - try{S=JSON.parse(JSON.stringify(save));const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return null; - compute();const before=R;l.cut=S.day+1;compute(); + try{const l0=save.links.find(x=>x.id===id);if(!l0||linkDown(l0))return null; + S=JSON.parse(JSON.stringify(save));const l=S.links.find(x=>x.id===id),before=live;l.cut=S.day+1;compute(); const allowed=new Set(Object.keys(S.pops).filter(popUp).concat(remoteCities())),adj={}; for(const x of S.links)if(!linkDown(x)&&allowed.has(x.a)&&allowed.has(x.b)){(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);} const seen=new Set([l.a]),q=[l.a];for(let i=0;i=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`

${tr('link_panels.biggest_feeder_egress_in_city_set',{egress:esc(d.lab),city:CITY[d.city].name})}

`;} return h+``; } +// Safari keeps the number field focused through a button tap, and renderPanel() skips a focused field: let go first (#131). +const metBlur=()=>{const t=$('metIn');if(t&&document.activeElement===t)t.blur();}; function metricSection(l){const key=edgeKey(l),cur=pairMet(key),pl=pairLinks(l.a,l.b),sb=!!l.standby,base=l.km+60,sel=k=>cur===k?'pink sm':'ghost sm'; let h=`

${tr('common.routing_metric')}

${tr('link_panels.your_routers_pick_the_lowest_cost_0160')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},sel(k))).join('')}${btn(tr('common.custom'),'setMetric',{id:l.id,v:'custom'},sel('custom'))}
`; const cm=pairCm(key); diff --git a/src/game/94-dashboard/10-progress.js b/src/game/94-dashboard/10-progress.js index be14c3a..111df9b 100644 --- a/src/game/94-dashboard/10-progress.js +++ b/src/game/94-dashboard/10-progress.js @@ -4,7 +4,7 @@ const RS_G=80,RS_DAYS=30,asiaG=()=>S.links.reduce((a,l)=>a+((CITY[l.a].reg==='AS const pSrv=g=>({l:tr('common.traffic_served'),v:R.served,max:g,txt:`${fmtG(R.served)} / ${fmtG(g)}`}); const pReach=()=>({l:tr('common.reach'),v:R.reach,max:0.99,txt:`${pct(R.reach)} / 99%`}); const pChk=(l,ok)=>({l,v:ok?1:0,max:1,txt:ok?'✓':'—'}); -const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.45,txt:`${pct(R.reach)} / 45%`},pSrv(300)],redsea:()=>{const g=asiaG(),n=S.stats.asiaRun||0;return [pChk(tr('progress.a_path_from_marseille_to_singapore'),pathExists('mrs','sin')),{l:tr('progress.your_traffic_to_and_from_asia'),v:Math.min(g,RS_G),max:RS_G,txt:`${fmtG(g)} / ${fmtG(RS_G)}`},{l:tr('progress.days_in_a_row_at_g',{g:fmtG(RS_G)}),v:n,max:RS_DAYS,txt:`${n} / ${RS_DAYS}`}];},spat:()=>[pReach(),pSrv(150)], +const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.5,txt:`${pct(R.reach)} / 50%`},pSrv(300)],redsea:()=>{const g=asiaG(),n=S.stats.asiaRun||0;return [pChk(tr('progress.a_path_from_marseille_to_singapore'),pathExists('mrs','sin')),{l:tr('progress.your_traffic_to_and_from_asia'),v:Math.min(g,RS_G),max:RS_G,txt:`${fmtG(g)} / ${fmtG(RS_G)}`},{l:tr('progress.days_in_a_row_at_g',{g:fmtG(RS_G)}),v:n,max:RS_DAYS,txt:`${n} / ${RS_DAYS}`}];},spat:()=>[pReach(),pSrv(150)], carnaval:()=>[pChk(tr('progress.carnaval_delivered_in_full'),(S.stats.evFull||0)>=1)],ixbr:()=>{const n=brIxN();return [{l:tr('progress.ix_brrr_ports'),v:n,max:15,txt:`${n} / 15`},pChk(tr('progress.a_port_on_ix_brrr_manaus'),S.ixp.mao!==undefined),pSrv(200)];}, c2c:()=>[pChk(tr('progress.a_path_from_cape_town_to'),pathExists('cpt','cai')),...['lag','nbo'].map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)], pac:()=>[pChk(tr('progress.1_6t_on_every_hop_from'),fastPath('lax','syd',1600)),pChk(tr('progress.a_path_from_los_angeles_to'),pathExists('lax','tok')),pSrv(150)], diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 61ca3e3..d32be2c 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -38,7 +38,7 @@ function whatsNew(returning,force){ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot_no_clock')],['sandbox','🏖️',tr('common.sandbox'),tr('title.a_billion_dollars_and_every_toy')],['normal','📟',tr('common.normal'),tr('title.the_real_game_climb_from_tier')],['scn','🏆',tr('title.scenarios_amp_weekly'),tr('title.hand_built_crises_and_one_world')]]; const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'}; function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'; - return `
${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('')}
${Object.entries(CHAOS).map(([k,C])=>``).join('')}

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

`;} diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index 1ae57a6..dc45fdf 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -4,23 +4,25 @@ function pzTwistTxt(t){const P=S.pz; if(t.k==='sub')return tr('puzzles.no_subsea_cables'); if(t.k==='ring')return tr('puzzles.one_ring_through_every_pop'); if(t.k==='g')return tr('puzzles.every_link_n_g_or_more',{n:P.minG}); - if(t.k==='avoid')return tr('puzzles.no_pop_in_list',{list:P.avoid.map(c=>CITY[c].name).join(', ')}); const [a,b,ms]=P.lat;return isFinite(t.ms)?tr('puzzles.a_to_b_under_ms_now',{a:CITY[a].name,b:CITY[b].name,ms,now:t.ms.toFixed(1)}):tr('puzzles.a_to_b_under_ms',{a:CITY[a].name,b:CITY[b].name,ms});} // The short version, for the puzzle list. -function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} -const pzUnitName=u=>{const l=S.links.find(x=>pzUnit(x)===u);return l?`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`:'';}; +function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} +// A cable carrying several of your waves is named on its own: cutting it takes them all. +const pzUnitName=u=>{const ls=S.links.filter(x=>pzUnit(x)===u),l=ls[0];return !l?'':l.cable&&ls.length>1?esc(CAB[l.cable].name):`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`;}; function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false; const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); const star=(on,l)=>`⭐${l}`; - let h=`
${pk?esc(pk.n):tr('puzzles.weekly_puzzle')}

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

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

${esc(d.j)}

`; + let h=`
${pk?esc(pk.n):P.theme&&own(PZ_WK_THEMES,P.theme)?`${PZ_WK_THEMES[P.theme].i} ${tr('puzzles.weekly_puzzle')} · ${tr(PZ_WK_THEMES[P.theme].t)}`:tr('puzzles.weekly_puzzle')}

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

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

${esc(d.j)}

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

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

`; h+=`
${star(e.goal,tr('puzzles.goal'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; - h+=`
${e.marks.map(m=>`${esc(CITY[m.c].name)}${m.st===2?' ✓':m.st===1?' ·':' …'}`).join('')}
`; - for(const t of e.tw)h+=`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; + // ○ still to reach, ◐ has a POP, ✓ joined up. A leading mark, so nothing looks cut off. + h+=`
${e.marks.map(m=>` ${esc(CITY[m.c].name)}`).join('')}
`; + // Cities to avoid cannot be built in at all, so they read as a rule, not as a box to tick. + for(const t of e.tw)h+=t.k==='avoid'?`
🚫 ${tr('puzzles.rule_not_via_list',{list:P.avoid.map(c=>esc(CITY[c].name)).join(', ')})}
`:`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; const sp=fmt$(e.spend); h+=P.budget?`
${tr('puzzles.spent_x_of_y',{x:sp,y:fmt$(P.budget)})}${e.cheap?'✓':'✗'}
` :`
${tr('puzzles.spent_x',{x:sp})}${tr('puzzles.no_budget_star_on_the_house')}
`; - h+=!e.conn?`
🛡 ${tr('puzzles.n_1_connect_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut')}
`:`
⚠️ ${tr('puzzles.one_cut_splits_it_where',{where:pzUnitName(e.weak[0])})}
`; + h+=!e.conn?`
🛡 ${tr('puzzles.n_1_connect_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut')}
`:`
⚠️ ${tr('puzzles.one_cut_splits_it_where',{where:pzUnitName(e.weak[0])})}${pzOneMore(e)?`
${tr('puzzles.so_close_one_more_link_and')}`:''}
`; h+=`
${btn('↶ '+tr('puzzles.undo'),'pzUndo',{},'ghost sm',!(UI.pzHist&&UI.pzHist.length))}${btn(tr('puzzles.reset'),'pzReset',{},'ghost sm',!S.links.length&&!Object.keys(S.pops).length)}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}
`; if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} function pzPanel(sel){const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; @@ -28,7 +30,7 @@ function pzPanel(sel){const head=(eb,name,facts)=>`
${tr('common.your_pop')}`:'')+'
'; if(k==='avoid')return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

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

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

${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`; + if(!p)h+=`

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

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

${tr('puzzles.drag_from_this_pop_onto_another')}

${tr('puzzles.lease_a_wave_to')}

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

${tr('common.links')}

`+ls.map(l=>`
${esc(CITY[l.a===c?l.b:l.a].name)}
${capName(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join(''); @@ -54,26 +56,36 @@ function pzLinkModal(a,b,keep){const kb=pzKind(b); h+=`
${PZ_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),c=pzLinkCost(r,i,div)+pop;return ``;}).join('')}
`; openModal(h);} // ---------- results ---------- -function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?tr('puzzles.one_backhoe_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');} +function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?(pzOneMore(e)?tr('puzzles.so_close_one_more_link_and'):tr('puzzles.one_backhoe_away_from_a_very')):tr('puzzles.rock_solid_and_gold_plated_the');} +// Stars still to win in this puzzle's pack, from the progress just saved. +function pzPackLeft(P){const d=pzDef(P.id);if(!d)return null;const p=pzLoad(),xs=PZ.filter(x=>x.pack===d.pack);return xs.length*3-xs.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);} function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h=''; for(let i=0;i<28;i++)h+=``; return ``;} -function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(); +function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left=pzPackLeft(P),done=e.stars>=3; const row=(ok,l,v)=>`
${ok?'⭐':'☆'} ${l}${v}
`; const stars=[0,1,2].map(i=>`⭐`).join(''); openModal(`
${e.stars>=3?pzConfetti():''}
${tr('puzzles.puzzle_solved')}

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

-
${stars}

${pzLine(e)}

+
${stars}

${pzLine(e)}

${left==null?'':`

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

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

${tr('puzzles.small_calm_network_builds')}

${tr('puzzles.no_clock_no_bills_nothing_breaks')}

${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}
`; if(pzOn())h+=`
${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; - h+=`
${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})} ${wr?`${pzStarStr(wr.st)}`:''}
${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}
${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}
${btn(tr('common.play'),'pzWeekly',{},'pink')}
`; + h+=pzWkRow(); for(const pk of PZ_PACKS){const open=tot>=pk.need,got=PZ.filter(x=>x.pack===pk.id).reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0),n=PZ.filter(x=>x.pack===pk.id).length; h+=`

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

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

`; for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzTwistTag(d); diff --git a/src/i18n/en.js b/src/i18n/en.js index 3af0189..73bd44a 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2595,8 +2595,10 @@ "ops.anycast_annie":"Anycast Annie", "ops.at_least_port":"at least {port}", "ops.budget":"Budget", +"ops.budget_running":"Adds at most", "ops.by_hand":"One-off batches", "ops.by_hand_note":"For when you want it all done right now: every peer at every exchange, a redundancy kit, PNIs with everyone.", +"ops.caches_rent":"Free to rack, but each box costs {price}/mo in space and power.", "ops.cheapest":"Cheapest", "ops.ff_desc":"labelled a port in {city} “TODO: fix later (do not fix)”", "ops.ff_hostname":"renamed the router in {city} to router-final-FINAL-v2", @@ -2609,8 +2611,8 @@ "ops.floor":"Keep at least", "ops.hire_an_intern":"Hire a NOC intern", "ops.hire_mo":"Hire · {price}/mo", -"ops.hire_pitch":"Tired of clicking the same fifteen buttons in every city? Hire a NOC intern. You write the standing orders once; they run them every day, pay exactly what your clicks would, and leave one line in the log.", "ops.hire_pitch_short":"Set the rules once, and an intern clicks the buttons every day.", +"ops.hire_pitch_weekly":"Tired of clicking the same fifteen buttons in every city? Hire a NOC intern. You write the standing orders once; they run them every day, pay exactly what your clicks would, and hand you a shift report every week.", "ops.hired":"{name} joined the NOC. Write some standing orders and they get to work tomorrow.", "ops.how_add":"add a router", "ops.how_auto":"add, then swap", @@ -2625,6 +2627,7 @@ "ops.l_decom":{"one":"handed back a small wave on {where}","other":"handed back {n} small waves ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"lit a channel on {where}","other":"lit {n} channels ({where})"}, +"ops.l_paid":"Cost: {cost} up front, {mo}/mo.", "ops.l_peer":{"one":"peered with a network at {where}","other":"peered with {n} networks at {where}"}, "ops.l_pni":{"one":"ordered a PNI in {where}","other":"ordered {n} PNIs ({where})"}, "ops.l_quiet":"{name} watched the graphs. Nothing needed doing.", @@ -2632,10 +2635,22 @@ "ops.l_routers":{"one":"upgraded routers in {where}","other":"upgraded routers in {n} places ({where})"}, "ops.l_rs":{"one":"joined a route server","other":"joined {n} route servers"}, "ops.l_sales":{"one":"signed a customer","other":"signed {n} customers"}, +"ops.l_snag":{"one":"got stuck on {where} and paused it until you have a look","other":"got stuck on {n} orders ({where}) and paused them until you have a look"}, "ops.l_transit":{"one":"topped up transit in {where}","other":"topped up transit {n} times ({where})"}, "ops.locked":"The NOC hires interns from customer level {lv}.", "ops.lpm_off":"The peering inbox is still yours. Hire the Large Peering Model for that; {name} does not do email.", "ops.lpm_on":"The Large Peering Model answers the peering inbox. {name} keeps out of its way.", +"ops.mood_annie":"Annie answered three questions before you asked them, from whichever desk was closest.", +"ops.mood_broke":"{name} has a shopping list ready for when next month's budget comes in.", +"ops.mood_busy":"{name} has had a busy week and is on their third energy drink.", +"ops.mood_kevin":"Kevin says it was quieter back in 2001. It was not.", +"ops.mood_new":"{name} has found the coffee machine and the CLI, in that order. Ready when you are.", +"ops.mood_oops":"{name} is being very careful today. Nobody mention the interface descriptions.", +"ops.mood_outage":"{name} is watching the outage graphs and refreshing the status page. A lot.", +"ops.mood_quiet":"{name} is quietly reading RFCs. The graphs are flat, which is how they like them.", +"ops.mood_sales":"{name} is walking a little taller: someone signed on their shift.", +"ops.mood_snag":"{name} hit something odd, paused that order and left you a sticky note.", +"ops.mood_tracy":"Tracy is three hops into a traceroute, with only one star so far.", "ops.never":"never", "ops.no_cap":"no limit", "ops.no_clock":"No clock, no shifts: these rules have no days for an intern to work.", @@ -2673,9 +2688,11 @@ "ops.per_pop":"Per POP", "ops.per_pop_note":"Green orders run in this POP. Switch one off to decide here by hand.", "ops.really_fire":"Really let go?", +"ops.report_last":"Last week's shift report", +"ops.report_now":"This week so far", "ops.salary":"Salary {price}/mo · since {d}", -"ops.shift":"{name}'s shift", -"ops.spent_this_month":"Spent this month: {price}", +"ops.shift_report":"{name}'s week", +"ops.spent_and_mo":"This month: {price} up front, {mo}/mo on the bill", "ops.standing_orders":"Standing orders", "ops.template":"New POP from template", "ops.template_note":"Pick what {name} sets up when you open a city from the template. The standing orders take it from there.", @@ -2691,6 +2708,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Follows every packet hop by hop. Gets there in the end, with a star or two on the way.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Week total: {cost} up front, {mo}/mo.", +"ops.w_oops":{"one":"made one small oops","other":"made {n} small oopses"}, +"ops.w_sales":{"one":"signed a customer ({rev}/mo)","other":"signed {n} customers ({rev}/mo)"}, "optic_counts.apply_price":"Apply · {price}", "optic_counts.count_for_model":"Number of {model} channels", "optic_counts.only_n_channels_free":"Only {n} channels are free on this fiber.", @@ -2918,6 +2939,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Every internet starts with one tube.", "puzzles.every_link_n_g_or_more":"Every link {n}G or more", +"puzzles.every_star_in_this_pack_is":"Every star in this pack is yours.", "puzzles.fat_pipes_only":"Fat Pipes Only", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"For architects who sleep through backhoe season.", @@ -2936,19 +2958,23 @@ "puzzles.keep_building":"Keep building", "puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad", "puzzles.lease_a_wave_to":"Lease a wave to", +"puzzles.loading_this_week_s_puzzle":"Loading this week's puzzle…", "puzzles.more_puzzles":"More puzzles", "puzzles.n_1_club":"N-1 Club", "puzzles.n_1_connect_everything_first":"N-1: connect everything first", "puzzles.n_g_links":"{n}G links", +"puzzles.n_stars_left_in_this_pack":{"one":"{n} ⭐ left in this pack","other":"{n} ⭐ left in this pack"}, "puzzles.n_week_streak":{"one":"{n} week in a row","other":"{n} weeks in a row"}, +"puzzles.new_this_sunday":"New this Sunday!", "puzzles.new_zealand_is_far_from_everything":"New Zealand is far from everything. That is the point, and the problem.", "puzzles.next_pack_unlocks_at_n":"Next pack, {pack}, unlocks at {n}⭐", "puzzles.next_puzzle":"Next puzzle", +"puzzles.next_weekly_in_d_h":"Next weekly puzzle in {d} d {h} h", +"puzzles.next_weekly_in_h_m":"Next weekly puzzle in {h} h {m} min", "puzzles.no_budget":"no budget", "puzzles.no_budget_star_on_the_house":"no budget: ⭐ on the house", "puzzles.no_cable_lands_in_both_try":"No cable lands in both {a} and {b}. Try a stepping stone in between.", "puzzles.no_clock_no_bills_nothing_breaks":"No clock, no bills, nothing breaks. Connect the cities, then go for three stars: under budget, and still connected when any one link is cut.", -"puzzles.no_pop_in_list":"No POP in {list}", "puzzles.no_subsea":"no subsea", "puzzles.no_subsea_cables":"No subsea cables", "puzzles.nobody_ever_got_fired_for_buying":"Nobody ever got fired for buying 100G.", @@ -2975,6 +3001,7 @@ "puzzles.ring":"ring", "puzzles.ring_of_fire":"Ring of Fire", "puzzles.rock_solid_and_gold_plated_the":"Rock solid, and gold plated. The CFO has questions.", +"puzzles.rule_not_via_list":"Rule: not via {list}", "puzzles.samba_sprint":"Samba Sprint", "puzzles.same_puzzle_for_everyone_this_week":"Same puzzle for everyone this week", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Same trench (cheaper, one backhoe cuts both)", @@ -2985,6 +3012,7 @@ "puzzles.size":"Size", "puzzles.small_calm_network_builds":"Small, calm network builds", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"So close: one more link and a backhoe can't touch you.", "puzzles.speed_runs":"Speed Runs", "puzzles.spent_x":"Spent {x}", "puzzles.spent_x_of_y":"Spent {x} / {y}", @@ -3007,8 +3035,38 @@ "puzzles.weekly_puzzle":"Weekly puzzle", "puzzles.weekly_puzzle_key":"Weekly puzzle {key}", "puzzles.with_the_pop_price":"with the POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Your first tubes. No pressure, no budget.", +"puzzles.your_first_tubes_roomy_budgets":"Your first tubes. Roomy budgets, and the first two are on the house.", "puzzles.your_stars":"Your stars", +"puzzles_weekly.detour":"Detour", +"puzzles_weekly.island_hopping":"Island hopping", +"puzzles_weekly.joke_a_ring_survives_one_cut":"A ring survives any one cut. That is the whole point of a ring.", +"puzzles_weekly.joke_a_road_trip_for_photons":"A road trip for photons. Snacks not included.", +"puzzles_weekly.joke_a_to_b_under_ms":"{a} to {b} in under {ms} ms. The traders are watching.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Every hop is a cable, and every cable is a long boat trip.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} is having a very expensive week. Route around it.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} cities, one landmass and a lot of trenches to dig.", +"puzzles_weekly.joke_one_ring_through_every_pop":"One ring through every POP: two links each, no shortcuts, no spurs.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Somewhere between {a} and {b} a repair ship is already waiting. Plan for it.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"The cheapest way between two islands is rarely a straight line.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"The obvious path goes through {hub}. The obvious path is closed.", +"puzzles_weekly.joke_the_ocean_is_big_and":"The ocean is big and the anchors are many. Bring a spare cable.", +"puzzles_weekly.joke_the_speed_of_light_is":"The speed of light is not a suggestion. Pick the straightest glass.", +"puzzles_weekly.latency_sprint":"Latency sprint", +"puzzles_weekly.name_across_the_big_blue":"Across the Big Blue", +"puzzles_weekly.name_anywhere_but_hub":"Anywhere but {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Are We There Yet, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Hop, Skip and a Cable", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms or Bust", +"puzzles_weekly.name_one_ring_to_rule_reg":"One Ring to Rule {reg}", +"puzzles_weekly.name_race_to_b":"Race to {b}", +"puzzles_weekly.name_ring_around_reg":"Ring Around {reg}", +"puzzles_weekly.name_sea_you_in_b":"Sea You in {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sun, Sea and Subsea", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Who Needs {hub}?", +"puzzles_weekly.ocean_crossing":"Ocean crossing", +"puzzles_weekly.region_tour":"Region tour", +"puzzles_weekly.ring":"Ring", "reach_and_subsea.premium_submarine_terminals":"Premium submarine terminals", "release_notes.and_n_more_change":{"one":"…and {n} more change","other":"…and {n} more changes"}, "release_notes.read_the_full_notes_on_github":"Read the full notes on GitHub", @@ -3267,7 +3325,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, in the Azores, halfway across the Atlantic. Florida to Spain and Lisbon to Lagos are just too long for a 1.6T wave: straight across, each carries 1.2T. Land on the islands in between, start the light fresh, and every hop runs at 1.6T or better. You start with 1.6T gear unlocked.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs in Bogotá, Lima, Santiago and São Paulo, and 150 Gbps served", "scenarios.ports_on_15_ix_brrr_exchanges":"Ports on 15 IX.brrr exchanges, one of them in Manaus, and 200 Gbps served", -"scenarios.reach_45_of_the_internet_and":"Reach 45% of the internet and serve 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Reach 50% of the internet and serve 300 Gbps", "scenarios.red_sea_crisis":"Red Sea Crisis", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio from scratch. Carnaval starts in 90 days and wants 400 Gbps for five days straight. The whole world is watching.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Sandbox mode
A billion dollars and every unlock. Chaos: {chaos}. Build the internet you always wanted, and keep a spare backhoe handy.", diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css index 5dc6720..6a2cbf5 100644 --- a/src/styles/36-ops.css +++ b/src/styles/36-ops.css @@ -11,3 +11,6 @@ .ops-p{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} .ops-p .b{white-space:normal;text-align:left;min-height:36px} .ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto} +.ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)} +.ops-rep{border-left:3px solid #8E5CF7;background:#F7F2FF;border-radius:0 8px 8px 0;padding:6px 8px;margin:6px 0;font-size:13px;line-height:1.35;overflow-wrap:anywhere} +.ops-rep .eyebrow{margin-bottom:2px} diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index 20fa6b1..e879143 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -6,8 +6,9 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzs{display:flex;gap:6px;margin:6px 0}.pzs span{flex:1;display:flex;flex-direction:column;align-items:center;border:2.5px solid var(--ink);border-radius:11px;padding:3px 0;font-size:20px;filter:grayscale(1);opacity:.45;transition:transform .25s,opacity .25s} .pzs span small{font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em}.pzs span.on{filter:none;opacity:1;background:#FFF3C4;transform:scale(1.05)} .pzck{display:flex;flex-wrap:wrap;gap:5px;margin:6px 0}.pzc{font-weight:900;font-size:12px;border:2px solid var(--ink);border-radius:999px;padding:1px 8px;background:#fff} +.pzc i{font-style:normal} .pzc.s1{background:#FFE3F0}.pzc.s2{background:var(--ok);color:#fff} -.pztw{font-size:12.5px;font-weight:800;color:var(--bad);margin:3px 0}.pztw.ok{color:var(--eye)} +.pztw{font-size:12.5px;font-weight:800;color:var(--bad);margin:3px 0}.pztw.ok{color:var(--eye)}.pztw.rule{color:var(--ink2)} .pzbud{margin:6px 0}.pzbud .kv{font-size:12.5px} .pzn1{font-size:12.5px;font-weight:800;margin:6px 0;padding:4px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} .pzn1.on{border-color:var(--ok);background:#DFFBEA;color:var(--ink);animation:pzglow 1.6s ease-in-out infinite}.pzn1.bad{border-color:var(--warn);background:#FFF4D6;color:var(--ink)} @@ -18,6 +19,10 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .scn.lock{opacity:.5} .pzres{position:relative}.pzstars{display:flex;justify-content:center;gap:10px;margin:10px 0 2px} .pzbig{font-size:46px;filter:grayscale(1);opacity:.3}.pzbig.on{filter:none;opacity:1} +.pzleft{text-align:center;font-weight:900;font-size:13px;margin:2px 0 0;color:var(--ink2)} +.btns.pzdone .pznext{flex:1 1 100%;font-size:22px;padding:10px 18px 8px;animation:pznudge 1.8s ease-in-out 1.6s infinite} +@keyframes pznudge{50%{transform:translateY(-2px);box-shadow:0 5px 0 var(--ink)}} +@media (prefers-reduced-motion:reduce){.btns.pzdone .pznext{animation:none}} .pzbig.pop{animation:pzpop .5s cubic-bezier(.3,1.6,.5,1) var(--d) both} @keyframes pzpop{0%{transform:scale(0) rotate(-40deg);opacity:0}100%{transform:scale(1) rotate(0);opacity:1}} .pzconf{position:absolute;inset:-16px;pointer-events:none;overflow:hidden;z-index:2} @@ -26,6 +31,9 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB @media (max-width:760px),(max-height:500px) and (pointer:coarse){ #pzBox{top:auto;left:0;right:0;width:auto;bottom:0;max-height:min(46%,330px);border-radius:20px 20px 0 0;border-bottom:0;box-shadow:0 -3px 0 var(--ink);padding:0 12px calc(10px + env(safe-area-inset-bottom,0px))} #pzBox .grab{display:block} + #pzBox .btns .b,#pzBox .pzh .b{min-height:40px;min-width:40px;padding:4px 12px} + /* Long languages make the sheet scroll: Undo, Reset and Back stay pinned at its foot. */ + #pzBox>.btns{position:sticky;bottom:0;background:var(--paper);margin:6px -12px 0;padding:6px 12px 0;box-shadow:0 -6px 6px -6px rgba(30,38,64,.25)} #pzBox.mini{max-height:none}#pzBox.mini>:not(.grab):not(.pzh):not(.pzs){display:none} #pzBox.mini .pzs{margin-top:0} body.pz.sheet-open #pzBox{display:none} @@ -34,7 +42,13 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzbig{font-size:40px} } @media (orientation:landscape) and (max-height:500px) and (pointer:coarse),(orientation:landscape) and (max-width:760px) and (max-height:500px){ - #pzBox{left:auto;right:0;width:min(360px,52%);top:calc(env(safe-area-inset-top,0px) + 50px);max-height:none;border-radius:20px 0 0 0;border-right:0} + #pzBox{left:auto;right:0;width:min(360px,52%);top:calc(env(safe-area-inset-top,0px) + 50px);max-height:calc(100% - 50px - env(safe-area-inset-top,0px));overscroll-behavior:contain;border-radius:20px 0 0 0;border-right:0} + #pzBox .pzj{display:none}#pzBox .pzs span{font-size:16px;padding:1px 0} body.pz #hint{bottom:12px !important;left:30% !important} body.pz #toasts{left:8px !important;transform:none !important;width:calc(48% - 16px) !important} } +/* The weekly puzzle: a badge on the Puzzles door and in the list while this week's puzzle is unplayed. */ +.pznew{display:inline-block;font:900 10.5px/1.2 var(--body);font-style:normal;text-transform:uppercase;letter-spacing:.04em;background:var(--me);color:#fff;border:2px solid var(--ink);border-radius:999px;padding:1px 7px;white-space:nowrap;vertical-align:1px} +.door .pznew{position:absolute;top:-9px;right:8px;transform:rotate(4deg);animation:pznew 2.4s ease-in-out infinite} +@keyframes pznew{50%{transform:rotate(-3deg) scale(1.08)}} +.scn.wk{flex-wrap:wrap}.scn.wk .grow{min-width:0;flex:1 1 200px}.pzcd{font-weight:800;color:var(--ink)} diff --git a/tests/badges-variants.test.js b/tests/badges-variants.test.js index 648aaed..9f1b6a2 100644 --- a/tests/badges-variants.test.js +++ b/tests/badges-variants.test.js @@ -135,3 +135,37 @@ test('the share card rings the variant badges', () => { assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`); assert.deepEqual(errors, []); }); + +test('a variant named after an Object prototype key is not a variant', () => { + const { ev, errors } = load(); + start(ev); + for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { + ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${JSON.stringify(k)}};S=migrate(o)`); + assert.equal(ev('S.achP.hello'), 'oncall', k); + assert.equal(ev(`bvar(${JSON.stringify(k)}).k`), 'oncall', `bvar(${k})`); + ev(`S.rules={preset:${JSON.stringify(k)}}`); + assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`); + } + ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()"); + assert.deepEqual(errors, []); +}); + +test('"Badge upgraded" means the collection on this device got a better variant', () => { + const { ev, errors } = load(); + const spy = () => ev("window.__t=[];if(!window.__sp){window.__sp=1;const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);};}"); + // a new game, but this device already holds the frosted badge: the standard one upgrades it + start(ev, 'oncall'); + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{freeze:'2026-01-01'}}}))"); + spy(); earnHello(ev); + assert.match(ev("window.__t.join(' ')"), /Badge upgraded/); + assert.equal(hof(ev).hello.v, 'oncall'); + // another new game, the device already holds the fiery one: earning the frosted one is a plain unlock + start(ev, 'freeze'); + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{bgp:'2026-01-01'}}}))"); + spy(); earnHello(ev); + const t = ev("window.__t.join(' ')"); + assert.match(t, /Badge unlocked/); + assert.doesNotMatch(t, /Badge upgraded/); + assert.equal(hof(ev).hello.v, 'bgp', 'the best variant stays on the shelf'); + assert.deepEqual(errors, []); +}); diff --git a/tests/link-trial.test.js b/tests/link-trial.test.js new file mode 100644 index 0000000..ae39a32 --- /dev/null +++ b/tests/link-trial.test.js @@ -0,0 +1,24 @@ +// #62 on a big network: a redundancy check routes once (the failed link), and uses the live routing as "before". +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('#62 a redundancy check computes only the trial, and matches comparing two fresh routings', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}]"); + ev("S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0},{id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0}];compute()"); + ev("window.__n=0;window.__c=compute;compute=function(){window.__n++;return window.__c.apply(this,arguments);}"); + const t = JSON.parse(ev("JSON.stringify(linkTrial('main'))")); + assert.equal(ev('window.__n'), 1, 'one routing pass per check'); + assert.equal(t.split, false); + assert.equal(t.loss, 70); + assert.equal(ev("linkTrial('nope')"), null); + assert.equal(ev('window.__n'), 1, 'an unknown link costs nothing'); + ev('compute=window.__c'); + // the old way: route the copy twice, before and after the cut + const old = ev(`(()=>{const save=S,live=R;try{S=JSON.parse(JSON.stringify(save));compute();const b=R;S.links[0].cut=S.day+1;compute(); + const g=c=>Math.max(0,(b.citySrv[c]||0)-(R.citySrv[c]||0)),l2=Math.max(0,(b.l2.circuit||0)-(R.l2.circuit||0)); + return Object.keys(S.pops).reduce((a,c)=>a+(g(c)>.01?g(c):0),0)+(l2>.01?l2:0);}finally{S=save;R=live;}})()`); + assert.equal(t.loss, old); + assert.deepEqual(errors, []); +}); diff --git a/tests/metric-panel.test.js b/tests/metric-panel.test.js new file mode 100644 index 0000000..fdf2d5a --- /dev/null +++ b/tests/metric-panel.test.js @@ -0,0 +1,40 @@ +// #131 on Safari: the custom metric field keeps focus through a button tap, and the panel skips re-rendering a +// focused field, so switching between multiplier and cost (or to a preset) left the old panel on screen. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const setup = (ev) => { + ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal()"); + ev("window.L=S.links[0].id;ACT.selLink({id:L});renderAll();ACT.setMetric({id:L,v:'custom'});renderAll()"); +}; + +test('#131 switching the custom metric mode re-renders even while the field has focus', () => { + const { ev, dom, errors } = load(); + const d = dom.window.document; + setup(ev); + d.getElementById('metIn').focus(); + assert.equal(d.activeElement.id, 'metIn'); + ev("ACT.metricMode({id:L,k:'w'})"); + assert.equal(d.getElementById('metIn').getAttribute('step'), '1', 'the field is now the exact cost'); + assert.equal(+d.getElementById('metIn').value, ev("S.pairMet[edgeKey(S.links[0])].v")); + d.getElementById('metIn').focus(); + ev("ACT.metricMode({id:L,k:'f'})"); + assert.equal(d.getElementById('metIn').getAttribute('step'), '0.1', 'and back to a multiplier'); + d.getElementById('metIn').focus(); + ev("ACT.setMetric({id:L,v:'normal'})"); + assert.equal(d.getElementById('metIn'), null, 'a preset hides the field'); + assert.deepEqual(errors, []); +}); + +test('#131 the daily re-render still keeps a half-typed value', () => { + const { ev, dom, errors } = load(); + const d = dom.window.document; + setup(ev); + const t = d.getElementById('metIn'); + t.focus(); t.value = '3.5'; + ev("S.day++;renderPanel()"); + assert.equal(d.getElementById('metIn').value, '3.5'); + assert.equal(d.activeElement.id, 'metIn'); + assert.deepEqual(errors, []); +}); diff --git a/tests/modes.test.js b/tests/modes.test.js index 622de40..95ef1bd 100644 --- a/tests/modes.test.js +++ b/tests/modes.test.js @@ -409,8 +409,8 @@ test('#114 Only Spätzle-IX can be won by peering alone', () => { const { ev, errors } = load(); ev("ACT.startScn({id:'stg',sure:1})"); assert.equal(ev("scnRule('local')&&scnRule('noTransit')"), true); - assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /45%.*300 Gbps/); - assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.45, 300]); + assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /50%.*300 Gbps/); + assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.5, 300]); // a game saved before the fix picks the rule up on load ev("const o=JSON.parse(JSON.stringify(S));delete o.scn.rules.local;migrate(o);window.__mig=o.scn.rules.local"); assert.equal(ev('window.__mig'), true); diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index b7c4d6e..d96acea 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -7,23 +7,24 @@ const { load } = require('./harness'); // `one` earns the goal star, `three` earns all three. A second land link on the same pair is a diverse route. const REF = { hello: { one: [['lon', 'nyc', 'grace']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'amitie']] }, - eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['lon', 'ams', 'uly'], ['lon', 'ams', 'concerto'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] }, - shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['nyc', 'chi', 'land'], ['chi', 'sjc', 'land'], ['sjc', 'dal', 'land'], ['dal', 'nyc', 'land']] }, - smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['hel', 'cph', 'land'], ['cph', 'osl', 'land']] }, - downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['adl', 'bne', 'land'], ['bne', 'syd', 'land']] }, - aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['sjc', 'hnl', 'scx'], ['sjc', 'hnl', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] }, - rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['tok', 'hkg', 'adc'], ['tok', 'hkg', 'apg'], ['hkg', 'sin', 'sjc2'], ['hkg', 'sin', 'land']] }, - fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] }, - kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'sea', 'hwk'], ['sea', 'hnl', 'hwk'], ['hnl', 'akl', 'hwk'], ['akl', 'syd', 'tasman'], ['akl', 'syd', 'scx']] }, - guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']] }, - flash: { one: [['nyc', 'lon', 'hibx']], three: [['nyc', 'lon', 'hibx'], ['nyc', 'lon', 'grace']] }, + eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['ams', 'lon', 'concerto'], ['ams', 'lon', 'nshuttle'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] }, + shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['chi', 'nyc', 'land'], ['chi', 'sjc', 'land'], ['dal', 'nyc', 'land'], ['dal', 'sjc', 'land']] }, + smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['cph', 'osl', 'land'], ['cph', 'hel', 'land'], ['hel', 'sto', 'land']] }, + downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['mel', 'syd', 'land'], ['bne', 'syd', 'land'], ['adl', 'mel', 'land'], ['adl', 'bne', 'land']] }, + aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['hnl', 'sjc', 'scx'], ['hnl', 'sjc', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] }, + rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['hkg', 'tok', 'apg'], ['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['hkg', 'sin', 'land']] }, + fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] }, + // Hawaiki is Seattle's only cable south, so the second way out runs overland to LA and on via Suva. + kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'syd', 'tasman'], ['akl', 'sea', 'hwk'], ['suv', 'syd', 'scxn'], ['lax', 'sea', 'land'], ['lax', 'suv', 'scxn']] }, + guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['mnl', 'tok', 'jup'], ['syd', 'tok', 'sushi'], ['gum', 'mnl', 'bifrost'], ['gum', 'syd', 'guam']] }, + flash: { one: [['nyc', 'lon', 'hibx']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'hibx']] }, pingpong: { one: [['lax', 'tok', 'jup']], three: [['lax', 'tok', 'jup'], ['lax', 'sea', 'land'], ['sea', 'tok', 'fast']] }, - suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['mrs', 'bom', 'twoaf'], ['bom', 'sin', 'land']] }, - samba: { one: [['sao', 'mia', 'monet']], three: [['sao', 'mia', 'monet'], ['sao', 'for', 'land'], ['for', 'mia', 'monet']] }, - sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land'], ['mil', 'lis', 'land']] }, - braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix'], ['dub', 'nyc', 'havf']] }, - nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land'], ['zrh', 'ams', 'land']] }, - fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1], ['zrh', 'par', 'land', 1]] }, + suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['bom', 'sin', 'land'], ['bom', 'mrs', 'twoaf']] }, + samba: { one: [['sao', 'mia', 'monet']], three: [['for', 'sao', 'land'], ['for', 'sao', 'land'], ['for', 'mia', 'monet'], ['for', 'mia', 'sam1']] }, + sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['lis', 'mil', 'land'], ['mad', 'par', 'land'], ['mil', 'par', 'land']] }, + braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['lon', 'nyc', 'grace'], ['dub', 'nyc', 'havf'], ['dub', 'lon', 'celtix']] }, + nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ams', 'zrh', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']] }, + fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'zrh', 'land', 1], ['mrs', 'par', 'land', 1], ['mil', 'mrs', 'land', 1], ['mil', 'zrh', 'land', 1]] }, }; // Builds links the way a player does: POP at the first city, then the link picker for each hop. @@ -61,6 +62,45 @@ test('puzzle data: every puzzle is valid, solvable, and its 3-star reference ear assert.deepEqual(errors, []); }); +// Brute force over every route between the puzzle's cities (one size: 10G, or 100G under minG): is any 3-star build +// cheaper than `limit`? Each cable is one failure unit; each overland link its own trench (a second one is diverse). +function cheaper3(ev, id, limit) { + const D = JSON.parse(ev(`(()=>{pzBegin(pzDef('${id}'));const P=S.pz,cs=[...P.cities,...P.via],tier=P.minG?1:0,o=[]; + for(const a of cs)for(const b of cs)if(a o[i].cab ? 'c' + o[i].cab : 't' + i; + const reach = (ls, skip) => { const adj = {}; for (const i of ls) { if (unit(i) === skip) continue; const { a, b } = o[i]; (adj[a] = adj[a] || []).push(b); (adj[b] = adj[b] || []).push(a); } + const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) for (const v of adj[q.pop()] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } return P.cities.every((c) => seen.has(c)); }; + const lat = (ls) => { const d = { [P.lat[0]]: 0 }, done = new Set(); for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null) return Infinity; if (u === P.lat[1]) return d[u]; done.add(u); + for (const i of ls) { const l = o[i]; if (l.a !== u && l.b !== u) continue; const v = l.a === u ? l.b : l.a, nd = d[u] + l.ms + 0.05; if (!(nd >= d[v])) d[v] = nd; } } }; + const ring = (ls) => { const nb = {}; for (const i of ls) { const { a, b } = o[i]; (nb[a] = nb[a] || new Set()).add(b); (nb[b] = nb[b] || new Set()).add(a); } const ns = Object.keys(nb); + if (ns.length < 3 || !ns.every((c) => nb[c].size === 2)) return false; let prev = null, cur = ns[0], n = 0; do { const nx = [...nb[cur]].find((x) => x !== prev); prev = cur; cur = nx; n++; } while (cur !== ns[0] && n <= ns.length); return n === ns.length; }; + const ok = (ls) => { if (!reach(ls, null) || (P.ring && !ring(ls)) || (P.lat && lat(ls) > P.lat[2])) return false; return [...new Set(ls.map(unit))].every((u) => reach(ls, u)); }; + let found = null; + const rec = (start, ls, cost) => { if (found) return; if (ls.length && cost < limit - 1) { const pops = new Set(P.cities); for (const i of ls) { pops.add(o[i].a); pops.add(o[i].b); } const tot = cost + [...pops].reduce((x, c) => x + pop[c], 0); if (tot < limit - 1 && ok(ls)) { found = tot; return; } } + if (ls.length >= 7) return; for (let i = start; i < o.length; i++) { if (o[i].div && !ls.some((j) => !o[j].div && !o[j].cab && o[j].a === o[i].a && o[j].b === o[i].b)) continue; if (cost + o[i].cost < limit - 1) rec(i + 1, [...ls, i], cost + o[i].cost); } }; + rec(0, [], 0); + return found; +} + +test('budgets follow the difficulty curve: roomy first pack, ~10% in the middle, tight N-1 Club', () => { + const { ev, errors } = load(); + const SLACK = { hello: [0.15, 0.2], fire: [0.09, 0.11], speed: [0.09, 0.11], n1: [0.05, 0.08] }; + const rows = JSON.parse(ev('JSON.stringify(PZ.filter(p=>p.budget).map(p=>({id:p.id,pack:p.pack,budget:p.budget})))')); + for (const { id, pack, budget } of rows) { + ev(`pzBegin(pzDef('${id}'))`); + build(ev, REF[id].three); + const e = evalP(ev); + assert.equal(e.stars, 3, id); + assert.equal(cheaper3(ev, id, e.spend), null, `${id}: the reference is the cheapest 3-star build`); + const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack]; + assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`); + } + assert.match(ev("PZ_PACKS[0].d"), /Roomy budgets/, 'the first pack does not promise "no budget"'); + assert.deepEqual(errors, []); +}); + test('stars: goal, budget, N-1 and twists each count', () => { const { ev, errors } = load(); ev("pzBegin(pzDef('braces'))"); @@ -77,6 +117,15 @@ test('stars: goal, budget, N-1 and twists each count', () => { build(ev, REF.shining.one); ev("ACT.pzLinkTo({a:'nyc',b:'chi'});ACT.pzVia({v:'land'});ACT.pzDiv({v:0});ACT.pzLink({tier:0})"); assert.equal(ev("new Set(S.links.filter(l=>edgeKey(l)==='chi|nyc').map(pzUnit)).size"), 1, 'same trench shares the cut'); + // A cable fails as a whole: two waves on one cable, even between different cities, are one cut. + ev("pzBegin(pzDef('guam'))"); + build(ev, [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']]); + e = evalP(ev); + assert.ok(e.goal && !e.n1, 'both of Sydney\'s links ride the Guam cable: one anchor splits Sydney off'); + assert.equal(ev("new Set(S.links.filter(l=>l.cable==='guam').map(pzUnit)).size"), 1, 'one cable, one failure unit'); + assert.ok(ev("document.getElementById('pzBox').textContent").includes('One cut splits it: ' + ev('CAB.guam.name')), 'the weak spot names the cable'); + ev("ACT.pzRmLink({id:S.links[3].id})");build(ev, [['tok', 'syd', 'sushi']]); + assert.equal(evalP(ev).stars, 3, 'a second cable into Sydney fixes it'); // Twists: no subsea, ring, latency, minimum size, cities to avoid. ev("pzBegin(pzDef('sharks'))");build(ev, REF.sharks.one); assert.ok(evalP(ev).goal); @@ -180,16 +229,16 @@ test('weekly puzzle: stable seed per ISO week, solvable, share string and streak assert.equal(w.key, '2026-W44'); assert.ok(w.cities.length >= 4 && w.cities.length <= 5 && w.budget > 0); // Every week of a few years can be solved with three stars by its own reference ring. - for (let i = 0; i < 160; i += 7) { + for (let i = 0; i < 400; i += 7) { ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`); - const ring = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')).ref)')); - const links = ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; }); - build(ev, links); + const w = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')))')); + const cabs = w.refVia.filter((v) => v !== 'land'); + assert.equal(new Set(cabs).size, cabs.length, `week +${i}: no two hops of the reference ring share a cable`); + build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]])); assert.equal(evalP(ev).stars, 3, `week +${i}`); } ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))"); - const ring = w.ref; - build(ev, ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; })); + build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]])); assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$\d+k · seriesoftub\.es$/); assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1); // A streak counts weeks in a row; a gap starts again. @@ -253,3 +302,146 @@ test('puzzles in every language', () => { assert.deepEqual(errors, [], lang); } }); + +test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('kiwi'))"); + assert.ok(ev('colo("suv")') > 1, 'Suva is a thin market'); + assert.equal(ev("pzPopCost('suv')"), ev("popCost('suv')+12*popMo('suv')")); + assert.ok(ev("pzPopCost('suv')") > ev("popCost('suv')+12*POP_MO")); + ev("selectCity('suv')"); + assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo')); + assert.deepEqual(errors, []); +}); + +test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))"); + const rec = () => JSON.parse(ev("JSON.stringify(pzLoad().s.braces||null)")); + build(ev, REF.braces.one); + const two = evalP(ev).spend; + assert.deepEqual(rec(), { st: 2, sp: two }); + // A gold-plated third link: N-1 but over budget is still two stars, and dearer, so the best stays. + ev("ACT.pzLinkTo({a:'dub',b:'nyc'});ACT.pzVia({v:'havf'});ACT.pzLink({tier:2});closeModal()"); + assert.equal(evalP(ev).stars, 2); + assert.deepEqual(rec(), { st: 2, sp: two }); + // Shrinking it to 10G earns the third star: the best spend starts again at the 3-star build. + ev('ACT.pzTier({id:S.links[2].id,tier:0})'); + const three = evalP(ev); + assert.equal(three.stars, 3); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + // With a looser budget, a dearer 3-star build does not replace it; going back to the cheaper one keeps it. + ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:1})'); + assert.equal(evalP(ev).stars, 3); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + // A cheaper 3-star build after a dearer first one is recorded (the old code only recorded star rises). + ev("localStorage.removeItem('sot-puzzles')"); + ev('ACT.pzTier({id:S.links[1].id,tier:1})'); + const dear = evalP(ev).spend; + assert.deepEqual(rec(), { st: 3, sp: dear }); + ev('ACT.pzTier({id:S.links[1].id,tier:0});ACT.pzTier({id:S.links[0].id,tier:0})'); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + // Fewer stars never overwrite more. + ev('ACT.pzRmLink({id:S.links[2].id})'); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + ev('ACT.puzzleMenu({})'); + assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`))); + assert.deepEqual(errors, []); +}); + +test('main-game toasts and leftover buttons do nothing in a puzzle', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true)"); + ev("toast('main game news','bad',[{l:'Fix',act:'opsOpen',args:{}}]);save(true)"); + assert.ok(ev("document.querySelectorAll('#toasts .toast').length") > 0); + const before = ev("localStorage.getItem('sot-save-v1')"); + ev("ACT.pzStart({id:'hello'})"); + assert.equal(ev("[...document.querySelectorAll('#toasts .toast')].filter(t=>/main game news/.test(t.textContent)).length"), 0, 'main-game toasts are cleared'); + ev("ACT.pzPop({city:'lon'})"); + const st = () => ev("JSON.stringify({p:S.pops,l:S.links.length,c:S.cash,m:S.mode,te:!!S.te,ops:S.ops,sc:S.scrubs.length,dash:$('dash').hidden,bank:$('bankBox').hidden,left:$('left').hidden,modal:$('modal').hidden,cam:[cam.x,cam.y]})"); + const s0 = st(); + for (const a of ["opsOpen({})", "inbox({})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})", + "exportSave({})", "launchBB({city:'lon'})", "ad({city:'lon'})", "addRouter({city:'lon'})", "upRouter({city:'lon'})", "addSite({city:'lon'})", "buyTE({})", + "buildScrub({city:'lon',tier:0})", "buildPop({city:'par'})", "buyTransit({city:'lon',net:'cog',tier:1})", "scenarios({})", "share({})", "importGo({})", "cont({})", "start({})", "newgame({})"]) { + ev('ACT.' + a); + assert.equal(st(), s0, `${a} does nothing in a puzzle`); + } + assert.equal(ev('S.mode'), 'puzzle'); + // A leftover toast button is a no-op too, through the real click path. + ev("toast('stray','',[{l:'Go',act:'opsOpen',args:{}}]);document.querySelector('#toasts [data-act=opsOpen]').click()"); + assert.equal(st(), s0); + ev("toast('puzzle news','good')"); + ev('ACT.pzLeave({})'); + assert.equal(ev("document.querySelectorAll('#toasts .toast').length"), 0, 'puzzle toasts do not follow you home'); + assert.equal(ev("localStorage.getItem('sot-save-v1')"), before); + // Back in the main game, the same actions work again. + ev("ACT.addRouter({city:'ams'})"); + assert.equal(ev('S.pops.ams.routers'), 2); + assert.deepEqual(errors, []); +}); + +test('a city to avoid reads as a rule, not a goal that can fail', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('nofra'))"); + const tw = () => ev("[...document.querySelectorAll('#pzBox .pztw')].map(x=>x.className+'|'+x.textContent).join('\\n')"); + assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/); + assert.doesNotMatch(tw(), /[✓✗].*Frankfurt/); + build(ev, REF.nofra.three); + assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/, 'still a rule once solved'); + assert.equal(evalP(ev).stars, 3); + assert.deepEqual(errors, []); +}); + +test('phone sheet: 40 px touch targets, pinned actions, and goal chips with a clear mark', () => { + const { ev, errors } = load(); + // jsdom has no layout: read the phone media rules from the page's stylesheet (Chromium at 360 px measures 40 px). + const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText)) + .flatMap(m=>[...m.cssRules]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),mw:r.style.getPropertyValue('min-width'),pos:r.style.getPropertyValue('position'),bottom:r.style.getPropertyValue('bottom')})))`)); + const tap = rules.find((r) => /#pzBox \.btns \.b/.test(r.sel) && /#pzBox \.pzh \.b/.test(r.sel)); + assert.ok(tap && parseFloat(tap.mh) >= 40 && parseFloat(tap.mw) >= 40, `Undo/Reset/Back/☰ are at least 40 px (${JSON.stringify(tap)})`); + const pin = rules.find((r) => /^#pzBox ?> ?\.btns$/.test(r.sel)); + assert.ok(pin && pin.pos === 'sticky' && parseFloat(pin.bottom) === 0, `the action row stays at the foot of a scrolling sheet (${JSON.stringify(pin)})`); + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));pzBegin(pzDef('braces'))"); + const chips = () => ev("[...document.querySelectorAll('#pzBox .pzc')].map(x=>x.textContent).join('|')"); + assert.equal(chips(), '○ New York|○ London|○ Dublin', 'not reached yet: a hollow mark, nothing that looks cut off'); + assert.doesNotMatch(chips(), /…/); + build(ev, [['nyc', 'lon', 'grace']]); + ev("ACT.pzPop({city:'dub'})"); + assert.equal(chips(), '✓ New York|✓ London|◐ Dublin'); + assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes'); + assert.deepEqual(errors, []); +}); + +test('results pull you on: Next is the big tap after three stars, stars left in the pack, and a nudge when 3 stars are one link away', () => { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))"); + build(ev, REF.braces.one); + let card = ev("document.getElementById('modalCard').textContent"); + assert.equal(evalP(ev).stars, 2); + assert.match(card, /So close: one more link and a backhoe can't touch you\./, 'Dublin to New York would do it, within budget'); + assert.match(ev("document.getElementById('pzBox').textContent"), /So close/); + assert.match(card, /10 ⭐ left in this pack/, '4 puzzles × 3 stars, 2 won'); + assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); + assert.ok(!ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')")); + build(ev, [['dub', 'nyc', 'havf']]); + card = ev("document.getElementById('modalCard').textContent"); + assert.match(card, /9 ⭐ left in this pack/); + assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"), 'three stars: the big Next layout'); + assert.ok(ev("document.activeElement===document.querySelector('#modalCard .pznext')"), 'the big button has the focus'); + assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars'); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/, 'the last pack points back to the list'); + ev("pzBegin(pzDef('eurotrip'))");build(ev, REF.eurotrip.three); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/); + assert.equal(ev("document.activeElement.dataset.act"), 'pzStart'); + // No nudge when no single link fits the budget: an over-budget gold plate is not "close". + ev("pzBegin(pzDef('braces'));S.pz.budget=245000"); + build(ev, REF.braces.one); + assert.equal(evalP(ev).stars, 2); + assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /So close/); + assert.match(ev("document.getElementById('modalCard').textContent"), /One backhoe away/); + // A finished pack says so. + ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{sharks:{st:3},braces:{st:3},nofra:{st:3},fatpipes:{st:2}}}));pzBegin(pzDef('fatpipes'))"); + build(ev, REF.fatpipes.three); + assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/); + assert.deepEqual(errors, []); +}); diff --git a/tests/regions.test.js b/tests/regions.test.js index 139c27f..875f3a1 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -1076,7 +1076,12 @@ test('prices follow real connectivity: thin markets cost more, hubs stay put', ( const { ev, errors } = load(); start(ev); assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(CITY_PDB).filter(c=>!CITY[c]))')), [], 'every entry is a city on the map'); - assert.ok(ev('Object.keys(CITY_PDB).length') >= 190, 'real-world data for most cities'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(CITIES.filter(c=>!CITY_PDB[c.id]).map(c=>c.id))')), [], 'every city has data, so none keeps the plain price by accident'); + assert.ok(ev('Object.values(CITY_PDB).every(q=>Array.isArray(q)&&q.length===3&&q.every(x=>Number.isInteger(x)&&x>=0)&&q[1]>=0)'), '[facilities, presences, ASNs], whole numbers'); + // The cities that used to have none: thin markets cost more than Frankfurt, and the Arctic has no neutral data center. + for (const c of ['dus', 'rix', 'mct', 'mle', 'fuk', 'sju', 'kin', 'anc', 'tik']) assert.ok(ev(`txComp('${c}')`) > 1, `${c} is no hub`); + for (const c of ['brw', 'tik', 'pvs', 'hav']) assert.equal(ev(`colo('${c}')`), 1.5, `${c}: no carrier-neutral data center`); + assert.ok(ev("txComp('dus')") < ev("txComp('rix')") && ev("txComp('rix')") < ev("txComp('mle')"), 'Düsseldorf, Riga, Malé: ever thinner'); // A city without data keeps the plain regional price. assert.equal(ev("(()=>{const q=CITY_PDB.fra;delete CITY_PDB.fra;const r=[txComp('fra'),colo('fra'),popMo('fra')];CITY_PDB.fra=q;return r.join()})()"), `1,1,${ev('POP_MO')}`); assert.equal(ev("regionMult('syd')"), ev('AU_TRANSIT'), 'Australia keeps its hand-set transit price'); diff --git a/tests/routing-reference.test.js b/tests/routing-reference.test.js index 8a239ad..8ebacc1 100644 --- a/tests/routing-reference.test.js +++ b/tests/routing-reference.test.js @@ -54,3 +54,28 @@ test('indexed routing matches the simple allocation loop across network changes' } finally { dom.window.close(); } }); + +// Islands: POPs no backbone joins. Exit lists are split per island (a flow only scans exits it can reach), +// and must route exactly like the full scan, also when a cut splits an island or joins two. +test('indexed routing matches the simple allocation loop on a network of islands', () => { + const { ev, dom, errors } = load(); + try { + network(ev); + ev("S.links=S.links.filter(l=>!['df4','df9','w3','w4','w8','w9'].includes(l.id));compute()"); + assert.ok(ev("Object.keys(S.pops).some(c=>!pathExists('fra',c))"), 'the network is in pieces'); + const changes = [ + '', + "S.pni.forEach((p,i)=>p.pref=i%3===0?'high':i%3===1?'low':'normal')", + "S.te={on:true,script:'prefer pni for goggle\\nspill at 80%'}", + "S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}", + "S.links[0].cut=S.day+2", + "S.te=null;S.links[0].cut=0;S.links.push({id:'join',a:'par',b:'pek',kind:'wave',tier:2,km:8000,cut:0,mo:100})", + ]; + for (const change of changes) { + ev(change); + ev('window.priorR=JSON.stringify(R);referenceCompute();window.expectedR=JSON.stringify(R);R=JSON.parse(priorR);compute()'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(R)')), JSON.parse(ev('expectedR')), change || 'baseline'); + } + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); diff --git a/tests/sales-trial.test.js b/tests/sales-trial.test.js new file mode 100644 index 0000000..814b62b --- /dev/null +++ b/tests/sales-trial.test.js @@ -0,0 +1,73 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); + +// The sales trial (#185, the intern's sales order) runs the pass with the offer first and skips the pass without +// it when it cannot change the answer. It must sign exactly the offers the original two-pass trial signs. +const ORIGINAL = `(function(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; + const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; + if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null; + if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id; + if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;} + const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day); + try{S={...S,biz:S.biz}; + if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();} + const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); + return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; + }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}})`; + +test('the faster sales trial signs exactly the offers the two-pass trial signs', () => { + const { ev, dom, errors } = load(); + try { + const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();window.slowOffer=${ORIGINAL};`); + assert.ok(ev('S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day)'), 'the fixture has events booked ahead, so the shortcut runs'); + const seen = { yes: 0, no: 0, skipped: 0, third: 0 }; + ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}'); + for (let day = 0; day < 6; day++) { + ev(`__reseed(${1000 + day});S.offers=[];for(let i=0;i<10;i++)spawnOffer();`); + // Small offers that fit, and on alternate days a squeeze, so offers fail on capacity and on others' service too. + ev(`for(const o of S.offers)o.bw=Math.max(1,Math.round(o.bw*${day % 2 ? 1 : 0.05}))`); + if (day % 2) ev('for(const c in S.pops)S.pops[c].bb&&(S.pops[c].bb.d*=1.3)'); + // And circuits over the busiest links, which take bandwidth from customers who had it. + ev(`for(const l of S.links.filter(l=>!linkDown(l)&&S.pops[l.a]&&S.pops[l.b]&&R.load[l.id]>1).sort((x,y)=>R.load[y.id]/capOf(y)-R.load[x.id]/capOf(x)).slice(${day},${day}+2)) + S.offers.push({id:'sq'+l.id,city:l.a,city2:l.b,name:'Squeeze',type:'l2vpn',bw:${day % 2 ? 300 : 2},rate:100,reqs:[],exp:S.day+30})`); + for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) { + const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`; + const before = ev('JSON.stringify(R.load)+R.served'); + ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n'); + assert.equal(ev('JSON.stringify(R.load)+R.served'), before, 'a trial leaves the live result alone'); + const slow = ev(`JSON.stringify(slowOffer(${o}))`); + assert.equal(fast, slow, `offer ${id} (${ev(`${o}.type`)}) on day ${day}`); + if (fast !== 'null') seen.yes++; else seen.no++; + if (n === 1) seen.skipped++; + if (n === 2) seen.third++; + } + ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()'); + } + assert.ok(seen.yes >= 3 && seen.no >= 3, `both answers come up (${JSON.stringify(seen)})`); + assert.ok(seen.skipped >= 5, `the second pass is often skipped (${JSON.stringify(seen)})`); + assert.ok(seen.third >= 3, `and run when the offer hurts someone (${JSON.stringify(seen)})`); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); + +test('with a scenic circuit the sales trial keeps both passes in their original order', () => { + const { ev, dom, errors } = load(); + try { + const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.biz.find(b=>BIZ_T[b.type].l2).route='scenic';compute();window.slowOffer=${ORIGINAL};`); + ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}'); + ev('__reseed(77);S.offers=[];for(let i=0;i<6;i++)spawnOffer();'); + for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) { + const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`; + ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n'); + assert.equal(fast, ev(`JSON.stringify(slowOffer(${o}))`), id); + assert.ok(n === 0 || n === 2, 'both passes, as before'); + } + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index fc9bd6f..ecb4848 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -231,13 +231,66 @@ test('the shift runs inside dayTick, respects a stopped clock, batches its work assert.deepEqual(errors, []); }); -test('the daily log line is folded into one NOC notification', t => { +test('the NOC gets one notice a week, the shift report; the daily lines stay in the Ops sheet', t => { const { ev, errors } = game(t, "S.transit[0].hist=[600]"); - hire(ev); on(ev, 'transit', { x: 1.5 }); + ev('S.day=14'); + hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'sales', { acc: true, min: 5000 }); + ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()'); const n0 = ev('S.log.length'); - shift(ev); - assert.equal(ev('S.log.length'), n0 + 1); - assert.match(ev('S.log[0].t'), /Kevin's shift Kevin topped up transit/); + for (let d = 14; d < 21; d++) { + if (d === 15) ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:60},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:60}]"); + ev(`S.day=${d}`); shift(ev); + } + assert.equal(ev('S.log.length'), n0, 'a whole week of shifts: no NOC notice yet'); + assert.ok(ev('S.ops.log.length') >= 2, 'the Ops sheet has the daily detail'); + ev('S.day=21'); shift(ev); + assert.equal(ev('S.log.length'), n0 + 1, 'one notice for the week'); + assert.match(ev('S.log[0].t'), /^Kevin's week Kevin signed a customer \(\+\$6\.0k\/mo\), topped up transit .*declined a tiny offer.*Week total: \$[\d.]+k up front, \+\$[\d.]+k\/mo\./); + assert.equal(ev('S.log[0].k'), 'good'); + ev('S.day=22'); shift(ev); + assert.equal(ev('S.log.length'), n0 + 1, 'and nothing more until the next week ends'); + // Only the sales order now: one tiny offer declined on day 23, reported when the week ends. + ev("for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.sales=true;S.offers=[{id:'t2',city:'fra',name:'T2',type:'dia',bw:1,rate:600,reqs:[],exp:60}];S.day=23");shift(ev); + ev("S.day=28");shift(ev); + assert.equal(ev('S.log.length'), n0 + 2); + assert.match(ev('S.log[0].t'), /declined a tiny offer\.$/, 'nothing spent: no money line'); + assert.equal(ev('S.log[0].k'), ''); + ev("S.day=35");shift(ev); + assert.equal(ev('S.log.length'), n0 + 2, 'an idle week: no notice'); + assert.deepEqual(errors, []); +}); + +test('the Ops sheet opens with the intern\'s mood and the weekly shift report, at 360 px, in every language', t => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const h = load(lang === 'en' ? {} : { lang }); + const { ev, dom, errors } = h; + ev(BASE); ev('S.day=14'); dom.window.innerWidth = 360; + hire(ev); + ev('opsModal()'); + const mood = () => dom.window.document.querySelector('#modalCard .ops-mood').textContent; + assert.equal(mood(), ev("tr('ops.mood_new',{name:opsName()})"), lang + ': a new hire says so'); + on(ev, 'transit', { x: 1.5 }, 0); + ev("S.transit[0].hist=[600];S.day=21");shift(ev);ev("S.transit[0].hist=[6000];S.day=28");shift(ev);ev('opsModal()'); + const reps = [...dom.window.document.querySelectorAll('#modalCard .ops-rep')]; + assert.equal(reps.length, 2, lang + ': last week, and this week so far'); + assert.equal(reps[0].lastElementChild.textContent, ev('opsWeekLine(S.ops.rep)'), lang); + assert.ok(mood().length > 10, lang); + assert.doesNotMatch(dom.window.document.getElementById('modalCard').textContent, /\bops\.[a-z_]+/, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); + +test('the mood follows the week, with no dice', t => { + const { ev, errors } = game(t); + ev('S.day=100'); hire(ev); ev('S.day=110'); + const quiet = ev('opsMood()'); + assert.equal(ev('opsMood()'), quiet, 'the same day reads the same'); + assert.ok([ev("tr('ops.mood_quiet',{name:'Kevin'})"), ev("tr('ops.mood_kevin')")].includes(quiet)); + ev("S.ops.wk=opsWkNew(Math.floor(S.day/7));S.ops.wk.n.sales=1"); + assert.equal(ev('opsMood()'), ev("tr('ops.mood_sales',{name:'Kevin'})")); + ev("S.ops.wk.n.broke=1;delete S.ops.wk.n.sales"); + assert.equal(ev('opsMood()'), ev("tr('ops.mood_broke',{name:'Kevin'})")); assert.deepEqual(errors, []); }); @@ -292,6 +345,9 @@ test('saves: old saves load with no intern and everything off, settings survive assert.equal(ev("JSON.stringify(S.ops.skip)"), '{"fra":["transit"]}'); assert.equal(ev("JSON.stringify(S.ops.log)"), '[{"d":1,"i":"kevin","r":[["transit",2,["fra +1×100G"]]]}]'); assert.equal(ev('S.ops.floor===50000&&S.ops.tpl.bb===true'), true); + ev(`S.ops.wk={w:3,i:'kevin',n:{sales:2,evil:9,transit:'x'},wh:{transit:['fra +1×100G','']},up:-5,mo:'a',rev:41000,ff:99};S.ops.rep={i:'mallory'};S=migrate(S)`); + assert.equal(ev("JSON.stringify(S.ops.wk)"), '{"w":3,"i":"kevin","n":{"sales":2},"wh":{"transit":["fra +1×100G"]},"up":0,"mo":0,"rev":41000,"ff":7}'); + assert.equal(ev('S.ops.rep'), null); assert.deepEqual(errors, []); }); @@ -339,3 +395,170 @@ test('sales trial at most one offer a shift, and an offer that did not fit waits ev('autoOffer=__a'); assert.deepEqual(errors, []); }); + +test('re-hiring in a later month starts on a fresh budget, not last month\'s spending', t => { + const { ev, errors } = game(t); + hire(ev); + ev("S.ops.spent.transit=50000;ACT.opsFire();ACT.opsFire();S.day=400;ACT.opsHire({id:'kevin'});closeModal()"); + assert.equal(ev('S.ops.spent.transit'), 0); + assert.equal(ev('S.ops.mon'), ev('Math.floor(S.day/30)')); + ev("S.ops.spent.transit=1234;ACT.opsFire();ACT.opsFire();ACT.opsHire({id:'annie'});closeModal()"); + assert.equal(ev('S.ops.spent.transit'), 1234, 'the same month: what was spent stays spent'); + assert.deepEqual(errors, []); +}); + +test('transit never comes from a provider that breaks a promise: no-Cogentle customers, bank covenants, the Spat', t => { + const { ev, errors } = game(t, "S.transit=[];ACT.buyTransit({city:'fra',net:'lvl',tier:0});compute();S.transit[0].hist=Array(30).fill(200)"); + hire(ev); on(ev, 'transit', { x: 1.5 }); + assert.equal(ev("cheapestTransit('fra').id"), 'cog', 'Cogentle is the cheapest here, so it would be the pick'); + ev("S.biz.push({id:'b1',city:'fra',name:'X',type:'dia',bw:1,rate:100,mood:100,since:S.day,reqs:['nocog']})"); + assert.equal(ev("reqOk(S.biz[0])"), true); + shift(ev); + assert.ok(ev('S.transit.length') > 1 || ev('S.transit[0].n') > 1, 'the intern still topped up'); + assert.equal(ev("S.transit.some(t=>t.net==='cog')"), false); + assert.equal(ev("reqOk(S.biz[0])"), true, 'the customer still gets what they signed for'); + ev("S.ops.p.transit={x:1.5,prov:'cog'}"); + assert.notEqual(ev("opsProv('fra').id"), 'cog', 'even when the player picked Cogentle'); + assert.notEqual(ev("opsTplQuote('ams').net"), 'cog', 'and the new-POP template too'); + // A bank covenant says the same. + ev("S.biz=[];S.loans=[{bank:'db',covs:['nocog'],pay:1,bal:1}]"); + assert.notEqual(ev("cheapestTransit('fra').id"), 'cog'); + // Cogentle is not speaking to Goggle: the Spat scenario, or a de-peering. + ev("S.loans=[]"); + assert.equal(ev("cheapestTransit('fra').id"), 'cog'); + ev("S.ev.depeer=S.day+5"); + assert.notEqual(ev("cheapestTransit('fra').id"), 'cog'); + ev("S.ev.depeer=0;S.scn={id:'spat',rules:{spat:true}}"); + assert.notEqual(ev("cheapestTransit('fra').id"), 'cog'); + // Two upstreams: once met, never undone (adding is fine; the order never removes). + ev("S.scn=null;S.biz=[{id:'b2',city:'fra',name:'Y',type:'dia',bw:1,rate:1,mood:100,since:0,reqs:['twoup']}]"); + assert.ok(ev("cheapestTransit('fra')")); + ev("S.transit=[]"); + assert.equal(ev("cheapestTransit('fra')"), undefined, 'a lone first upstream would break "two upstreams"'); + assert.deepEqual(errors, []); +}); + +test('decommission keeps its spare in another trench than the big link', t => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T1'],['s2',0,'T2']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:tr});compute()"); + hire(ev); on(ev, 'decom', { keep: true }); + ev("R.load={big:1,s1:0,s2:0}"); + shift(ev); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 's2'], 'the 100G in the same trench goes, the 10G in its own trench stays'); + // Every small wave shares the big one's trench: keep the largest, as before. + ev("S.links=S.links.filter(l=>l.id==='big');for(const [id,tier] of [['a',1],['b',0]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:'T1'});compute();R.load={big:1}"); + shift(ev); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['a', 'big']); + assert.deepEqual(errors, []); +}); + +test('decommission sees the traffic of a customer signed earlier in the same shift', t => { + const { ev, errors } = game(t, "S.pops.fra.bb.d=30;ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T2'],['s2',1,'T3']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:1000,trench:tr});compute()"); + hire(ev); on(ev, 'sales', { acc: true, min: 0 }); on(ev, 'decom', { keep: false }); + ev("S.offers=[{id:'o1',city:'fra',city2:'ams',name:'Bulk Co',type:'l2vpn',bw:450,rate:20,reqs:[],exp:S.day+20}]"); + shift(ev); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')).length, 1, 'signed'); + assert.equal(ev('S.links.length'), 3, 'its 450G needs every wave, so none goes'); + ev('compute()'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bizWhy(S.biz[0]))')), []); + assert.deepEqual(errors, []); +}); + +test('no recompute on a shift that only declined offers or stopped at a budget', t => { + const { ev, errors } = game(t); + hire(ev); on(ev, 'sales', { acc: false, min: 50000 }); on(ev, 'transit', { x: 3 }, 10000); + ev("S.ops.spent.transit=10000;S.transit[0].hist=[600];S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30}]"); + const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"); + assert.equal(n, 0, 'nothing in the network changed'); + assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, stopped at the budget/); + ev("S.ops.spent.transit=0"); + assert.equal(ev("window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"), 1, 'a real job still recomputes once'); + assert.deepEqual(errors, []); +}); + +test('per-POP exceptions go with the POP: on decommission, and in a save that lost it', t => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buildPop({city:'lon'});compute()"); + hire(ev); + ev("ACT.opsPop({k:'transit',city:'ams'});ACT.opsPop({k:'caches',city:'lon'});closeModal()"); + ev("decommission(['ams'])"); + assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}'); + ev("ACT.buildPop({city:'ams'});closeModal()"); + assert.equal(ev("opsHere('transit','ams')"), true, 'a rebuilt POP starts with every order on'); + ev("S.ops.skip.par=['transit'];S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}', 'no POP in Paris: its exception is dropped on load'); + assert.deepEqual(errors, []); +}); + +test('one order that throws is paused and noted; the rest of the shift and the day still run', t => { + const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]"); + hire(ev); on(ev, 'repair'); on(ev, 'transit', { x: 1.5 }); + ev("window.__r=OPS_RUN.repair;OPS_RUN.repair=()=>{throw new Error('boom')};window.__e=console.error;console.error=()=>{}"); + const d = ev('S.day'), saves = ev("window.__s=0;window.__sv=save;save=()=>{__s++;return __sv()};S.day=29;dayTick();save=__sv;__s"); + ev("OPS_RUN.repair=__r;console.error=__e"); + assert.ok(d >= 0 && saves >= 1, 'dayTick reached the save on day 30'); + assert.equal(ev('S.ops.on.repair'), false, 'the broken order is paused'); + assert.ok(ev("(S.transit[0].n||1)") > 1, 'the next order still ran'); + assert.match(ev('opsEntry(S.ops.log[0])'), /got stuck on Rush repairs and paused it/); + assert.deepEqual(errors, []); +}); + +test('the fat-fingered LAG member respects a paused transit order and per-POP exceptions', t => { + const { ev, errors } = game(t); + hire(ev); + // Each shift rolls: fat finger yes, the only POP, the LAG slip (index 3). + ev("S.rules=makeRules('bgp');window.__r=Math.random;window.__k=0;Math.random=()=>[0,0,0.7][__k++%3]"); + const n0 = ev('S.transit[0].n||1'), c0 = cash(ev); + shift(ev); + assert.equal(ev('__k'), 3); + assert.equal(ev('S.ops.log[0].f'), 0, 'transit order paused: a harmless label instead'); + assert.equal(ev('S.transit[0].n||1'), n0); assert.equal(cash(ev), c0); + on(ev, 'transit', { x: 1 }); ev("ACT.opsPop({k:'transit',city:'fra'});closeModal();S.transit[0].hist=[0]"); + shift(ev); + assert.equal(ev('S.ops.log[0].f'), 0, 'Frankfurt excepted: the same'); + ev("ACT.opsPop({k:'transit',city:'fra'});closeModal()"); + shift(ev); + assert.equal(ev('S.ops.log[0].f'), 3, 'allowed: the extra member'); + assert.equal(ev('S.transit[0].n||1'), n0 + 1); + ev('Math.random=__r'); + assert.deepEqual(errors, []); +}); + +test('caches: the cash floor and a running-cost budget hold; the panel and the log show what a month costs', t => { + const { ev, errors } = game(t); + hire(ev); on(ev, 'caches', { g: 1 }); + const add = () => ev("utilityCaches('fra').add.filter(x=>(R.cityDem.fra||0)*NSH[x.net]>=1).length"); + assert.ok(add() >= 2, 'several boxes on offer'); + ev('S.ops.floor=50000;S.cash=1000'); + shift(ev); + assert.equal(ev('S.caches.length'), 0, 'below the floor: no new rent either'); + assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Accept free caches/); + ev('S.cash=1e8;S.ops.cap.caches=1000'); + const m0 = ev('opsMoNow()'); + shift(ev); + assert.equal(ev('S.caches.length'), 2, 'a $1k/mo budget fits two $400/mo boxes'); + assert.equal(ev('S.ops.addMo.caches'), 800); + assert.equal(ev('opsMoNow()') - m0, 800); + assert.equal(ev('S.ops.log[0].mo'), 800); + assert.match(ev('opsEntry(S.ops.log[0])'), /racked 2 free caches \(Frankfurt\).*Cost: \$0 up front, \+\$800\/mo\./); + ev('opsModal()'); + const txt = ev("document.getElementById('modalCard').textContent"); + assert.match(txt, /each box costs \$400\/mo/); + assert.match(txt, /Adds at most: \+\$1\.0k\/mo/); + assert.match(txt, /This month: \$0 up front, \+\$800\/mo on the bill/); + ev('S.day+=30;S.ops.cap.caches=0'); shift(ev); + assert.equal(ev('S.ops.addMo.caches'), (ev('S.caches.length') - 2) * 400, 'a new month counts from zero'); + assert.deepEqual(errors, []); +}); + +test('transit: the log line and budget line show the monthly cost a top-up adds', t => { + const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]"); + hire(ev); on(ev, 'transit', { x: 1.5 }); + const m0 = ev('opsMoNow()'), c0 = cash(ev); + shift(ev); + const mo = ev('opsMoNow()') - m0; + assert.ok(mo > 0); + assert.equal(ev('S.ops.log[0].up'), c0 - cash(ev)); + assert.equal(ev('S.ops.log[0].mo'), Math.round(mo)); + assert.equal(ev('Math.round(S.ops.addMo.transit)'), Math.round(mo)); + assert.match(ev('opsEntry(S.ops.log[0])'), /Cost: \$[\d.]+k up front, \+\$[\d.]+k?\/mo\./); + assert.deepEqual(errors, []); +}); diff --git a/tests/tier1-cone.test.js b/tests/tier1-cone.test.js index bc79518..55b5372 100644 --- a/tests/tier1-cone.test.js +++ b/tests/tier1-cone.test.js @@ -23,8 +23,12 @@ test('cones are built once at load and hold customers of customers', () => { assert.equal(ev("NETS.filter(n=>n.tail).every(n=>ANC[n.id].some(u=>NET[u].type==='t1'))"), true, 'from a Tier 1, directly or through a carrier'); assert.equal(ev("NET.tail45.up.join()"), 'mag', 'Auckland has no Tier 1: Hobbit Hole buys from a carrier that is there'); assert.equal(ev("NETS.filter(n=>n.tail).map(n=>n.up.join('+')).join()"), ev("NETS.filter(n=>n.tail).map(n=>tailUp(n.name,n.pops).join('+')).join()"), 'stable: picked by name'); - // Australians buy only from Australian carriers, so a Tier 1 PNI is still no back door into Australia. - assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false); + // Australia's big ISPs buy only from Australian carriers, so a Tier 1 PNI is no back door to them. + assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg','inp'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false); + // The smaller ones that buy from a Tier 1 or a carrier of one do come along, and these are exactly the ones. + const au = "NETS.filter(n=>n.type==='eye'&&n.pops.length&&n.pops.every(c=>CITY[c].au)&&t1Need().some(t=>CONE_S[t.id].has(n.id))).map(n=>n.id).sort().join()"; + assert.equal(ev(au), 'ddo,ext,spn,tail44', 'Doodoo, Lintel, Spin2wintel, Kangaroo Courier'); + assert.equal(ev("[NET.tail44.name,NET.tail44.up.join(),NET.ddo.up.join(),NET.spn.up.join(),NET.ext.up.join(),NET.voc.up.join(),NET.spl.up.join()].join('|')"), 'Kangaroo Courier|cog|voc|voc|spl|ntt,tly|tly'); assert.deepEqual(errors, []); }); @@ -146,3 +150,48 @@ test('routing with cones costs about what it did: exits are asked once, cones ar assert.ok(t < plain * 2 + 20, `compute() with cones ${t.toFixed(1)} ms vs without ${plain.toFixed(1)} ms`); assert.deepEqual(errors, []); }); + +test('the panel names the peer that really carries a network, not the first Tier 1 it buys from', () => { + const { ev, dom, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50"); + // a long-tail network that buys from Cogentle first and Level Tree second; peer only with Level Tree + const t = ev("NETS.find(n=>n.tail&&n.up.length===2&&n.up[0]==='cog'&&n.up[1]==='lvl').id"); + ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pl',net:'lvl',city:'fra',tier:2}];compute()"); + assert.equal(ev(`R.cone.${t}`), 'lvl'); + ev(`UI.left='goals';UI.leftOpen=true;ACT.netFocus({id:'${t}'})`); + const txt = dom.window.document.getElementById('leftBody').textContent; + assert.match(txt, /Reached through the customer cone of Level Tree/); + assert.doesNotMatch(txt, /customer cone of Cogentle/); + // over an exchange: the member you have a session with + ev("S.pni=[];compute()"); + assert.equal(ev(`!!R.cone.${t}`), false); + assert.match(ev(`(ACT.netFocus({id:'${t}'}),document.getElementById('leftBody').textContent)`), /Buys transit from Cogentle/); + assert.deepEqual(errors, []); +}); + +test('a traceroute down a two-level cone shows every network on the way', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50"); + // Doodoo buys from Hocus Pocus, which buys from Not That Telecom; a PNI with Not That Telecom only + ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pn',net:'ntt',city:'fra',tier:2}];compute()"); + const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'ddo'}))")); + assert.deepEqual(tr.asPath, [ev('S.asn'), ev('NET.ntt.asn'), ev('NET.voc.asn'), ev('NET.ddo.asn')]); + assert.match(tr.text, /Not That Telecom hands it to its customer Hocus Pocus/); + assert.match(tr.text, /Hocus Pocus hands it to its customer Doodoo/); + assert.equal(ev("coneChain('ntt','ddo').join()"), 'ntt,voc,ddo'); + assert.equal(ev("R.cone.ddo"), 'ntt'); + assert.deepEqual(errors, []); +}); + +test('#114 Only Spätzle-IX still takes more than the exchange and two Tier 1 PNIs, now that cones count', () => { + const { ev, errors } = load(); + ev("UI.pitched=true;beginGame('T','stg',{scn:SCN.find(x=>x.id==='stg')});S.cash=1e9;S.lvl=10;S.pops.stg.bb={d:400};S.ixp.stg=0;for(const id of ixMembers('stg'))S.peers[id+'@stg']=1;compute()"); + const reach = (ts) => ev(`S.pni=[];for(const t of ${JSON.stringify(ts)})S.pni.push({id:'p'+t,net:t,city:'stg',tier:2});compute();R.reach`); + const T = ['lvl', 'ntt', 'tly', 'cog', 'tat']; + const goal = ev("SCN.find(x=>x.id==='stg').ok.toString()"); + assert.match(goal, /R\.reach>=0\.5/); + for (let i = 0; i < T.length; i++) for (let j = i + 1; j < T.length; j++) + assert.ok(reach([T[i], T[j]]) < 0.5, `${T[i]}+${T[j]} is not enough`); + assert.ok(reach(['lvl', 'ntt', 'tly']) >= 0.5, 'three Tier 1 PNIs and the exchange can be'); + assert.deepEqual(errors, []); +}); diff --git a/tests/utilities.test.js b/tests/utilities.test.js index d096951..feba9a5 100644 --- a/tests/utilities.test.js +++ b/tests/utilities.test.js @@ -136,3 +136,24 @@ test('route-server batch leaves peering policy and player-owned exchanges alone' assert.equal(ev('S.rs.fra'), false, 'owned exchange has no join-route-server control'); assert.deepEqual(errors, []); }); + +test('#192 the Infra tab shows the kit as one line, without repeating its rows', t => { + for (const w of [1280, 360]) { + const { ev, dom, errors } = setup(t); + ev(`window.innerWidth=${w}`); + ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];compute();selectCity('fra');ACT.tab({t:'links'})"); + const body = dom.window.document.getElementById('panelBody'); + const txt = body.textContent; + assert.match(txt, /PoP redundancy kit · One-off: /); + assert.doesNotMatch(txt, /Second site(None|Installed)/, 'no second copy of the second-site row'); + assert.doesNotMatch(txt, /At least two routers/, 'no second copy of the routers row'); + assert.doesNotMatch(txt, /Request missing caches/, 'caches are in the Peering tab and Utilities'); + assert.equal(body.querySelectorAll('section h3').length, [...body.querySelectorAll('section h3')].filter(h => h.textContent !== 'PoP redundancy kit').length); + assert.equal(txt.split('Backup generator').length - 1, 1, 'the generator shows once, in Power'); + assert.ok(body.querySelector('[data-act="utilityKit"]'), 'the kit is one tap away'); + body.querySelector('[data-act="utilities"]').click(); + assert.match(dom.window.document.getElementById('modalCard').textContent, /At least two routers/, 'the full kit is in Utilities'); + assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra'); + assert.deepEqual(errors, [], `${w}px`); + } +}); diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js new file mode 100644 index 0000000..f8107f5 --- /dev/null +++ b/tests/weekly-puzzle.test.js @@ -0,0 +1,240 @@ +// The published weekly puzzle: Sunday 06:00 Berlin weeks, the generator (scripts/weekly-puzzle.js), its --check, +// and the game's fetch: only when Puzzles opens, validated strictly, with the seeded weekly as the fallback. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { load } = require('./harness'); +const G = require('../scripts/weekly-puzzle'); + +const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly'); +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-')); +const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8'))); +const tick = () => new Promise((r) => setTimeout(r, 30)); + +test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run across New Year', () => { + const { ev, errors } = load(); + const key = (iso) => ev(`pzWeekKey(new Date('${iso}'))`), start = (k) => ev(`new Date(pzWeekStart('${k}')).toISOString()`); + // Winter (CET, UTC+1): 06:00 Berlin is 05:00 UTC. + assert.equal(key('2026-11-01T04:59:59Z'), '2026-W44'); + assert.equal(key('2026-11-01T05:00:00Z'), '2026-W45', 'the week starting Sunday 1 Nov is named after its Monday'); + assert.equal(key('2026-11-07T23:00:00Z'), '2026-W45', 'Saturday night is still the same week'); + assert.equal(start('2026-W45'), '2026-11-01T05:00:00.000Z'); + // Summer (CEST, UTC+2): 06:00 Berlin is 04:00 UTC. + assert.equal(key('2026-07-05T03:59:00Z'), '2026-W27'); + assert.equal(key('2026-07-05T04:00:00Z'), '2026-W28'); + // The weekends the clocks change: the change is at 01:00 UTC that same Sunday, before the week starts. + assert.equal(start('2026-W14'), '2026-03-29T04:00:00.000Z', 'spring forward: first CEST Sunday'); + assert.equal(start('2026-W13'), '2026-03-22T05:00:00.000Z'); + assert.equal(start('2026-W44'), '2026-10-25T05:00:00.000Z', 'fall back: first CET Sunday'); + assert.equal(start('2026-W43'), '2026-10-18T04:00:00.000Z'); + assert.equal(key('2026-03-29T03:59:00Z'), '2026-W13'); + assert.equal(key('2026-03-29T04:00:00Z'), '2026-W14'); + assert.equal(key('2026-10-25T04:59:00Z'), '2026-W43'); + assert.equal(key('2026-10-25T05:00:00Z'), '2026-W44'); + // New Year: 2026 has 53 ISO weeks, 2027 has 52. + assert.equal(key('2026-12-27T05:00:00Z'), '2026-W53'); + assert.equal(key('2027-01-03T04:59:00Z'), '2026-W53'); + assert.equal(key('2027-01-03T05:00:00Z'), '2027-W01'); + assert.equal(key('2027-12-26T05:00:00Z'), '2027-W52'); + assert.equal(key('2028-01-02T05:00:00Z'), '2028-W01'); + assert.equal(ev("pzKeyAdd('2026-W53',1)"), '2027-W01'); + assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53'); + assert.equal(ev("pzPrevKey('2028-W01')"), '2027-W52'); + assert.equal(ev("pzWeekStart('2027-W53')"), null, '2027 has no week 53'); + assert.equal(ev("pzWeekStart('2026-W00')"), null); + assert.equal(ev("pzWeekStart('nope')"), null); + // Every week of ten years: 7 days apart (give or take the DST hour), keys round-trip, never two Sundays the same key. + let k = '2026-W01', seen = new Set(); + for (let i = 0; i < 522; i++) { + const t = ev(`pzWeekStart('${k}')`), n = ev(`pzKeyAdd('${k}',1)`), tn = ev(`pzWeekStart('${n}')`); + assert.equal(new Date(t).getUTCDay(), 0, `${k} starts on a Sunday`); + assert.ok([7 * 864e5, 7 * 864e5 - 3600e3, 7 * 864e5 + 3600e3].includes(tn - t), `${k} → ${n}`); + assert.equal(ev(`pzWeekKey(${t})`), k); + assert.equal(ev(`pzWeekKey(${t - 1})`), ev(`pzPrevKey('${k}')`)); + assert.ok(!seen.has(k)); seen.add(k); k = n; + } + // The countdown. + assert.equal(ev("pzWkNext(Date.parse('2026-10-29T14:00:00Z'))"), 'Next weekly puzzle in 2 d 15 h'); + assert.equal(ev("pzWkNext(Date.parse('2026-11-01T03:20:00Z'))"), 'Next weekly puzzle in 1 h 40 min'); + assert.deepEqual(errors, []); +}); + +// Weeks already out are not compared with a fresh run: a later release may change prices, and a published week stays as +// it was (--check still makes sure the weeks not over yet can be solved). +test('generator: deterministic for a week', () => { + const g = G.game(), a = tmp(), b = tmp(); + const first = G.list(DIR).slice(-3)[0]; + const keys = Math.min(3, G.list(DIR).length); + for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d)); + for (const k of G.list(a)) { + assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`); + } + assert.ok(G.list(DIR).length >= 3, 'the release ships with weeklies in place'); +}); + +test('generator: a quarter of weeks, all verified, varied, small and in the schema', () => { + const g = G.game(), d = tmp(); + let k = '2027-W10'; + const out = []; + for (let i = 0; i < 12; i++, k = g.ev(`pzKeyAdd('${k}',1)`)) { const j = G.generate(g, k, d); G.writeWeek(d, j); out.push(j); } + assert.deepEqual(G.check(g, d, 0), [], 'every week verifies: both references earn their stars in the game'); + for (let i = 1; i < out.length; i++) { + assert.notEqual(out[i].theme, out[i - 1].theme, `${out[i].key}: not last week's theme`); + for (const c of out[i].cities) assert.ok(!out[i - 1].cities.includes(c), `${out[i].key}: ${c} was a city last week too`); + } + assert.ok(new Set(out.map((j) => j.theme)).size >= 5, 'most themes come round in a quarter'); + for (const j of out) { + assert.ok(j.cities.length >= 3 && j.cities.length <= 6); + assert.ok(j.ref.one <= j.ref.three && j.ref.three <= j.budget && j.budget <= j.ref.three * 1.06 + 10000, `${j.key}: budget ${j.budget} just above the N-1 build ${j.ref.three}`); + assert.ok(JSON.stringify(j).length < 600, 'small file'); + assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'via', 'avoid', 'budget', 'twist', 'name', 'joke', 'ref']); + } + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(d, 'index.json'), 'utf8')).weeks, out.map((j) => j.key)); +}); + +test('--check passes on the committed files and rejects tampered ones', () => { + const g = G.game(); + // Weeks still to come are re-solved; past ones are checked the way the game reads them. + assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify'); + const bad = (edit, why) => { + const d = tmp(); + for (const k of G.list(DIR).slice(-3)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json')); + G.writeIndex(d); + const k = G.list(d)[0], f = path.join(d, k + '.json'), j = JSON.parse(fs.readFileSync(f, 'utf8')); + const r = edit(j, d, k); fs.writeFileSync(f, typeof r === 'string' ? r : JSON.stringify(j)); + assert.notDeepEqual(G.check(g, d, 0), [], why); + }; + bad((j) => { j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; }, 'a budget nobody can earn three stars under'); + bad((j) => { j.cities[0] = 'xxx'; }, 'an unknown city'); + bad((j) => { j.name.l = 'puzzles.hello_world'; }, 'a label that is not a weekly name'); + bad((j) => { j.joke.p = { hub: 'fra' }; }, 'parameters the label does not take'); + bad((j) => { j.extra = ''; }, 'an unknown field'); + bad((j) => { j.key = '2030-W01'; }, 'a file under another week\'s name'); + bad((j) => { j.twist = { lat: [j.cities[0], j.cities[1], 0.5] }; }, 'an impossible latency target'); + bad(() => '{nope', 'not JSON'); + bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks'); +}); + +test('the page never asks for a weekly puzzle on load, only when Puzzles opens', async () => { + const { ev, errors } = load(); + ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}"); + ev("showTitle();for(let i=0;i<5;i++)frame(performance.now()+i*1000);renderAll()"); + assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing on the title screen'); + assert.equal(ev("UI.pzWk===undefined"), true); + ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()"); + assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing while playing'); + ev('ACT.puzzleMenu({})'); + const key = ev('pzWeekKey(new Date())'); + assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/puzzles/.test(u)))"), JSON.stringify([`puzzles/weekly/${key}.json`]), 'one relative, same-origin request'); + ev('closeModal();ACT.puzzleMenu({})'); + assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 1, 'once is enough while it is loading'); + await tick(); + assert.deepEqual(errors, []); +}); + +test('the published puzzle is played when it is good, the seeded one when it is missing, offline or bad', async () => { + const src = committed()[1], { ev, dom, errors } = load(); + const key = ev('pzWeekKey(new Date())'), good = { ...src, key }; + const serve = (how) => { ev(`UI.pzWk=null;window.fetch=()=>${how}`); ev('ACT.puzzleMenu({})'); }; + const seeded = JSON.parse(ev('JSON.stringify(pzWeekly())')); + for (const [how, why] of [ + ["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'], + ["Promise.reject(new TypeError('offline'))", 'offline'], + ["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'], + [`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'], + [`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'], + ]) { + serve(how); + await tick(); + assert.equal(ev('UI.pzWk.st'), 'fb', why); + assert.deepEqual(JSON.parse(ev('JSON.stringify(pzWkDef().cities)')), seeded.cities, `${why}: the seeded weekly stands in`); + assert.match(ev("document.getElementById('pzWk').textContent"), new RegExp(`Weekly puzzle ${key}`)); + assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), false); + } + // While it loads, the button waits a moment. + ev("UI.pzWk=null;window.fetch=()=>new Promise(()=>{})"); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/); + assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true); + // The good one. + serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(good)})})`); + await tick(); + assert.equal(ev('UI.pzWk.st'), 'ok'); + const row = ev("document.getElementById('pzWk').textContent"); + assert.ok(row.includes(ev('pzName(pzWkDef())')), 'its pun name'); + assert.ok(row.includes(ev('pzTxt(pzWkDef().wj)')), 'its joke'); + assert.match(row, /New this Sunday!/); + assert.match(row, /Next weekly puzzle in \d+ (d \d+ h|h \d+ min)/); + ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()"); + assert.equal(ev('S.pz.key'), key); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.pz.cities)')), good.cities); + assert.equal(ev('S.pz.budget'), good.budget); + assert.match(ev("document.getElementById('pzBox').textContent"), new RegExp(ev('pzTxt(S.pz.wj)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); + // Solve it with three stars: the share line and the streak use the published key. + const sol = G.solve(G.world(ev), { cities: good.cities, via: good.via, avoid: good.avoid, ring: !!good.twist.ring, noSub: false, lat: good.twist.lat || null }).three; + for (const l of sol.links) { + if (!ev(`!!S.pops['${l.a}']`)) ev(`ACT.pzPop({city:'${l.a}'})`); + ev(`ACT.pzLinkTo({a:'${l.a}',b:'${l.b}'});ACT.pzVia({v:'${l.via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:0})`); + } + assert.equal(ev('pzEval().stars'), 3); + assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`)); + const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); + assert.equal(p.wk[key].st, 3); + assert.equal(p.streak.last, key); + ev('ACT.pzLeave({})'); + assert.doesNotMatch(ev("document.querySelector('.door[data-door=puzzle]').textContent"), /New this Sunday/, 'played: no badge'); + void dom; + assert.deepEqual(errors, []); +}); + +test('the file is checked field by field', () => { + const { ev, errors } = load(); + const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`); + assert.ok(ok(j)); + const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); }; + no((o) => { o.v = 2; }, 'a newer schema'); + no((o) => { o.theme = 'constructor'; }, 'an unknown theme'); + no((o) => { o.cities = ['fra']; }, 'too few cities'); + no((o) => { o.cities = [...o.cities, o.cities[0]]; }, 'a city twice'); + no((o) => { o.via = [o.cities[0]]; }, 'a goal city as a stepping stone'); + no((o) => { o.cities[0] = 'pek'; }, 'a city that needs a licence'); + no((o) => { o.budget = '240000'; }, 'a budget as text'); + no((o) => { o.budget = 1e9; }, 'a silly budget'); + no((o) => { o.twist = { ring: 'yes' }; }, 'a twist that is not true'); + no((o) => { o.twist = { avoidAll: true }; }, 'an unknown twist'); + no((o) => { o.name = { l: 'puzzles_weekly.name_tour_de_reg', p: { reg: 'XX' } }; }, 'an unknown region'); + no((o) => { o.name = { l: 'puzzles_weekly.name_race_to_b', p: { b: '' } }; }, 'markup as a city'); + no((o) => { o.joke = 'Ha ha'; }, 'raw English'); + no((o) => { o.__proto__ = { budget: 1 }; o.extra = 1; }, 'extra fields'); + assert.equal(ev(`pzWkValid(null,'${k}')`), null); + assert.equal(ev(`pzWkValid([],'${k}')`), null); + // Every label a theme may use exists in English, and every file names its text in the player's language. + assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))")); + for (const f of committed()) { + const d = ev(`JSON.stringify(pzWkValid(${JSON.stringify(f)},'${f.key}'))`); + assert.ok(d, f.key); + assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`); + } + assert.deepEqual(errors, []); +}); + +test('weekly puzzle in every language and on a 360 px phone', async () => { + const f = committed()[0]; + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, errors } = load({ lang }); + const key = ev('pzWeekKey(new Date())'); + ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...f, key })})})`); + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()"); + ev('ACT.puzzleMenu({})'); + await tick(); + const row = ev("document.getElementById('pzWk').textContent"); + assert.doesNotMatch(row, /puzzles(_weekly)?\.|\{/, `${lang}: no raw labels or placeholders`); + assert.notEqual(ev('pzName(pzWkDef())'), ev("EN[pzWkDef().wn.l]"), `${lang}: translated name`); + ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()"); + assert.equal(ev("document.getElementById('pzBox').hidden"), false); + assert.doesNotMatch(ev("document.getElementById('pzBox').textContent"), /puzzles(_weekly)?\./); + assert.deepEqual(errors, [], lang); + } +});