Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
1a85014
Scenario land parcels, terrain shapes, tree stands; remix hard parks …
jiro-by-nori[bot] Nov 1, 2026
ae445af
Scenario previews from the real park map; show terrain and challenge …
jiro-by-nori[bot] Nov 1, 2026
547aced
Play-proof tests for the hard parks; Mossgrove trails inside the flat…
jiro-by-nori[bot] Nov 1, 2026
6ddc981
Regenerate previews; match apron error text
jiro-by-nori[bot] Nov 1, 2026
e234828
Catalog inventory tests respect forbidden ride types; timeouts for ma…
jiro-by-nori[bot] Nov 1, 2026
aa21d21
Check each hard park enforces its advertised rules
jiro-by-nori[bot] Nov 1, 2026
4e4aacf
Site-plan strategies for the hard parks; browser proof spec; remix de…
jiro-by-nori[bot] Nov 1, 2026
f4188da
Scenario-aware site plans for every hard park; harness plays the real…
jiro-by-nori[bot] Nov 1, 2026
eb94c29
Regenerate Copper Ridge preview
jiro-by-nori[bot] Nov 1, 2026
565a69e
Mossgrove Isle: richer site plan; ride income target set from demonst…
jiro-by-nori[bot] Nov 1, 2026
41e7437
Review fixes: rule tests with control runs, parser checks for parcels…
jiro-by-nori[bot] Nov 1, 2026
942c448
Proof spec: optional small viewport
jiro-by-nori[bot] Nov 1, 2026
920aaa9
Document land parcels, terrain shapes, tree stands, site plans and pr…
jiro-by-nori[bot] Nov 1, 2026
6ef7b90
Site plans: entrances and exits may join an existing level path
jiro-by-nori[bot] Nov 1, 2026
05f0a06
Site plans: link queue pieces in order so turning queues connect
jiro-by-nori[bot] Nov 1, 2026
bb79f2c
Format Copper Ridge plan
jiro-by-nori[bot] Nov 1, 2026
1b0168b
Balance results for the hard-park remixes
jiro-by-nori[bot] Nov 1, 2026
c99c6d2
Test hygiene: shared rider count, clearer failures and names
jiro-by-nori[bot] Nov 1, 2026
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: 4 additions & 1 deletion bench/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ 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. 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.
- [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.
- [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).
- [stats.ts](stats.ts) supplies nearest-rank percentile and budget helpers used by the benchmark and its tests.

### Core Implementation
Expand Down
339 changes: 339 additions & 0 deletions bench/hard-parks.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,339 @@
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 { ElementType } from '../src/sim/map/tile-map';
import { SceneryItem } from '../src/sim/map/scenery';
import { RideState, ridersInRecentWindow } from '../src/sim/rides/ride-store';
import { RideType } from '../src/sim/rides/ride-types';
import { SCENARIOS } from '../src/sim/scenario/catalog';
import { ParkGrid } from '../src/sim/scenario/park-grid';
import { prepareScenarioPark } from '../src/sim/scenario/scenario-layout';
import type { ScenarioDef } from '../src/sim/scenario/scenario';
import { ParkBuilder } from './strategy/builder';
import {
clearScenery,
connectOnGround,
flatGroundPath,
layRoute,
openCoaster,
openFlatRide,
waypoints,
} from './strategy/site';
import type { CoasterSite } from './strategy/site';

/**
* Plays the start of each hard park through ordinary player commands with the park's real cash:
* guests arrive through the gate, the first stalls and rides open, and the park's defining move
* (a gulch crossing, a pier bridge, a cliff descent, a mountainside coaster, a woodland clearing)
* is built and used.
*/

interface Park {
def: ScenarioDef;
sim: Simulation;
builder: ParkBuilder;
}

function open(id: string, items: readonly string[]): Park {
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);
const builder = new ParkBuilder(sim, def);
for (const name of items) expect(builder.build(name), name).toBeGreaterThanOrEqual(0);
return { def, sim, builder };
}

