diff --git a/CLAUDE.md b/CLAUDE.md index f95b71d..88760ba 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -133,6 +133,15 @@ the roster is still the roster. The search side and the measurements behind `src/lib/state/CLAUDE.md`; the readout's plan line in `src/lib/components/inspector/CLAUDE.md`. +### The cash limit + +Beside the plan on the Buildings tab, a **cash limit** solves for the most power +a sum buys rather than the most at any price: what changing the board in Edit +into the layout may cost, net of sale refunds, moves free. One budget couples +every landmass, so a budgeted run is one island, and Solve all is hidden while a +limit is set. The search side is in `docs/SOLVER.md`; the app side in +`src/lib/state/CLAUDE.md`. + ## Architecture ### Folder map diff --git a/docs/SOLVER.md b/docs/SOLVER.md index 2a67ae4..62da28f 100644 --- a/docs/SOLVER.md +++ b/docs/SOLVER.md @@ -697,7 +697,7 @@ the reactor comes first. Holding a layout to every order of three +1 upgrades (7 31–59% of the best target power; a fixed order kept 59–99%. So the plan is ordered and the player states the order. -**How the search honours it.** `planHolds` simulates the layout at each plan roster, re-reading +**How the search honours it.** `layoutHolds` simulates the layout at each plan roster, re-reading every placement by building id, and every gate that admits a layout asks it beside the ordinary stability test: the best record, repair, the composition swaps, pruning, right-sizing, the tie shortlist and `stabilize`. Power is still measured at the target alone. Without a plan the call @@ -712,6 +712,45 @@ both and keeping whichever runs better across the plan costs one extra seed cons Splitting the budget between a target-scored and a today-scored search was measured too: a few points better on cooler plans, a few worse on reactor ones, so it was not kept. +### Cash limits — the most power a sum buys + +`SolveOptions.cashBudget` maximises power within a sum of cash instead of at any price. The sum is +what turning the board as it stands into the layout costs, **net of what the sales pay back**: +the player may sell everything and rebuild, or build on what they have, and both are one figure. + +**The spend is a sum over building types of a function of each type's count alone.** Moves are +free, so a type is never sold and rebuilt — its count rises, each copy bought at the next copy's +price, or falls, each sale refunding a share of the current one — and the order between types +changes nothing. Selling first is always possible, so the net is also all the cash the change needs +on hand. That makes three things cheap: `search/cashLimit.ts` tabulates each type's spend by count +once per island, a composition's spend is known before it is arranged, and a building removed +always lowers it. `netSpend` in `data/buildingPrices.ts` is the same figure computed directly, and +`cashLimit.test.ts` holds the tables to it. + +How the search honours it, by the same route as an upgrade plan: + +- **`layoutHolds` asks it** beside the plan, so every gate that admits a layout keeps only + affordable ones, and **`stabilize` steps a layout down until it fits** (`trimToBudget`: the type + whose last copy costs most gives one up, stepped to the next cheaper building of its role where + that saves money, removed where not) — so nothing `stabilize` hands back is over. +- **The walk never leaves the budget**: a replacement that would overspend is refused before it is + simulated. A swap cannot change the spend. +- **The board as it stands competes as a seed**, repaired on the same terms as the built seed: it + costs nothing, so it is always an answer the budget allows. +- **Repair tries three tiers of every role**, not only the top generator and cooler: the top tier + is exactly what a budget runs out on. +- **`planSolve` hands the board over whole** (`splitGridIntoIslands`' `wholeBoard`), as under a + cooling pool — one budget pays for every landmass and every copy raises the next price — and + first drops every building that the cash plus every refund cannot buy one of + (`affordableRoster`), which is sound and keeps the seed and the bound off unreachable tiers. + +Measured on Magma Rift at full unlocks, where the unlimited layout costs 9.6e34 from empty and +makes 4.72AD: 1e20 buys 170T, 1e24 124AA, 1e27 20.3AB, 1e30 2.35–2.80AC at 8s and 2.78–2.85AC at +30s, 1e33 282AC — about a hundredfold power per thousandfold cash, with mixed tiers throughout. +The spread is wider than the unlimited search's (7.6% at 8s, 2.3% at 30s), and **the bound does +not know the budget**, so layout efficiency under one reads far below 100%. Starting from the 1e30 +board with 0 cash keeps its 2.35AC; with another 1e30 it reaches 4.13AC. + --- ## The RNG contract @@ -884,6 +923,9 @@ could not see would restart numbering at 1 and overwrite an untagged run. distinct layouts at the end and the worst, median and best of every attempt — the spread is what tells two settings apart when both reach the same best. Ctrl-C stops it and still prints the report. +`--cash AMOUNT` solves within a cash limit; a `--code` board's placements are what stands, a +shipped map starts empty, and the run prints what the best layout spends. + Three flags reproduce a player's setup rather than a shipped one. `--code BLUEPRINT` solves a pasted board, taking its anomaly (unless `--anomaly` is given) and its Time Lab research from the code's rules section. `--tier ID=LEVEL` holds a building below its last tier, and `--plan diff --git a/packages/solver/bin/solve.ts b/packages/solver/bin/solve.ts index 33577cf..c12d949 100644 --- a/packages/solver/bin/solve.ts +++ b/packages/solver/bin/solve.ts @@ -43,6 +43,7 @@ import { resolveUpgradePlan, type UpgradeStep, } from "../src/data/upgradePlan"; +import { netSpend, priceRules } from "../src/data/buildingPrices"; import { prestigeScales } from "../src/data/prestige"; import { blueprintKey, @@ -60,11 +61,16 @@ import { } from "../src/solver/solver"; import type { AnomalyId, + CashBudget, IslandLayout, OptimizationResult, Tile, } from "../src/solver/types"; -import { formatNumberForFilename } from "../src/utils/formatters"; +import { + formatNumber, + formatNumberForFilename, + parseHugeNumber, +} from "../src/utils/formatters"; import { Leaderboard } from "./leaderboard"; import { DEFAULT_MAP_NUM, MAPS, MAPS_BY_NUM, type CliMap } from "./maps"; import { WorkerPool } from "./pool"; @@ -158,6 +164,31 @@ interface Progress { research: Record; /** The plan's rosters before its target, today's first — `resolveUpgradePlan`'s `along`. */ upgradePlan: Record[]; + /** `--cash`, when given. */ + cash?: number; + /** The cash limit on the board being solved — `withBudget` fills it per board. */ + cashBudget?: CashBudget; +} + +/** + * `progress` with the cash limit for one board, whose own placements are what + * stands: a `--code` board's buildings are kept for free, a shipped map's + * none. There are no other islands here, so nothing is counted elsewhere. + */ +function withBudget( + progress: Progress, + standing: CashBudget["standing"], +): Progress { + if (progress.cash === undefined) return progress; + return { + ...progress, + cashBudget: { + cash: progress.cash, + standing: standing.map(({ x, y, buildingId }) => ({ x, y, buildingId })), + elsewhere: {}, + prices: priceRules(progress.research), + }, + }; } // --- Solving ------------------------------------------------------------- @@ -190,6 +221,7 @@ async function solveWithPool( anomalyId, prestigeScales(progress.research), progress.upgradePlan, + progress.cashBudget, ); if (!plan || plan.islands.length < 2 || !pool || pool.size < 2) return solve( @@ -201,6 +233,7 @@ async function solveWithPool( anomalyId, prestige: prestigeScales(progress.research), upgradePlan: progress.upgradePlan, + cashBudget: progress.cashBudget, }, seed, ); @@ -228,6 +261,7 @@ async function solveWithPool( // the same string. anomaly: plan.anomaly, upgradeSteps: plan.upgradeSteps, + cashBudget: plan.cashBudget, }, })), (i, result) => { @@ -295,10 +329,11 @@ async function solveMap( filenameFor: (run: SolveRun, bestPower: number) => string, seed: number | undefined, anomalyId: AnomalyId | undefined, - progress: Progress, + boardProgress: Progress, pool: WorkerPool | null, ): Promise { - const { grid } = await decodeBlueprint(gameMap.code); + const { grid, placements } = await decodeBlueprint(gameMap.code); + const progress = withBudget(boardProgress, placements); const roster = getEffectiveBuildings( BUILDINGS, unlockedUpgrades, @@ -335,6 +370,10 @@ async function solveMap( b.result.totalPower > a.result.totalPower ? b : a, ); verify(grid, roster, best.result); + if (progress.cashBudget !== undefined) + console.log( + `Spend: ${formatNumber(netSpend(best.result.placements, progress.cashBudget))} of ${formatNumber(progress.cashBudget.cash)}`, + ); return results; } @@ -423,10 +462,11 @@ function workerCount(attempts: number, requested?: number): number { async function runSession( gameMap: CliMap, unlockedUpgrades: Record, - progress: Progress, + boardProgress: Progress, args: Args, ): Promise { - const { grid } = await decodeBlueprint(gameMap.code); + const { grid, placements } = await decodeBlueprint(gameMap.code); + const progress = withBudget(boardProgress, placements); const roster = getEffectiveBuildings( BUILDINGS, unlockedUpgrades, @@ -477,6 +517,7 @@ async function runSession( anomalyId: args.anomalyId, prestige: prestigeScales(progress.research), upgradePlan: progress.upgradePlan, + cashBudget: progress.cashBudget, }, })), (attempt, raw) => { @@ -551,12 +592,14 @@ interface Args { plan: UpgradeStep[]; /** A pasted board to solve instead of a shipped map. */ code: string | undefined; + /** A cash limit on what the run may spend. */ + cash: number | undefined; } const USAGE = `usage: solve [-h] [--map NUM] [--all] [--runs RUNS] [--time TIME_LIMIT_S] [--attempts N] [--top K] [--workers N] [--seed SEED] [--anomaly ID] [--tier ID=LEVEL] [--plan ID=LEVEL] - [--code BLUEPRINT] + [--code BLUEPRINT] [--cash AMOUNT] Decode a map, solve it, and report on the result. @@ -591,7 +634,13 @@ options: solve a pasted board instead of a shipped map. Its rules section, when it has one, supplies the anomaly (unless --anomaly is given) and the Time Lab research; placements - on it are ignored + on it are ignored, unless --cash is given + --cash AMOUNT maximise power within a cash limit: what changing the board + into the layout may cost, net of sale refunds, at the base + prices less the code's research. AMOUNT is a number, e-notation + or the game's ladder (15AC). A --code board's buildings stand + already and cost nothing to keep or move; a shipped map starts + empty This renders no picture. Each run writes its blueprint code to solves/, named after what it found and after the anomaly it found it under; paste one into the @@ -612,6 +661,7 @@ function parseArgs(argv: string[]): Args | null { tiers: {}, plan: [], code: undefined, + cash: undefined, }; const takeValue = ( @@ -718,6 +768,12 @@ function parseArgs(argv: string[]): Args | null { [raw, i] = takeValue(flag, inline, i); args.code = raw; break; + case "--cash": + [raw, i] = takeValue(flag, inline, i); + args.cash = parseHugeNumber(raw); + if (!Number.isFinite(args.cash) || args.cash < 0) + throw new Error(`argument ${flag}: invalid amount: '${raw}'`); + break; case "--tier": case "--plan": { [raw, i] = takeValue(flag, inline, i); @@ -787,7 +843,9 @@ export async function main(argv: string[]): Promise { console.error("--plan raises nothing: no step is above its --tier"); return 1; } - const progress: Progress = { research, upgradePlan }; + const progress: Progress = { research, upgradePlan, cash: args.cash }; + if (args.cash !== undefined) + console.log(`Cash limit: ${formatNumber(args.cash)}`); if (Object.keys(research).length) console.log( `Research: ${Object.entries(research) diff --git a/packages/solver/bin/worker.ts b/packages/solver/bin/worker.ts index dbb87dd..d393aeb 100644 --- a/packages/solver/bin/worker.ts +++ b/packages/solver/bin/worker.ts @@ -15,6 +15,7 @@ import { solve } from "../src/solver/solver"; import type { AnomalyDefinition, AnomalyId, + CashBudget, EffectiveBuilding, IslandSubGrid, PrestigeScales, @@ -30,6 +31,7 @@ type Task = seed?: number; anomaly?: AnomalyDefinition; upgradeSteps?: EffectiveBuilding[][]; + cashBudget?: CashBudget; } | { kind: "attempt"; @@ -40,6 +42,7 @@ type Task = anomalyId?: AnomalyId; prestige?: PrestigeScales; upgradePlan?: Record[]; + cashBudget?: CashBudget; }; parentPort?.on( @@ -56,6 +59,7 @@ parentPort?.on( payload.seed, payload.anomaly, payload.upgradeSteps, + payload.cashBudget, ) : await solve( payload.grid, @@ -66,6 +70,7 @@ parentPort?.on( anomalyId: payload.anomalyId, prestige: payload.prestige, upgradePlan: payload.upgradePlan, + cashBudget: payload.cashBudget, }, payload.seed, ); diff --git a/packages/solver/src/data/buildingPrices.ts b/packages/solver/src/data/buildingPrices.ts index 8687454..c9ed6bb 100644 --- a/packages/solver/src/data/buildingPrices.ts +++ b/packages/solver/src/data/buildingPrices.ts @@ -1,3 +1,4 @@ +import type { CashBudget } from "../solver/types"; import { findBuilding } from "./buildings"; import { TIME_LAB } from "./timeLab"; @@ -108,17 +109,118 @@ export function layoutCost( layout: readonly { buildingId: string }[], rules: PriceRules = BASE_RULES, ): number { - const copies = new Map(); - for (const p of layout) - copies.set(p.buildingId, (copies.get(p.buildingId) ?? 0) + 1); let cost = 0; - for (const [id, n] of copies) { + for (const [id, n] of Object.entries(countBuildings(layout))) { const base = findBuilding(id)?.price ?? 0; for (let k = 0; k < n; k++) cost += buildPrice(base, k, rules); } return cost; } +/** Building id to how many stand. */ +export type BuildingCounts = Record; + +/** How many of each building a list holds. */ +export function countBuildings( + list: readonly { buildingId: string }[], +): BuildingCounts { + const counts: BuildingCounts = {}; + for (const p of list) counts[p.buildingId] = (counts[p.buildingId] ?? 0) + 1; + return counts; +} + +/** + * The one statement of the rule: what changing a board holding `before` into + * one holding `after` costs, net of what the sales pay back. + * + * Moves are free, so no type is sold and rebuilt: a type whose count rises + * buys each new copy at the next copy's price, one whose count falls refunds + * each sale at the current one, and the order between types changes nothing. + * Copies on the player's other islands (`elsewhere`) count towards every + * price. `scale` is the sum of each type's net taken unsigned — the size of + * the terms, which "within budget" is judged against. + */ +function changeTerms( + after: Readonly, + before: Readonly, + elsewhere: Readonly, + rules: PriceRules, +): { spend: number; scale: number } { + let spend = 0; + let scale = 0; + for (const id of new Set([...Object.keys(after), ...Object.keys(before)])) { + const base = findBuilding(id)?.price ?? 0; + const others = elsewhere[id] ?? 0; + const c = before[id] ?? 0; + const t = after[id] ?? 0; + let term = 0; + for (let k = c; k < t; k++) { + const p = buildPrice(base, others + k, rules); + spend += p; + term += p; + } + for (let k = c; k > t; k--) { + const r = sellRefund(base, others + k, rules); + spend -= r; + term -= r; + } + scale += Math.abs(term); + } + return { spend, scale }; +} + +/** `changeTerms`' net spend, read off counts rather than placements. */ +export function countsSpend( + after: Readonly, + before: Readonly, + elsewhere: Readonly, + rules: PriceRules, +): number { + return changeTerms(after, before, elsewhere, rules).spend; +} + +/** + * What turning the board `budget.standing` holds into `layout` costs, net of + * what the sales pay back — the figure a cash limit is on. See `changeTerms`. + */ +export function netSpend( + layout: readonly { buildingId: string }[], + budget: CashBudget, +): number { + return countsSpend( + countBuildings(layout), + countBuildings(budget.standing), + budget.elsewhere, + budget.prices, + ); +} + +/** + * Relative slack for "within budget": a net spend sums buys and refunds + * across thirty orders of magnitude, so it is compared against the size of + * its own terms rather than exactly. The engine's `countsFit` + * (`solver/search/cashLimit.ts`) applies the same rule to the same terms. + */ +const SPEND_RELATIVE_TOLERANCE = 1e-9; + +/** Whether `layout` is within `budget`'s cash, by the engine's own test. */ +export function fitsBudget( + layout: readonly { buildingId: string }[], + budget: CashBudget, +): boolean { + const { spend, scale } = changeTerms( + countBuildings(layout), + countBuildings(budget.standing), + budget.elsewhere, + budget.prices, + ); + return ( + spend <= + budget.cash + + SPEND_RELATIVE_TOLERANCE * Math.max(scale, Math.abs(budget.cash)) + ); +} + /** * Relative slack for "the same cost": two layouts holding the same buildings * sum them in a different order and can disagree in the last bits. @@ -132,20 +234,23 @@ const COST_TIE_RELATIVE_TOLERANCE = 1e-9; * layout leaving more of the land empty wins. Stable, so layouts neither * figure separates keep the order they came in. * - * Each layout is costed once, not once per comparison. + * Each layout is costed once, not once per comparison. `costOf` replaces + * `layoutCost` where cost means something else — under a cash limit, what the + * layout spends from the board standing. */ -export function cheapestFirst( +export function cheapestFirst( items: readonly T[], - placementsOf: (item: T) => readonly { buildingId: string }[], + placementsOf: (item: T) => readonly P[], + costOf: (placements: readonly P[]) => number = layoutCost, ): T[] { return items .map((item) => { const placements = placementsOf(item); - return { item, cost: layoutCost(placements), count: placements.length }; + return { item, cost: costOf(placements), count: placements.length }; }) .sort((a, b) => Math.abs(a.cost - b.cost) > - COST_TIE_RELATIVE_TOLERANCE * Math.max(a.cost, b.cost) + COST_TIE_RELATIVE_TOLERANCE * Math.max(Math.abs(a.cost), Math.abs(b.cost)) ? a.cost - b.cost : a.count - b.count, ) diff --git a/packages/solver/src/solver/island.ts b/packages/solver/src/solver/island.ts index c4b049a..818bb15 100755 --- a/packages/solver/src/solver/island.ts +++ b/packages/solver/src/solver/island.ts @@ -176,17 +176,23 @@ function wholeBoardIsland(grid: Tile[][]): IslandSubGrid { * rather than of the grid — see `minIslandTiles`. Under a shared cooling pool * the islands this produces are no longer independent either, which is the * board-level problem and not this function's. + * + * `wholeBoard` asks for the board as one island regardless of the rules: a + * cash limit couples every landmass on it the way a pool does, since one + * budget pays for all of them and every copy anywhere raises the next price. */ export function splitGridIntoIslands( grid: Tile[][], canCoolDp = true, anomaly?: AnomalyDefinition, + wholeBoard = false, ): IslandSubGrid[] { if (!grid || grid.length === 0 || !grid[0] || grid[0].length === 0) return []; // A shared cooling pool is the one rule that reaches across the whole board, // so under it the board is one island and the decomposition does not apply. - if (anomaly?.rule === "shared_cooling") return [wholeBoardIsland(grid)]; + if (wholeBoard || anomaly?.rule === "shared_cooling") + return [wholeBoardIsland(grid)]; const originalHeight = grid.length; const originalWidth = grid[0].length; diff --git a/packages/solver/src/solver/placementSearch.ts b/packages/solver/src/solver/placementSearch.ts index b88764b..b097725 100755 --- a/packages/solver/src/solver/placementSearch.ts +++ b/packages/solver/src/solver/placementSearch.ts @@ -6,6 +6,7 @@ import { Pacer } from "./pacer"; import { randomSeed, Rng } from "./rng"; import type { AnomalyDefinition, + CashBudget, EffectiveBuilding, IslandLayout, IslandSubGrid, @@ -14,6 +15,13 @@ import type { SearchHooks, } from "./types"; import { hillClimb } from "./search/anneal"; +import { + affordableRoster, + layoutSpend, + setCashLimit, + standingPlacement, + withinBudget, +} from "./search/cashLimit"; import { arrangeComposition, generatorCapacityTable, @@ -108,9 +116,14 @@ export { downgradeOversized } from "./search/rightSize"; * **Under an upgrade plan "stable" means stable at every step.** The search * scores at the plan's target, but every gate that admits a layout — the best * record, repair, the composition swaps, pruning, right-sizing, the tie - * shortlist and `stabilize` itself — also asks `planHolds`, so a layout that + * shortlist and `stabilize` itself — also asks `layoutHolds`, so a layout that * overheats at any tier on the way is never kept. Without a plan that call * returns at once and nothing here changes. + * + * **Under a cash limit an answer is also one the player can afford** — the + * same gates, through the same call (see `search/cashLimit.ts`). `stabilize` + * steps a layout down until it fits, so anything it hands back is affordable, + * and the walk refuses an over-budget move before simulating it. */ /** Share of the time budget reserved for repair before and after annealing. */ @@ -344,7 +357,12 @@ export async function solveIsland( rngSeed?: number, anomaly?: AnomalyDefinition, upgradeSteps?: EffectiveBuilding[][], + cashBudget?: CashBudget, ): Promise { + // A building the budget can never buy is no candidate anywhere; `planSolve` + // has already done this, and it is idempotent. + if (cashBudget !== undefined) + effectiveBuildings = affordableRoster(effectiveBuildings, cashBudget); const ctx = buildIslandContext( island.grid, island.buildable, @@ -363,6 +381,10 @@ export async function solveIsland( buffer: emptyPlacement(ctx.n), }); } + // What the layout may cost to build from the board as it stands — see + // `search/cashLimit.ts`. Like the plan, it only narrows what may be kept. + if (cashBudget !== undefined) + setCashLimit(ctx, effectiveBuildings, cashBudget); // The pools every stage draws on, in the units the board will hold: a rule // that scales a whole role (a cooling pool's `coolerMultiplier`) is folded in here, so the @@ -486,6 +508,7 @@ export async function solveIsland( generators, coolers, directProducers, + cashBudget !== undefined, ); const polishBudgetMs = timeBudgetMs * POLISH_SHARE; @@ -537,6 +560,28 @@ export async function solveIsland( ); if (plainPolished.power + EPS >= polished.power) polished = plainPolished; } + + // Under a cash limit the seed above is built for power and then stepped down + // until it fits, which can leave little of it. The board as it stands costs + // nothing at all, so it is always an answer the budget allows: repaired on + // the same terms, the search starts from whichever runs higher, the board + // on a tie — it is the one that spends nothing. + if (cashBudget !== undefined) { + const standing = emptyPlacement(ctx.n); + standingPlacement(ctx, effectiveBuildings, cashBudget, standing); + const standingPolished = await greedyPolish( + standing, + ctx, + candidates, + Math.min( + deadlineMs, + performance.now() + Math.max(polishElapsedMs, PLAIN_SEED_POLISH_MIN_MS), + ), + pacer, + ); + if (standingPolished.power + EPS >= polished.power) + polished = standingPolished; + } let placement = polished.placement; let bestPower = polished.power; @@ -575,6 +620,10 @@ export async function solveIsland( ) { break; } + // A composition's spend is its counts' alone, so one the budget cannot + // buy is known before it is arranged. Not a `break`: the list descends by + // power, not by price, and a smaller target further down may fit. + if (!withinBudget(target.composition, ctx)) continue; const arranged = await arrangeComposition( target.composition, @@ -720,9 +769,18 @@ export async function solveIsland( ); // Every one of these ties on power, so the cheapest to build goes first and // is the one the island shows. Stable, so equal costs keep the walk's order. + // Under a cash limit "cheapest" is what it spends from the board standing, + // which is the figure the limit is on. const [best, ...rest] = cheapestFirst( [{ placements, powerOutput: tidied.power }, ...alternates], (l) => l.placements, + cashBudget === undefined + ? undefined + : (l) => + layoutSpend( + l.map((p) => ({ id: p.buildingId })), + ctx, + ) ?? 0, ); return { ...best, alternates: rest }; } diff --git a/packages/solver/src/solver/search/anneal.ts b/packages/solver/src/solver/search/anneal.ts index 1dc5a68..ef28af0 100644 --- a/packages/solver/src/solver/search/anneal.ts +++ b/packages/solver/src/solver/search/anneal.ts @@ -6,12 +6,13 @@ import { generatorEnergyRatio, wasteIsCovered } from "../physics"; import { Rng } from "../rng"; import { type SimPlacedBuilding, simulateIsland } from "../simulate"; import type { EffectiveBuilding, Placement } from "../types"; +import { withinBudget } from "./cashLimit"; import { copyInto, put, ratedFor } from "./placement"; import { islandProgress } from "./repair"; import { anyOfflineProducer, isUnderFed, - planHolds, + layoutHolds, stabilize, } from "./stability"; @@ -96,14 +97,14 @@ export async function hillClimb( powerTies(power, collector.power) && collector.accepts(snapshot) && !anyOfflineProducer(snapshot, rows) && - planHolds(snapshot, ctx) + layoutHolds(snapshot, ctx) ) { collector.offer(power, snapshot); } return; } - if (!anyOfflineProducer(snapshot, rows) && planHolds(snapshot, ctx)) { + if (!anyOfflineProducer(snapshot, rows) && layoutHolds(snapshot, ctx)) { bestPower = power; bestPlacement = snapshot.slice(); collector?.offer(power, snapshot); @@ -245,6 +246,10 @@ export async function hillClimb( // see `ratedFor`. if (ratedFor(ctx, tile, topCooler) !== old) { put(current, ctx, tile, topCooler); + if (!withinBudget(current, ctx)) { + put(current, ctx, tile, old); + continue; + } const trial = simulateIsland(current, ctx); if (!accept(trial.totalPower, trial.placements)) put(current, ctx, tile, old); @@ -263,6 +268,10 @@ export async function hillClimb( const old = current[tile]; if (ratedFor(ctx, tile, topGenerator) !== old) { put(current, ctx, tile, topGenerator); + if (!withinBudget(current, ctx)) { + put(current, ctx, tile, old); + continue; + } const trial = simulateIsland(current, ctx); if (!accept(trial.totalPower, trial.placements)) put(current, ctx, tile, old); @@ -316,6 +325,13 @@ export async function hillClimb( if (ratedFor(ctx, tile, replacement) === old) continue; put(current, ctx, tile, replacement); + // Under a cash limit the walk never leaves it: an over-budget layout can + // never be kept, and simulating one is the whole cost of a step. A swap + // moves two buildings and so never changes the spend. + if (!withinBudget(current, ctx)) { + current[tile] = old; + continue; + } const trial = simulateIsland(current, ctx); if (!accept(trial.totalPower, trial.placements)) current[tile] = old; } diff --git a/packages/solver/src/solver/search/cashLimit.ts b/packages/solver/src/solver/search/cashLimit.ts new file mode 100644 index 0000000..5b99055 --- /dev/null +++ b/packages/solver/src/solver/search/cashLimit.ts @@ -0,0 +1,267 @@ +import { buildPrice, sellRefund } from "../../data/buildingPrices"; +import { findBuilding } from "../../data/buildings"; +import type { IslandContext } from "../context"; +import type { CashBudget, EffectiveBuilding, Placement } from "../types"; +import { put } from "./placement"; + +/** + * A cash limit: what turning the board as it stands into the layout may cost, + * net of what the sales along the way pay back. + * + * Moves are free, so no building type is ever sold and rebuilt — its count on + * the board only goes up, each copy bought at the next copy's price, or down, + * each sale refunding a share of the current one. The net spend is therefore a + * sum over types of a function of that type's count alone, the same in every + * order, and each of those functions is tabulated once per island. Selling + * first is always possible, so the net is also the most cash the change ever + * needs on hand. + */ +interface CashLimit { + cash: number; + /** Building id to its row in `spendAt`. */ + slot: Map; + /** + * Per type, the net spend at each count on the island: 0 at the count + * standing, climbing above it and negative below. Strictly increasing, + * since every price and refund is positive. + */ + spendAt: Float64Array[]; + /** Per type, the next cheaper building of the same role, or null. */ + cheaper: (EffectiveBuilding | null)[]; + /** Scratch: per type, its count in the layout being priced. */ + counts: Int32Array; +} + +/** + * Relative slack for "within budget": a net spend sums buys and refunds + * across thirty orders of magnitude, so it is compared against the size of + * its own terms rather than exactly. + */ +const SPEND_RELATIVE_TOLERANCE = 1e-9; + +/** + * Held beside the context like `upgradePlans`, so every stage's signature is + * untouched without a limit — which is always the case for the fixtures. + */ +const cashLimits = new WeakMap(); + +/** The net spend at each count, 0 at `standing`. */ +function spendTable( + id: string, + standing: number, + elsewhere: number, + maxCount: number, + budget: CashBudget, +): Float64Array { + const base = findBuilding(id)?.price ?? 0; + const table = new Float64Array(Math.max(standing, maxCount) + 1); + for (let t = standing + 1; t < table.length; t++) + table[t] = + table[t - 1] + buildPrice(base, elsewhere + t - 1, budget.prices); + for (let t = standing - 1; t >= 0; t--) + table[t] = + table[t + 1] - sellRefund(base, elsewhere + t + 1, budget.prices); + return table; +} + +/** Each building id standing on the island, and how many. */ +function standingCounts(budget: CashBudget): Map { + const counts = new Map(); + for (const p of budget.standing) + counts.set(p.buildingId, (counts.get(p.buildingId) ?? 0) + 1); + return counts; +} + +/** + * The roster less every building the budget can never buy: one whose next copy + * costs more than the cash plus what selling everything standing pays back, + * and of which none stands. Sound — no layout within the budget holds one — + * and it is what keeps the seed, the repair and the bound from building + * around a top tier the player cannot reach. + */ +export function affordableRoster( + roster: EffectiveBuilding[], + budget: CashBudget, +): EffectiveBuilding[] { + const standing = standingCounts(budget); + let refundAll = 0; + for (const [id, c] of standing) + refundAll -= spendTable(id, c, budget.elsewhere[id] ?? 0, 0, budget)[0]; + const reach = budget.cash + refundAll; + return roster.filter((b) => { + const c = standing.get(b.id) ?? 0; + if (c > 0) return true; + const first = spendTable(b.id, 0, budget.elsewhere[b.id] ?? 0, 1, budget); + return first[1] <= reach * (1 + SPEND_RELATIVE_TOLERANCE); + }); +} + +/** + * Puts a cash limit on the island. `roster` is every building a layout may + * hold, in any rating — the limit reads ids — and the standing board's types + * are priced too, since selling one is a refund every layout without it gets. + */ +export function setCashLimit( + ctx: IslandContext, + roster: EffectiveBuilding[], + budget: CashBudget, +): void { + const standing = standingCounts(budget); + const ids = [...new Set([...roster.map((b) => b.id), ...standing.keys()])]; + const slot = new Map(ids.map((id, i) => [id, i])); + const spendAt = ids.map((id) => + spendTable( + id, + standing.get(id) ?? 0, + budget.elsewhere[id] ?? 0, + ctx.n, + budget, + ), + ); + const price = (b: EffectiveBuilding) => findBuilding(b.id)?.price ?? 0; + const cheaper = ids.map((id) => { + const self = roster.find((b) => b.id === id); + if (self === undefined) return null; + let best: EffectiveBuilding | null = null; + for (const b of roster) { + if (b.type !== self.type || price(b) >= price(self)) continue; + if (best === null || price(b) > price(best)) best = b; + } + return best; + }); + cashLimits.set(ctx, { + cash: budget.cash, + slot, + spendAt, + cheaper, + counts: new Int32Array(ids.length), + }); +} + +/** + * Anything a spend can be read off: a placement, a composition, or a list of + * ids. Only ids count — where a building stands is free. + */ +type Priced = readonly ({ id: string } | null)[]; + +/** Fills `limit.counts` from the layout. */ +function countInto(placement: Priced, limit: CashLimit): void { + limit.counts.fill(0); + for (const b of placement) { + if (b === null) continue; + const s = limit.slot.get(b.id); + if (s !== undefined) limit.counts[s]++; + } +} + +/** Whether the counts in `limit.counts` are within the cash. */ +function countsFit(limit: CashLimit): boolean { + let spend = 0; + let scale = 0; + for (let s = 0; s < limit.spendAt.length; s++) { + const v = limit.spendAt[s][limit.counts[s]]; + spend += v; + scale += Math.abs(v); + } + return ( + spend <= + limit.cash + + SPEND_RELATIVE_TOLERANCE * Math.max(scale, Math.abs(limit.cash)) + ); +} + +/** Whether the layout is within the island's cash limit. Free without one. */ +export function withinBudget(placement: Priced, ctx: IslandContext): boolean { + const limit = cashLimits.get(ctx); + if (limit === undefined) return true; + countInto(placement, limit); + return countsFit(limit); +} + +/** The layout's net spend, or null when the island has no cash limit. */ +export function layoutSpend( + placement: Priced, + ctx: IslandContext, +): number | null { + const limit = cashLimits.get(ctx); + if (limit === undefined) return null; + countInto(placement, limit); + let spend = 0; + for (let s = 0; s < limit.spendAt.length; s++) + spend += limit.spendAt[s][limit.counts[s]]; + return spend; +} + +/** + * Brings the layout within the cash limit, in place: while it is over, the + * type whose last copy costs the most gives one up — stepped down to the next + * cheaper building of its role where that saves money, removed where it does + * not. Reports whether anything changed. + * + * Every step lowers the spend strictly, and the empty board's spend is at most + * nothing, so this always ends within any cash of zero or more. What it + * leaves may have producers offline, which is `stabilize`'s to clear. + */ +export function trimToBudget( + placement: Placement, + ctx: IslandContext, +): boolean { + const limit = cashLimits.get(ctx); + if (limit === undefined) return false; + let changed = false; + for (;;) { + countInto(placement, limit); + if (countsFit(limit)) return changed; + + let worst = -1; + let saving = 0; + for (let s = 0; s < limit.spendAt.length; s++) { + const c = limit.counts[s]; + if (c === 0) continue; + const d = limit.spendAt[s][c] - limit.spendAt[s][c - 1]; + if (d > saving) { + saving = d; + worst = s; + } + } + if (worst < 0) return changed; + + let tile = -1; + for (let t = ctx.n - 1; t >= 0 && tile < 0; t--) { + const b = placement[t]; + if (b !== null && limit.slot.get(b.id) === worst) tile = t; + } + + const down = limit.cheaper[worst]; + const ds = down === null ? undefined : limit.slot.get(down.id); + const added = + ds === undefined + ? Infinity + : limit.spendAt[ds][limit.counts[ds] + 1] - + limit.spendAt[ds][limit.counts[ds]]; + if (down !== null && added < saving) put(placement, ctx, tile, down); + else placement[tile] = null; + changed = true; + } +} + +/** + * The board as it stands, as a placement on this island: where every building + * of `budget.standing` would sit, in `roster`'s buildings by id. A building + * the roster does not hold is left off — the run sells it. + */ +export function standingPlacement( + ctx: IslandContext, + roster: EffectiveBuilding[], + budget: CashBudget, + into: Placement, +): void { + const byId = new Map(roster.map((b) => [b.id, b])); + const at = new Map(); + for (let t = 0; t < ctx.n; t++) at.set(`${ctx.xs[t]},${ctx.ys[t]}`, t); + for (const p of budget.standing) { + const t = at.get(`${p.x},${p.y}`); + const b = byId.get(p.buildingId); + if (t !== undefined && b !== undefined) put(into, ctx, t, b); + } +} diff --git a/packages/solver/src/solver/search/composition.ts b/packages/solver/src/solver/search/composition.ts index a7876ed..3391aeb 100644 --- a/packages/solver/src/solver/search/composition.ts +++ b/packages/solver/src/solver/search/composition.ts @@ -7,7 +7,7 @@ import { simulateIsland } from "../simulate"; import type { EffectiveBuilding, IslandSubGrid, Placement } from "../types"; import { chebyshev, put, ratedFor, SWAP_RADIUS } from "./placement"; import { POLISH_REACTOR_TIERS } from "./repair"; -import { anyOfflineProducer, planHolds } from "./stability"; +import { anyOfflineProducer, layoutHolds } from "./stability"; /** * Composition retargeting: deciding WHAT to build is a counting problem, so it @@ -444,7 +444,7 @@ export async function arrangeComposition( if ( trial.totalPower - basePower > bestGain && !anyOfflineProducer(current, trial.placements) && - planHolds(current, ctx) + layoutHolds(current, ctx) ) { bestGain = trial.totalPower - basePower; bestSwap = [a, b]; diff --git a/packages/solver/src/solver/search/emptyTiles.ts b/packages/solver/src/solver/search/emptyTiles.ts index ca28164..8c9ccf9 100644 --- a/packages/solver/src/solver/search/emptyTiles.ts +++ b/packages/solver/src/solver/search/emptyTiles.ts @@ -3,7 +3,7 @@ import { type SimPlacedBuilding, simulateIsland } from "../simulate"; import type { EffectiveBuilding, Placement } from "../types"; import { chebyshev, emptyPlacement, put } from "./placement"; import { covers } from "./rightSize"; -import { anyOfflineProducer, planHolds } from "./stability"; +import { anyOfflineProducer, layoutHolds } from "./stability"; /** * Pushing the tiles a finished layout leaves empty out to the edge of the land @@ -156,7 +156,7 @@ export function gatherEmptyTiles( covers(trial.totalPower, floor) && !anyOfflineProducer(current, trial.placements) && idleCount(current, trial.placements) <= idleFloor && - planHolds(current, ctx) + layoutHolds(current, ctx) ) { changed = true; moved = true; diff --git a/packages/solver/src/solver/search/pooledCoolers.ts b/packages/solver/src/solver/search/pooledCoolers.ts index 608a44d..90b2af2 100644 --- a/packages/solver/src/solver/search/pooledCoolers.ts +++ b/packages/solver/src/solver/search/pooledCoolers.ts @@ -11,7 +11,7 @@ import { SWAP_RADIUS, } from "./placement"; import { covers } from "./rightSize"; -import { anyOfflineProducer, planHolds } from "./stability"; +import { anyOfflineProducer, layoutHolds } from "./stability"; /** * Under a shared cooling pool only: gathering the coolers the search scattered, @@ -251,7 +251,7 @@ function relocateHub( return ( covers(final.totalPower, floor) && !anyOfflineProducer(trial, final.placements) && - planHolds(trial, ctx) + layoutHolds(trial, ctx) ); } @@ -385,7 +385,7 @@ export function gatherPooledCoolers( if ( covers(trial.totalPower, floor) && !anyOfflineProducer(current, trial.placements) && - planHolds(current, ctx) + layoutHolds(current, ctx) ) { changed = true; break; diff --git a/packages/solver/src/solver/search/repair.ts b/packages/solver/src/solver/search/repair.ts index d16731f..006e871 100644 --- a/packages/solver/src/solver/search/repair.ts +++ b/packages/solver/src/solver/search/repair.ts @@ -10,7 +10,8 @@ import { ratedFor, toPlacedBuildings, } from "./placement"; -import { anyOfflineProducer, planHolds, stabilize } from "./stability"; +import { layoutSpend, withinBudget } from "./cashLimit"; +import { anyOfflineProducer, layoutHolds, stabilize } from "./stability"; /** * Local repair and pruning: steepest ascent over single-tile changes, and the @@ -35,20 +36,25 @@ const POLISH_DIRTY_RADIUS = 2; * that a weaker one is genuinely useful for topping up a generator's spare heat * capacity when there is leftover cooling, so a few reactor tiers are kept. * Every extra candidate costs another full pass over the island. + * + * Under a cash limit that argument fails: the top tier is the one the budget + * runs out on, and a weaker generator or cooler is often what the last of the + * cash buys. `budgeted` keeps as many tiers of every role as of reactors. */ export function polishCandidates( reactors: EffectiveBuilding[], generators: EffectiveBuilding[], coolers: EffectiveBuilding[], directProducers: EffectiveBuilding[], + budgeted = false, ): (EffectiveBuilding | null)[] { - const candidates: (EffectiveBuilding | null)[] = reactors.slice( - 0, - POLISH_REACTOR_TIERS, - ); - if (generators.length > 0) candidates.push(generators[0]); - if (coolers.length > 0) candidates.push(coolers[0]); - if (directProducers.length > 0) candidates.push(directProducers[0]); + const tiers = budgeted ? POLISH_REACTOR_TIERS : 1; + const candidates: (EffectiveBuilding | null)[] = [ + ...reactors.slice(0, POLISH_REACTOR_TIERS), + ...generators.slice(0, tiers), + ...coolers.slice(0, tiers), + ...directProducers.slice(0, tiers), + ]; // Leaving the tile empty is a real option. candidates.push(null); return candidates; @@ -76,7 +82,10 @@ export async function greedyPolish( let current = placement.slice(); const sim = simulateIsland(current, ctx); let bestPower = sim.totalPower; - if (anyOfflineProducer(current, sim.placements) || !planHolds(current, ctx)) { + if ( + anyOfflineProducer(current, sim.placements) || + !layoutHolds(current, ctx) + ) { const stabilized = stabilize(current, ctx); current = stabilized.placement; bestPower = stabilized.power; @@ -105,10 +114,57 @@ export async function greedyPolish( const gains = new Float64Array(ctx.n * nCandidates).fill(-Infinity); const dirty = new Uint8Array(ctx.n).fill(1); + // A cash limit is the one thing locality does not cover: the budget is + // shared by the whole island, so a move anywhere can bring a far candidate + // back within it — or put it out — without touching its neighbourhood. + // Under a limit the budget is checked before the simulation, as `hillClimb` + // does, and every (tile, candidate) it turned away is flagged here and + // re-checked after each applied move. The re-check is the cheap test alone; + // only a candidate that now fits is simulated. Null without a limit, where + // the sweep is exactly what it was. + const overBudget = + layoutSpend(current, ctx) === null + ? null + : new Uint8Array(ctx.n * nCandidates); + let recheckBudget = false; + + const measure = (tile: number, k: number, held: EffectiveBuilding | null) => { + const building = candidates[k]; + if (overBudget !== null) overBudget[tile * nCandidates + k] = 0; + // The candidate list is the plain roster, `held` is rated for this tile: + // asked the wrong way round, a scaled tile re-simulates its own layout + // once per sweep for nothing. See `ratedFor`. + if (ratedFor(ctx, tile, building) === held) return -Infinity; + let gain = -Infinity; + put(current, ctx, tile, building); + if (overBudget !== null && !withinBudget(current, ctx)) { + overBudget[tile * nCandidates + k] = 1; + } else { + const trial = simulateIsland(current, ctx); + if ( + trial.totalPower - bestPower > 0 && + !anyOfflineProducer(current, trial.placements) && + layoutHolds(current, ctx) + ) { + gain = trial.totalPower - bestPower; + } + } + put(current, ctx, tile, held); + return gain; + }; + + const anyOverBudget = (tile: number) => { + if (overBudget === null) return false; + for (let k = 0; k < nCandidates; k++) + if (overBudget[tile * nCandidates + k] === 1) return true; + return false; + }; + while (performance.now() < deadlineMs && !pacer.stopRequested) { let cut = false; for (let tile = 0; tile < ctx.n; tile++) { - if (dirty[tile] === 0) continue; + const full = dirty[tile] === 1; + if (!full && !(recheckBudget && anyOverBudget(tile))) continue; const now = performance.now(); if (now >= deadlineMs) { cut = true; @@ -125,27 +181,14 @@ export async function greedyPolish( dirty[tile] = 0; const held = current[tile]; for (let k = 0; k < nCandidates; k++) { - const building = candidates[k]; - let gain = -Infinity; - // The candidate list is the plain roster, `held` is rated for this tile: - // asked the wrong way round, a scaled tile re-simulates its own layout - // once per sweep for nothing. See `ratedFor`. - if (ratedFor(ctx, tile, building) !== held) { - put(current, ctx, tile, building); - const trial = simulateIsland(current, ctx); - if ( - trial.totalPower - bestPower > 0 && - !anyOfflineProducer(current, trial.placements) && - planHolds(current, ctx) - ) { - gain = trial.totalPower - bestPower; - } - put(current, ctx, tile, held); - } - gains[tile * nCandidates + k] = gain; + // A clean tile is visited only for its budget-rejected candidates; + // the rest keep their cached figure. + if (!full && overBudget?.[tile * nCandidates + k] !== 1) continue; + gains[tile * nCandidates + k] = measure(tile, k, held); } } if (cut) break; + recheckBudget = false; let bestGain = 0.0; let bestTile = -1; @@ -167,13 +210,18 @@ export async function greedyPolish( if ( trial.totalPower - bestPower > 0 && !anyOfflineProducer(current, trial.placements) && - planHolds(current, ctx) + layoutHolds(current, ctx) ) { bestPower = trial.totalPower; for (let tile = 0; tile < ctx.n; tile++) { if (chebyshev(ctx, tile, bestTile) <= POLISH_DIRTY_RADIUS) dirty[tile] = 1; } + // After any applied move, not only one that lowers the total: a type's + // price depends on its own count, so a move that sells a copy of one + // type makes that type's next copy cheaper elsewhere even while the + // total climbs. + if (overBudget !== null) recheckBudget = true; } else { // Stale: the layout moved under it. Back to the sweep for a fresh figure. put(current, ctx, bestTile, held); @@ -251,7 +299,7 @@ export function pruneDeadWeight( if ( trial.totalPower >= bestPower - EPS && !anyOfflineProducer(current, trial.placements) && - planHolds(current, ctx) + layoutHolds(current, ctx) ) { bestPower = trial.totalPower; rows = trial.placements; diff --git a/packages/solver/src/solver/search/rightSize.ts b/packages/solver/src/solver/search/rightSize.ts index eeab458..34b9b47 100644 --- a/packages/solver/src/solver/search/rightSize.ts +++ b/packages/solver/src/solver/search/rightSize.ts @@ -3,7 +3,7 @@ import { wasteIsCovered } from "../physics"; import { type SimPlacedBuilding, simulateIsland } from "../simulate"; import type { EffectiveBuilding, Placement } from "../types"; import { emptyPlacement, isReactor, put } from "./placement"; -import { anyOfflineProducer, planHolds } from "./stability"; +import { anyOfflineProducer, layoutHolds } from "./stability"; /** * Right-sizing the finished layout: every building swapped for the smallest @@ -188,7 +188,7 @@ export function downgradeOversized( if ( covers(trial.totalPower, floor) && !anyOfflineProducer(current, trial.placements) && - planHolds(current, ctx) + layoutHolds(current, ctx) ) { power = trial.totalPower; rows = trial.placements; @@ -223,7 +223,7 @@ export function downgradeOversized( if ( covers(trial.totalPower, floor) && !anyOfflineProducer(current, trial.placements) && - planHolds(current, ctx) + layoutHolds(current, ctx) ) { power = trial.totalPower; rows = trial.placements; diff --git a/packages/solver/src/solver/search/stability.ts b/packages/solver/src/solver/search/stability.ts index 7a0dd32..12419ba 100644 --- a/packages/solver/src/solver/search/stability.ts +++ b/packages/solver/src/solver/search/stability.ts @@ -2,11 +2,13 @@ import { EPS } from "../constants"; import type { IslandContext } from "../context"; import { type SimPlacedBuilding, simulateIsland } from "../simulate"; import type { EffectiveBuilding, Placement } from "../types"; +import { trimToBudget, withinBudget } from "./cashLimit"; import { isDirectProducer } from "./placement"; /** * What makes a layout an answer: every producer online, at the target and at - * every step of an upgrade plan. See the stability rule in `placementSearch.ts`. + * every step of an upgrade plan, within the island's cash limit. See the + * stability rule in `placementSearch.ts`. */ /** @@ -116,9 +118,13 @@ function planFailure( return null; } -/** Whether the layout runs at every step of the island's plan. */ -export function planHolds(placement: Placement, ctx: IslandContext): boolean { - return planFailure(placement, ctx) === null; +/** + * Whether the layout runs at every step of the island's plan and is within its + * cash limit — everything an answer has to be beyond stable at the target. + * Free when the island has neither. + */ +export function layoutHolds(placement: Placement, ctx: IslandContext): boolean { + return withinBudget(placement, ctx) && planFailure(placement, ctx) === null; } interface StableLayout { @@ -135,6 +141,14 @@ interface StableLayout { * can push THEIR waste past what their coolers cover and take them offline in * turn. Power can legitimately fall as a result — a layout that only scores * well by parking heat in an overheating building is not a layout we want. + * + * Under a cash limit, once nothing is offline it steps the layout down until + * it fits (`trimToBudget`) and goes round again, since a cut can take a + * producer offline. Offline producers go first because they are going anyway: + * trimming first could cut a productive building to cover an overspend that + * stripping a dead one would have covered alone. Removing a building only ever + * lowers the spend, so nothing stripped afterwards can put the layout back + * over. Without a limit `trimToBudget` is a no-op and this is the plain loop. */ export function stabilize( placement: Placement, @@ -149,13 +163,16 @@ export function stabilize( // overheats at any step goes too, and so on until every step runs. if (offline.length === 0) offline = planFailure(current, ctx) ?? []; if (offline.length === 0) { - return { - placement: current, - power: sim.totalPower, - rows: sim.placements, - }; + if (!trimToBudget(current, ctx)) { + return { + placement: current, + power: sim.totalPower, + rows: sim.placements, + }; + } + } else { + for (const tile of offline) current[tile] = null; } - for (const tile of offline) current[tile] = null; sim = simulateIsland(current, ctx); } } diff --git a/packages/solver/src/solver/solver.ts b/packages/solver/src/solver/solver.ts index 50055d4..6788798 100755 --- a/packages/solver/src/solver/solver.ts +++ b/packages/solver/src/solver/solver.ts @@ -5,11 +5,13 @@ import { splitGridIntoIslands, } from "./island"; import { solveIsland, type IslandSolution } from "./placementSearch"; +import { affordableRoster } from "./search/cashLimit"; import { getAnomaly } from "../data/anomalies"; import { getEffectiveBuildings } from "../data/effectiveBuildings"; import type { AnomalyDefinition, BuildingDefinition, + CashBudget, EffectiveBuilding, PrestigeScales, IslandSubGrid, @@ -160,6 +162,12 @@ export interface IslandPlan { * plan. */ upgradeSteps?: EffectiveBuilding[][]; + /** + * The cash limit, when there is one. The board is then a single island + * (`splitGridIntoIslands`' `wholeBoard`), so its standing board's board + * coordinates are that island's coordinates too. + */ + cashBudget?: CashBudget; } /** @@ -179,6 +187,7 @@ export function planSolve( anomalyId?: string, prestige?: PrestigeScales, upgradePlan?: Record[], + cashBudget?: CashBudget, ): IslandPlan | null { if (!grid || grid.length === 0 || !grid[0] || grid[0].length === 0) return null; @@ -188,11 +197,13 @@ export function planSolve( // Research folds in here, at the one place the roster is resolved, so every // island and every attempt is handed the same already-scaled buildings. - const effectiveBuildings = getEffectiveBuildings( - buildings, - unlockedUpgrades, - prestige, - ); + // A cash limit then takes out what it can never buy, here rather than per + // island so the bound below is the budget's roster as well as the search's. + const unlocked = getEffectiveBuildings(buildings, unlockedUpgrades, prestige); + const effectiveBuildings = + cashBudget === undefined + ? unlocked + : affordableRoster(unlocked, cashBudget); if (effectiveBuildings.length === 0) return null; // Taken by id rather than as a definition, because that is also the worker @@ -208,6 +219,7 @@ export function planSolve( grid, canCoolDirectProducer(effectiveBuildings), anomaly, + cashBudget !== undefined, ); if (islands.length === 0) return null; @@ -234,6 +246,7 @@ export function planSolve( upgradeSteps: (upgradePlan ?? []).map((unlocks) => getEffectiveBuildings(buildings, unlocks, prestige), ), + cashBudget, }; } @@ -341,6 +354,7 @@ export async function solve( options?.anomalyId, options?.prestige, options?.upgradePlan, + options?.cashBudget, ); if (!plan) return createEmptyResult(grid?.[0]?.length ? countGrassTiles(grid) : 0); @@ -366,6 +380,7 @@ export async function solve( plan.seeds[i], plan.anomaly, plan.upgradeSteps, + plan.cashBudget, ); options?.onProgress?.(buildOptimizationResult(plan, islandResults)); } diff --git a/packages/solver/src/solver/types.ts b/packages/solver/src/solver/types.ts index 31e7419..6366134 100755 --- a/packages/solver/src/solver/types.ts +++ b/packages/solver/src/solver/types.ts @@ -1,3 +1,5 @@ +import type { PriceRules } from "../data/buildingPrices"; + export type BuildingType = "cooler" | "reactor" | "generator" | "direct_producer"; @@ -420,6 +422,30 @@ export interface SearchHooks { reportIntervalMs?: number; } +/** + * A cash limit on a solve: what turning the board as it stands into the layout + * may cost, net of what the sales along the way pay back. Moves are free, so a + * building kept costs nothing wherever it ends up. + * + * A budget makes the board one problem — prices climb with copies across every + * landmass on it — so a budgeted solve hands the board over whole, as a cooling + * pool does. + */ +export interface CashBudget { + /** The most the change may spend, net of refunds. Zero or more. */ + cash: number; + /** What stands on the board now, in board coordinates. */ + standing: { x: number; y: number; buildingId: string }[]; + /** + * Each building's count on the player's other islands. Prices climb with + * every copy anywhere, so these make this board's copies dearer; they are + * held where they are. + */ + elsewhere: Record; + /** The player's price research — `priceRules`. */ + prices: PriceRules; +} + export interface SolveOptions { onProgress?: (result: OptimizationResult) => void; shouldStop?: () => boolean; @@ -471,6 +497,11 @@ export interface SolveOptions { * the search changes. */ upgradePlan?: Record[]; + /** + * A cash limit — see `CashBudget`. Power is still what is maximised; no + * layout over the limit is ever kept. Omitted means no limit. + */ + cashBudget?: CashBudget; } // ============================================================================ @@ -495,6 +526,11 @@ export type IslandWorkerRequest = * so the research folded into them crosses with them. */ upgradeSteps?: EffectiveBuilding[][]; + /** + * The cash limit, its standing board in this island's coordinates — + * which for the whole-board island a budget solves on are the board's. + */ + cashBudget?: CashBudget; } | { id: string; type: "STOP" }; diff --git a/packages/solver/tests/cashLimit.test.ts b/packages/solver/tests/cashLimit.test.ts new file mode 100644 index 0000000..827af86 --- /dev/null +++ b/packages/solver/tests/cashLimit.test.ts @@ -0,0 +1,261 @@ +/** + * The cash limit: what a layout spends from the board standing, and the search + * keeping every layout it returns within it. + * + * The search half is pinned as invariants, the way the upgrade plan's is: the + * returned layout spends no more than the cash, a board kept whole with no cash + * at all loses nothing, and the board is solved as one island. What power a + * given sum reaches is a measurement, and the CLI's `--cash` is where it is + * taken. + */ +import { describe, expect, it } from "vitest"; +import { + buildPrice, + fitsBudget, + layoutCost, + netSpend, + priceRules, + sellRefund, +} from "../src/data/buildingPrices"; +import { allUpgradesUnlocked, BUILDINGS } from "../src/data/buildings"; +import { getEffectiveBuildings } from "../src/data/effectiveBuildings"; +import { makeGrid } from "../src/grid"; +import { buildIslandContext } from "../src/solver/context"; +import { Rng } from "../src/solver/rng"; +import { + affordableRoster, + layoutSpend, + setCashLimit, + trimToBudget, + withinBudget, +} from "../src/solver/search/cashLimit"; +import { splitGridIntoIslands } from "../src/solver/island"; +import { planSolve, solve } from "../src/solver/solver"; +import type { + BuildingDefinition, + CashBudget, + Placement, +} from "../src/solver/types"; + +const CATALOGUE = BUILDINGS as BuildingDefinition[]; +const UNLOCKS = allUpgradesUnlocked(); +const ROSTER = getEffectiveBuildings(CATALOGUE, UNLOCKS); +const PRICES = priceRules({}); +const price = (id: string) => CATALOGUE.find((b) => b.id === id)!.price; + +const at = (x: number, y: number, buildingId: string) => ({ + x, + y, + buildingId, +}); + +function budget( + cash: number, + standing: CashBudget["standing"] = [], + elsewhere: Record = {}, +): CashBudget { + return { cash, standing, elsewhere, prices: PRICES }; +} + +describe("netSpend", () => { + it("is the build cost from empty when nothing stands", () => { + const layout = [ + at(0, 0, "cooler3"), + at(1, 0, "cooler3"), + at(2, 0, "generator2"), + ]; + expect(netSpend(layout, budget(0))).toBeCloseTo(layoutCost(layout), 6); + }); + + it("charges nothing for keeping a building or for moving it", () => { + const standing = [at(0, 0, "cooler3"), at(1, 0, "generator2")]; + const moved = [at(4, 4, "generator2"), at(3, 3, "cooler3")]; + expect(netSpend(standing, budget(0, standing))).toBe(0); + expect(netSpend(moved, budget(0, standing))).toBe(0); + }); + + it("refunds a sale at the current price, the copies elsewhere counted", () => { + const standing = [at(0, 0, "cooler3"), at(1, 0, "cooler3")]; + const spend = netSpend( + [at(0, 0, "cooler3")], + budget(0, standing, { cooler3: 4 }), + ); + // Six copies stand across the islands before the sale. + expect(spend).toBeCloseTo(-sellRefund(price("cooler3"), 6, PRICES), 9); + }); + + it("prices a new copy after every copy anywhere", () => { + const spend = netSpend( + [at(0, 0, "cooler3")], + budget(0, [], { cooler3: 3 }), + ); + expect(spend).toBeCloseTo(buildPrice(price("cooler3"), 3, PRICES), 9); + }); +}); + +describe("fitsBudget", () => { + it("holds a layout to its net spend, as the engine does", () => { + const standing = [at(0, 0, "cooler3")]; + const layout = [at(0, 0, "cooler3"), at(1, 0, "cooler3")]; + const spend = netSpend(layout, budget(0, standing)); + expect(fitsBudget(layout, budget(spend, standing))).toBe(true); + expect(fitsBudget(layout, budget(spend * 0.99, standing))).toBe(false); + // Keeping the board as it stands fits any cash, none included. + expect(fitsBudget(standing, budget(0, standing))).toBe(true); + }); +}); + +describe("the island's spend tables", () => { + const grid = makeGrid(["GGGGG", "GGGGG", "GGGGG", "GGGGG"]); + const [island] = splitGridIntoIslands(grid); + const ctx = buildIslandContext( + island.grid, + island.buildable, + undefined, + island.waterAdjacent, + ); + const cheap = ROSTER.filter((b) => b.id.match(/^(cooler|generator)[1-3]$/)); + const standing = [ + at(ctx.xs[0], ctx.ys[0], "cooler2"), + at(ctx.xs[1], ctx.ys[1], "cooler2"), + at(ctx.xs[2], ctx.ys[2], "generator1"), + ]; + const limit = budget(5e4, standing, { cooler2: 7, generator3: 2 }); + setCashLimit(ctx, cheap, limit); + + const random = (rng: Rng): Placement => + Array.from({ length: ctx.n }, () => + rng.random() < 0.4 ? null : cheap[rng.int(cheap.length)], + ); + const asPlaced = (placement: Placement) => + placement.flatMap((b, t) => + b === null ? [] : [at(ctx.xs[t], ctx.ys[t], b.id)], + ); + + it("agree with netSpend on any layout", () => { + const rng = new Rng(11); + for (let i = 0; i < 200; i++) { + const placement = random(rng); + const expected = netSpend(asPlaced(placement), limit); + // Relative: the two sum the same prices in a different order. + const spend = layoutSpend(placement, ctx)!; + expect(Math.abs(spend - expected)).toBeLessThanOrEqual( + 1e-12 * Math.max(1, Math.abs(expected)), + ); + } + }); + + it("trims any layout to within the cash, and leaves one inside it alone", () => { + const rng = new Rng(3); + for (let i = 0; i < 100; i++) { + const placement = random(rng); + const before = placement.slice(); + const wasWithin = withinBudget(placement, ctx); + const changed = trimToBudget(placement, ctx); + expect(withinBudget(placement, ctx)).toBe(true); + expect(netSpend(asPlaced(placement), limit)).toBeLessThanOrEqual( + limit.cash * (1 + 1e-9), + ); + expect(changed).toBe(!wasWithin); + if (wasWithin) expect(placement).toEqual(before); + } + }); +}); + +describe("affordableRoster", () => { + it("drops what the cash and every refund together cannot buy one of", () => { + const kept = affordableRoster(ROSTER, budget(1e6)); + expect(kept.length).toBeGreaterThan(0); + for (const b of kept) expect(price(b.id)).toBeLessThanOrEqual(1e6); + expect(kept.some((b) => b.id === "cooler8")).toBe(false); + }); + + it("keeps a building that stands, whatever it costs", () => { + const kept = affordableRoster(ROSTER, budget(0, [at(0, 0, "cooler8")])); + expect(kept.some((b) => b.id === "cooler8")).toBe(true); + }); +}); + +describe("a budgeted solve", () => { + const grid = makeGrid([ + "GGGGGG.GGG", + "GGGGGG.GGG", + "GGGGGG.GGG", + "GGGGGG....", + ]); + + it("solves the board as one island, since one budget pays for all of it", () => { + expect(planSolve(grid, CATALOGUE, UNLOCKS, 1)!.islands).toHaveLength(2); + expect( + planSolve( + grid, + CATALOGUE, + UNLOCKS, + 1, + 1, + undefined, + undefined, + undefined, + budget(1e20), + )!.islands, + ).toHaveLength(1); + }); + + it("returns a layout within the cash, and more cash buys more power", async () => { + let previous = 0; + for (const cash of [1e12, 1e18, 1e24]) { + const limit = budget(cash); + const result = await solve( + grid, + CATALOGUE, + UNLOCKS, + 0.6, + { cashBudget: limit }, + 5, + ); + expect(result.totalPower).toBeGreaterThan(previous); + expect(netSpend(result.placements, limit)).toBeLessThanOrEqual( + cash * (1 + 1e-9), + ); + previous = result.totalPower; + } + }); + + it("with no cash, keeps what the standing board makes and spends nothing", async () => { + const built = await solve( + grid, + CATALOGUE, + UNLOCKS, + 0.6, + { cashBudget: budget(1e18) }, + 9, + ); + const standing = built.placements.map((p) => at(p.x, p.y, p.buildingId)); + const limit = budget(0, standing); + const result = await solve( + grid, + CATALOGUE, + UNLOCKS, + 0.6, + { cashBudget: limit }, + 9, + ); + expect(netSpend(result.placements, limit)).toBeLessThanOrEqual(0); + expect(result.totalPower).toBeGreaterThanOrEqual( + built.totalPower * (1 - 1e-9), + ); + }); + + it("builds nothing when nothing is affordable", async () => { + const result = await solve( + grid, + CATALOGUE, + UNLOCKS, + 0.3, + { cashBudget: budget(1) }, + 1, + ); + expect(result.totalPower).toBe(0); + expect(result.placements).toHaveLength(0); + }); +}); diff --git a/src/App.svelte b/src/App.svelte index 0e59981..921a433 100755 --- a/src/App.svelte +++ b/src/App.svelte @@ -22,6 +22,7 @@ SolveModeInfoModal, TimeLabPlannerModal, TransferModal, + IslandStatsModal, UpgradePlanModal, } from "./lib/components"; import { Eye } from "lucide-svelte"; @@ -345,6 +346,7 @@ + + + +
+
+
Base
+
{formatNumber(pricing.base)}
+
+
+
Built
+
{pricing.built}
+
+
+
Next
+
+ {formatNumber(pricing.next)} +
+
+
@@ -310,6 +339,46 @@ color: #b8d8ff; } + /* Price row: part of the stat rows' px sub-layout above. */ + .price-row { + display: flex; + gap: 10px; + margin: 0 0 2px 4px; + font-size: 11px; + } + + .price-row div { + display: flex; + gap: 3px; + align-items: center; + min-width: 0; + } + + .price-row dt { + color: var(--text-dim); + font-weight: 600; + } + + .price-row dd { + margin: 0; + color: var(--text-muted); + font-weight: 700; + white-space: nowrap; + } + + .price-row .next { + display: flex; + align-items: center; + gap: 2px; + color: var(--text); + } + + .cash-icon { + width: 12px; + height: 12px; + object-fit: contain; + } + /* Upgrades Row */ .upgrades-bar { display: flex; diff --git a/src/lib/components/sidebar/BuildingUnlockList.svelte b/src/lib/components/sidebar/BuildingUnlockList.svelte index b580f0c..04b1cb6 100755 --- a/src/lib/components/sidebar/BuildingUnlockList.svelte +++ b/src/lib/components/sidebar/BuildingUnlockList.svelte @@ -1,10 +1,12 @@
@@ -87,6 +93,7 @@ every screen of it. --> +
+ {/if} +
+ + diff --git a/src/lib/components/sidebar/TemplateSelector.svelte b/src/lib/components/sidebar/TemplateSelector.svelte index 60def17..11156bf 100755 --- a/src/lib/components/sidebar/TemplateSelector.svelte +++ b/src/lib/components/sidebar/TemplateSelector.svelte @@ -4,12 +4,18 @@ editorState, layoutState, solverState, + timelineState, uiState, viewportState, } from "../../state"; - import { ISLAND_TEMPLATES, MAX_CUSTOM_ISLANDS } from "@reactor2/solver"; + import { + formatNumber, + ISLAND_TEMPLATES, + MAX_CUSTOM_ISLANDS, + } from "@reactor2/solver"; + import { STAT_ICON } from "../statIcons"; import type { IslandTemplate } from "../../types/building"; - import { Plus, RotateCcw, Trash2 } from "lucide-svelte"; + import { LandPlot, Plus, RotateCcw, Trash2 } from "lucide-svelte"; import SolveAllButton from "./SolveAllButton.svelte"; import { onDestroy } from "svelte"; import { createConfirmArm } from "../confirmArm.svelte"; @@ -22,6 +28,14 @@ */ const confirm = createConfirmArm(); + /* + * Each shipped island's power, from the pass the header already runs — the + * board on screen live, the rest from their saved layouts. + */ + let islandPower = $derived( + Object.fromEntries(timelineState.islands.map((i) => [i.id, i.power])), + ); + // The sidebar unmounts when collapsed; don't leave a timer poking at state. onDestroy(confirm.disarm); @@ -99,13 +113,18 @@
{#each ISLAND_TEMPLATES as template (template.id)} {@const isModified = layoutState.isTemplateModified(template)} + {@const power = islandPower[template.id] ?? 0}
@@ -133,6 +152,15 @@ {/each}
+ + +
My Islands @@ -221,6 +249,33 @@ .solve-all-slot { margin-bottom: 0.6rem; } + /* Matches SolveAllButton, the other whole-row action in this panel. */ + .stats-btn { + display: flex; + align-items: center; + gap: 0.45rem; + width: 100%; + height: var(--ctl); + margin-top: 0.6rem; + padding: 0 0.75rem; + border: 1px solid var(--border); + border-radius: var(--radius-sm); + background: transparent; + color: var(--text); + font-size: var(--fs-sm); + font-weight: 600; + cursor: pointer; + transition: all var(--dur-fast); + } + .stats-btn:hover { + background: var(--surface-raised); + border-color: var(--accent-dim); + } + @media (pointer: coarse) { + .stats-btn { + height: var(--tap); + } + } .template-list { display: flex; flex-direction: column; @@ -282,6 +337,25 @@ border-radius: var(--radius-xs); letter-spacing: 0.4px; } + /* + * An island's power says more than "Modified" did — the reset button beside + * it already marks a changed island — so it takes the chip's place, in the + * same neutral idiom. "Modified" stays for a changed board with nothing on it. + */ + .badge-power { + display: flex; + align-items: center; + gap: 0.2rem; + font-size: var(--fs-xs); + font-weight: 700; + font-variant-numeric: tabular-nums; + color: var(--text-muted); + } + .badge-power img { + width: 12px; + height: 12px; + object-fit: contain; + } .icon-btn { background: var(--danger-bg); border: 1px solid var(--danger-line); diff --git a/src/lib/pixi/gridPainter.ts b/src/lib/pixi/gridPainter.ts index fa7a600..feb1197 100755 --- a/src/lib/pixi/gridPainter.ts +++ b/src/lib/pixi/gridPainter.ts @@ -953,15 +953,28 @@ export class GridRenderer { } // A move is also an arrow from the tile it leaves to the one it takes, // stopping short of the target's centre so the head sits on its edge. + // A swap is two arrows over the same line, so each is drawn off to its + // own right: opposite arrows land side by side, each head on show. + const paired = (from: { x: number; y: number }, to: typeof from) => + arrows.some( + (o) => + o.from.x === to.x && + o.from.y === to.y && + o.to.x === from.x && + o.to.y === from.y, + ); for (const { from, to } of arrows) { - const a = gridToIso(from.x, from.y); - const b = gridToIso(to.x, to.y); - const dx = b.x - a.x; - const dy = b.y - a.y; + const a0 = gridToIso(from.x, from.y); + const b0 = gridToIso(to.x, to.y); + const dx = b0.x - a0.x; + const dy = b0.y - a0.y; const len = Math.hypot(dx, dy); if (len < 1) continue; const ux = dx / len; const uy = dy / len; + const side = paired(from, to) ? 9 : 0; + const a = { x: a0.x - uy * side, y: a0.y + ux * side }; + const b = { x: b0.x - uy * side, y: b0.y + ux * side }; const tip = { x: b.x - ux * (TILE_HEIGHT / 3), y: b.y - uy * (TILE_HEIGHT / 3), diff --git a/src/lib/simulation/islandStats.test.ts b/src/lib/simulation/islandStats.test.ts new file mode 100644 index 0000000..b386c79 --- /dev/null +++ b/src/lib/simulation/islandStats.test.ts @@ -0,0 +1,169 @@ +import { + buildPrice, + findBuilding, + netSpend, + priceRules, + type Tile, +} from "@reactor2/solver"; +import { describe, expect, it } from "vitest"; +import { + addCounts, + buildingPricing, + changeSpend, + countBuildings, + islandPrice, + nextRemoval, + terrainStats, +} from "./islandStats"; + +const grid = (rows: string[]): Tile[][] => + rows.map((row, y) => + [...row].map((c, x) => ({ + x, + y, + type: ( + { + ".": "grass", + "~": "water", + r: "rock", + t: "tree1", + T: "tree2", + p: "pond", + } as const + )[c]!, + })), + ); + +describe("terrainStats", () => { + it("counts the edge as water and a pond as an obstacle", () => { + // 5×5: the ring touches the board edge, so all of it is shore; the + // centre's eight neighbours are a pond and grass, so it is inland. + const stats = terrainStats( + grid([".....", "..p..", ".....", ".r.t.", "....T"]), + ); + expect(stats).toEqual({ + grass: 21, + shore: 16 - 1, // the ring holds the T + rocks: 1, + trees: 2, + ponds: 1, + }); + }); + + it("finds shore inland of a water tile, corners included", () => { + const stats = terrainStats( + grid([ + ".......", + ".......", + ".......", + "...~...", + ".......", + ".......", + ".......", + ]), + ); + // 24 edge tiles + the 8 around the water. + expect(stats.shore).toBe(24 + 8); + expect(stats.grass).toBe(48); + }); +}); + +describe("counts", () => { + it("tallies and adds per building", () => { + const a = countBuildings([ + { buildingId: "cooler1" }, + { buildingId: "cooler1" }, + { buildingId: "generator" }, + ]); + expect(a).toEqual({ cooler1: 2, generator: 1 }); + addCounts(a, { cooler1: 1, nuclear_reactor: 4 }); + expect(a).toEqual({ cooler1: 3, generator: 1, nuclear_reactor: 4 }); + }); +}); + +describe("buildingPricing", () => { + it("prices the next copy after every copy built, and the rebuild as their sum", () => { + const rules = priceRules({ BuildingsCostMultiplierResearchSO: 9 }); + const base = findBuilding("nuclear_reactor")!.price; + const p = buildingPricing("nuclear_reactor", 3, rules); + expect(p.base).toBe(base); + expect(p.built).toBe(3); + expect(p.next).toBe(buildPrice(base, 3, rules)); + expect(p.rebuild).toBeCloseTo( + buildPrice(base, 0, rules) + + buildPrice(base, 1, rules) + + buildPrice(base, 2, rules), + ); + }); + + it("costs nothing to rebuild with none built", () => { + const p = buildingPricing("cooler1", 0, priceRules({})); + expect(p.rebuild).toBe(0); + expect(p.next).toBe(findBuilding("cooler1")!.price); + }); +}); + +describe("nextRemoval", () => { + it("is five minutes for the first clear with no research", () => { + expect(nextRemoval(0, {})).toEqual({ + removed: 0, + nextSeconds: 300, + freeWindow: 0, + left: 0, + allSeconds: 0, + }); + }); + + it("grows per clear and takes both reductions off, multiplied", () => { + // Clearance Crews 7 (-85%), Phase Breaker 6 (-68%), Erased from Time 7. + const c = nextRemoval(100, { + ObstacleRemovalTimeResearchSO: 7, + phase_breaker: 6, + erased_from_time: 7, + }); + expect(c.nextSeconds).toBeCloseTo(300 * 1.025 ** 100 * 0.15 * 0.32); + expect(c.freeWindow).toBe(7200); + }); +}); + +describe("changeSpend", () => { + it("agrees with the solver's netSpend on the same change", () => { + const rules = priceRules({ + BuildingsCostMultiplierResearchSO: 9, + BuildingSellRefundResearchSO: 10, + }); + const list = (counts: Record) => + Object.entries(counts).flatMap(([buildingId, n]) => + Array.from({ length: n }, () => ({ x: 0, y: 0, buildingId })), + ); + const before = { nuclear_reactor: 5, cooler1: 3, generator: 2 }; + const after = { nuclear_reactor: 8, cooler1: 1, generator2: 4 }; + const elsewhere = { nuclear_reactor: 20, cooler1: 7 }; + expect(changeSpend(after, before, elsewhere, rules)).toBe( + netSpend(list(after), { + cash: 0, + standing: list(before), + elsewhere, + prices: rules, + }), + ); + }); +}); + +describe("clearing everything", () => { + it("adds up each clear's wait past the free window", () => { + const research = { erased_from_time: 1 }; // 900 s free + const c = nextRemoval(0, research, 3); + // 300 s each times 1.025^k, all inside the window. + expect(c.allSeconds).toBe(0); + const late = nextRemoval(200, research, 2); + const t = (k: number) => 300 * 1.025 ** k; + expect(late.allSeconds).toBeCloseTo(t(200) - 900 + (t(201) - 900)); + expect(late.left).toBe(2); + }); + + it("prices the islands the record lists, and nothing else", () => { + expect(islandPrice("area_8")).toBe(3.13e28); + expect(islandPrice("area_99")).toBeNull(); + }); +}); diff --git a/src/lib/simulation/islandStats.ts b/src/lib/simulation/islandStats.ts new file mode 100644 index 0000000..443f582 --- /dev/null +++ b/src/lib/simulation/islandStats.ts @@ -0,0 +1,221 @@ +import { + buildPrice, + computeWaterAdjacency, + countsSpend, + findBuilding, + timeLabLevels, + timeLabResearch, + type BuildingCounts, + type PriceRules, + type Tile, +} from "@reactor2/solver"; + +/** + * What a board holds and what its buildings cost — the figures the island + * stats and the building ribbon print. + * + * Pure functions over a board, so the timeline store can memo them per saved + * code and the board on screen can derive them live from the same code. + */ + +// Counting is the package's, so the counts these figures read are the ones +// its prices are computed over. +export { countBuildings, type BuildingCounts } from "@reactor2/solver"; + +/** `into` plus `from`, per building, written into `into`. */ +export function addCounts(into: BuildingCounts, from: BuildingCounts): void { + for (const [id, n] of Object.entries(from)) into[id] = (into[id] ?? 0) + n; +} + +export interface TerrainStats { + /** Tiles a building can stand on. */ + grass: number; + /** + * Grass beside water, corners included — what Tidal Ascendancy rates. Off + * the board counts as water, as it does in the solver: the shipped maps are + * trimmed from one ocean (`computeWaterAdjacency`). + */ + shore: number; + /** Obstacles still standing, by kind. */ + rocks: number; + trees: number; + /** A pond is an obstacle, not water: it grants no shore. */ + ponds: number; +} + +export function terrainStats(grid: Tile[][]): TerrainStats { + const stats: TerrainStats = { + grass: 0, + shore: 0, + rocks: 0, + trees: 0, + ponds: 0, + }; + const width = grid[0]?.length ?? 0; + const shore = computeWaterAdjacency(grid); + grid.forEach((row, y) => + row.forEach((tile, x) => { + switch (tile.type) { + case "grass": + stats.grass++; + if (shore[y * width + x] === 1) stats.shore++; + break; + case "rock": + stats.rocks++; + break; + case "tree1": + case "tree2": + stats.trees++; + break; + case "pond": + stats.ponds++; + break; + } + }), + ); + return stats; +} + +export interface BuildingPricing { + /** The catalogue's price, before copies and research. */ + base: number; + /** Copies standing across every island — what the price climbs with. */ + built: number; + /** What the next copy costs, research included. */ + next: number; + /** + * What the standing copies cost to buy again from none, at today's + * research. Not what the player paid: research bought since, and copies + * sold and rebought, both make that differ. + */ + rebuild: number; +} + +export function buildingPricing( + id: string, + built: number, + rules: PriceRules, +): BuildingPricing { + const base = findBuilding(id)?.price ?? 0; + let rebuild = 0; + for (let k = 0; k < built; k++) rebuild += buildPrice(base, k, rules); + return { base, built, next: buildPrice(base, built, rules), rebuild }; +} + +/** Obstacles of every kind still standing. */ +export function obstacleCount(t: TerrainStats): number { + return t.rocks + t.trees + t.ponds; +} + +/** + * How long clearing an obstacle takes, from the extractor's progression record + * (`tools/data/progression.json`): five minutes, ×1.025 for every obstacle + * cleared before it, less Clearance Crews (city research) and Phase Breaker + * (Time Lab), which multiply. Erased from Time then finishes a clear for free + * once what is left of it fits its window, so a clear no longer than the + * window costs no wait at all. + * + * "Every obstacle cleared before it" is read as the whole save's count, the way + * a building's price counts copies on every island. + */ +const REMOVAL_BASE_SECONDS = 5 * 60; +const REMOVAL_GROWTH = 1.025; + +/** Clearance Crews: the share of removal time taken off, by level from 1. */ +const CLEARANCE_CREWS = [0.2, 0.38, 0.53, 0.65, 0.74, 0.8, 0.85]; + +/** The research id a game export spells Clearance Crews with. */ +const CLEARANCE_CREWS_ID = "ObstacleRemovalTimeResearchSO"; + +export interface ObstacleClearing { + /** Obstacles cleared so far, on every island. */ + removed: number; + /** How long the next clear takes, in seconds. */ + nextSeconds: number; + /** Erased from Time's free-finish window, in seconds; 0 without it. */ + freeWindow: number; + /** Obstacles left to clear. */ + left: number; + /** + * The wait to clear every one left, one after another, each finished free + * once it fits the window. Clears can run side by side in the game, so + * this is the sum of the waits rather than a date. + */ + allSeconds: number; +} + +/** What one clear waits after the free finish: its length less the window. */ +export const clearWait = (c: { nextSeconds: number; freeWindow: number }) => + Math.max(0, c.nextSeconds - c.freeWindow); + +/** A level's share off, 0 at level 0 and clamped past the table. */ +const levelShare = (table: readonly number[], level: number) => + level > 0 ? table[Math.min(level, table.length) - 1] : 0; + +export function nextRemoval( + removed: number, + research: Readonly>, + left = 0, +): ObstacleClearing { + const lab = timeLabLevels(research); + const crews = levelShare(CLEARANCE_CREWS, research[CLEARANCE_CREWS_ID] ?? 0); + const breaker = levelShare( + timeLabResearch("phase_breaker").values!, + lab.phase_breaker, + ); + const seconds = (cleared: number) => + REMOVAL_BASE_SECONDS * + REMOVAL_GROWTH ** cleared * + (1 - crews) * + (1 - breaker); + const freeWindow = levelShare( + timeLabResearch("erased_from_time").values!, + lab.erased_from_time, + ); + let allSeconds = 0; + for (let k = 0; k < left; k++) + allSeconds += Math.max(0, seconds(removed + k) - freeWindow); + return { + removed, + nextSeconds: seconds(removed), + freeWindow, + left, + allSeconds, + }; +} + +/** + * What changing a board holding `before` into one holding `after` costs, net + * of the sales, `elsewhere` copies on other islands counting towards every + * price. The package's `countsSpend` — the rule `netSpend` and a cash limit + * are computed by — so the figure printed is the one a run is held to. + */ +export function changeSpend( + after: BuildingCounts, + before: BuildingCounts, + elsewhere: BuildingCounts, + rules: PriceRules, +): number { + return countsSpend(after, before, elsewhere, rules); +} + +/** + * What each island costs to buy, by the game's area id — transcribed from the + * extractor's progression record, like the clearing figures above. The + * research that would discount it ships unused. + */ +const ISLAND_PRICES: Record = { + area_1: 0, + area_2: 2e6, + area_3: 1e10, + area_4: 5e13, + area_5: 2.5e17, + area_6: 1.25e21, + area_7: 6.25e24, + area_8: 3.13e28, +}; + +/** An island's price by area id, or null for one the record does not list. */ +export function islandPrice(areaId: string): number | null { + return ISLAND_PRICES[areaId] ?? null; +} diff --git a/src/lib/simulation/moveSteps.test.ts b/src/lib/simulation/moveSteps.test.ts index f2ee1aa..6b76266 100644 --- a/src/lib/simulation/moveSteps.test.ts +++ b/src/lib/simulation/moveSteps.test.ts @@ -22,6 +22,7 @@ import { type BoardBuilding, type MovePlan, type MoveStep, + type StepPricing, } from "./moveSteps"; const b = (buildingId: string, x: number, y: number): BoardBuilding => ({ @@ -61,6 +62,12 @@ function replay(start: readonly BoardBuilding[], plan: MovePlan) { board.delete(at(s.from.x, s.from.y)); board.set(at(s.to.x, s.to.y), s.buildingId); return; + case "swap": + expect(board.get(at(s.a.x, s.a.y)), `step ${i}`).toBe(s.a.buildingId); + expect(board.get(at(s.b.x, s.b.y)), `step ${i}`).toBe(s.b.buildingId); + board.set(at(s.a.x, s.a.y), s.b.buildingId); + board.set(at(s.b.x, s.b.y), s.a.buildingId); + return; case "build": expect(board.has(at(s.x, s.y)), `step ${i} onto taken`).toBe(false); board.set(at(s.x, s.y), s.buildingId); @@ -88,7 +95,7 @@ describe("planMoveSteps", () => { b("generator", 2, 0), b("cooler2", 3, 3), ]; - const plan = await planMoveSteps(start, target, [], [], count); + const plan = await planMoveSteps(start, target, [], count); expect(asSet(replay(start, plan))).toEqual(asSet(target)); expect(asSet(plan.boards.at(-1)!)).toEqual(asSet(target)); @@ -103,7 +110,6 @@ describe("planMoveSteps", () => { [b("cooler1", 0, 0), b("cooler1", 9, 9)], [b("cooler1", 1, 0), b("cooler1", 8, 9)], [], - [], count, ); // Each cooler goes to the wanted tile nearest it, not across the board. @@ -134,7 +140,6 @@ describe("planMoveSteps", () => { { x: 2, y: 2, type: "rock" }, { x: 5, y: 5, type: "tree1" }, ], - [], count, ); expect(plan.steps[0]).toEqual({ @@ -147,54 +152,79 @@ describe("planMoveSteps", () => { expect(plan.steps.filter((s) => s.kind === "clear")).toHaveLength(1); }); - it("breaks a ring of moves by parking one on a free tile", async () => { + it("swaps two buildings that want each other's tile", async () => { const start = [b("cooler1", 0, 0), b("generator", 1, 0)]; const target = [b("generator", 0, 0), b("cooler1", 1, 0)]; - const plan = await planMoveSteps( - start, - target, - [], - [{ x: 5, y: 5 }], - count, - ); + const plan = await planMoveSteps(start, target, [], count); expect(asSet(replay(start, plan))).toEqual(asSet(target)); - expect(plan.steps.some((s) => s.kind === "move" && s.to.x === 5)).toBe( - true, - ); - expect(plan.steps.every((s) => s.kind === "move")).toBe(true); + expect(plan.steps).toEqual([ + { + kind: "swap", + a: { buildingId: "cooler1", x: 0, y: 0 }, + b: { buildingId: "generator", x: 1, y: 0 }, + }, + ]); }); - it("sells and rebuilds to break a ring with nowhere to park", async () => { - const start = [b("cooler1", 0, 0), b("generator", 1, 0)]; - const target = [b("generator", 0, 0), b("cooler1", 1, 0)]; - const plan = await planMoveSteps(start, target, [], [], count); + it("turns a longer ring with nowhere to park by swaps alone", async () => { + // Three buildings each wanting the next one's tile, and no free tile. + const start = [ + b("cooler1", 0, 0), + b("generator", 1, 0), + b("cooler2", 2, 0), + ]; + const target = [ + b("cooler2", 0, 0), + b("cooler1", 1, 0), + b("generator", 2, 0), + ]; + const plan = await planMoveSteps(start, target, [], count); expect(asSet(replay(start, plan))).toEqual(asSet(target)); - expect(plan.steps.some((s) => s.kind === "sell")).toBe(true); - expect(plan.steps.some((s) => s.kind === "build")).toBe(true); + expect(plan.steps.every((s) => s.kind === "swap")).toBe(true); + expect(plan.steps).toHaveLength(2); }); it("replaces a building in place rather than selling and building", async () => { const start = [b("cooler1", 0, 0), b("generator", 1, 0)]; const target = [b("cooler2", 0, 0), b("generator", 1, 0)]; - const plan = await planMoveSteps(start, target, [], [], count); + const plan = await planMoveSteps(start, target, [], count); expect(plan.steps).toEqual([ { kind: "replace", from: "cooler1", to: "cooler2", x: 0, y: 0 }, ]); }); - it("sells everything and starts again when the island changes almost entirely", async () => { + it("sells everything and starts again when nothing on the island survives", async () => { // Five tiles, all changing to buildings found nowhere on the start, and // the target on tiles the start does not use: walking it is ten steps. const start = [0, 1, 2, 3, 4].map((x) => b("cooler1", x, 0)); const target = [0, 1, 2, 3].map((x) => b("generator", x, 5)); - const plan = await planMoveSteps(start, target, [], [], count); + const plan = await planMoveSteps(start, target, [], count); expect(plan.steps[0]).toMatchObject({ kind: "sellAll", count: 5 }); expect(plan.steps).toHaveLength(1 + target.length); expect(asSet(replay(start, plan))).toEqual(asSet(target)); }); + it("never sells everything while a building survives, however many steps it saves", async () => { + // One cooler moves and the rest change: starting again would be one step + // fewer, but it would sell the cooler and buy it back at a loss. + const start = [0, 1, 2, 3, 4].map((x) => b("cooler1", x, 0)); + const target = [ + b("cooler1", 0, 5), + ...[1, 2, 3].map((x) => b("generator", x, 5)), + ]; + const plan = await planMoveSteps(start, target, [], count); + expect(plan.steps.some((s) => s.kind === "sellAll")).toBe(false); + expect(plan.steps).toContainEqual({ + kind: "move", + buildingId: "cooler1", + from: { x: 0, y: 0 }, + to: { x: 0, y: 5 }, + }); + expect(asSet(replay(start, plan))).toEqual(asSet(target)); + }); + it("stops once the island makes the target's power", async () => { // Power is the generators; the target only shuffles the coolers about. const score = (board: ReadonlyMap) => @@ -203,7 +233,6 @@ describe("planMoveSteps", () => { [b("cooler1", 0, 0), b("cooler1", 1, 0)], [b("generator", 5, 5), b("cooler1", 2, 0), b("cooler1", 3, 0)], [], - [], score, { stopAtPower: 1 }, ); @@ -234,7 +263,6 @@ describe("planMoveSteps", () => { running, [...running, b("generator", 2, 0), b("cooler1", 3, 0)], [], - [], score, ); expect( @@ -263,7 +291,7 @@ describe("planMoveSteps", () => { ); const t0 = performance.now(); - const plan = await planMoveSteps([], island.placements, [], [], score); + const plan = await planMoveSteps([], island.placements, [], score); const ms = performance.now() - t0; expect(plan.steps).toHaveLength(island.placements.length); @@ -289,7 +317,6 @@ describe("planMoveSteps", () => { [b("cooler1", 0, 0)], [b("cooler1", 0, 0), b("cooler1", 1, 0), b("cooler1", 2, 0)], [], - [], count, ); // One cooler1 stands elsewhere too: two copies before the first build. @@ -305,7 +332,6 @@ describe("planMoveSteps", () => { [b("cooler1", 0, 0), b("generator", 5, 5)], [b("cooler2", 0, 0), b("generator", 6, 5)], [], - [], count, ); const prices = priceSteps( @@ -330,7 +356,6 @@ describe("planMoveSteps", () => { start, [b("generator", 9, 9)], [], - [], count, ); expect(plan.steps[0].kind).toBe("sellAll"); @@ -339,4 +364,84 @@ describe("planMoveSteps", () => { expect(prices[0]).toEqual({ spend: 0, refund: 700 }); }); }); + + describe("under prices", () => { + // Each type its own base, each copy x2, refunds of half the current price. + const BASE: Record = { + cooler1: 300, + cooler2: 100, + generator: 50, + nuclear_reactor: 700, + }; + const pricing = (copies: Map): StepPricing => ({ + copies, + build: (id, n) => BASE[id] * 2 ** n, + refund: (id, n) => (n > 0 ? BASE[id] * 2 ** n * 0.5 : 0), + }); + /** What MoveStepsBar prints: the net, and the most needed at once. */ + const money = (plan: MovePlan, p: StepPricing) => { + let running = 0; + let peak = 0; + for (const s of priceSteps(plan, p.copies, p.build, p.refund)) { + running += s.spend - s.refund; + peak = Math.max(peak, running); + } + return { net: running, peak }; + }; + + it("sells before the build the sale pays for, power waiting on cash", async () => { + // More buildings is more power, so on power alone the new cooler goes + // in first, and 100 is needed at once for a change that pays out 200. + const start = [b("generator", 0, 0), b("cooler1", 1, 0)]; + const target = [b("generator", 0, 0), b("cooler2", 2, 0)]; + const p = pricing(new Map([["cooler1", 1]])); + + const free = await planMoveSteps(start, target, [], count); + expect(free.steps.map((s) => s.kind)).toEqual(["build", "sell"]); + expect(money(free, p).peak).toBe(100); + + const plan = await planMoveSteps(start, target, [], count, { cash: p }); + expect(plan.steps.map((s) => s.kind)).toEqual(["sell", "build"]); + expect(money(plan, p)).toEqual({ net: -200, peak: 0 }); + expect(asSet(replay(start, plan))).toEqual(asSet(target)); + }); + + it("never needs more at once than the change costs, on any board", async () => { + // A seeded walk over small random boards: sells, builds, replaces, + // moves and swaps mixed, with copies on other islands. + let seed = 7; + const rand = () => { + seed = (seed * 1103515245 + 12345) % 2 ** 31; + return seed / 2 ** 31; + }; + const ids = Object.keys(BASE); + const board = () => { + const tiles = new Map(); + for (let k = 0; k < 7; k++) { + const x = Math.floor(rand() * 4); + const y = Math.floor(rand() * 3); + tiles.set(`${x},${y}`, b(ids[Math.floor(rand() * ids.length)], x, y)); + } + return [...tiles.values()]; + }; + for (let trial = 0; trial < 60; trial++) { + const start = board(); + const target = board(); + const copies = new Map(); + for (const id of ids) copies.set(id, Math.floor(rand() * 3)); + for (const s of start) + copies.set(s.buildingId, copies.get(s.buildingId)! + 1); + const p = pricing(copies); + + const plan = await planMoveSteps(start, target, [], count, { + cash: p, + }); + const { net, peak } = money(plan, p); + expect(peak, `trial ${trial}`).toBeLessThanOrEqual( + Math.max(0, net) * (1 + 1e-9), + ); + expect(asSet(replay(start, plan))).toEqual(asSet(target)); + } + }); + }); }); diff --git a/src/lib/simulation/moveSteps.ts b/src/lib/simulation/moveSteps.ts index 3ab5b79..d8a6823 100644 --- a/src/lib/simulation/moveSteps.ts +++ b/src/lib/simulation/moveSteps.ts @@ -14,10 +14,14 @@ import type { TileType } from "../types"; * lead: they free ground, change no power, and in the game they are timers * worth starting early. * - * When the island changes almost entirely — a new roster swaps most of its + * When the island changes entirely — a new roster swaps every one of its * buildings — walking it tile by tile is longer than starting again, so the - * plan opens with one **sell everything** and builds from there. Whichever of - * the two routes takes fewer steps is the one planned. + * plan opens with one **sell everything** and builds from there. Only then, + * though: a building the target keeps, where it stands or moved, would be sold + * at a share of its price and bought back at the next copy's, and a step saved + * is not worth cash lost — under a cash limit, it is the difference between a + * plan the budget pays for and one it does not. With nothing kept the two + * routes buy and sell the same copies, so the shorter is planned. * * The order is greedy on power. At every step each action that can be taken * now — a sell or a replace always can; a move or a build once its tile is @@ -28,10 +32,20 @@ import type { TileType } from "../types"; * the solve's power well before it *is* the solve; with `stopAtPower` the plan * ends there, since the rest would only rearrange it. * - * Moves can block each other in a ring — A wants B's tile while B wants A's. - * The ring is broken by parking one building on a free tile and moving it on - * once its destination opens; with no free tile at all, by selling it and - * building it again. + * Power is not the only thing a step can run short of: a build put ahead of + * the sale that pays for it needs cash the finished change does not. Given + * the prices (`PlanOptions.cash`), no step is taken that would leave more + * spent, net of refunds so far, than the whole change costs — or than + * nothing, for a change that pays out. So the most a player must hold at once + * is never more than the layout's own net spend, the figure a cash limit + * holds it to. Among the steps that fit, power still decides. + * + * A move onto a tile another building is still waiting to leave is a + * **swap**: the game trades two buildings' places in one action. So moves can + * never block each other — not in a ring where A wants B's tile while B wants + * A's, nor on a board with no free tile — and nothing is ever sold to be built + * again. A swap finishes the one move, and the other building moves on from + * where it landed, if it is not already home. */ export interface Pos { @@ -47,6 +61,8 @@ export type MoveStep = | { kind: "clear"; x: number; y: number; obstacle: TileType } | { kind: "sellAll"; count: number; tiles: Pos[] } | { kind: "move"; buildingId: string; from: Pos; to: Pos } + /** `a` and `b` trade tiles: `a` ends at `b`'s, `b` at `a`'s. */ + | { kind: "swap"; a: BoardBuilding; b: BoardBuilding } | { kind: "replace"; from: string; to: string; x: number; y: number } | { kind: "build"; buildingId: string; x: number; y: number } | { kind: "sell"; buildingId: string; x: number; y: number }; @@ -73,17 +89,75 @@ export interface PlanOptions { cancelled?: () => boolean; /** End the plan once the board makes this much. */ stopAtPower?: number; + /** + * Prices to order by: no step may push the cash needed at once past what + * the whole change costs net (or past nothing, for one that pays out). + */ + cash?: StepPricing; } +/** + * The prices a plan is charged at. `copies` is each building's count across + * all the player's islands before the first step; `build` and `refund` are + * `buildPrice` and `sellRefund` from the solver package, passed in so this + * module stays free of the rules' tables. + */ +export interface StepPricing { + copies: ReadonlyMap; + build: (buildingId: string, copies: number) => number; + refund: (buildingId: string, copies: number) => number; +} + +/** + * The copies standing as a plan goes, and what each purchase and sale comes + * to: a build at the next copy's price, a sale refunding a share of the + * current one, the count moving with each. + */ +function cashLedger(p: StepPricing) { + const count = new Map(p.copies); + const n = (id: string) => count.get(id) ?? 0; + return { + /** What buying one would cost now. */ + buyPrice: (id: string) => p.build(id, n(id)), + /** What selling one would pay back now. */ + sellPrice: (id: string) => p.refund(id, n(id)), + buy(id: string) { + const price = p.build(id, n(id)); + count.set(id, n(id) + 1); + return price; + }, + sell(id: string) { + const back = p.refund(id, n(id)); + count.set(id, Math.max(0, n(id) - 1)); + return back; + }, + }; +} + +/** + * Relative slack for "within the cash": spends sum terms across thirty orders + * of magnitude, so they are compared against the size of their own terms. + */ +const CASH_TOLERANCE = 1e-9; + const key = (p: Pos) => `${p.x},${p.y}`; const dist = (a: Pos, b: Pos) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y); /** Steps of equal power go in this order: no sense selling what could move. */ -const PRIORITY = { move: 0, replace: 1, build: 2, sell: 3 } as const; +const PRIORITY = { move: 0, swap: 1, replace: 2, build: 3, sell: 4 } as const; /** Power within this fraction of the target counts as reaching it. */ const REACHED = 1e-9; +/** A step the planner could take next, measured. */ +interface Choice { + power: number; + rank: number; + /** Cash out, net of what it refunds; 0 without prices. */ + cost: number; + apply: () => void; +} + interface PendingMove { buildingId: string; from: Pos; @@ -95,6 +169,8 @@ interface Diff { replaces: { from: string; to: string; x: number; y: number }[]; builds: BoardBuilding[]; sells: BoardBuilding[]; + /** Start buildings the target keeps on their own tile. */ + kept: number; } /** What separates two boards, paired into moves and replaces. */ @@ -155,10 +231,20 @@ function diffBoards( sells.push(out); } } - return { moves, replaces, builds: [...arrivingAt.values()], sells }; + return { + moves, + replaces, + builds: [...arrivingAt.values()], + sells, + kept: start.length - leaving.length, + }; } -/** Steps a route takes, clears aside: tile by tile, or sell everything. */ +/** + * Steps a route takes, clears aside: tile by tile, or sell everything — the + * latter only open when no building survives into the target, so it never + * costs more cash than the walk. + */ function routeLengths( start: readonly BoardBuilding[], target: readonly BoardBuilding[], @@ -170,7 +256,10 @@ function routeLengths( diff.replaces.length + diff.builds.length + diff.sells.length, - restart: start.length > 0 ? 1 + target.length : Infinity, + restart: + start.length > 0 && diff.kept === 0 && diff.moves.length === 0 + ? 1 + target.length + : Infinity, }; } @@ -200,7 +289,6 @@ export async function planMoveSteps( start: readonly BoardBuilding[], target: readonly BoardBuilding[], obstacles: readonly (Pos & { type: TileType })[], - freeTiles: readonly Pos[], score: (board: ReadonlyMap) => number, options: PlanOptions = {}, ): Promise { @@ -241,12 +329,39 @@ export async function planMoveSteps( steps.push({ kind: "clear", x: o.x, y: o.y, obstacle: o.type }); snapshot(); } + /* + * The cash. Each type's count only rises or only falls — one leaving and + * one arriving would have been paired into a move — so what the change + * costs net is the same in any order, and that is the ceiling. It is always + * reachable: a sale lowers the cash out, and with none left the cheapest + * build or replace now costs at most its share of what remains, since + * prices climb with copies and refunds fall with them. + */ + const ledger = options.cash ? cashLedger(options.cash) : null; + let spent = 0; + let ceiling = Infinity; + if (options.cash) { + const all = cashLedger(options.cash); + let net = 0; + if (fresh) for (const b of start) net -= all.sell(b.buildingId); + for (const s of sells) net -= all.sell(s.buildingId); + for (const r of replaces) net += all.buy(r.to) - all.sell(r.from); + for (const b of builds) net += all.buy(b.buildingId); + ceiling = Math.max(0, net); + } + const fits = (cost: number) => + spent + cost <= + ceiling + + CASH_TOLERANCE * + Math.max(Math.abs(ceiling), Math.abs(spent), Math.abs(cost)); + if (fresh) { steps.push({ kind: "sellAll", count: state.size, tiles: start.map(({ x, y }) => ({ x, y })), }); + if (ledger) for (const id of state.values()) spent -= ledger.sell(id); state.clear(); snapshot(); } @@ -280,21 +395,62 @@ export async function planMoveSteps( while (pending() > 0 && !reached()) { await breathe(); - let best: { power: number; rank: number; apply: () => void } | null = null; - const consider = (power: number, rank: number, apply: () => void) => { + let best: Choice | null = null; + // Should no step fit the cash — only rounding could do that — the + // cheapest is taken rather than none. + let cheapest: Choice | null = null; + const consider = ( + power: number, + rank: number, + cost: number, + apply: () => void, + ) => { + const c: Choice = { power, rank, cost, apply }; + if (!cheapest || cost < cheapest.cost) cheapest = c; + if (!fits(cost)) return; if ( !best || power > best.power || (power === best.power && rank < best.rank) ) - best = { power, rank, apply }; + best = c; }; + const buyCost = (id: string) => (ledger ? ledger.buyPrice(id) : 0); + const sellBack = (id: string) => (ledger ? ledger.sellPrice(id) : 0); moves.forEach((m, i) => { - if (state.has(key(m.to))) return; + if (state.has(key(m.to))) { + // Taken by a building still to move: swap the two. + const j = moves.findIndex((o) => key(o.from) === key(m.to)); + if (j < 0) return; + const other = moves[j]; + const fromKey = key(m.from); + const toKey = key(m.to); + state.set(toKey, m.buildingId); + state.set(fromKey, other.buildingId); + const power = score(state); + state.set(toKey, other.buildingId); + state.set(fromKey, m.buildingId); + consider(power, PRIORITY.swap, 0, () => { + state.set(toKey, m.buildingId); + state.set(fromKey, other.buildingId); + steps.push({ + kind: "swap", + a: { buildingId: m.buildingId, ...m.from }, + b: { buildingId: other.buildingId, ...m.to }, + }); + other.from = { ...m.from }; + // Drop both if the other is now home, the later index first. + const done = [i]; + if (key(other.from) === key(other.to)) done.push(j); + for (const k of done.sort((x, y) => y - x)) moves.splice(k, 1); + }); + return; + } consider( tryOn(m.from, { ...m.to, id: m.buildingId }), PRIORITY.move, + 0, () => { moves.splice(i, 1); state.delete(key(m.from)); @@ -307,61 +463,47 @@ export async function planMoveSteps( consider( tryOn(null, { x: r.x, y: r.y, id: r.to }), PRIORITY.replace, + buyCost(r.to) - sellBack(r.from), () => { replaces.splice(i, 1); state.set(key(r), r.to); steps.push({ kind: "replace", ...r }); + if (ledger) { + const back = ledger.sell(r.from); + spent += ledger.buy(r.to) - back; + } }, ); }); builds.forEach((b, i) => { if (state.has(key(b))) return; - consider(tryOn(null, { ...b, id: b.buildingId }), PRIORITY.build, () => { - builds.splice(i, 1); - state.set(key(b), b.buildingId); - steps.push({ kind: "build", ...b }); - }); + consider( + tryOn(null, { ...b, id: b.buildingId }), + PRIORITY.build, + buyCost(b.buildingId), + () => { + builds.splice(i, 1); + state.set(key(b), b.buildingId); + steps.push({ kind: "build", ...b }); + if (ledger) spent += ledger.buy(b.buildingId); + }, + ); }); sells.forEach((s, i) => { - consider(tryOn(s, null), PRIORITY.sell, () => { + consider(tryOn(s, null), PRIORITY.sell, -sellBack(s.buildingId), () => { sells.splice(i, 1); state.delete(key(s)); steps.push({ kind: "sell", ...s }); + if (ledger) spent -= ledger.sell(s.buildingId); }); }); - if (best) { - (best as { apply: () => void }).apply(); - snapshot(); - continue; - } - - // Only moves are left and every one is blocked: a ring. Park the first - // on a free tile no pending step wants, or sell and rebuild it. - const m = moves[0]; - const wanted = new Set([ - ...moves.map((p) => key(p.to)), - ...builds.map(key), - ]); - const park = freeTiles.find( - (t) => !state.has(key(t)) && !wanted.has(key(t)), - ); - if (park) { - state.delete(key(m.from)); - state.set(key(park), m.buildingId); - steps.push({ - kind: "move", - buildingId: m.buildingId, - from: m.from, - to: park, - }); - m.from = park; - } else { - moves.shift(); - state.delete(key(m.from)); - steps.push({ kind: "sell", buildingId: m.buildingId, ...m.from }); - builds.push({ buildingId: m.buildingId, ...m.to }); - } + // Every pending step is always takeable — a sell or a replace at once, a + // build onto a tile only a mover can hold, and a blocked move as a swap — + // so there is always a best, or under prices at least a cheapest. + const chosen = (best ?? cheapest) as Choice | null; + if (!chosen) throw new Error("No step can be taken: the plan is stuck."); + chosen.apply(); snapshot(); } @@ -378,46 +520,32 @@ export interface StepPrice { /** * Prices a plan's steps in order, as the game would charge them: each build * at the next copy's price and each sale refunding a share of the current - * one, the copies counted across every island and moving with every step. - * - * `copies` is each building's count across all the player's islands before - * the first step; `baseOf` its base price. Prices come from `buildPrice` and - * `sellRefund` in the solver package, passed in so this module stays free of - * the rules' tables. + * one, the copies counted across every island and moving with every step — + * the ledger the planner orders by under `PlanOptions.cash`. `copies`, + * `build` and `refund` are a `StepPricing`'s. */ export function priceSteps( plan: MovePlan, copies: ReadonlyMap, - build: (buildingId: string, copies: number) => number, - refund: (buildingId: string, copies: number) => number, + build: StepPricing["build"], + refund: StepPricing["refund"], ): StepPrice[] { - const count = new Map(copies); - const n = (id: string) => count.get(id) ?? 0; - const sell = (id: string) => { - const r = refund(id, n(id)); - count.set(id, Math.max(0, n(id) - 1)); - return r; - }; - const buy = (id: string) => { - const p = build(id, n(id)); - count.set(id, n(id) + 1); - return p; - }; + const ledger = cashLedger({ copies, build, refund }); return plan.steps.map((step, i) => { switch (step.kind) { case "build": - return { spend: buy(step.buildingId), refund: 0 }; + return { spend: ledger.buy(step.buildingId), refund: 0 }; case "sell": - return { spend: 0, refund: sell(step.buildingId) }; + return { spend: 0, refund: ledger.sell(step.buildingId) }; case "replace": { - const back = sell(step.from); - return { spend: buy(step.to), refund: back }; + const back = ledger.sell(step.from); + return { spend: ledger.buy(step.to), refund: back }; } case "sellAll": return { spend: 0, refund: plan.boards[i].reduce( - (sum, b) => sum + sell(b.buildingId), + (sum, b) => sum + ledger.sell(b.buildingId), 0, ), }; diff --git a/src/lib/simulation/simulator.ts b/src/lib/simulation/simulator.ts index 4de6024..089d5ff 100755 --- a/src/lib/simulation/simulator.ts +++ b/src/lib/simulation/simulator.ts @@ -9,7 +9,7 @@ import { type EffectiveBuilding, type PrestigeScales, } from "@reactor2/solver"; -import { unscoredPlacement } from "../data/placements"; +import { placementStatus, unscoredPlacement } from "../data/placements"; import type { BuildingDefinition, PlacedBuilding, Tile } from "../types"; /** @@ -198,6 +198,43 @@ export function boardPower( return simulateIsland(placement, ctx).totalPower; } +/** A board's power, and how many of its buildings are not working. */ +export interface BoardHealth { + power: number; + /** Buildings doing nothing: no neighbour to work with. */ + idle: number; + /** Buildings overheating: their waste heat is not cooled. */ + starved: number; +} + +/** + * `boardPower` with the buildings' states counted as well, by the readout's + * own rule (`placementStatus`). Its own context for the same reason. + */ +export function boardHealth( + grid: Tile[][], + buildings: readonly BuildingDefinition[], + placedBuildings: readonly PlacedBuilding[], + prestige?: PrestigeScales, + anomaly: AnomalyDefinition = getAnomaly(undefined), +): BoardHealth { + const health: BoardHealth = { power: 0, idle: 0, starved: 0 }; + if (!grid?.length || !grid[0]?.length || placedBuildings.length === 0) { + return health; + } + const ctx = buildIslandContext(grid, undefined, anomaly); + if (ctx.n === 0) return health; + const { placement } = layoutFor(ctx, buildings, placedBuildings, prestige); + const scored = simulateIsland(placement, ctx, true); + health.power = scored.totalPower; + for (const row of scored.placements) { + const status = placementStatus(row); + if (status === "idle") health.idle++; + else if (status === "starved") health.starved++; + } + return health; +} + /** * Scores many versions of one board fast: the island context is built once, * and each building's rating on each tile is resolved once and reused. diff --git a/src/lib/state/CLAUDE.md b/src/lib/state/CLAUDE.md index de97a58..71a1a44 100644 --- a/src/lib/state/CLAUDE.md +++ b/src/lib/state/CLAUDE.md @@ -65,6 +65,31 @@ The search side is in `docs/SOLVER.md`; the readout's plan line in uses. Null during a run and on a preview, which is someone else's board at their tiers. +## The cash limit: the app side + +The search side is in `docs/SOLVER.md`. + +- **`configState.cashLimit` is a figure the player types**, persisted, null for + none. Never read off a game export: its cash is stale by the time anyone + solves. +- **`uiState` builds the `CashBudget` at launch** (`#cashBudget`), because the + price research is on the timeline and `solverState` cannot read it. What + stands is `layoutState.placements` — the board in Edit is the player's, a + shown solve is not — and every other game island's copies come from + `timelineState.copiesOnOtherIslands()`, the same count step mode prices with, + read through the memo the island figures fill. Reading it makes the launch + asynchronous, so `#launching` refuses a second press until the run has + started, and a launch whose island was switched away in the meantime is + dropped rather than solving the new island within the old one's budget. +- **A held layout over the limit defends nothing**: `runOptimizer` drops it from + `previousVariants`, so "keep the better one" never keeps an unaffordable board. + And **landmasses from two boards are not combined** under a limit: each board + fit it, and one landmass of each together may not. That covers both runs + (`#composeIslands`) and the player's own mixing — `islandPickers` is empty + while a limit is set. +- **Solve all is hidden** while a limit is set (`canSolveAll`): one figure + cannot be handed to every island in turn. + ## The stores **`layoutState` imports nothing from the rest of the state layer.** It is the @@ -299,6 +324,24 @@ keeping them apart is the point.** eight islands through it would evict it each time. Answers are memoised by board code and rules, and the board on screen is skipped, since it is re-saved after every paint. Custom islands and a previewed layout are not counted. +- **`islands` and `copies` ride on the same pass.** `refreshIslands` also reads + each saved board's building counts and terrain (`simulation/islandStats.ts`), + memoised by code alone since neither depends on the rules; the board on + screen is derived live, by the same rule as its power. `copies` sums them + over every game island, which is what a price climbs with, so the HUD + ribbon's and the Buildings card's "next copy" price and `IslandStatsModal` + all read one count. `priceRules` comes off the last import's research, the + base rules with none — the same fallback the cash limit takes. The same + pass scores each board's idle and overheating buildings (`boardHealth`) and + keeps each stored solve's counts, so an island's `solveCost` is + `changeSpend` from its board to its solve, the other islands' copies + counting towards every price. +- **Obstacle figures read the game's boards when imported.** Cleared counts + are the map's obstacles less what stands on the import's board — a board + here may be a plan — and `obstacleClearing` prices the next clear by the + whole save's count (5 min × 1.025 per clear, less Clearance Crews and Phase + Breaker, finished free inside Erased from Time's window). The player + confirmed it against the game. - **`projection` is the game's, run forward.** It is the last import's timeline carried from `exportedAt` to `now` at `record.energyPerTick` — the power the game's own boards made, scored at import from the _resolved_ levels rather than @@ -365,8 +408,9 @@ move steps and their prices — works the same either way. What to buy with the Chronons a jump leaves. The levels are the game's, read off the import (`timelineState.timeLabLevels`); the plan is extra levels on top -(`timeLabPlan`), kept for the session and cleared by an import, since it is -priced against the levels the last code reported. **The budget is the target's** +(`timeLabPlan`), kept for the session and cleared by an import that changes +what it was priced against — a jump, another anomaly, levels bought, less power +(`continuesRun`); a later code from the same run keeps it, and the target too. **The budget is the target's** — `targetEta.held`, what the panel says a jump would leave — plus the +88 when `planWithBonus` is set and an anomaly is left to earn it, so moving the target re-prices the plan. @@ -392,27 +436,35 @@ they say they are. The clears come from the game's board as imported game. Prices count each building's copies on the boards here, this island from Edit. The kinds are what the game allows: a building can be **moved** (paired with one of its kind wanted -elsewhere, nearest first) and put down **on top of another** (a tile whose -building changes is one **replace**); the rest are sells and builds, and clears -lead. When the island changes almost entirely, one **sell everything** and the -builds is the shorter route, and whichever route is shorter is planned. +elsewhere, nearest first), two can trade tiles in one **swap** (so moves never +block each other and nothing is sold to be rebuilt, even with no free tile), and +one can be put down **on top of another** (a tile whose building changes is one +**replace**); the rest are sells and builds, and clears +lead. When **nothing** on the island survives into the target, one **sell +everything** and the builds may be the shorter route, and is then planned; one +building kept or moved rules it out, since selling it at a share of its price and +buying it back at the next copy's loses cash a step saved is not worth — under a +cash limit, enough to put the steps over a budget the layout itself fits. **As few steps as it takes.** Of a solve's tied layouts, the one nearest the island (`stepCount`) is put on screen and aimed at. The order is greedy on power — each step takes the available action that leaves the most — so the gains come first, and the plan **stops at the solve's power** (`stopAtPower`, scored by the same scorer): what would be left only rearranges buildings, and the last step -says so. An island already at the solve's power gets no plan, just a toast. +says so. **Under a cash limit cash comes first** (`PlanOptions.cash`): no step +may take the cash needed at once past what the whole change costs net, so a +sale that pays for a build comes before it and a layout that fits the limit +never has a step that does not; power orders the steps that fit. An island already at the solve's power gets no plan, just a toast. Every candidate is scored by `createBoardScorer` — one island context, each building's rating per tile cached — ~0.2ms a board; the planner yields every 30ms and reports progress. **Step mode shows the one building a step is about.** The canvas fades every other building, pad and badge to 40% (`GridRenderer.setFocus`) and draws the -step's own a little larger, drops the state and anomaly icons and the pulse, -outlines the step's tiles on the ground beneath their buildings and draws a -move as an arrow over everything. The fill gauges stay: how hard each building works after a step is half -of what the step is for, and with them gone players read the board as broken. +step's own a little larger, drops the fill gauges, the state and anomaly icons +and the pulse, outlines the step's tiles on the ground beneath their buildings +and draws a move as an arrow over everything — a swap as two, side by side. The +step bar carries the power. **Step mode is a sub-mode of the solver view.** While `stepsActive`, `visiblePlacements` is the scored board after the step on screen, so the canvas, @@ -693,6 +745,16 @@ deliberately does not overwrite the current custom island, since that would be a destructive act with no undo behind a button marked "Import". At `MAX_CUSTOM_ISLANDS` it refuses and says so. +**A code drawn on a shipped map may also land there, beside that default.** +`layoutState.matchingTemplate` recognises a board that is a shipped map with +nothing changed but obstacles cleared (`sameMap`) — exactly what a saved layout +on that island can be, so writing it there keeps the fixed-map rule. +`importOntoTemplate` writes it through `importGameIslands`, and Import offers it +as a second button behind two presses, since it replaces that island's board. +The island's solve goes through `carryOverSolves`, as after a game import — +narrowed to that island, so no other island's solve is judged by it. +`state/importOnto.test.ts` pins the match and the refusals. + **A game code is the one exception, and it keeps the rule.** The game's Export to Optimizer button writes an `R2X1.` code (`encoding/gameExport.ts`; the spec the game was built from is `docs/game-export.md`) holding the player's whole diff --git a/src/lib/state/config.svelte.ts b/src/lib/state/config.svelte.ts index dcce3d4..43fea0d 100755 --- a/src/lib/state/config.svelte.ts +++ b/src/lib/state/config.svelte.ts @@ -16,6 +16,7 @@ import { import { anomalyStorage, buildingStorage, + cashLimitStorage, prestigeStorage, upgradePlanStorage, } from "../storage/storage"; @@ -102,8 +103,23 @@ class ConfigState { resolveUpgradePlan(BUILDINGS, this.buildingUpgrades, this.upgradePlan), ); + /** + * The most a run may spend changing the board into its layout, net of what + * the sales pay back — or null, and a run maximises power at any price. + * + * A solve input like the plan beside it: the player's cash is one figure + * across every island, so it is set once rather than per board, and the + * board it is spent from is whichever one the run starts on. Persisted. + * + * It is typed by the player rather than read off a game export, whose cash + * is a snapshot from the moment of export and is stale by the time anyone + * solves with it. + */ + cashLimit = $state(null); + constructor() { this.loadCatalog(); + this.cashLimit = cashLimitStorage.loadCashLimit(); this.anomalyId = anomalyStorage.loadAnomaly(); this.prestigeLevels = prestigeStorage.loadPrestige(); this.upgradePlan = upgradePlanStorage.loadPlan(); @@ -193,6 +209,13 @@ class ConfigState { upgradePlanStorage.savePlan($state.snapshot(this.upgradePlan)); } + /** Sets the cash limit; null, or anything not a cash figure, clears it. */ + setCashLimit(cash: number | null) { + this.cashLimit = + cash !== null && Number.isFinite(cash) && cash >= 0 ? cash : null; + cashLimitStorage.saveCashLimit(this.cashLimit); + } + loadCatalog() { const saved = buildingStorage.loadBuildings(); const keys = Object.keys(saved); diff --git a/src/lib/state/importOnto.test.ts b/src/lib/state/importOnto.test.ts new file mode 100644 index 0000000..5b68193 --- /dev/null +++ b/src/lib/state/importOnto.test.ts @@ -0,0 +1,74 @@ +/** + * A share code drawn on a shipped map may land on that island: the map with + * obstacles cleared and buildings placed is exactly a saved layout there. + * Anything else — another size, a painted tile, an obstacle added — is not + * that island and still needs a custom slot. + */ +import { + decodeBlueprint, + encodeBlueprint, + ISLAND_TEMPLATES, + type Tile, +} from "@reactor2/solver"; +import { describe, expect, it } from "vitest"; +import { isObstacleType } from "../types/grid"; +import { layoutState } from "./layout.svelte"; + +const island = ISLAND_TEMPLATES.find((t) => t.id === "island2")!; + +async function mapGrid(): Promise { + return (await decodeBlueprint(island.code)).grid; +} + +const find = (grid: Tile[][], ok: (t: Tile) => boolean) => + grid.flat().find(ok)!; + +describe("a share code drawn on a shipped map", () => { + it("matches its island with obstacles cleared and buildings placed", async () => { + const grid = await mapGrid(); + const rock = find(grid, (t) => isObstacleType(t.type)); + grid[rock.y][rock.x] = { ...rock, type: "grass" }; + const grass = find(grid, (t) => t.type === "grass"); + const code = await encodeBlueprint(grid, [ + { x: grass.x, y: grass.y, buildingId: "cooler1" }, + ]); + expect((await layoutState.matchingTemplate(code))?.id).toBe(island.id); + }); + + it("does not match once a tile is painted or an obstacle added", async () => { + const painted = await mapGrid(); + const water = find(painted, (t) => t.type === "water"); + painted[water.y][water.x] = { ...water, type: "grass" }; + expect( + await layoutState.matchingTemplate(await encodeBlueprint(painted, [])), + ).toBeNull(); + + const added = await mapGrid(); + const grass = find(added, (t) => t.type === "grass"); + added[grass.y][grass.x] = { ...grass, type: "rock" }; + expect( + await layoutState.matchingTemplate(await encodeBlueprint(added, [])), + ).toBeNull(); + }); + + it("lands on that island as its board, and opens it", async () => { + await layoutState.hydrate({}); + const grid = await mapGrid(); + const grass = find(grid, (t) => t.type === "grass"); + const code = await encodeBlueprint(grid, [ + { x: grass.x, y: grass.y, buildingId: "cooler1" }, + ]); + await layoutState.importOntoTemplate(code, island.id, { cooler1: 0 }); + expect(layoutState.activeTemplateId).toBe(island.id); + expect(layoutState.placements).toHaveLength(1); + expect(layoutState.isTemplateModified(island)).toBe(true); + expect(layoutState.customIslands).toHaveLength(0); + }); + + it("refuses an island the code is not drawn on", async () => { + const code = await encodeBlueprint(await mapGrid(), []); + await expect( + layoutState.importOntoTemplate(code, "island1", {}), + ).rejects.toThrow("not drawn on that island"); + }); +}); diff --git a/src/lib/state/layout.svelte.ts b/src/lib/state/layout.svelte.ts index 69dd9ae..0c8f17a 100755 --- a/src/lib/state/layout.svelte.ts +++ b/src/lib/state/layout.svelte.ts @@ -938,6 +938,57 @@ class LayoutState { } } + /** + * The shipped island a share code is drawn on, or null. A match is a board + * a shipped island could become: the same size, and every tile its map's — + * or grass where the map has an obstacle, cleared. Those are the only + * changes a fixed map allows, so a matching code can land on that island + * without breaking the rule; anything else still needs a custom slot. + */ + async matchingTemplate(code: string): Promise { + let decoded: DecodedBlueprint; + try { + decoded = await decodeBlueprint(code.trim()); + } catch { + return null; + } + for (const template of ISLAND_TEMPLATES) { + const map = await this.#decodeTemplate(template); + if (map && sameMap(map, decoded)) return template; + } + return null; + } + + /** + * Puts a share code on the shipped island it matches (`matchingTemplate`), + * replacing that island's board, and opens it. The caller asks twice: the + * board it replaces has no undo once another board is on screen. + * + * Written as a game import writes its islands — the code's own grid is the + * map with some obstacles cleared, which is exactly a saved layout. + * + * Throws with a message meant to be shown as-is. + */ + async importOntoTemplate( + code: string, + templateId: string, + unlockedUpgrades: Record, + ) { + const template = ISLAND_TEMPLATES.find((t) => t.id === templateId); + const decoded = await decodeBlueprint(code.trim()).catch(() => null); + const map = template ? await this.#decodeTemplate(template) : null; + if (!template || !decoded || !map || !sameMap(map, decoded)) { + throw new Error("That code is not drawn on that island."); + } + await this.importGameIslands( + [{ templateId, grid: decoded.grid, placements: decoded.placements }], + unlockedUpgrades, + ); + if (this.activeTemplateId !== templateId) { + await this.loadTemplate(template, unlockedUpgrades); + } + } + /** * Every board as storage holds it, with the one on screen encoded now * rather than whenever its queued save lands — what a transfer code sends. @@ -1380,4 +1431,21 @@ class LayoutState { } } +/** + * Whether `board` is `map` with nothing changed but obstacles cleared: the + * same size, and every tile the map's own or grass where the map has an + * obstacle. See `LayoutState.matchingTemplate`. + */ +function sameMap(map: DecodedBlueprint, board: DecodedBlueprint): boolean { + if (map.width !== board.width || map.height !== board.height) return false; + return map.grid.every((row, y) => + row.every((tile, x) => { + const type = board.grid[y]?.[x]?.type; + return ( + type === tile.type || (type === "grass" && isObstacleType(tile.type)) + ); + }), + ); +} + export const layoutState = new LayoutState(); diff --git a/src/lib/state/solveCarryOver.test.ts b/src/lib/state/solveCarryOver.test.ts index 7960fe9..14f8c4c 100644 --- a/src/lib/state/solveCarryOver.test.ts +++ b/src/lib/state/solveCarryOver.test.ts @@ -138,6 +138,13 @@ describe("carrying stored solves through a game import", () => { expect(solverStorage.loadSolve(ISLAND)).toBeNull(); }); + it("leaves islands outside `only` alone", async () => { + // A share code laid onto another island must not judge this one's solve. + stage([layout(0)], 0, "cryo_nexus"); + await solverState.carryOverSolves([], ["island2"]); + expect(solverStorage.loadSolve(ISLAND)?.anomalyId).toBe("cryo_nexus"); + }); + it("drops only the layouts an imported obstacle now covers", async () => { stage([layout(0), layout(1), layout(2)], 1); await rockOn(0); diff --git a/src/lib/state/solver.svelte.ts b/src/lib/state/solver.svelte.ts index 7c6a223..eaf21ba 100755 --- a/src/lib/state/solver.svelte.ts +++ b/src/lib/state/solver.svelte.ts @@ -2,8 +2,11 @@ import type { OptimizationResult, PlacedBuilding, Tile } from "../types"; import { DEFAULT_ANOMALY_ID, getAnomaly, + fitsBudget, + netSpend, type AnomalyDefinition, type AnomalyId, + type CashBudget, } from "@reactor2/solver"; import { SolverWorkerClient, @@ -102,6 +105,7 @@ export function chooseSolveVariants( fresh: OptimizationResult[], limit: number = MAX_SOLVE_VARIANTS, rank: (result: OptimizationResult) => number = (r) => r.totalPower, + budget?: CashBudget, ): { variants: OptimizationResult[]; selected: number; defended: boolean } { if (fresh.length === 0) return { variants: held, selected: heldIndex, defended: true }; @@ -132,8 +136,14 @@ export function chooseSolveVariants( variants.push(variant); } const onScreen = variants[selected]; - // Stable, so equal costs keep held layouts ahead of fresh ones. - const ranked = cheapestFirst(variants, (v) => v.placements); + // Stable, so equal costs keep held layouts ahead of fresh ones. Under a + // cash limit the cost is the spend from the board standing, as the + // engine ranked them. + const ranked = cheapestFirst( + variants, + (v) => v.placements, + budget && ((placements) => netSpend(placements, budget)), + ); return { variants: ranked, selected: ranked.indexOf(onScreen), @@ -679,10 +689,15 @@ class SolverState { * have more than one layout at this power — empty otherwise, and the * whole-board cycler says everything there is to say. Under a shared * cooling pool the board is one island, so there is never more than one. + * + * None while a cash limit is set: each whole board was bought within it, + * but one landmass from each of two boards together may not be — the reason + * `#composeIslands` stands aside under a limit too. */ get islandPickers(): IslandChoices[] { const result = this.optimizationResult; - if (!result || this.variants.length < 2) return []; + if (!result || this.variants.length < 2 || configState.cashLimit !== null) + return []; const { islandOf, tiles } = this.#islandIndex(); const pickers = islandChoices( this.variants, @@ -706,7 +721,7 @@ class SolverState { */ showIslandLayout(island: number, delta: 1 | -1) { const result = this.optimizationResult; - if (!result) return; + if (!result || configState.cashLimit !== null) return; const { islandOf, tiles } = this.#islandIndex(); const picker = islandChoices( this.variants, @@ -1022,9 +1037,17 @@ class SolverState { * roster now give, as `rescoreResult` does for the island on screen. Like it, * this searches nothing, so a cleared obstacle shows up as room a re-run can * use rather than as a changed layout. + * + * `only` narrows the pass to the islands an import actually rewrote. A + * share code laid onto one island must not touch the others: their solves + * would otherwise be judged against the anomaly now in force and cleared, + * where `restore()` would have kept them. */ - async carryOverSolves(locked: readonly string[]) { - for (const templateId of solverStorage.solveIds()) { + async carryOverSolves( + locked: readonly string[], + only: readonly string[] = solverStorage.solveIds(), + ) { + for (const templateId of only) { const saved = solverStorage.loadSolve(templateId); if (!saved) continue; const grid = locked.includes(templateId) @@ -1233,11 +1256,14 @@ class SolverState { * genuinely can come back worse — which is the whole reason the choice is * put to the user (see `uiState.requestSolve`) rather than assumed. */ - async runOptimizer(options: { keepBest?: boolean } = {}) { + async runOptimizer( + options: { keepBest?: boolean; cashBudget?: CashBudget } = {}, + ) { if (this.isOptimizing) { this.stopOptimizer(); return; } + const runBudget = options.cashBudget; // Captured before the panel starts streaming the new run over it. The // whole shortlist is held, not just the layout on screen: a run that comes @@ -1247,9 +1273,21 @@ class SolverState { // A result with no shortlist behind it can only be a streaming snapshot // left by a run that failed, and it is not something to defend — falling // back to it would hand the next run a bar of nearly zero. - const previousVariants = + // + // Under a cash limit a held layout is a bar only if the player could buy + // it: one over the limit is an answer to a question nobody is asking. + const heldVariants = options.keepBest && this.variants.length > 0 ? this.variants : []; - const previousIndex = this.variantIndex; + const previousVariants = heldVariants.filter( + (v) => !runBudget || fitsBudget(v.placements, runBudget), + ); + // The layout on screen, found again in the filtered list: the filter can + // shift it down, and an index into the unfiltered one would then follow a + // different layout. One the limit filtered out leaves the first held. + const previousIndex = Math.max( + 0, + previousVariants.indexOf(heldVariants[this.variantIndex]), + ); /* * The upgrade plan, resolved once at launch like the rules beside it. @@ -1416,6 +1454,7 @@ class SolverState { anomalyId: this.#runAnomalyId, prestige: configState.prestige, upgradePlan: runPlan?.along, + cashBudget: runBudget, }, ); this.activeTask = handle; @@ -1450,24 +1489,29 @@ class SolverState { // each run won some islands, the boards made of every island's winner // beat both, and stand in for the fresh run (`composeIslandBests`). // Scored against the board on screen, so only while it is this run's. - const composed = onScreen() - ? this.#composeIslands( - previousVariants, - finalVariants, - runGrid, - runPlan - ? runPlan.target - : $state.snapshot(configState.buildingUpgrades), - runAnomaly, - islandPower, - ) - : null; + // + // Not under a cash limit: each board was bought within it, and one + // landmass of each together may not be. + const composed = + onScreen() && !runBudget + ? this.#composeIslands( + previousVariants, + finalVariants, + runGrid, + runPlan + ? runPlan.target + : $state.snapshot(configState.buildingUpgrades), + runAnomaly, + islandPower, + ) + : null; const { variants, selected, defended } = chooseSolveVariants( previousVariants, previousIndex, composed ?? finalVariants, MAX_SOLVE_VARIANTS, rank, + runBudget, ); // A defended layout keeps its own run's clock: it is still that solve, diff --git a/src/lib/state/timeline.svelte.ts b/src/lib/state/timeline.svelte.ts index 35fc095..945e705 100644 --- a/src/lib/state/timeline.svelte.ts +++ b/src/lib/state/timeline.svelte.ts @@ -13,6 +13,7 @@ import { getAnomaly, ISLAND_TEMPLATES, PRESTIGE_UPGRADES, + priceRules, prestigeScales, projectTimeline, secondsUntilAward, @@ -24,12 +25,30 @@ import { type GameExport, type PlacedBuilding, type PrestigeScales, + type PriceRules, type ResolvedGameImport, type Tile, type TimelineProjection, } from "@reactor2/solver"; -import { createPlacement } from "../data/placements"; -import { boardPower, boardPowers } from "../simulation/simulator"; +import { createPlacement, placementStatus } from "../data/placements"; +import { + addCounts, + changeSpend, + countBuildings, + islandPrice, + nextRemoval, + obstacleCount, + terrainStats, + type BuildingCounts, + type ObstacleClearing, + type TerrainStats, +} from "../simulation/islandStats"; +import { + boardHealth, + boardPower, + boardPowers, + type BoardHealth, +} from "../simulation/simulator"; import { gameImportStorage, solverStorage, @@ -42,6 +61,44 @@ import { layoutState } from "./layout.svelte"; /** The shipped islands that exist in the game — the ones a total adds up. */ const GAME_ISLANDS = ISLAND_TEMPLATES.filter((t) => t.game); +/** + * Whether `next` is a later code from the same run as `prev`, with nothing + * changed that a Chronon target or a Time Lab plan was set against: the same + * anomaly at the same balance, every Time Lab research at the same level (a + * jump spends Chronons there), the timeline carried on rather than restarted + * (the same generation — a jump also zeroes its energy and clock, but a run + * played long enough passes the old figures again), and the islands making at least what + * they made. Re-importing to catch up on a session's progress then keeps both. + */ +function continuesRun( + prev: SavedGameImport | null, + next: SavedGameImport, +): boolean { + if (!prev) return false; + if ( + prev.anomalyId !== next.anomalyId || + prev.anomalyBalance !== next.anomalyBalance + ) + return false; + const was = timeLabLevels(prev.research); + const now = timeLabLevels(next.research); + if (TIME_LAB.some((r) => was[r.id] !== now[r.id])) return false; + const a = prev.timeline; + const b = next.timeline; + if ((a === null) !== (b === null)) return false; + // The generation counts jumps outright; energy and clock only betray one + // until the new run has caught up with the old snapshot. + if ( + a && + b && + (b.generation !== a.generation || + b.energy < a.energy || + b.elapsedSeconds < a.elapsedSeconds) + ) + return false; + return next.energyPerTick >= prev.energyPerTick * (1 - 1e-9); +} + /** * The player's timeline as a whole: the power of every island at once, and * where the Chronon count stands. @@ -71,9 +128,10 @@ class TimelineState { /** * The jump award the player is waiting for, or null for none set — in which * case `targetEta` reads today's award: what a jump now would leave the - * player holding. Kept across reloads, and cleared by an import: a new code - * is a new situation, and a goal set against the last one left standing - * reads as an import that did not take. + * player holding. Kept across reloads, and cleared by an import from a new + * situation — a goal set against the last one left standing reads as an + * import that did not take — but kept across a later code from the same run + * (`continuesRun`), which is only catching up on progress. */ chrononTarget = $state( uiStorage.loadPrefs().chrononTarget ?? null, @@ -90,8 +148,23 @@ class TimelineState { */ #solvePower = $state>({}); - /** Power by board and rules, so an unchanged island is not re-scored. */ + /** Solve power by solve, terrain and rules, so an unchanged one is not re-scored. */ #memo = new Map(); + + /** A saved board's power and building states by board and rules. */ + #boardMemo = new Map(); + + /** Each island's saved board's idle and overheating buildings. */ + #savedHealth = $state>({}); + + /** Each stored solve's buildings, for pricing the change to it. */ + #solveCounts = $state>({}); + + /** Each island's buildings and terrain from its saved board, keyed by template id. */ + #facts = $state>({}); + + /** Buildings and terrain by board code: neither depends on the rules. */ + #factsMemo = new Map(); #refreshSeq = 0; /** @@ -143,16 +216,27 @@ class TimelineState { code: layoutState.savedGrids[t.id]?.code ?? t.code, })); + // The game's own boards, for counting the obstacles cleared in the game + // rather than on boards here, which may be plans. + const gameCodes = this.record?.islands ?? null; + const next: Record = {}; + const nextHealth: Record = {}; + const nextFacts: Record = {}; for (const { id, code } of boards) { + const facts = await this.#factsOf(code); + if (seq !== this.#refreshSeq) return; + nextFacts[id] = facts; + const key = `${anomaly.id}|${rules}|${code}`; - let power = this.#memo.get(key); - if (power === undefined) { - power = await scoreBoard(code, upgrades, prestige, anomaly); + let health = this.#boardMemo.get(key); + if (health === undefined) { + health = await scoreBoard(code, upgrades, prestige, anomaly); if (seq !== this.#refreshSeq) return; - this.#memo.set(key, power); + this.#boardMemo.set(key, health); } - next[id] = power; + next[id] = health.power; + nextHealth[id] = health; } // A memo keyed on whole boards grows with every edit; past a few rounds // of islands it is cheaper to start again than to track which are live. @@ -167,7 +251,9 @@ class TimelineState { return [{ id: t.id, saved, grid, code }]; }); const solved: Record = {}; + const solvedCounts: Record = {}; for (const { id, saved, grid, code } of solves) { + solvedCounts[id] = countBuildings(saved.result.placements); const terrain = grid ? blueprintKey(grid) : code; const key = [ "solve", @@ -198,10 +284,197 @@ class TimelineState { } if (this.#memo.size > GAME_ISLANDS.length * 8) this.#memo.clear(); + if (this.#boardMemo.size > GAME_ISLANDS.length * 8) this.#boardMemo.clear(); + if (this.#factsMemo.size > GAME_ISLANDS.length * 4) this.#factsMemo.clear(); + // Obstacles per island on the map as shipped, and on the game's own board + // when there is an import — see `#clearedOn`. + const nextMapObstacles: Record = {}; + const nextGameObstacles: Record = {}; + for (const t of GAME_ISLANDS) { + const map = await this.#factsOf(t.code); + const code = gameCodes?.[t.id]; + const inGame = code ? await this.#factsOf(code) : null; + if (seq !== this.#refreshSeq) return; + nextMapObstacles[t.id] = obstacleCount(map.terrain); + if (inGame) nextGameObstacles[t.id] = obstacleCount(inGame.terrain); + } + this.#savedPower = next; + this.#savedHealth = nextHealth; this.#solvePower = solved; + this.#solveCounts = solvedCounts; + this.#facts = nextFacts; + this.#mapObstacles = nextMapObstacles; + this.#gameObstacles = nextGameObstacles; + } + + /** + * Each building's count on every game island but the one on screen, each + * from its saved layout or its map — the copies a price climbs with that + * no change to this board touches. An unreadable board counts for nothing. + * + * Read through the memo the island figures fill, so a budgeted launch does + * not decode every board again — they are almost always counted already. + */ + async copiesOnOtherIslands(): Promise> { + const active = layoutState.activeTemplateId; + const codes = GAME_ISLANDS.filter((t) => t.id !== active).map( + (t) => layoutState.savedGrids[t.id]?.code ?? t.code, + ); + const counts = new Map(); + for (const code of codes) + for (const [id, n] of Object.entries((await this.#factsOf(code)).counts)) + counts.set(id, (counts.get(id) ?? 0) + n); + return counts; + } + + /** A board's buildings and terrain, memoised by code. */ + async #factsOf(code: string): Promise { + let facts = this.#factsMemo.get(code); + if (facts === undefined) { + facts = await readFacts(code); + this.#factsMemo.set(code, facts); + } + return facts; + } + + #mapObstacles = $state>({}); + #gameObstacles = $state>({}); + + /** + * Obstacles cleared on an island: the map's less what still stands. What + * stands is read off the game's board when the last import has it — a + * board here may be a plan that clears more than the game has — and off + * the board here otherwise. + */ + #clearedOn(id: string, here: TerrainStats): number { + const map = this.#mapObstacles[id]; + if (map === undefined) return 0; + return Math.max(0, map - (this.#gameObstacles[id] ?? obstacleCount(here))); + } + + /** + * Obstacles cleared on every game island, and how long the next clear takes + * under the last import's research — the game prices each clear by how many + * came before it. Null before the islands have been read. + */ + get obstacleClearing(): ObstacleClearing | null { + const islands = this.islands; + if (islands.length === 0) return null; + const removed = islands.reduce((s, i) => s + i.cleared, 0); + // What is left to clear, on the islands the player has: in the game when + // imported, on the boards here otherwise. + const left = islands + .filter((i) => !i.locked) + .reduce( + (s, i) => s + (this.#gameObstacles[i.id] ?? obstacleCount(i.terrain)), + 0, + ); + return nextRemoval(removed, this.record?.research ?? {}, left); + } + + /** + * The next island still locked in the game and what it costs to buy, or + * null when the last import has every island open (or there is none). + */ + get nextIsland(): { name: string; price: number } | null { + const locked = new Set(this.record?.lockedTemplateIds ?? []); + const next = GAME_ISLANDS.find((t) => locked.has(t.id)); + const price = next?.game ? islandPrice(next.game.areaId) : null; + return next && price !== null ? { name: next.name, price } : null; } + /** + * The price rules the player's research gives, off the last game import — + * the base rules with nothing imported, which is a player with none of the + * price research. + */ + get priceRules(): PriceRules { + return priceRules(this.record?.research ?? {}); + } + + /** + * The board on screen's buildings and terrain, live — or null when it is not + * one the totals count (see `#livePower`). + */ + #liveFacts: BoardFacts | null = $derived.by(() => { + const terrain = this.#liveTerrain; + if (terrain === null) return null; + return { counts: countBuildings(layoutState.placements), terrain }; + }); + + /** + * The board on screen's terrain, apart from its buildings: a full shore + * scan that placing a building — which leaves `grid` alone — must not + * repeat on every stroke. + */ + #liveTerrain: TerrainStats | null = $derived.by(() => { + if (layoutState.isPreview) return null; + if (!GAME_ISLANDS.some((t) => t.id === layoutState.activeTemplateId)) + return null; + return terrainStats(layoutState.grid); + }); + + /** + * Every game island's buildings and terrain, the board on screen live and + * the rest from their saved boards — the figures `IslandStatsModal` prints. + * An island whose board is still being read is absent. + */ + get islands(): IslandFacts[] { + return this.#islands.list; + } + + /** + * Each building's copies across every game island — what its price climbs + * with, since the game counts copies everywhere. + */ + get copies(): BuildingCounts { + return this.#islands.copies; + } + + /** Derived once per change rather than per read: several panels read it. */ + #islands = $derived.by(() => { + const live = this.#liveFacts; + const locked = new Set(this.record?.lockedTemplateIds ?? []); + const list = GAME_ISLANDS.flatMap((t) => { + const isLive = live !== null && t.id === layoutState.activeTemplateId; + const facts = isLive ? live : this.#facts[t.id]; + if (!facts) return []; + const health = isLive ? liveHealth() : this.#savedHealth[t.id]; + return [ + { + id: t.id, + name: t.name, + ...facts, + power: isLive + ? (this.#livePower ?? 0) + : (this.#savedPower[t.id] ?? 0), + idle: health?.idle ?? 0, + starved: health?.starved ?? 0, + solvePower: this.#solvePower[t.id] ?? null, + solveCost: null as number | null, + locked: locked.has(t.id), + cleared: this.#clearedOn(t.id, facts.terrain), + }, + ]; + }); + + const copies: BuildingCounts = {}; + for (const island of list) addCounts(copies, island.counts); + + // What building each stored solve in place of the board costs: the + // board's buildings are what stands, every other island's are elsewhere. + const rules = this.priceRules; + for (const island of list) { + const solve = this.#solveCounts[island.id]; + if (!solve || island.solvePower === null) continue; + const elsewhere: BuildingCounts = { ...copies }; + for (const [id, n] of Object.entries(island.counts)) elsewhere[id] -= n; + island.solveCost = changeSpend(solve, island.counts, elsewhere, rules); + } + return { list: list as IslandFacts[], copies }; + }); + /** How many game islands have a stored solve — what "With solves" covers. */ get solvedIslands(): number { return Object.keys(this.#solvePower).length; @@ -450,12 +723,16 @@ class TimelineState { } : null, }; + const carriesOn = continuesRun(this.record, record); this.record = record; this.now = Date.now(); gameImportStorage.save(record); + // A target and a plan are kept across a fresh code from the same run — see + // `continuesRun`. Otherwise a plan priced against the last import's levels + // is against levels the player may no longer hold, and a target set for + // that run's award means nothing to the next. + if (carriesOn) return; this.setChrononTarget(null); - // A plan priced against the last import's levels is against levels the - // player may no longer hold. this.timeLabPlan = {}; } @@ -463,8 +740,9 @@ class TimelineState { /** * Extra levels the player means to buy at the jump, by research id. Kept for - * the session and cleared by an import, like the target: a plan is priced - * against the levels the last code reported. + * the session and cleared by an import, like the target and on the same + * terms (`continuesRun`): a plan is priced against the levels the last code + * reported. */ timeLabPlan = $state>({}); @@ -649,6 +927,55 @@ async function decodeBoard( } } +/** What a board holds, apart from how much power it makes. */ +interface BoardFacts { + counts: BuildingCounts; + terrain: TerrainStats; +} + +/** One game island's figures, as `TimelineState.islands` lists them. */ +interface IslandFacts extends BoardFacts { + id: string; + name: string; + /** The board's power per tick, under today's rules. */ + power: number; + /** Its stored solve's, re-scored under today's rules; null with none. */ + solvePower: number | null; + /** Still locked in the game, by the last import. */ + locked: boolean; + /** Obstacles cleared, in the game when imported — see `#clearedOn`. */ + cleared: number; + /** Buildings on the board doing nothing, and overheating. */ + idle: number; + starved: number; + /** + * What building the stored solve in place of the board costs, net of sales + * (`changeSpend`); null with no solve. + */ + solveCost: number | null; +} + +/** The board on screen's idle and overheating buildings, from its live scores. */ +function liveHealth(): BoardHealth { + const health: BoardHealth = { power: 0, idle: 0, starved: 0 }; + for (const p of layoutState.placements) { + const status = placementStatus(p); + if (status === "idle") health.idle++; + else if (status === "starved") health.starved++; + } + return health; +} + +/** A saved board's buildings and terrain; empty if it cannot be read. */ +async function readFacts(code: string): Promise { + try { + const { grid, placements } = await decodeBlueprint(code); + return { counts: countBuildings(placements), terrain: terrainStats(grid) }; + } catch { + return { counts: {}, terrain: terrainStats([]) }; + } +} + /** A saved board's terrain, or null if it cannot be read. */ async function decodeTerrain(code: string): Promise { try { @@ -658,16 +985,19 @@ async function decodeTerrain(code: string): Promise { } } -/** One saved board's power under the given rules; 0 if it cannot be read. */ +/** + * One saved board's power and building states under the given rules; nothing + * if it cannot be read. + */ async function scoreBoard( code: string, upgrades: Record, prestige: PrestigeScales, anomaly: AnomalyDefinition, -): Promise { +): Promise { try { const { grid, placements } = await decodeBlueprint(code); - return boardPower( + return boardHealth( grid, BUILDINGS, placements.map((p) => createPlacement(p.buildingId, p.x, p.y, upgrades)), @@ -675,7 +1005,7 @@ async function scoreBoard( anomaly, ); } catch { - return 0; + return { power: 0, idle: 0, starved: 0 }; } } diff --git a/src/lib/state/timeline.test.ts b/src/lib/state/timeline.test.ts index 0ba4381..4535fa6 100644 --- a/src/lib/state/timeline.test.ts +++ b/src/lib/state/timeline.test.ts @@ -279,6 +279,86 @@ describe("the timeline", () => { }); }); + it("keeps the target and the plan across a later code from the same run", async () => { + await importFixture("gen2_city52_9c43e4b7"); + timelineState.setChrononTarget(15000); + timelineState.planLevels("chronon_reactor", 1); + // The same code again, and the same run an hour on. + await importFixture("gen2_city52_9c43e4b7"); + const { exp, resolved } = await fixture("gen2_city52_9c43e4b7"); + const t = exp.timeline!; + await timelineState.recordImport( + { + ...exp, + timeline: { + ...t, + exportedAt: t.exportedAt + 3600, + elapsedSeconds: t.elapsedSeconds + 3600, + energy: t.energy * 1.01, + }, + }, + resolved, + ); + expect(timelineState.chrononTarget).toBe(15000); + expect(timelineState.timeLabPlan).toEqual({ chronon_reactor: 1 }); + }); + + it("clears the target and the plan once the timeline restarts", async () => { + await importFixture("gen2_city52_9c43e4b7"); + timelineState.setChrononTarget(15000); + timelineState.planLevels("chronon_reactor", 1); + const { exp, resolved } = await fixture("gen2_city52_9c43e4b7"); + // A jump into the same anomaly with nothing bought: a fresh clock. + await timelineState.recordImport( + { + ...exp, + timeline: { ...exp.timeline!, energy: 0, elapsedSeconds: 60 }, + }, + resolved, + ); + expect(timelineState.chrononTarget).toBeNull(); + expect(timelineState.timeLabPlan).toEqual({}); + }); + + it("clears the target and the plan after a jump the new run has outgrown", async () => { + await importFixture("gen2_city52_9c43e4b7"); + timelineState.setChrononTarget(15000); + timelineState.planLevels("chronon_reactor", 1); + const { exp, resolved } = await fixture("gen2_city52_9c43e4b7"); + const t = exp.timeline!; + // One jump on, and played past the old snapshot's energy and clock. + await timelineState.recordImport( + { + ...exp, + timeline: { + ...t, + generation: t.generation + 1, + elapsedSeconds: t.elapsedSeconds + 7200, + energy: t.energy * 1000, + }, + }, + resolved, + ); + expect(timelineState.chrononTarget).toBeNull(); + expect(timelineState.timeLabPlan).toEqual({}); + }); + + it("clears the target and the plan when the islands make less", async () => { + await importFixture("gen2_city52_9c43e4b7"); + timelineState.setChrononTarget(15000); + timelineState.planLevels("chronon_reactor", 1); + const { exp, resolved } = await fixture("gen2_city52_9c43e4b7"); + await timelineState.recordImport(exp, { + ...resolved, + islands: resolved.islands.map((island) => ({ + ...island, + placements: [], + })), + }); + expect(timelineState.chrononTarget).toBeNull(); + expect(timelineState.timeLabPlan).toEqual({}); + }); + it("clears a target that is not a positive number", () => { timelineState.setChrononTarget(-4); expect(timelineState.chrononTarget).toBeNull(); diff --git a/src/lib/state/ui.svelte.ts b/src/lib/state/ui.svelte.ts index bb8b665..df036d8 100755 --- a/src/lib/state/ui.svelte.ts +++ b/src/lib/state/ui.svelte.ts @@ -7,13 +7,14 @@ import type { Tile, } from "../types"; import { isObstacleType } from "../types/grid"; -import type { BuildingCategory } from "@reactor2/solver"; +import type { BuildingCategory, CashBudget } from "@reactor2/solver"; import { buildShareUrl, clearSharedCode } from "../encoding/shareLink"; import { buildTransferUrl, clearTransferLink, decodeTransfer, encodeTransfer, + isTransferCode, readTransferLink, type TransferBundle, type TransferSolve, @@ -28,7 +29,6 @@ import { encodeBlueprint, findBuilding, getAnomaly, - priceRules, sellRefund, decodeGameExport, formatNumberForFilename, @@ -90,6 +90,7 @@ type ActiveModal = | "timeLab" | "transfer" | "transferIn" + | "islandStats" | null; /** @@ -521,6 +522,12 @@ class UIState { * asking to replace anything. Null for anything else in the box. */ gameImport = $state(null); + /** + * The shipped island a pasted share code is drawn on, when it is one + * (`layoutState.matchingTemplate`) — which lets the dialog offer to put it + * on that island as well as in a new custom slot. + */ + importMatch = $state(null); /** * The same code as the game wrote it. The resolver translates what a board * needs and drops the rest — the economy research, the timeline — which @@ -852,7 +859,51 @@ class UIState { */ #beginSolve(options: { keepBest?: boolean } = {}) { this.setSheetDetent("closed"); - void solverState.runOptimizer(options); + if (configState.cashLimit === null) { + void solverState.runOptimizer(options); + return; + } + // The budget needs the other islands' boards decoded first, and the run + // has not started while that happens, so a second press would start a + // second run beside it. + if (this.#launching) return; + this.#launching = true; + // The budget is read off this island's board, and the run starts from + // whichever board is on screen once it is built: an island switched to + // in between would be solved within the one left behind. Such a launch is + // dropped — the player has moved on from it. + const templateId = layoutState.activeTemplateId; + void this.#cashBudget(configState.cashLimit) + .then((cashBudget) => { + if (layoutState.activeTemplateId !== templateId || this.isPreview) + return; + return solverState.runOptimizer({ ...options, cashBudget }); + }) + .finally(() => (this.#launching = false)); + } + + /** Set while a budgeted run's inputs are being gathered — see `#beginSolve`. */ + #launching = false; + + /** + * The cash limit as a run takes it: the board in Edit is what stands — it + * is the player's — every other island's copies make its prices dearer, + * and the price research comes off the last game import. + * + * Built here rather than in `solverState`, which cannot read the timeline. + */ + async #cashBudget(cash: number): Promise { + const standing = layoutState.placements.map(({ x, y, buildingId }) => ({ + x, + y, + buildingId, + })); + return { + cash, + standing, + elsewhere: Object.fromEntries(await timelineState.copiesOnOtherIslands()), + prices: timelineState.priceRules, + }; } /** @@ -936,7 +987,10 @@ class UIState { !solverState.isOptimizing && this.solveAll === null && configState.canProducePower && - this.solveAllTargets.length > 0 + this.solveAllTargets.length > 0 && + // One cash figure cannot be spent on every island in turn: each run + // would be handed all of it. Hidden while a limit is set. + configState.cashLimit === null ); } @@ -1078,10 +1132,6 @@ class UIState { } const result = solverState.optimizationResult!; const target = shapeOf(result); - const free = grid - .flat() - .filter((t) => t.type === "grass") - .map(({ x, y }) => ({ x, y })); const score = createBoardScorer( grid, BUILDINGS, @@ -1097,7 +1147,15 @@ class UIState { this.moveStepsPlanning = { done: 0, total: 0 }; try { - const plan = await planMoveSteps(start, target, obstacles, free, score, { + const rules = timelineState.priceRules; + const baseOf = (id: string) => findBuilding(id)?.price ?? 0; + const pricing = { + copies: await this.#copiesAcrossIslands(), + build: (id: string, n: number) => buildPrice(baseOf(id), n, rules), + refund: (id: string, n: number) => sellRefund(baseOf(id), n, rules), + }; + if (stale()) return; + const plan = await planMoveSteps(start, target, obstacles, score, { onProgress: (done, total) => { if (!stale()) this.moveStepsPlanning = { done, total }; }, @@ -1107,21 +1165,22 @@ class UIState { stopAtPower: score( new Map(target.map((b) => [`${b.x},${b.y}`, b.buildingId])), ), + // Under a cash limit the steps must never need more at once than the + // layout, which fits it, costs in all: sales that pay for a build + // come before it. Without one, power alone orders them. + cash: configState.cashLimit !== null ? pricing : undefined, }); if (stale()) return; if (plan.steps.every((step) => step.kind === "clear")) { this.showToast("Your island already makes as much as this layout"); return; } - const rules = priceRules(timelineState.record?.research ?? {}); - const baseOf = (id: string) => findBuilding(id)?.price ?? 0; const prices = priceSteps( plan, - await this.#copiesAcrossIslands(), - (id, n) => buildPrice(baseOf(id), n, rules), - (id, n) => sellRefund(baseOf(id), n, rules), + pricing.copies, + pricing.build, + pricing.refund, ); - if (stale()) return; this.moveSteps = { templateId, result, @@ -1143,21 +1202,9 @@ class UIState { * from its board in Edit, every other from its saved layout. */ async #copiesAcrossIslands(): Promise> { - const counts = new Map(); - const active = layoutState.activeTemplateId; + const counts = await timelineState.copiesOnOtherIslands(); for (const p of layoutState.placements) counts.set(p.buildingId, (counts.get(p.buildingId) ?? 0) + 1); - const codes = ISLAND_TEMPLATES.filter((t) => t.game && t.id !== active).map( - (t) => layoutState.savedGrids[t.id]?.code ?? t.code, - ); - for (const code of codes) { - try { - for (const p of (await decodeBlueprint(code)).placements) - counts.set(p.buildingId, (counts.get(p.buildingId) ?? 0) + 1); - } catch { - // An unreadable board counts for nothing rather than failing the plan. - } - } return counts; } @@ -1502,6 +1549,12 @@ class UIState { this.activeModal = "settings"; } + /** Opens the island and building figures across the whole save. */ + openIslandStats() { + this.overflowOpen = false; + this.activeModal = "islandStats"; + } + /** Opens the import dialog on a clean slate — a stale error is confusing. */ openImport() { this.overflowOpen = false; @@ -1520,9 +1573,13 @@ class UIState { */ async readImportCode(code: string) { const seq = ++this.#gameReadSeq; + this.importMatch = null; if (!isGameExportCode(code)) { this.gameImport = null; this.#gameExport = null; + if (!code.trim() || isTransferCode(code)) return; + const match = await layoutState.matchingTemplate(code); + if (seq === this.#gameReadSeq) this.importMatch = match; return; } try { @@ -1591,6 +1648,43 @@ class UIState { } } + /** + * Puts the pasted code on the shipped island it matches, replacing that + * island's board, and closes on success. The dialog asks twice first. + * + * The island's stored solve is kept if the new board still lets it be + * built — the same carry-over a game import runs, since this changes the + * island's terrain too. + */ + async importOntoMatch() { + const match = this.importMatch; + if (!match || this.isImporting) return; + this.isImporting = true; + this.importError = null; + try { + await solverState.settleOptimizer(); + await layoutState.importOntoTemplate( + this.importCode, + match.id, + configState.buildingUpgrades, + ); + // Only the island this rewrote: the others' solves are untouched. + await solverState.carryOverSolves([], [match.id]); + this.activeModal = null; + this.importCode = ""; + this.importMatch = null; + solverState.restore(); + this.closeInspector(); + this.recenterCanvas(); + this.showToast(`Imported onto ${match.name}`); + } catch (err) { + this.importError = + err instanceof Error ? err.message : "That import could not be read."; + } finally { + this.isImporting = false; + } + } + /** * Loads the pasted code as a new custom island and closes on success. * diff --git a/src/lib/storage/storage.ts b/src/lib/storage/storage.ts index f3d68ec..9e268cf 100755 --- a/src/lib/storage/storage.ts +++ b/src/lib/storage/storage.ts @@ -30,6 +30,7 @@ const KEYS = { ANOMALY: "anomaly", PRESTIGE: "prestige", UPGRADE_PLAN: "upgrade_plan", + CASH_LIMIT: "cash_limit", UI: "ui_prefs", SOLVE: "solver_result", GAME_IMPORT: "game_import", @@ -300,6 +301,17 @@ export const upgradePlanStorage = { savePlan: (steps: UpgradeStep[]): void => setItem(KEYS.UPGRADE_PLAN, steps), }; +export const cashLimitStorage = { + /** The cash limit a run spends within, or null for none. */ + loadCashLimit: (): number | null => { + const raw = getItem(KEYS.CASH_LIMIT, null); + return typeof raw === "number" && Number.isFinite(raw) && raw >= 0 + ? raw + : null; + }, + saveCashLimit: (cash: number | null): void => setItem(KEYS.CASH_LIMIT, cash), +}; + export const uiStorage = { loadPrefs: (): UiPrefs => ({ ...DEFAULT_UI_PREFS, diff --git a/src/lib/worker/islandBest.test.ts b/src/lib/worker/islandBest.test.ts index 42197b6..2e10f7c 100755 --- a/src/lib/worker/islandBest.test.ts +++ b/src/lib/worker/islandBest.test.ts @@ -8,6 +8,7 @@ */ import { describe, expect, it } from "vitest"; import { IslandBest } from "./islandBest"; +import { MAX_ALTERNATES, priceRules } from "@reactor2/solver"; import type { IslandLayout, PlacedBuilding } from "@reactor2/solver"; /** One building on an island-local tile, carrying `power` and nothing else. */ @@ -162,6 +163,20 @@ describe("IslandBest", () => { expect(shapes(best)).toEqual(["cooler1@2", "cooler2@0"]); }); + it("ranks by the spend from the board standing under a cash limit", () => { + // Two hundred cooler1s on the other islands make the next one dearer than + // a cooler2, so the tie that is cheaper from empty spends more here. + const best = new IslandBest(MAX_ALTERNATES, { + cash: 1e300, + standing: [], + elsewhere: { cooler1: 200 }, + prices: priceRules({}), + }); + best.offer(layout("cooler1", 0, 100)); + best.offer(layout("cooler2", 1, 100)); + expect(shapes(best)).toEqual(["cooler2@1", "cooler1@0"]); + }); + it("holds later attempts to the best power reached, not the cheapest's", () => { // Ties are relative (1e-9), so a cheaper tie can sit a hair under the // best. Measured from it, a third attempt a hair under *that* would tie diff --git a/src/lib/worker/islandBest.ts b/src/lib/worker/islandBest.ts index 0dc44d7..88bf9e7 100755 --- a/src/lib/worker/islandBest.ts +++ b/src/lib/worker/islandBest.ts @@ -1,11 +1,16 @@ import { cheapestFirst, isDistinctLayout, + netSpend, powerTies, MAX_ALTERNATES, } from "@reactor2/solver"; import type { IslandSolution } from "@reactor2/solver"; -import type { IslandLayout, PlacedBuilding } from "@reactor2/solver"; +import type { + CashBudget, + IslandLayout, + PlacedBuilding, +} from "@reactor2/solver"; /** * The answer for one island, gathered from however many attempts it was given. @@ -41,6 +46,11 @@ import type { IslandLayout, PlacedBuilding } from "@reactor2/solver"; * still judged against the best power any attempt reached, not the primary's: * a tie may sit a hair below the bar, and measuring from the cheapest would let * the island's figure creep down one tolerance at a time. + * + * Under a cash limit "cheapest" is what the layout spends from the board + * standing, as the engine ranked it — not its cost from empty, which would + * put a tie that sells the player's dear buildings ahead of one that keeps + * them, and evict the engine's choice once the shortlist is full. */ export class IslandBest { #primary: IslandLayout = { placements: [], powerOutput: 0 }; @@ -51,10 +61,15 @@ export class IslandBest { /** The best power any attempt reached — the bar the next one is held to. */ #bar = 0; readonly #limit: number; + readonly #budget: CashBudget | undefined; - /** `limit` caps the alternates kept, matching what one search would keep. */ - constructor(limit: number = MAX_ALTERNATES) { + /** + * `limit` caps the alternates kept, matching what one search would keep; + * `budget` is the run's cash limit, if it has one. + */ + constructor(limit: number = MAX_ALTERNATES, budget?: CashBudget) { this.#limit = limit; + this.#budget = budget; } /** What this island contributes to the board: its best layout and its ties. */ @@ -114,10 +129,12 @@ export class IslandBest { this.#kept.push(layout.placements); pool.push(layout); } - const ranked = cheapestFirst(pool, (l) => l.placements).slice( - 0, - this.#limit + 1, - ); + const budget = this.#budget; + const ranked = cheapestFirst( + pool, + (l) => l.placements, + budget && ((placements) => netSpend(placements, budget)), + ).slice(0, this.#limit + 1); this.#primary = ranked[0]; this.#alternates = ranked.slice(1); this.#kept = ranked.map((l) => l.placements); diff --git a/src/lib/worker/islandWorker.ts b/src/lib/worker/islandWorker.ts index 9e8956f..cb22eed 100755 --- a/src/lib/worker/islandWorker.ts +++ b/src/lib/worker/islandWorker.ts @@ -45,6 +45,7 @@ self.addEventListener( req.rngSeed, getAnomaly(req.anomalyId), req.upgradeSteps, + req.cashBudget, ); post({ id: req.id, diff --git a/src/lib/worker/solverCoordinator.ts b/src/lib/worker/solverCoordinator.ts index c329a4f..d2cb676 100755 --- a/src/lib/worker/solverCoordinator.ts +++ b/src/lib/worker/solverCoordinator.ts @@ -105,6 +105,7 @@ export class SolverCoordinator { options?.anomalyId, options?.prestige, options?.upgradePlan, + options?.cashBudget, ); if (!plan) return [createEmptyResult(grid?.[0]?.length ? countGrassTiles(grid) : 0)]; @@ -152,7 +153,9 @@ export class SolverCoordinator { } /** The answer per island: finished attempts only. */ - const finals = plan.islands.map(() => new IslandBest()); + const finals = plan.islands.map( + () => new IslandBest(undefined, plan.cashBudget), + ); /* * What the screen shows while the run is in flight — the best anything has @@ -333,6 +336,9 @@ export class SolverCoordinator { upgradeSteps: plan.upgradeSteps?.length ? plan.upgradeSteps : undefined, + // Absent without a limit; with one the board is a single island, so + // its standing board's coordinates are already that island's. + cashBudget: plan.cashBudget, // Every attempt needs its own random stream — running the same walk // ten times over would only cost ten times as much. An unseeded run // gets a fresh stream per task already; a seeded one is offset so it diff --git a/src/lib/worker/variants.ts b/src/lib/worker/variants.ts index 727d1ad..c6473f8 100755 --- a/src/lib/worker/variants.ts +++ b/src/lib/worker/variants.ts @@ -1,5 +1,10 @@ import { buildOptimizationResult, type IslandPlan } from "@reactor2/solver"; -import { cheapestFirst, layoutKey, powerTies } from "@reactor2/solver"; +import { + cheapestFirst, + layoutKey, + netSpend, + powerTies, +} from "@reactor2/solver"; import type { IslandSolution } from "@reactor2/solver"; import type { OptimizationResult } from "@reactor2/solver"; @@ -76,6 +81,13 @@ export function buildSolveVariants( take(swapped); } - // Stable, so equal costs keep the order they were generated in. - return cheapestFirst(variants, (v) => v.placements); + // Stable, so equal costs keep the order they were generated in. Under a + // cash limit the cost is the spend from the board standing, as the engine + // ranked each island's shortlist. + const budget = plan.cashBudget; + return cheapestFirst( + variants, + (v) => v.placements, + budget && ((placements) => netSpend(placements, budget)), + ); } diff --git a/src/lib/worker/workerClient.ts b/src/lib/worker/workerClient.ts index 0781e09..a81995a 100755 --- a/src/lib/worker/workerClient.ts +++ b/src/lib/worker/workerClient.ts @@ -2,6 +2,7 @@ import type { Tile, AnomalyId, BuildingDefinition, + CashBudget, OptimizationResult, PrestigeScales, } from "@reactor2/solver"; @@ -82,6 +83,11 @@ export interface SolveRunOptions { * only layouts that also run at every one of these. */ upgradePlan?: Record[]; + /** + * A cash limit — see `CashBudget`. The run still maximises power, and keeps + * no layout that would cost more than this to build from the board standing. + */ + cashBudget?: CashBudget; } export interface SolveTaskHandle { @@ -148,6 +154,7 @@ export class SolverWorkerClient { anomalyId: run?.anomalyId, prestige: run?.prestige, upgradePlan: run?.upgradePlan, + cashBudget: run?.cashBudget, reportIntervalMs: this.options.reportIntervalMs, onProgress: (result) => { if (!entry.stopped) entry.onProgress?.(result);