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
5 changes: 3 additions & 2 deletions bench/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ Path: @/bench
- [audio.ts](audio.ts) feeds a warmed synthetic snapshot with a large guest count and many rides through [AudioEngine](../src/audio/audio.ts), using a recording Web Audio context so the benchmark measures JavaScript update and scheduling overhead without browser audio rendering.
- [balance.ts](balance.ts) (`pnpm balance`) is the gameplay-balance harness: [balance-park.ts](balance-park.ts) scripts a starter park (rides take their real footprints: each side of the spine allocates rows for queue, exit and body, and late additions that no longer fit are skipped) (minimal, sensible, modest or ambitious profile) with player commands, and the runner steps one in-game year (flags `--admission DOLLARS`, `--repay-loan-month N` and `--stalls-at-value` stand in for a player who sets the gate price, prices stalls at their value and pays off the loan) and prints guest count, rating curve, cash, ride usage (including reliability, breakdown count and downtime ticks), the guest thought histogram, the ledger and the objective result. Stalls and facilities use adjacent public paths for direct access; ordinary rides use entrances, exits and queues. `balance.test.ts` pins determinism and basic health. Its year-end objective checks run default scenario seed 2026 and fixed seeds 1 to 3; the scripted park hires eight handymen and two mechanics by the time the coaster opens. The extra mechanic is assigned when the coaster is built so it can enter service with maintenance staff. Paired measurements are in [the PR proof](https://github.com/tilework-tech/opencoaster/tree/nori/pr-proofs/exterior-litter-graffiti). Results are recorded in [docs/BALANCE.md](../docs/BALANCE.md).
- [finance-proof-save.ts](finance-proof-save.ts) writes a scripted starter park as a save file after a few months, for filming the Finances window ([e2e/finances.spec.ts](../e2e/finances.spec.ts)).
- [scenario-balance.ts](scenario-balance.ts) (`pnpm balance --scenario <id|all> [--seeds 12] [--jobs N] [--trace]`) plays each shipped scenario with its scripted strategy over seeds 1..N, one child process per seed group, and prints the win count and per-seed outcome. [strategy/](strategy) holds the scripts: `builder.ts` places rides, stalls, and coasters on the gate-relative park grid; ordinary rides and coasters use entrance/exit and queue paths, while stalls and facilities use an adjacent public path for direct access. The builder adds bins along paths and a walkway around each coaster; `growth.ts` is the build-order strategy (cash-gated, optional per-seed imperfection); `coasters.ts` holds the searched circuits; `strategies.ts` assigns one per scenario. Parks are prepared with `prepareScenarioPark`, the same path as a new game, so the strategy plays the real map including the approach path and ambient trees (scenery near a coaster station feeds its excitement rating, so leaving trees out would skew results). The balance harness unlocks the ride catalog before play to isolate park and economy tuning from research pacing; normal scenarios still enforce their own unlocks at the simulation command boundary. `scenario-balance.test.ts` checks every scenario has a strategy that builds an open park. A have-fun scenario counts as won when, after four years, the park is solvent, rated 600 or more and holds 200 guests.
- The hard parks (rough terrain, odd-shaped land, protected trees, build limits) cannot be played by the spine-based growth strategy, so they use `sitePlanStrategy` in [strategy/site-plan.ts](strategy/site-plan.ts) with a per-park plan in [strategy/plans/](strategy/plans). A plan is an ordered list of steps (`item` on the builder's spine, `route` footpath, `coaster` at a pinned site, `flat` ride beside its own spine, `buy` land or rights, `clear` scenery); each is built in order once cash covers its estimated cost plus a reserve, optionally borrowing in $1,000 steps. The strategy also keeps handymen and mechanics in proportion to the park, deals handymen patrol rectangles in turn, can plant decoration round each coaster station, and can repay the loan above a cash margin.
- [scenario-balance.ts](scenario-balance.ts) (`pnpm balance --scenario <id|all> [--seeds 12] [--jobs N] [--trace]`) plays each shipped scenario with its scripted strategy over seeds 1..N, one child process per seed group, and prints the win count and per-seed outcome. [strategy/](strategy) holds the scripts: `builder.ts` places rides, stalls, and coasters on the gate-relative park grid; ordinary rides and coasters use entrance/exit and queue paths, while stalls and facilities use an adjacent public path for direct access. The builder adds bins along paths and a walkway around each coaster; `growth.ts` is the build-order strategy (cash-gated, optional per-seed imperfection); `coasters.ts` holds the searched circuits; `strategies.ts` assigns one per scenario. Parks are prepared with `prepareScenarioPark`, the same path as a new game, so the strategy plays the real map including the approach path and ambient trees (scenery near a coaster station feeds its excitement rating, so leaving trees out would skew results). The balance harness unlocks the ride catalog before play to isolate park and economy tuning from research pacing unless `runScenario` gets `realResearch`, which keeps the scenario's own research state; normal scenarios still enforce their own unlocks at the simulation command boundary. `scenario-balance.test.ts` checks every scenario has a strategy that builds an open park. A have-fun scenario counts as won when, after four years, the park is solvent, rated 600 or more and holds 200 guests.
- The hard parks (rough terrain, odd-shaped land, protected trees, build limits) cannot be played by the spine-based growth strategy, so they use `sitePlanStrategy` in [strategy/site-plan.ts](strategy/site-plan.ts) with a per-park plan in [strategy/plans/](strategy/plans). A plan is an ordered list of steps: `item` on the builder's spine, `route` footpath (optionally a bin on every other tile), `coaster` at a pinned site, `flat` ride beside its own spine (optionally clearing scenery from the spine, frontage and footprint first, via `flatRideTiles` in site.ts), `buy` land or rights, `clear` scenery, `bins` on every non-queue footpath in a rectangle (bins are free), `repay` the whole loan, and `wait` (holds the remaining steps until a given month). Each is built in order once cash covers its estimated cost plus a reserve, optionally borrowing in $1,000 steps; `repay` waits until the cash covers the loan plus the reserve. The strategy also keeps handymen and mechanics in proportion to the park, deals handymen patrol rectangles in turn (a null entry leaves that handyman roaming), can set research funding on the first tick, can plant decoration round each coaster station, and can repay the loan above a cash margin.
- [strategy/site.ts](strategy/site.ts) holds the legal-construction helpers those plans and the hard-park tests share: `buildCircuit` lays a wooden coaster template at a pinned site (supports over slopes, tunnels into ground); `layRoute` lays a footpath that keeps to the ground and otherwise climbs, descends or bridges one level per tile; `connectOnGround` finds the shortest ground-level connector to an existing path; `startCoaster`/`openCoaster` add queue and exit paths and run the test; `openFlatRide` places a flat ride beside a spine; `circuitTiles` finds the tiles a coaster actually needs by building it on a copy of the park, so only those trees are cleared. Everything goes through ordinary player commands, so ownership, terrain and scenario restrictions apply.
- [hard-parks.test.ts](hard-parks.test.ts) plays each hard park's opening and its defining move (e.g. a gulch crossing, a pier bridge, a cliff descent) with the park's real cash, and checks with control runs that each park enforces the restrictions it advertises. With `HARD_PROOF_SAVES` set it also writes each built park as a save plus a focus tile, consumed by [e2e/hard-parks-proof.spec.ts](../e2e/hard-parks-proof.spec.ts).
- [hard-park-wins.ts](hard-park-wins.ts) (run by `hard-park-wins.tidewater.test.ts` and `hard-park-wins.thunderhead.test.ts`, one file per park so the runs go in parallel) plays Tidewater Docks and Thunderhead Mesa to their deadlines with their site plans on the new-game map (the scenario's own seed) and `realResearch`, and asserts a win at the deadline. It also checks that research starts from the scenario's set without the catalog unlocked, and (as soft checks, at month 12) that every ride placed so far is open or broken and that every queued ride has room for more than four guests, the capacity of a ride with no queue tiles. With `HARD_PROOF_SAVES` set it writes each won park as `<id>-won.ocsave` plus `<id>-won.json` (view tiles with their heights) for the won-park browser proof. Each park has a five-minute test timeout.
- [stats.ts](stats.ts) supplies nearest-rank percentile and budget helpers used by the benchmark and its tests.

### Core Implementation
Expand Down
3 changes: 3 additions & 0 deletions bench/hard-park-wins.thunderhead.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { describeHardParkWin } from './hard-park-wins';

describeHardParkWin('thunderhead-mesa');
3 changes: 3 additions & 0 deletions bench/hard-park-wins.tidewater.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { describeHardParkWin } from './hard-park-wins';

describeHardParkWin('tidewater-docks');
101 changes: 101 additions & 0 deletions bench/hard-park-wins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { serialize } from '../src/save/save';
import { Simulation } from '../src/sim/core/simulation';
import { TICKS_PER_MONTH } from '../src/sim/economy/calendar';
import { rideQueueCapacity } from '../src/sim/rides/ride-operations';
import { RideState } from '../src/sim/rides/ride-store';
import { RIDE_CATALOG } from '../src/sim/rides/ride-types';
import type { RideType } from '../src/sim/rides/ride-types';
import { SCENARIOS } from '../src/sim/scenario/catalog';
import { ScenarioStatus } from '../src/sim/scenario/scenario';
import { prepareScenarioPark } from '../src/sim/scenario/scenario-layout';
import { runScenario } from './strategy/run';
import { STRATEGIES } from './strategy/strategies';

/**
* Plays a hard park to its deadline on the map a new game generates (the scenario's own seed),
* with the scenario's own research, cash and loan, and only the commands a player issues; it must
* end in a win. Each park has its own test file (hard-park-wins.<park>.test.ts) so the long runs
* go in parallel. With HARD_PROOF_SAVES set, the won park is saved there for the browser proof.
*/

const TIMEOUT_MS = 300_000;

const QUEUED_CATEGORIES = new Set(['gentle', 'thrill', 'coaster', 'water', 'transport']);

/** Tiles the browser proof centres on: the busiest part of each won park, then its far end. */
const VIEWS: Record<string, ReadonlyArray<readonly [number, number]>> = {
'tidewater-docks': [
[15, 48],
[40, 52],
],
'thunderhead-mesa': [
[45, 16],
[22, 56],
],
};

function startingResearch(id: string): number[] {
const def = SCENARIOS.find((s) => s.id === id)!;
const sim = new Simulation({ seed: def.seed, width: def.mapWidth, height: def.mapHeight });
prepareScenarioPark(sim.world, def);
return [...sim.world.research.unlocked].sort((a, b) => a - b);
}

export function describeHardParkWin(id: 'tidewater-docks' | 'thunderhead-mesa'): void {
describe(id, () => {
const def = SCENARIOS.find((s) => s.id === id)!;

it(
'wins on the new-game map with the scenario research, its rides open and queueing',
() => {
let research: number[] = [];
const shortQueues: string[] = [];
const unopened: string[] = [];
let finalWorld: Simulation['world'] | null = null;
const result = runScenario(def, STRATEGIES[id], {
seed: def.seed,
realResearch: true,
onMonth: (month, world) => {
if (month === 1) research = [...world.research.unlocked].sort((a, b) => a - b);
finalWorld = world;
if (month !== 12) return;
const rides = world.rides.cols;
for (let slot = 0; slot < world.rides.count; slot++) {
const ride = RIDE_CATALOG[rides.typeId[slot] as RideType];
const where = `${ride.name} at ${rides.rideX[slot]},${rides.rideY[slot]}`;
const state = rides.state[slot];
if (state !== RideState.Open && state !== RideState.Broken) unopened.push(where);
if (QUEUED_CATEGORIES.has(ride.category) && rideQueueCapacity(world, slot) <= 4)
shortQueues.push(where);
}
},
});

const dir = process.env.HARD_PROOF_SAVES;
if (dir && finalWorld) {
const world: Simulation['world'] = finalWorld;
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, `${id}-won.ocsave`), serialize(world));
const views = VIEWS[id].map(([x, y]) => [x, y, world.map.heights[world.map.index(x, y)]]);
writeFileSync(join(dir, `${id}-won.json`), JSON.stringify({ views }));
}

expect(research, 'starts from the scenario research').toEqual(
expect.arrayContaining(startingResearch(id)),
);
expect(research.length, 'the catalog is not unlocked up front').toBeLessThan(
Object.keys(RIDE_CATALOG).length,
);
expect.soft(unopened, 'every ride placed in the first year opens').toEqual([]);
expect.soft(shortQueues, 'rides have room to queue').toEqual([]);
expect(result.status, JSON.stringify(result)).toBe(ScenarioStatus.Won);
expect(result.tick).toBeGreaterThanOrEqual(def.objective.byTick);
expect(result.tick).toBeLessThan(def.objective.byTick + TICKS_PER_MONTH);
},
TIMEOUT_MS,
);
});
}
Loading
Loading