/** The far end of the spine path the builder laid inward from the gate. */
function spineEnd(park: Park): [number, number] {
const m = park.sim.world.map;
let row = 0;
for (;;) {
const [x, y] = park.builder.grid.tile(row + 1, 0);
if (m.pathElement(m.index(x, y), -1) < 0) break;
row++;
}
return park.builder.grid.tile(row, 0);
}

function hasPath(park: Park, [x, y]: readonly [number, number]): boolean {
const m = park.sim.world.map;
return m.pathElement(m.index(x, y), -1) >= 0;
}

/** Lays a route from the spine end through `points` and returns its tiles. */
function route(park: Park, points: ReadonlyArray<readonly [number, number]>, clear: boolean) {
const m = park.sim.world.map;
const start = spineEnd(park);
const tiles = waypoints([start, ...points]).slice(1);
if (clear) clearScenery(park.sim, tiles);
const levels = layRoute(park.sim, tiles, m.heights[m.index(start[0], start[1])]);
expect(levels).not.toBeNull();
for (const tile of tiles) expect(hasPath(park, tile), `path at ${tile}`).toBe(true);
return { tiles, levels: levels! };
}

function joinsRoute(park: Park, tiles: ReadonlyArray<readonly [number, number]>) {
const m = park.sim.world.map;
const set = new Set(tiles.map(([x, y]) => m.index(x, y)));
return (t: number) => set.has(t) && flatGroundPath(park.sim, t);
}

function play(park: Park, ticks: number): void {
for (let t = 0; t < ticks; t++) {
park.builder.advance();
park.sim.step();
}
}

/** Guests who rode in the ride's recent rider window. */
function riders(park: Park, rideId: number): number {
const w = park.sim.world;
return ridersInRecentWindow(w, w.rides.idToSlot[rideId]);
}

function trees(park: Park): number {
const m = park.sim.world.map;
let n = 0;
for (let e = 0; e < m.elementCapacity; e++) if (m.elType[e] === ElementType.SmallScenery) n++;
return n;
}

function expectSolvent(park: Park): void {
const l = park.sim.world.economy;
expect(l.cash).toBeGreaterThanOrEqual(0);
expect(l.loan).toBeLessThanOrEqual(l.maxLoan);
}

const MONTH = 16_384;

/** With HARD_PROOF_SAVES set, each proof park is saved there for the browser screenshots. */
function keep(park: Park, focus: readonly [number, number]): void {
const dir = process.env.HARD_PROOF_SAVES;
if (!dir) return;
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, `${park.def.id}.ocsave`), serialize(park.sim.world));
const m = park.sim.world.map;
const z = m.heights[m.index(focus[0], focus[1])];
writeFileSync(join(dir, `${park.def.id}.json`), JSON.stringify({ focus: [...focus, z] }));
}

const TREES = new Set<number>([
SceneryItem.OakTree,
SceneryItem.Conifer,
SceneryItem.BlossomTree,
SceneryItem.BirchTree,
SceneryItem.AutumnTree,
SceneryItem.TopiaryTree,
SceneryItem.PalmTree,
SceneryItem.CactusTree,
]);

