Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 43 additions & 1 deletion docs/SOLVER.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
74 changes: 66 additions & 8 deletions packages/solver/bin/solve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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";
Expand Down Expand Up @@ -158,6 +164,31 @@ interface Progress {
research: Record<string, number>;
/** The plan's rosters before its target, today's first — `resolveUpgradePlan`'s `along`. */
upgradePlan: Record<string, number>[];
/** `--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 -------------------------------------------------------------
Expand Down Expand Up @@ -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(
Expand All @@ -201,6 +233,7 @@ async function solveWithPool(
anomalyId,
prestige: prestigeScales(progress.research),
upgradePlan: progress.upgradePlan,
cashBudget: progress.cashBudget,
},
seed,
);
Expand Down Expand Up @@ -228,6 +261,7 @@ async function solveWithPool(
// the same string.
anomaly: plan.anomaly,
upgradeSteps: plan.upgradeSteps,
cashBudget: plan.cashBudget,
},
})),
(i, result) => {
Expand Down Expand Up @@ -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<SolveRun[]> {
const { grid } = await decodeBlueprint(gameMap.code);
const { grid, placements } = await decodeBlueprint(gameMap.code);
const progress = withBudget(boardProgress, placements);
const roster = getEffectiveBuildings(
BUILDINGS,
unlockedUpgrades,
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -423,10 +462,11 @@ function workerCount(attempts: number, requested?: number): number {
async function runSession(
gameMap: CliMap,
unlockedUpgrades: Record<string, number>,
progress: Progress,
boardProgress: Progress,
args: Args,
): Promise<SessionReport> {
const { grid } = await decodeBlueprint(gameMap.code);
const { grid, placements } = await decodeBlueprint(gameMap.code);
const progress = withBudget(boardProgress, placements);
const roster = getEffectiveBuildings(
BUILDINGS,
unlockedUpgrades,
Expand Down Expand Up @@ -477,6 +517,7 @@ async function runSession(
anomalyId: args.anomalyId,
prestige: prestigeScales(progress.research),
upgradePlan: progress.upgradePlan,
cashBudget: progress.cashBudget,
},
})),
(attempt, raw) => {
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand All @@ -612,6 +661,7 @@ function parseArgs(argv: string[]): Args | null {
tiers: {},
plan: [],
code: undefined,
cash: undefined,
};

const takeValue = (
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -787,7 +843,9 @@ export async function main(argv: string[]): Promise<number> {
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)
Expand Down
5 changes: 5 additions & 0 deletions packages/solver/bin/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { solve } from "../src/solver/solver";
import type {
AnomalyDefinition,
AnomalyId,
CashBudget,
EffectiveBuilding,
IslandSubGrid,
PrestigeScales,
Expand All @@ -30,6 +31,7 @@ type Task =
seed?: number;
anomaly?: AnomalyDefinition;
upgradeSteps?: EffectiveBuilding[][];
cashBudget?: CashBudget;
}
| {
kind: "attempt";
Expand All @@ -40,6 +42,7 @@ type Task =
anomalyId?: AnomalyId;
prestige?: PrestigeScales;
upgradePlan?: Record<string, number>[];
cashBudget?: CashBudget;
};

parentPort?.on(
Expand All @@ -56,6 +59,7 @@ parentPort?.on(
payload.seed,
payload.anomaly,
payload.upgradeSteps,
payload.cashBudget,
)
: await solve(
payload.grid,
Expand All @@ -66,6 +70,7 @@ parentPort?.on(
anomalyId: payload.anomalyId,
prestige: payload.prestige,
upgradePlan: payload.upgradePlan,
cashBudget: payload.cashBudget,
},
payload.seed,
);
Expand Down
Loading
Loading