describe('hard parks are playable with legal construction', { timeout: 60_000 }, () => {
it('Copper Ridge: cross the gulch on the trail and open a coaster on the west bench', () => {
const park = open('copper-ridge', ['foodStall', 'drinkStall', 'toilets', 'merryGoRound']);
const [x0] = spineEnd(park);
const trail = route(
park,
[
[x0, 75],
[34, 75],
[34, 42],
],
true,
);
expect(Math.min(...trail.levels)).toBeLessThanOrEqual(6);
expect(Math.max(...trail.levels)).toBeGreaterThanOrEqual(11);
const site: CoasterSite = { template: 'compact', x: 28, y: 40, dir: 0, mirror: true };
const coaster = openCoaster(park.sim, site, joinsRoute(park, trail.tiles))!;
expect(coaster).not.toBeNull();
expect(coaster.state).toBe(RideState.Open);
expect(coaster.excitement).toBeGreaterThanOrEqual(park.def.objective.minimumExcitement!);
play(park, MONTH);
expect(riders(park, coaster.rideId)).toBeGreaterThan(0);
expectSolvent(park);
keep(park, [34, 60]);
});

it('Glacier Point: open stalls and a mountainside coaster above the 4.70 target', () => {
const park = open('glacier-point', ['foodStall', 'drinkStall', 'toilets']);
const site: CoasterSite = { template: 'compact', x: 80, y: 56, dir: 2, mirror: false };
const coaster = openCoaster(park.sim, site, (t) => flatGroundPath(park.sim, t))!;
expect(coaster).not.toBeNull();
expect(coaster.state).toBe(RideState.Open);
expect(coaster.excitement).toBeGreaterThanOrEqual(park.def.objective.minimumExcitement!);
play(park, MONTH);
expect(riders(park, coaster.rideId)).toBeGreaterThan(0);
expectSolvent(park);
keep(park, [80, 54]);
});

it('Tidewater Docks: buy rights over an inlet, bridge it and fit a ride on a narrow pier', () => {
const park = open('tidewater-docks', ['foodStall', 'drinkStall', 'toilets', 'merryGoRound']);
const sim = park.sim;
const m = sim.world.map;
const inlet = { x: 37, y: 43, width: 6, height: 3 };
sim.enqueue({ type: 'buyLand', ...inlet, rights: true });
sim.step();
const quay = route(
park,
[
[19, 47],
[19, 61],
[34, 61],
[34, 44],
[45, 44],
[45, 52],
],
true,
);
const bridge = quay.tiles.filter(([x, y]) => y === 44 && x >= 37 && x <= 42);
expect(
bridge.every(
([x, y]) =>
m.waterLevel[m.index(x, y)] > m.heights[m.index(x, y)] || m.slope[m.index(x, y)] !== 0,
),
).toBe(true);
expect(bridge.some(([x, y]) => m.waterLevel[m.index(x, y)] > m.heights[m.index(x, y)])).toBe(
true,
);
const pier = new ParkGrid(45, 58, 'south');
const wheel = openFlatRide(sim, pier, 10, 2, 'ferrisWheel')!;
expect(wheel).not.toBeNull();
expect(wheel.state).toBe(RideState.Open);
play(park, MONTH);
expect(riders(park, wheel.rideId)).toBeGreaterThan(0);
expectSolvent(park);
keep(park, [40, 46]);
});

it('Thunderhead Mesa: take the cliff trail down to the west shelf and open a ride there', () => {
const park = open('thunderhead-mesa', ['foodStall', 'drinkStall', 'toilets', 'merryGoRound']);
const [x0] = spineEnd(park);
const descent: Array<[number, number]> = [
[x0, 24],
[34, 24],
];
for (let y = 27; y <= 51; y += 3) descent.push([Math.round(34 - ((y - 24) * 10) / 26), y]);
descent.push([24, 54]);
const trail = route(park, descent, true);
expect(trail.levels[0]).toBe(16);
expect(trail.levels[trail.levels.length - 1]).toBe(11);
const shelf = new ParkGrid(24, 51, 'north');
const ride = openFlatRide(park.sim, shelf, 3, 2, 'drinkStall')!;
expect(ride).not.toBeNull();
const pad: Array<[number, number]> = [];
for (let y = 52; y <= 58; y++) for (let x = 15; x <= 23; x++) pad.push([x, y]);
clearScenery(park.sim, pad);
const carousel = openFlatRide(park.sim, shelf, 3, -6, 'merryGoRound');
expect(carousel?.state ?? -1).toBe(RideState.Open);
play(park, MONTH);
expect(riders(park, carousel!.rideId)).toBeGreaterThan(0);
expectSolvent(park);
keep(park, [28, 44]);
});

it('Mossgrove Isle: thread a path through the protected woods to a clearing without felling a tree', () => {
const park = open('mossgrove-isle', ['foodStall', 'drinkStall', 'toilets']);
const sim = park.sim;
const m = sim.world.map;
const before = trees(park);
const clearing = new ParkGrid(44, 38, 'south');
const spine = [clearing.tile(1, 0), clearing.tile(2, 0), clearing.tile(3, 0)];
for (const [x, y] of spine) sim.enqueue({ type: 'placePath', x, y });
sim.step();
for (const tile of spine) expect(hasPath(park, tile)).toBe(true);
const own = new Set(spine.map(([x, y]) => m.index(x, y)));
const trail = connectOnGround(
sim,
clearing.tile(0, 0),
(t) => !own.has(t) && flatGroundPath(sim, t),
);
expect(trail).not.toBeNull();
expect(trail!.length).toBeGreaterThan(4);
const carousel = openFlatRide(sim, clearing, 3, 2, 'merryGoRound')!;
expect(carousel).not.toBeNull();
expect(carousel.state).toBe(RideState.Open);
play(park, MONTH);
expect(riders(park, carousel.rideId)).toBeGreaterThan(0);
expect(trees(park)).toBe(before);
expectSolvent(park);
keep(park, [42, 39]);
});
});

describe('each hard park enforces the rules it advertises', () => {
/** The park as shipped, or with its rules removed for a control run. */
function fresh(id: string, rules = true): Simulation {
const shipped = SCENARIOS.find((s) => s.id === id)!;
const def = rules ? shipped : { ...shipped, restrictions: undefined };
const sim = new Simulation({ seed: def.seed, width: def.mapWidth, height: def.mapHeight });
prepareScenarioPark(sim.world, def);
return sim;
}

function raisedBench(sim: Simulation): boolean {
const m = sim.world.map;
const before = m.vertexHeights[m.vertexIndex(52, 80)];
sim.enqueue({ type: 'raiseLand', x: 50, y: 78, width: 4, height: 4 });
sim.step();
return m.vertexHeights[m.vertexIndex(52, 80)] !== before;
}

it('Copper Ridge refuses to reshape its owned land', () => {
expect(raisedBench(fresh('copper-ridge', false))).toBe(true);
expect(raisedBench(fresh('copper-ridge'))).toBe(false);
});

it('Mossgrove Isle keeps every tree when the player tries to clear the woods', () => {
const count = (sim: Simulation) => {
const m = sim.world.map;
let n = 0;
for (let e = 0; e < m.elementCapacity; e++)
if (m.elType[e] === ElementType.SmallScenery && TREES.has(m.elData[e])) n++;
return n;
};
const clear = (sim: Simulation) => {
const before = count(sim);
sim.enqueue({ type: 'clearScenery', x: 20, y: 18, width: 30, height: 20 });
sim.step();
return before - count(sim);
};
expect(clear(fresh('mossgrove-isle', false))).toBeGreaterThan(100);
expect(clear(fresh('mossgrove-isle'))).toBe(0);
});

it('Glacier Point refuses a flat ride where one would otherwise fit', () => {
const attempt = (sim: Simulation, x: number, y: number) => {
sim.world.research.unlocked.add(RideType.MerryGoRound);
const rides = sim.world.rides.count;
sim.enqueue({ type: 'createRide', rideType: RideType.MerryGoRound, x, y });
sim.step();
return sim.world.rides.count > rides;
};
const spot = [
[80, 50],
[78, 54],
[76, 48],
[84, 56],
].find(([x, y]) => attempt(fresh('glacier-point', false), x, y));
expect(spot).toBeDefined();
expect(attempt(fresh('glacier-point'), spot![0], spot![1])).toBe(false);
});

it('Thunderhead Mesa refuses marketing and tall construction', () => {
const tryBoth = (sim: Simulation) => {
const l = sim.world.economy;
const campaign = l.campaignId;
sim.enqueue({ type: 'economy', action: { type: 'startCampaign', campaignId: 1, weeks: 2 } });
const m = sim.world.map;
const ground = m.heights[m.index(44, 14)];
sim.enqueue({ type: 'placePath', x: 44, y: 14, z: ground + 8 });
sim.step();
return { marketed: l.campaignId !== campaign, tall: m.pathElement(m.index(44, 14), -1) >= 0 };
};
expect(tryBoth(fresh('thunderhead-mesa', false))).toEqual({ marketed: true, tall: true });
expect(tryBoth(fresh('thunderhead-mesa'))).toEqual({ marketed: false, tall: false });
});
});
Loading
Loading