diff --git a/bench/docs.md b/bench/docs.md index 0e908e87f..69693e6ac 100644 --- a/bench/docs.md +++ b/bench/docs.md @@ -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 [--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 [--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 diff --git a/bench/hard-parks.test.ts b/bench/hard-parks.test.ts new file mode 100644 index 000000000..02b2f8548 --- /dev/null +++ b/bench/hard-parks.test.ts @@ -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, 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) { + 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([ + 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 }); + }); +}); diff --git a/bench/strategy/builder.ts b/bench/strategy/builder.ts index c69c2d3be..26120c947 100644 --- a/bench/strategy/builder.ts +++ b/bench/strategy/builder.ts @@ -405,6 +405,12 @@ export class ParkBuilder { throw new Error('no walkway from the coaster exit to its connector'); } + /** Opens `rideId` once its test run, already started, finishes; see `advance`. */ + watch(rideId: number): void { + this.testing.set(rideId, this.sim.world.tick); + this.rideIds.push(rideId); + } + /** Opens each finished test run. Call regularly; it is cheap. */ advance(): void { const world = this.sim.world; diff --git a/bench/strategy/plans/copper-ridge.json b/bench/strategy/plans/copper-ridge.json new file mode 100644 index 000000000..4bef5e238 --- /dev/null +++ b/bench/strategy/plans/copper-ridge.json @@ -0,0 +1,47 @@ +[ + { "kind": "item", "name": "foodStall" }, + { "kind": "item", "name": "drinkStall" }, + { "kind": "item", "name": "toilets" }, + { "kind": "item", "name": "merryGoRound" }, + { + "kind": "route", + "points": [ + [46, 75], + [34, 75], + [34, 42] + ], + "clear": true + }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 24, "y": 42, "dir": 1, "mirror": false } + }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 42, "y": 44, "dir": 2, "mirror": false } + }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 54, "y": 78, "dir": 0, "mirror": false } + }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 42, "y": 80, "dir": 0, "mirror": true } + }, + { "kind": "buy", "x": 58, "y": 36, "width": 1, "height": 42, "rights": false }, + { + "kind": "route", + "points": [ + [58, 77], + [58, 36] + ], + "clear": true, + "from": [46, 77] + }, + { "kind": "buy", "x": 59, "y": 37, "width": 13, "height": 1, "rights": false }, + { "kind": "route", "points": [[70, 37]], "clear": true, "from": [58, 37] }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 74, "y": 36, "dir": 2, "mirror": false } + } +] diff --git a/bench/strategy/plans/glacier-point.json b/bench/strategy/plans/glacier-point.json new file mode 100644 index 000000000..79ab253b2 --- /dev/null +++ b/bench/strategy/plans/glacier-point.json @@ -0,0 +1,47 @@ +[ + { "kind": "item", "name": "foodStall" }, + { "kind": "item", "name": "drinkStall" }, + { "kind": "item", "name": "toilets" }, + { + "kind": "route", + "points": [ + [80, 52], + [80, 59], + [74, 59], + [74, 61], + [70, 61], + [70, 64], + [66, 64], + [66, 67], + [61, 67], + [61, 70] + ], + "clear": true + }, + { "kind": "buy", "x": 50, "y": 42, "width": 24, "height": 18, "rights": false }, + { "kind": "buy", "x": 50, "y": 42, "width": 24, "height": 18, "rights": true }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 82, "y": 56, "dir": 3, "mirror": false } + }, + { + "kind": "coaster", + "site": { "template": "switchback", "x": 66, "y": 48, "dir": 1, "mirror": false } + }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 58, "y": 50, "dir": 2, "mirror": true } + }, + { + "kind": "coaster", + "site": { "template": "switchback", "x": 82, "y": 46, "dir": 1, "mirror": false } + }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 70, "y": 54, "dir": 3, "mirror": true } + }, + { + "kind": "coaster", + "site": { "template": "compact", "x": 59, "y": 71, "dir": 1, "mirror": false } + } +] diff --git a/bench/strategy/plans/mossgrove-isle.json b/bench/strategy/plans/mossgrove-isle.json new file mode 100644 index 000000000..005553f32 --- /dev/null +++ b/bench/strategy/plans/mossgrove-isle.json @@ -0,0 +1,18 @@ +[ + { "kind": "item", "name": "foodStall" }, + { "kind": "item", "name": "drinkStall" }, + { "kind": "item", "name": "toilets" }, + { "kind": "route", "points": [[35, 38]], "clear": false }, + { "kind": "flat", "grid": [35, 38, "west"], "row": 2, "lateral": 6, "name": "swingingShip" }, + { "kind": "flat", "grid": [35, 38, "west"], "row": 8, "lateral": -2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [35, 38, "west"], "row": 8, "lateral": -6, "name": "swingingShip" }, + { "kind": "flat", "grid": [35, 38, "west"], "row": 10, "lateral": 2, "name": "toilets" }, + { "kind": "flat", "grid": [35, 38, "east"], "row": 2, "lateral": 6, "name": "merryGoRound" }, + { "kind": "flat", "grid": [35, 38, "east"], "row": 6, "lateral": -2, "name": "swingingShip" }, + { "kind": "flat", "grid": [25, 38, "south"], "row": 3, "lateral": -2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [25, 38, "south"], "row": 4, "lateral": 2, "name": "informationKiosk" }, + { "kind": "flat", "grid": [25, 38, "south"], "row": 16, "lateral": 6, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [45, 38, "south"], "row": 3, "lateral": 2, "name": "merryGoRound" }, + { "kind": "flat", "grid": [45, 38, "south"], "row": 8, "lateral": 6, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [45, 38, "south"], "row": 9, "lateral": 2, "name": "informationKiosk" } +] diff --git a/bench/strategy/plans/thunderhead-mesa.json b/bench/strategy/plans/thunderhead-mesa.json new file mode 100644 index 000000000..93351160d --- /dev/null +++ b/bench/strategy/plans/thunderhead-mesa.json @@ -0,0 +1,81 @@ +[ + { "kind": "item", "name": "foodStall" }, + { "kind": "item", "name": "drinkStall" }, + { "kind": "item", "name": "toilets" }, + { "kind": "item", "name": "merryGoRound" }, + { "kind": "route", "points": [[46, 20]], "clear": true }, + { + "kind": "route", + "points": [ + [46, 24], + [34, 24], + [33, 27], + [32, 30], + [31, 33], + [29, 36], + [28, 39], + [27, 42], + [26, 45], + [25, 48], + [24, 51], + [24, 54] + ], + "clear": true, + "from": [46, 20] + }, + { "kind": "flat", "grid": [46, 20, "west"], "row": 2, "lateral": -6, "name": "swingingShip" }, + { "kind": "flat", "grid": [46, 20, "west"], "row": 4, "lateral": 2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [46, 20, "west"], "row": 9, "lateral": 2, "name": "swingingShip" }, + { "kind": "flat", "grid": [46, 20, "west"], "row": 9, "lateral": -2, "name": "toilets" }, + { "kind": "flat", "grid": [46, 20, "east"], "row": 2, "lateral": 2, "name": "swingingShip" }, + { "kind": "flat", "grid": [46, 20, "east"], "row": 2, "lateral": -6, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [46, 20, "east"], "row": 3, "lateral": -2, "name": "merryGoRound" }, + { "kind": "flat", "grid": [46, 20, "east"], "row": 6, "lateral": -2, "name": "drinkStall" }, + { "kind": "flat", "grid": [46, 20, "east"], "row": 8, "lateral": 2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [46, 20, "east"], "row": 8, "lateral": -2, "name": "merryGoRound" }, + { "kind": "flat", "grid": [24, 51, "north"], "row": 2, "lateral": -2, "name": "swingingShip" }, + { "kind": "flat", "grid": [24, 51, "north"], "row": 2, "lateral": 6, "name": "toilets" }, + { "kind": "flat", "grid": [24, 51, "north"], "row": 2, "lateral": -6, "name": "merryGoRound" }, + { "kind": "flat", "grid": [24, 51, "north"], "row": 4, "lateral": 6, "name": "swingingShip" }, + { "kind": "flat", "grid": [24, 51, "north"], "row": 6, "lateral": 2, "name": "ferrisWheel" }, + { + "kind": "flat", + "grid": [24, 51, "north"], + "row": 7, + "lateral": -2, + "name": "informationKiosk" + }, + { "kind": "flat", "grid": [24, 51, "north"], "row": 8, "lateral": -6, "name": "merryGoRound" }, + { "kind": "buy", "x": 56, "y": 28, "width": 18, "height": 26, "rights": false }, + { "kind": "buy", "x": 56, "y": 28, "width": 18, "height": 26, "rights": true }, + { "kind": "buy", "x": 60, "y": 51, "width": 20, "height": 12, "rights": false }, + { + "kind": "route", + "points": [ + [60, 30], + [63, 30], + [63, 36], + [66, 36], + [66, 42], + [68, 42], + [68, 48], + [70, 48], + [70, 57], + [62, 57] + ], + "clear": true, + "from": [60, 20] + }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 2, "lateral": 2, "name": "swingingShip" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 2, "lateral": -2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 2, "lateral": 6, "name": "informationKiosk" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 4, "lateral": 6, "name": "swingingShip" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 5, "lateral": -6, "name": "merryGoRound" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 8, "lateral": 2, "name": "swingingShip" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 9, "lateral": -2, "name": "toilets" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 10, "lateral": 6, "name": "swingingShip" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 11, "lateral": -2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 14, "lateral": 2, "name": "merryGoRound" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 14, "lateral": -6, "name": "drinkStall" }, + { "kind": "flat", "grid": [62, 57, "west"], "row": 18, "lateral": 2, "name": "ferrisWheel" } +] diff --git a/bench/strategy/plans/tidewater-docks.json b/bench/strategy/plans/tidewater-docks.json new file mode 100644 index 000000000..061b7f6bf --- /dev/null +++ b/bench/strategy/plans/tidewater-docks.json @@ -0,0 +1,36 @@ +[ + { "kind": "item", "name": "foodStall" }, + { "kind": "item", "name": "drinkStall" }, + { "kind": "item", "name": "toilets" }, + { "kind": "item", "name": "merryGoRound" }, + { "kind": "buy", "x": 37, "y": 43, "width": 6, "height": 3, "rights": true }, + { + "kind": "route", + "points": [ + [19, 47], + [19, 61], + [34, 61], + [34, 44], + [45, 44], + [45, 52] + ], + "clear": true + }, + { "kind": "flat", "grid": [34, 61, "south"], "row": 3, "lateral": 2, "name": "swingingShip" }, + { "kind": "flat", "grid": [34, 61, "south"], "row": 9, "lateral": 2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [34, 61, "south"], "row": 9, "lateral": -2, "name": "swingingShip" }, + { "kind": "flat", "grid": [34, 61, "south"], "row": 13, "lateral": 2, "name": "toilets" }, + { "kind": "flat", "grid": [34, 61, "south"], "row": 15, "lateral": -2, "name": "swingingShip" }, + { "kind": "flat", "grid": [45, 52, "north"], "row": 2, "lateral": 2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [45, 52, "north"], "row": 2, "lateral": -2, "name": "swingingShip" }, + { "kind": "flat", "grid": [45, 52, "north"], "row": 6, "lateral": 2, "name": "toilets" }, + { "kind": "flat", "grid": [45, 52, "north"], "row": 8, "lateral": 2, "name": "merryGoRound" }, + { "kind": "flat", "grid": [45, 52, "north"], "row": 8, "lateral": -2, "name": "swingingShip" }, + { "kind": "flat", "grid": [19, 47, "north"], "row": 2, "lateral": -2, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [19, 47, "north"], "row": 4, "lateral": 2, "name": "informationKiosk" }, + { "kind": "flat", "grid": [19, 47, "north"], "row": 7, "lateral": 2, "name": "swingingShip" }, + { "kind": "flat", "grid": [19, 47, "north"], "row": 9, "lateral": -6, "name": "ferrisWheel" }, + { "kind": "flat", "grid": [19, 61, "west"], "row": 4, "lateral": 2, "name": "swingingShip" }, + { "kind": "flat", "grid": [19, 61, "west"], "row": 4, "lateral": -2, "name": "toilets" }, + { "kind": "flat", "grid": [19, 61, "west"], "row": 10, "lateral": 2, "name": "swingingShip" } +] diff --git a/bench/strategy/run.ts b/bench/strategy/run.ts index 94218f22d..26d4d36d3 100644 --- a/bench/strategy/run.ts +++ b/bench/strategy/run.ts @@ -1,6 +1,6 @@ import { Simulation } from '../../src/sim/core/simulation'; import { TICKS_PER_MONTH, TICKS_PER_YEAR } from '../../src/sim/economy/calendar'; -import { prepareScenario } from '../../src/sim/scenario/scenario-layout'; +import { prepareScenarioPark } from '../../src/sim/scenario/scenario-layout'; import { ScenarioStatus } from '../../src/sim/scenario/scenario'; import { objectiveMetric } from '../../src/sim/scenario/scenario-system'; import type { ScenarioDef } from '../../src/sim/scenario/scenario'; @@ -43,7 +43,7 @@ export function runScenario( opts: RunOptions, ): RunResult { const sim = new Simulation({ seed: opts.seed, width: def.mapWidth, height: def.mapHeight }); - prepareScenario(sim.world, def); + prepareScenarioPark(sim.world, def); // The strategy suite isolates park and economy balance from research pacing. sim.world.research.unlocked = new Set(Object.keys(RIDE_CATALOG).map(Number)); const builder = new ParkBuilder(sim, def); diff --git a/bench/strategy/site-plan.ts b/bench/strategy/site-plan.ts new file mode 100644 index 000000000..fd12eeab2 --- /dev/null +++ b/bench/strategy/site-plan.ts @@ -0,0 +1,261 @@ +import { + LAND_PRICE_CENTS, + PATH_COST_CENTS, + RIGHTS_PRICE_CENTS, + SALE_LAND, + SALE_RIGHTS, +} from '../../src/sim/map/tile-map'; +import { RIDE_CATALOG } from '../../src/sim/rides/ride-types'; +import { PathAddition } from '../../src/sim/map/paths'; +import { SCENERY_CATALOG } from '../../src/sim/map/scenery'; +import type { SceneryItem } from '../../src/sim/map/scenery'; +import { ParkGrid } from '../../src/sim/scenario/park-grid'; +import { PREBUILT_TYPES } from '../../src/sim/scenario/scenario-prebuilt'; +import type { EntranceSide } from '../../src/sim/scenario/scenario'; +import type { ParkBuilder } from './builder'; +import { StaffKind } from './builder'; +import type { Strategy, StrategyFactory } from './run'; +import { TICKS_PER_MONTH } from './run'; +import { + circuitTiles, + clearScenery, + flatGroundPath, + layRoute, + openFlatRide, + siteBounds, + startCoaster, + waypoints, +} from './site'; +import type { CoasterSite } from './site'; + +/** Loans move in $1,000 steps. */ +const LOAN_STEP_CENTS = 100_000; + +/** One build decision of a site plan; see `sitePlanStrategy`. */ +export type SiteStep = + /** A flat ride or stall on the builder's spine from the gate. */ + | { kind: 'item'; name: string } + /** + * A footpath through `points`, starting beside `from` (a tile already holding a flat path) or + * the end of the gate spine, clearing scenery on the way when the park allows it. + */ + | { kind: 'route'; points: Array<[number, number]>; clear: boolean; from?: [number, number] } + /** A coaster at a fixed site, buying the land and rights under it and clearing its track tiles first. */ + | { kind: 'coaster'; site: CoasterSite } + /** + * A flat ride or stall beside a spine path laid along `grid` (gate x, gate y, side) for rows + * 0..`row`, the way the builder lays rides along its own spine. + */ + | { + kind: 'flat'; + grid: [number, number, EntranceSide]; + row: number; + lateral: number; + name: string; + } + /** Buys land or rights in a rectangle. */ + | { kind: 'buy'; x: number; y: number; width: number; height: number; rights: boolean } + /** Clears scenery from the owned part of a rectangle with the Clear tool. */ + | { kind: 'clear'; x: number; y: number; width: number; height: number }; + +export interface SitePlan { + steps: SiteStep[]; + /** Cash kept back for wages and running costs. */ + reserveCents: number; + prices: Record; + /** One handyman per this many rides and stalls (rounded up), at least one. */ + itemsPerHandyman: number; + /** One mechanic per this many attractions. */ + attractionsPerMechanic: number; + /** Scenery planted round each coaster station before its test run. */ + decorate?: { item: SceneryItem; count: number }; + /** Repay the loan once cash exceeds it by this much. */ + repayAboveCents?: number; + /** Borrow up to the limit when a step is short of cash. */ + borrow?: boolean; + /** + * Patrol areas, inclusive tile rectangles [x0, y0, x1, y1], dealt to handymen in turn so a + * spread-out park is swept everywhere rather than only around the gate. + */ + patrols?: Array<[number, number, number, number]>; +} + +/** + * Plays a park through a fixed list of placements chosen for its terrain: each step is built, in + * order, as soon as the park can afford it on top of its reserve. Every placement goes through + * ordinary player commands, so the game's ownership, terrain and scenario rules apply. + */ +export function sitePlanStrategy(plan: SitePlan): StrategyFactory { + return () => { + let next = 0; + let nextDecision = 0; + let nextAdvance = 0; + const patrolled = new Set(); + const strategy: Strategy = { + step(b) { + const tick = b.tick; + if (tick === 0) b.prices = plan.prices; + if (tick >= nextAdvance) { + nextAdvance = tick + 64; + b.advance(); + } + if (tick < nextDecision) return; + nextDecision = tick + TICKS_PER_MONTH / 8; + while (next < plan.steps.length) { + const step = plan.steps[next]; + const cost = costOf(b, step, plan); + const l = b.sim.world.economy; + if (plan.borrow && l.cash < cost + plan.reserveCents && l.loan < l.maxLoan) { + const short = cost + plan.reserveCents - l.cash; + b.borrow( + Math.min(l.maxLoan - l.loan, Math.ceil(short / LOAN_STEP_CENTS) * LOAN_STEP_CENTS), + ); + b.sim.step(); + } + if (l.cash < cost + plan.reserveCents) break; + perform(b, step, plan); + next++; + } + const items = b.sim.world.rides.count; + b.staffTo(StaffKind.Handyman, Math.max(1, Math.ceil(items / plan.itemsPerHandyman))); + b.staffTo(StaffKind.Mechanic, Math.ceil(b.attractions() / plan.attractionsPerMechanic)); + if (plan.patrols) assignPatrols(b, plan.patrols, patrolled); + const l = b.sim.world.economy; + if ( + plan.repayAboveCents !== undefined && + l.loan > 0 && + l.cash > l.loan + plan.repayAboveCents + ) + b.repay(l.loan); + }, + }; + return strategy; + }; +} + +function assignPatrols( + b: ParkBuilder, + areas: Array<[number, number, number, number]>, + patrolled: Set, +): void { + const staff = b.sim.world.staff; + for (let slot = 0; slot < staff.count; slot++) { + const id = staff.slotToId[slot]; + if (staff.cols.kind[slot] !== StaffKind.Handyman || patrolled.has(id)) continue; + const [x0, y0, x1, y1] = areas[patrolled.size % areas.length]; + patrolled.add(id); + for (let y = y0; y <= y1; y += 4) + for (let x = x0; x <= x1; x += 4) + b.sim.enqueue({ type: 'setStaffPatrolTile', staffId: id, x, y, enabled: true }); + } +} + +function saleCost( + b: ParkBuilder, + r: { x: number; y: number; width: number; height: number }, +): number { + const m = b.sim.world.map; + let cents = 0; + for (let y = Math.max(0, r.y); y < Math.min(m.height, r.y + r.height); y++) + for (let x = Math.max(0, r.x); x < Math.min(m.width, r.x + r.width); x++) { + const o = m.ownership[m.index(x, y)]; + if (o & SALE_LAND) cents += LAND_PRICE_CENTS; + else if (o & SALE_RIGHTS) cents += RIGHTS_PRICE_CENTS; + } + return cents; +} + +function costOf(b: ParkBuilder, step: SiteStep, plan: SitePlan): number { + switch (step.kind) { + case 'item': + return b.costOf(step.name); + case 'route': + return waypoints(step.points).length * PATH_COST_CENTS * 3; + case 'coaster': { + const area = siteBounds(step.site); + const decor = plan.decorate + ? plan.decorate.count * SCENERY_CATALOG[plan.decorate.item].priceCents + : 0; + return 350_000 + saleCost(b, area) + area.width * area.height * 1_000 + decor; + } + case 'flat': + return RIDE_CATALOG[PREBUILT_TYPES[step.name]].cost + (step.row + 12) * PATH_COST_CENTS; + case 'buy': + return saleCost(b, step); + case 'clear': + return step.width * step.height * 2_000; + } +} + +function spineEnd(b: ParkBuilder): [number, number] { + const m = b.sim.world.map; + let row = 0; + while (m.pathElement(m.index(...b.grid.tile(row + 1, 0)), -1) >= 0) row++; + return b.grid.tile(row, 0); +} + +function perform(b: ParkBuilder, step: SiteStep, plan: SitePlan): void { + const sim = b.sim; + const m = sim.world.map; + switch (step.kind) { + case 'item': + b.build(step.name); + return; + case 'route': { + const start = step.from ?? spineEnd(b); + const tiles = waypoints([start, ...step.points]).slice(1); + if (step.clear) clearScenery(sim, tiles); + layRoute(sim, tiles, m.heights[m.index(start[0], start[1])]); + return; + } + case 'coaster': { + const area = siteBounds(step.site); + sim.enqueue({ type: 'buyLand', ...area, rights: false }); + sim.enqueue({ type: 'buyLand', ...area, rights: true }); + sim.step(); + clearScenery(sim, circuitTiles(sim, step.site)); + const rideId = startCoaster( + sim, + step.site, + (t) => flatGroundPath(sim, t), + true, + plan.decorate, + ); + if (rideId === null) return; + if (b.prices.coaster !== undefined) + sim.enqueue({ type: 'setRidePrice', rideId, priceCents: b.prices.coaster }); + b.watch(rideId); + return; + } + case 'flat': { + const grid = new ParkGrid(...step.grid); + for (let row = 0; row <= step.row; row++) { + const [x, y] = grid.tile(row, 0); + if (m.pathElement(m.index(x, y), -1) >= 0) continue; + sim.enqueue({ type: 'placePath', x, y }); + if (row % 2 === 0) + sim.enqueue({ type: 'setPathAddition', x, y, addition: PathAddition.Bin }); + } + sim.step(); + const ride = openFlatRide(sim, grid, step.row, step.lateral, step.name); + const price = ride ? b.prices[step.name] : undefined; + if (ride && price !== undefined) + sim.enqueue({ type: 'setRidePrice', rideId: ride.rideId, priceCents: price }); + return; + } + case 'buy': + sim.enqueue({ type: 'buyLand', ...step }); + sim.step(); + return; + case 'clear': + sim.enqueue({ + type: 'clearScenery', + x: step.x, + y: step.y, + width: step.width, + height: step.height, + }); + sim.step(); + return; + } +} diff --git a/bench/strategy/site.ts b/bench/strategy/site.ts new file mode 100644 index 000000000..b4a84cf23 --- /dev/null +++ b/bench/strategy/site.ts @@ -0,0 +1,497 @@ +import { TRACK_STEPS_PER_LEVEL } from '../../src/sim/core/constants'; +import { Simulation } from '../../src/sim/core/simulation'; +import { PIECES, pieceByName } from '../../src/sim/track/catalog'; +import type { SceneryItem } from '../../src/sim/map/scenery'; +import { SCENERY_RADIUS_TILES } from '../../src/sim/vehicles/vehicle-ratings'; +import { deserialize, serialize } from '../../src/save/save'; +import { getConstructionCursor, rotateTile } from '../../src/sim/track/construction'; +import { RIDE_CATALOG, RideType } from '../../src/sim/rides/ride-types'; +import { + DIR_DX, + DIR_DY, + ElementType, + PATH_BOARDING_MARKS, + PathFlag, + SLOPE_DIR_SHIFT, +} from '../../src/sim/map/tile-map'; +import { PathAddition, PathResult, planPathPlacement } from '../../src/sim/map/paths'; +import { COASTER_TEMPLATES, mirrored } from './coasters'; +import { RideState } from '../../src/sim/rides/ride-store'; +import { validateRidePlacement } from '../../src/sim/rides/ride-footprint'; +import { RideResult } from '../../src/sim/rides/ride-results'; +import { PREBUILT_TYPES } from '../../src/sim/scenario/scenario-prebuilt'; +import { rideFrontage } from '../../src/sim/scenario/park-grid'; +import type { ParkGrid } from '../../src/sim/scenario/park-grid'; + +/** + * A coaster circuit pinned to the map: the station tile, the heading of its first piece, the + * station's height level, and whether the template is mirrored so it turns the other way. + */ +export interface CoasterSite { + template: string; + x: number; + y: number; + dir: 0 | 1 | 2 | 3; + mirror: boolean; + /** Station height level; defaults to the ground under the station. */ + level?: number; +} + +export interface SiteBuild { + rideId: number; + closed: boolean; + /** Tiles beside the station for the entrance and the exit. */ + entrance: [number, number]; + exit: [number, number]; + /** The tiles in front of the entrance and the exit, where their paths begin. */ + entranceFront: [number, number]; + exitFront: [number, number]; + level: number; +} + +/** + * Creates a wooden coaster at `site` and lays its template through player commands. The circuit + * may climb over slopes on supports or run into the ground as a tunnel; a piece the game refuses + * leaves the circuit open, which `closed` reports. + */ +export function buildCircuit(sim: Simulation, site: CoasterSite): SiteBuild { + const world = sim.world; + const map = world.map; + const template = COASTER_TEMPLATES[site.template]; + const pieces = site.mirror ? mirrored(template.pieces) : template.pieces; + const level = site.level ?? map.heights[map.index(site.x, site.y)]; + const sigma = site.mirror ? -1 : 1; + const at = (i: number, j: number): [number, number] => { + const [rx, ry] = rotateTile(i, j, site.dir); + return [site.x + rx, site.y + ry]; + }; + const before = world.rides.count; + sim.enqueue({ type: 'createRide', rideType: RideType.WoodenCoaster, x: site.x, y: site.y }); + sim.step(); + if (world.rides.count === before) + return { + rideId: -1, + closed: false, + entrance: at(0, -sigma), + exit: at(0, sigma), + entranceFront: at(0, -2 * sigma), + exitFront: at(0, 2 * sigma), + level, + }; + const rideId = world.rides.slotToId[world.rides.count - 1]; + for (const [name, mode] of pieces) { + const cursor = getConstructionCursor(world, rideId); + const from = cursor.hasTrack + ? cursor + : { x: site.x, y: site.y, z: level * TRACK_STEPS_PER_LEVEL, dir: site.dir }; + sim.enqueue({ + type: 'placeTrack', + rideId, + pieceType: pieceByName(name)!.id, + x: from.x, + y: from.y, + z: from.z, + dir: from.dir, + mode, + }); + sim.step(); + } + return { + rideId, + closed: world.track.closed[rideId] === 1, + entrance: at(0, -sigma), + exit: at(0, sigma), + entranceFront: at(0, -2 * sigma), + exitFront: at(0, 2 * sigma), + level, + }; +} + +/** + * Lays a footpath along `tiles` (each edge-adjacent to the last), starting level with a path at + * `startLevel`. Each piece sits on or above its ground: the route keeps to the ground where it can + * and otherwise climbs, descends or bridges one level per tile, as a player's raised path would. + * Returns the levels of the pieces, or null when the route cannot start at `startLevel`. + */ +export function layRoute( + sim: Simulation, + tiles: ReadonlyArray, + startLevel: number, + queue = false, +): number[] | null { + const map = sim.world.map; + const top = tiles.map(([x, y]) => { + const i = map.index(x, y); + return Math.max(map.heights[i] + (map.slope[i] !== 0 ? 1 : 0), map.waterLevel[i]); + }); + const n = tiles.length; + const floor = Array.from({ length: n + 1 }, (_, k) => + Math.max(k > 0 ? top[k - 1] : 0, k < n ? top[k] : 0), + ); + floor[0] = Math.max(floor[0], startLevel); + const step = (k: number): number => { + const [x, y] = tiles[k]; + if (k === 0 && n === 1) return -1; + const [px, py] = k > 0 ? tiles[k - 1] : [x - (tiles[1][0] - x), y - (tiles[1][1] - y)]; + return [0, 1, 2, 3].find((d) => DIR_DX[d] === x - px && DIR_DY[d] === y - py)!; + }; + // A ramp only joins along its slope, so a tile where the route turns stays level. + const corner = tiles.map((_, k) => k + 1 < n && step(k + 1) !== step(k)); + let edge = floor; + for (let changed = true; changed;) { + edge = floor.map((_, k) => Math.max(...floor.map((f, j) => f - Math.abs(k - j)))); + changed = false; + for (let k = 0; k < n; k++) { + if (!corner[k] || edge[k] === edge[k + 1]) continue; + const level = Math.max(edge[k], edge[k + 1]); + floor[k] = Math.max(floor[k], level); + floor[k + 1] = Math.max(floor[k + 1], level); + changed = true; + } + } + if (edge[0] !== startLevel) return null; + const levels: number[] = []; + for (let k = 0; k < n; k++) { + const [x, y] = tiles[k]; + const forward = step(k); + const rise = edge[k + 1] - edge[k]; + const z = Math.min(edge[k], edge[k + 1]); + const slope = rise > 0 ? forward : rise < 0 ? (forward + 2) % 4 : -1; + sim.enqueue({ type: 'placePath', x, y, z, slope, queue }); + if (!queue && slope < 0 && k % 3 === 2) + sim.enqueue({ type: 'setPathAddition', x, y, addition: PathAddition.Bin }); + levels.push(z); + } + sim.step(); + return levels; +} + +/** + * Lays the shortest ground-level footpath from `start` (included) to beside any tile `goal` + * accepts, through tiles where the game would accept a path piece. Returns the tiles laid, + * `start` first, or null. + */ +export function connectOnGround( + sim: Simulation, + start: readonly [number, number], + goal: (tile: number) => boolean, + queue = false, + linkTo?: readonly [number, number], +): Array<[number, number]> | null { + const map = sim.world.map; + const origin = map.index(start[0], start[1]); + /** Level of the piece's edge on `side`, or -1 where a ramp's flank cannot join. */ + const edge = (tile: number, side: number): number => { + let z: number; + let rise: number; + const existing = map.pathElement(tile, map.heights[tile]); + if (existing >= 0) { + z = map.elBase[existing]; + rise = + map.elFlags[existing] & PathFlag.Sloped + ? (map.elFlags[existing] & PathFlag.SlopeDir) >> SLOPE_DIR_SHIFT + : -1; + } else { + const plan = planPathPlacement(map, { x: tile % map.width, y: Math.floor(tile / map.width) }); + if (plan.result !== PathResult.Ok || plan.existing >= 0) return -1; + z = plan.z; + rise = plan.dir; + } + if (rise < 0) return z; + return side === rise ? z + 1 : side === ((rise + 2) & 3) ? z : -1; + }; + const from = new Map([[origin, -1]]); + const frontier = [origin]; + for (let head = 0; head < frontier.length; head++) { + const here = frontier[head]; + if (here !== origin && goal(here)) { + const route: Array<[number, number]> = []; + for (let t = from.get(here)!; t >= 0; t = from.get(t)!) + route.push([t % map.width, Math.floor(t / map.width)]); + route.reverse(); + const placements = route.map(([x, y], k) => { + const [px, py] = k > 0 ? route[k - 1] : (linkTo ?? [x, y]); + const linkFrom = queue + ? [0, 1, 2, 3].find((d) => DIR_DX[d] === px - x && DIR_DY[d] === py - y) + : undefined; + return { x, y, queue, linkFrom, linkEnd: queue && k === route.length - 1 }; + }); + if (placements.length > 0) sim.enqueue({ type: 'placePathRun', placements }); + sim.step(); + return route; + } + if (here !== origin && map.pathElement(here, -1) >= 0) continue; + for (let d = 0; d < 4; d++) { + const n = map.neighbor(here, d); + if (n < 0 || from.has(n)) continue; + const out = edge(here, d); + if (out < 0 || out !== edge(n, (d + 2) & 3)) continue; + if (map.pathElement(n, -1) >= 0 && !goal(n)) continue; + from.set(n, here); + frontier.push(n); + } + } + return null; +} + +/** Edge-adjacent tiles through `points`, moving along x then y between each pair. */ +export function waypoints( + points: ReadonlyArray, +): Array<[number, number]> { + const out: Array<[number, number]> = [[points[0][0], points[0][1]]]; + for (let k = 1; k < points.length; k++) { + let [x, y] = out[out.length - 1]; + const [tx, ty] = points[k]; + while (x !== tx) out.push([(x += Math.sign(tx - x)), y]); + while (y !== ty) out.push([x, (y += Math.sign(ty - y))]); + } + return out; +} + +/** Removes the small scenery (trees, rocks) on `tiles` through the normal removal command. */ +export function clearScenery( + sim: Simulation, + tiles: ReadonlyArray, +): void { + const map = sim.world.map; + for (const [x, y] of tiles) { + const i = map.index(x, y); + for (let e = map.firstElement(i); e >= 0; e = map.nextElement(e)) + if (map.elType[e] === ElementType.SmallScenery) sim.enqueue({ type: 'removeScenery', x, y }); + } + sim.step(); +} + +/** + * True when tile `i` holds a flat footpath piece lying on its ground that is not a ride's entrance + * or exit tile, so a new path or queue can join it from any side. + */ +export function flatGroundPath(sim: Simulation, i: number): boolean { + const map = sim.world.map; + const e = map.pathElement(i, map.heights[i]); + return ( + e >= 0 && + !(map.elFlags[e] & PathFlag.Sloped) && + !map.isQueue(i) && + !(map.elData[e] & PATH_BOARDING_MARKS) + ); +} + +export interface OpenedRide { + rideId: number; + /** Ride state after the build: `RideState.Open` when it opened. */ + state: number; + excitement: number; +} + +/** + * Builds a coaster at `site`, lays its queue from the entrance and a path from the exit to tiles + * `joins` accepts, and starts its test run. With `clear`, scenery on the entrance and exit tiles + * is removed first. Returns the ride id, or null when the circuit does not close or a path cannot + * be laid. + */ +export function startCoaster( + sim: Simulation, + site: CoasterSite, + joins: (tile: number) => boolean, + clear = true, + decorate?: { item: SceneryItem; count: number }, +): number | null { + const world = sim.world; + const c = buildCircuit(sim, site); + const abandon = (): null => { + if (c.rideId >= 0) { + sim.enqueue({ type: 'demolishRide', rideId: c.rideId }); + sim.step(); + } + return null; + }; + if (!c.closed) return abandon(); + const map = world.map; + const tile = (t: readonly [number, number]) => map.index(t[0], t[1]); + const taken = (t: readonly [number, number]) => map.pathElement(tile(t), -1) >= 0; + const joinsAlready = (t: readonly [number, number]) => flatGroundPath(sim, tile(t)); + if (taken(c.entrance) || taken(c.exit)) return abandon(); + for (const front of [c.entranceFront, c.exitFront]) + if (taken(front) && !joinsAlready(front)) return abandon(); + if (clear) clearScenery(sim, [c.entrance, c.exit, c.entranceFront, c.exitFront]); + sim.enqueue({ type: 'placePath', x: c.entrance[0], y: c.entrance[1], queue: true }); + sim.enqueue({ type: 'placePath', x: c.exit[0], y: c.exit[1] }); + sim.step(); + const exitTile = tile(c.exit); + if ( + !joinsAlready(c.entranceFront) && + !connectOnGround(sim, c.entranceFront, (t) => t !== exitTile && joins(t), true, c.entrance) + ) + return abandon(); + if (!joinsAlready(c.exitFront) && !connectOnGround(sim, c.exitFront, joins)) return abandon(); + sim.enqueue({ type: 'placeRideEntrance', rideId: c.rideId, x: c.entrance[0], y: c.entrance[1] }); + sim.enqueue({ type: 'placeRideExit', rideId: c.rideId, x: c.exit[0], y: c.exit[1] }); + sim.step(); + if (decorate) plantAround(sim, site, decorate.item, decorate.count); + sim.enqueue({ type: 'setRideStatus', rideId: c.rideId, status: 'test' }); + sim.step(); + return c.rideId; +} + +/** + * Plants up to `count` scenery items on free tiles near the station, nearest first, the way a + * player decorates a coaster: scenery near the station lifts its excitement. + */ +export function plantAround( + sim: Simulation, + site: CoasterSite, + item: SceneryItem, + count: number, +): void { + const map = sim.world.map; + const spots: Array<[number, number, number]> = []; + for (let dy = -SCENERY_RADIUS_TILES; dy <= SCENERY_RADIUS_TILES; dy++) + for (let dx = -SCENERY_RADIUS_TILES; dx <= SCENERY_RADIUS_TILES; dx++) { + const x = site.x + dx; + const y = site.y + dy; + if (!map.inBounds(x, y) || map.firstElement(map.index(x, y)) >= 0) continue; + spots.push([dx * dx + dy * dy, x, y]); + } + spots.sort((a, b) => a[0] - b[0]); + for (const [, x, y] of spots.slice(0, count)) sim.enqueue({ type: 'placeScenery', x, y, item }); + sim.step(); +} + +/** `startCoaster`, then waits for the test run and opens the coaster. */ +export function openCoaster( + sim: Simulation, + site: CoasterSite, + joins: (tile: number) => boolean, + clear = true, +): OpenedRide | null { + const world = sim.world; + const rideId = startCoaster(sim, site, joins, clear); + if (rideId === null) return null; + const slot = () => world.rides.idToSlot[rideId]; + for (let t = 0; t < 12_000 && world.rides.cols.tested[slot()] !== 1; t++) sim.step(); + for (let t = 0; t < 4_000 && world.rides.cols.state[slot()] !== RideState.Open; t++) { + if (t % 50 === 0) sim.enqueue({ type: 'setRideStatus', rideId, status: 'open' }); + sim.step(); + } + return { + rideId, + state: world.rides.cols.state[slot()], + excitement: world.rides.cols.excitement[slot()], + }; +} + +/** Tile rectangle a coaster at `site` and its station paths can cover, with a margin. */ +export function siteBounds( + site: CoasterSite, + margin = 2, +): { + x: number; + y: number; + width: number; + height: number; +} { + const t = COASTER_TEMPLATES[site.template]; + const [y0, y1] = site.mirror ? [-t.maxY, 0] : [0, t.maxY]; + const corners = [ + [t.minX, y0 - 2], + [t.maxX, y0 - 2], + [t.minX, y1 + 2], + [t.maxX, y1 + 2], + ].map(([i, j]) => rotateTile(i, j, site.dir)); + const xs = corners.map(([x]) => site.x + x); + const ys = corners.map(([, y]) => site.y + y); + const x = Math.min(...xs) - margin; + const y = Math.min(...ys) - margin; + return { + x, + y, + width: Math.max(...xs) + margin - x + 1, + height: Math.max(...ys) + margin - y + 1, + }; +} + +/** + * Builds and opens a flat ride or stall beside a spine path the caller already laid, at + * (`row`, `lateral`) on `grid`, the way the scripted builder places rides along its spine. + */ +export function openFlatRide( + sim: Simulation, + grid: ParkGrid, + row: number, + lateral: number, + name: string, +): OpenedRide | null { + const world = sim.world; + const type = PREBUILT_TYPES[name]; + const frontage = rideFrontage(grid, row, lateral, RIDE_CATALOG[type].footprint); + if (validateRidePlacement(world, type, ...frontage.ride, frontage.dir) !== RideResult.Ok) + return null; + const service = + RIDE_CATALOG[type].category === 'stall' || RIDE_CATALOG[type].category === 'facility'; + for (const [x, y] of [...frontage.queue, ...frontage.exitPath]) { + const queue = frontage.queue.some(([qx, qy]) => qx === x && qy === y) && !service; + sim.enqueue({ type: 'placePath', x, y, queue }); + sim.enqueue({ type: 'setPathAddition', x, y, addition: PathAddition.Bin }); + } + sim.enqueue({ + type: 'createRide', + rideType: type, + x: frontage.ride[0], + y: frontage.ride[1], + dir: frontage.dir, + }); + sim.step(); + const rideId = world.rides.slotToId[world.rides.count - 1]; + sim.enqueue({ + type: 'placeRideEntrance', + rideId, + x: frontage.entrance[0], + y: frontage.entrance[1], + }); + if (!service) + sim.enqueue({ type: 'placeRideExit', rideId, x: frontage.exit[0], y: frontage.exit[1] }); + sim.enqueue({ type: 'setRideStatus', rideId, status: 'open' }); + sim.step(); + const slot = world.rides.idToSlot[rideId]; + return { + rideId, + state: world.rides.cols.state[slot], + excitement: world.rides.cols.excitement[slot], + }; +} + +/** + * Tiles a coaster at `site` needs free of scenery: its track footprint and the tiles beside the + * station for the entrance and exit. Found by building it on a copy of the park with the + * surrounding scenery cleared, so the real park only loses the trees the track actually needs. + */ +export function circuitTiles(sim: Simulation, site: CoasterSite): Array<[number, number]> { + const copy = new Simulation(deserialize(serialize(sim.world))); + const map = copy.world.map; + const area = siteBounds(site); + for (let y = area.y; y < area.y + area.height; y++) + for (let x = area.x; x < area.x + area.width; x++) { + if (!map.inBounds(x, y)) continue; + const i = map.index(x, y); + for (let e = map.firstElement(i); e >= 0;) { + const next = map.nextElement(e); + if (map.elType[e] === ElementType.SmallScenery) map.removeElement(i, e); + e = next; + } + } + const c = buildCircuit(copy, site); + const tiles = new Map(); + const add = (x: number, y: number) => tiles.set(map.index(x, y), [x, y]); + const t = copy.world.track; + const cols = t.pieces.cols; + for (let slot = 0; slot < t.pieces.count; slot++) { + if (cols.rideId[slot] !== c.rideId) continue; + for (const cell of PIECES[cols.pieceType[slot]].footprint) { + const [rx, ry] = rotateTile(cell.i, cell.j, cols.dir[slot] as 0 | 1 | 2 | 3); + add(cols.x[slot] + rx, cols.y[slot] + ry); + } + } + for (const tile of [c.entrance, c.exit, c.entranceFront, c.exitFront]) add(...tile); + return [...tiles.values()]; +} diff --git a/bench/strategy/strategies.ts b/bench/strategy/strategies.ts index 9107786b0..a2015bea7 100644 --- a/bench/strategy/strategies.ts +++ b/bench/strategy/strategies.ts @@ -1,5 +1,13 @@ import type { StrategyFactory } from './run'; import { growthStrategy } from './growth'; +import { SceneryItem } from '../../src/sim/map/scenery'; +import { sitePlanStrategy } from './site-plan'; +import type { SiteStep } from './site-plan'; +import thunderheadPlan from './plans/thunderhead-mesa.json'; +import tidewaterPlan from './plans/tidewater-docks.json'; +import mossgrovePlan from './plans/mossgrove-isle.json'; +import glacierPlan from './plans/glacier-point.json'; +import copperPlan from './plans/copper-ridge.json'; /** Build orders are written as space-separated names. */ const list = (names: string): string[] => names.split(/\s+/).filter(Boolean); @@ -50,65 +58,78 @@ STRATEGIES['bramblewood-hollow'] = growthStrategy({ growth: LONG_GROWTH.slice(0, 14), }); -STRATEGIES['copper-ridge'] = growthStrategy({ - ...BASE, +STRATEGIES['mossgrove-isle'] = sitePlanStrategy({ + steps: mossgrovePlan as SiteStep[], + reserveCents: 300_000, + patrols: [ + [28, 34, 44, 50], + [16, 18, 36, 40], + [36, 18, 54, 40], + ], + prices: RIDE_PRICES, + itemsPerHandyman: 1, + attractionsPerMechanic: 3, +}); + +STRATEGIES['copper-ridge'] = sitePlanStrategy({ + steps: copperPlan as SiteStep[], reserveCents: 150_000, prices: RIDE_PRICES, - jitter: { skipPercent: 15, startDelayMonths: 1 }, - opening: list('foodStall drinkStall toilets merryGoRound'), - growth: [ - 'coaster:compact:1', - ...list('ferrisWheel drinkStall'), - 'coaster:compact:-1', - ...list('foodStall swingingShip'), - 'coaster:riverRun:1', - ...list('twist toilets'), - 'coaster:riverRun:-1', - ...list('merryGoRound informationKiosk'), - 'coaster:compact:1', + itemsPerHandyman: 2, + attractionsPerMechanic: 2, + borrow: true, + decorate: { item: SceneryItem.Conifer, count: 30 }, + patrols: [ + [26, 72, 66, 88], + [14, 34, 46, 50], + [30, 44, 62, 76], ], }); -STRATEGIES['tidewater-docks'] = growthStrategy({ - ...BASE, - itemsPerHandyman: 1.5, - reserveCents: 600_000, +STRATEGIES['tidewater-docks'] = sitePlanStrategy({ + steps: tidewaterPlan as SiteStep[], + reserveCents: 400_000, + patrols: [ + [8, 38, 24, 56], + [8, 52, 24, 64], + [16, 56, 64, 64], + [30, 38, 50, 62], + ], prices: RIDE_PRICES, - jitter: { skipPercent: 15, startDelayMonths: 2 }, - opening: OPENING, - growth: LONG_GROWTH.slice(0, 18), - extra: (b) => { - const l = b.sim.world.economy; - if (l.loan > 0 && l.cash > l.loan + 150_000) b.repay(l.loan); - }, + itemsPerHandyman: 1.5, + attractionsPerMechanic: 3, + repayAboveCents: 150_000, }); -STRATEGIES['thunderhead-mesa'] = growthStrategy({ - ...BASE, - itemsPerHandyman: 1.5, +STRATEGIES['thunderhead-mesa'] = sitePlanStrategy({ + steps: thunderheadPlan as SiteStep[], + reserveCents: 200_000, + patrols: [ + [30, 8, 62, 28], + [30, 8, 62, 28], + [8, 46, 40, 64], + [30, 8, 62, 28], + [18, 22, 38, 52], + [58, 50, 84, 64], + [56, 26, 74, 52], + ], prices: RIDE_PRICES, - jitter: { skipPercent: 25, startDelayMonths: 3 }, - opening: OPENING, - growth: LONG_GROWTH.slice(0, 16), + itemsPerHandyman: 2, + attractionsPerMechanic: 3, }); -STRATEGIES['glacier-point'] = growthStrategy({ - ...BASE, +STRATEGIES['glacier-point'] = sitePlanStrategy({ + steps: glacierPlan as SiteStep[], reserveCents: 150_000, prices: RIDE_PRICES, - jitter: { skipPercent: 20, startDelayMonths: 3 }, - opening: list('foodStall drinkStall toilets merryGoRound'), - growth: [ - 'coaster:riverRun:1', - ...list('ferrisWheel drinkStall'), - 'coaster:switchback:-1', - ...list('foodStall twist'), - 'coaster:riverRun:1', - ...list('toilets swingingShip'), - 'coaster:switchback:-1', - ...list('merryGoRound informationKiosk'), - 'coaster:riverRun:1', - 'coaster:switchback:-1', + itemsPerHandyman: 2, + attractionsPerMechanic: 2, + borrow: true, + decorate: { item: SceneryItem.Conifer, count: 30 }, + patrols: [ + [70, 42, 92, 60], + [50, 42, 74, 60], + [54, 56, 82, 78], ], }); diff --git a/docs/BALANCE.md b/docs/BALANCE.md index 3cea63a71..cd55a43e5 100644 --- a/docs/BALANCE.md +++ b/docs/BALANCE.md @@ -391,6 +391,31 @@ Flat rides now occupy their real footprints (Merry-Go-Round 3x3, Ship 1x5, Ferri Scenario sweep after the retune (`pnpm balance -- --scenario all --seeds 12`): the table above. Bramblewood Hollow 11/12 (one miss), Riverside Fairground 12/12 (was 5/12, the wider apron now fits 31 rides), Thunderhead Mesa 7/12 and Glacier Point 6/12 stay inside the Expert band. +### Hard park remixes + +The Challenging and Expert parks were rebuilt on irregular, rough ground ([scenario-remixes.md](scenario-remixes.md)), and Mossgrove Isle was added. The old scripts assume a long flat apron and cannot fit rides on the new ground: run unchanged on the remixed maps, the Copper Ridge and Glacier Point scripts stop because no coaster closes, and Thunderhead Mesa, Tidewater Docks and Mossgrove Isle each build only 5 to 6 items and win 0/12. The hard parks are now played by **site plans** ([bench/strategy/site-plan.ts](../bench/strategy/site-plan.ts), plans in [bench/strategy/plans](../bench/strategy/plans)): fixed placements chosen for each map, built in order when affordable through ordinary commands, so ownership, terrain and park rules all apply. They lay trails with ramps and bridges, buy only the land a step needs, clear only the tiles track needs, plant scenery round coaster stations (Copper Ridge and Glacier Point), and give handymen patrol areas because the parks are long. + +The harness now prepares parks with `prepareScenarioPark`, the same path as a new game, so ambient trees are present. Ambient trees matter for coasters because scenery near a station adds up to 2.35 excitement. + +Before is `main` before the remix (12 seeds, old flat-apron scripts, old maps). After is this branch's full sweep (`pnpm balance -- --scenario all --seeds 12 --jobs 3`). + +| Park | Objective now | Before | After | After, range over seeds | +| -------------------- | --------------------------------------------------------------- | ------------------------------ | ----- | --------------------------------------------------------------------------------- | +| Copper Ridge | 5 coasters ≥ 4.60 by end of year 2 (was year 1) | 0/12 (no coaster reached 4.60) | 11/12 | 4–5 qualifying coasters; parks hold 5–25 guests, rating 0–92 | +| Glacier Point | 5 coasters ≥ 4.70 by end of year 2 (was 6 ≥ 4.90 in 1.4 months) | 0/12 | 6/12 | 4–5 qualifying coasters (ratings 5.98–6.68 when they open) | +| Tidewater Docks | repay loan, park value $5,500 by end of year 4 | 12/12 | 0/12 | value $2,888–$5,302, rating 504–852, loan never repaid (cash ends −$10k to −$15k) | +| Thunderhead Mesa | 460 guests, rating 700 by end of year 4 | 12/12 | 0/12 | 11–330 guests, rating 0–623 | +| Mossgrove Isle (new) | $350 a month ride income by end of year 3 | – | 2/12 | $247–$373 a month, 14–15 rides, no tree removed | + +Unchanged parks under the new harness: Bramblewood Hollow, Lantern Bay, Meadowbrook Green, Open Grounds, Riverside Fairground and Seaside Promenade all win 12/12. + +Notes on reading the table: + +- **Copper Ridge and Glacier Point show the goals can be met legally.** Their scripts only chase the coaster count: they build the opening stalls and then coasters, so the parks themselves run down. A player who also runs the park wins more easily. Glacier Point's misses are seeds where one coaster rates below 4.70 or opens late. +- **Tidewater Docks and Thunderhead Mesa keep their goals but no script wins them.** These are reported, not hidden. The hard part is upkeep in a long park: wages, breakdowns and litter outrun ride income in the scripted play. The best Tidewater seed reaches 96% of the park-value target, and Thunderhead's best seed holds 330 guests. Both are plausible for a player who prices and staffs actively, but this has not been demonstrated. +- **Mossgrove Isle's target was set from scripted play.** Its first draft target was $900 a month, while the best scripted seed made $373, so the target is $350. No tree is removed: the rule forbids it and the play test checks it. +- Each park's legal construction path (gate, stalls, first ride and the park's defining move) is checked separately in [bench/hard-parks.test.ts](../bench/hard-parks.test.ts). + ## Known gaps - Far rides still cost a long walk: after the change the wooden coaster (a 35-tile walk, open for the last two thirds of the year) serves 362 guests against 905 for the merry-go-round next to the gate, and it is capped by what its single train carries. Energy is a placeholder until the target-based needs model lands ([fidelity/guests.md](fidelity/guests.md) F2). diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index f6612ec22..bb278e440 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -27,7 +27,8 @@ Resolutions of the cross-spec conflicts listed in `docs/mechanics/README.md`. Co | Scenario restrictions | Optional per-scenario rules modelled on the prohibitions RCT2's scenario editor offered (tree removal, landscaping, high construction, marketing), plus banned ride types. The height cap is an OpenCoaster remix: a tunable 4–96 land levels measured from each tile's local ground rather than a fixed limit. Rules gate new actions only and are saved with the park. See [scenario-restrictions.md](scenario-restrictions.md). | | Awards | Seventeen candidate award definitions are checked at month starts; at most one is granted, four may remain active, and each lasts five months. Positive/negative awards scale natural guest generation by 1.25/0.75. Food-award hunger counts use satiation 128 or lower, matching stall seeking; the award guide does not specify this cutoff. Criteria for unavailable park systems use proxies; exact catalog scope, duration and multiplier stacking are unverified. | | Starter rating target | 450. After correcting food-award hunger eligibility, the default-seed modest build ends at rating 554 and wins; at 550 only 7 / 12 established modest-build seeds win. The recalibrated 450 target wins 10 / 12 (ratings 386–688); seeds 22 and 26 miss on rating. See [BALANCE.md](BALANCE.md#results-deferred-economy-pass). | -| Shipped scenarios | Ten parks beyond the starter, each with an original generated map and OpenCoaster-tuned finances and objectives, not transcriptions of any RCT2 scenario. Thresholds are set against the scripted strategy ([BALANCE.md](BALANCE.md#scenario-win-rates)): Beginner at least 10 of 12 seeds, Expert 3 to 9. Coaster excitement targets use this game's scale (best searched circuit 4.94). Have Fun has no terminal state; its harness check (solvent, rating 600+, 200+ guests after four years) is not a game rule. Completion is a browser-local record. | +| Shipped scenarios | Eleven parks beyond the starter, each with an original generated map and OpenCoaster-tuned finances and objectives, not transcriptions of any RCT2 scenario. The Challenging and Expert parks are remixes of RCT2 ideas on irregular owned land and shaped terrain ([scenario-remixes.md](scenario-remixes.md)). Thresholds are set against scripted play ([BALANCE.md](BALANCE.md#scenario-win-rates)): Beginner at least 10 of 12 seeds with the flat-apron scripts, Expert 3 to 9. The hard parks are played by site plans fitted to their terrain; a hard park's goal must be reached by a legal script on at least one seed, except that Thunderhead Mesa and Tidewater Docks keep their earlier goals without a scripted win (reported, not hidden). Coaster excitement targets use this game's scale; scenery near a station adds up to 2.35, so wooded and decorated stations rate far above the bare-apron circuits. Have Fun has no terminal state; its harness check (solvent, rating 600+, 200+ guests after four years) is not a game rule. Completion is a browser-local record. | +| Scenario land shapes | A scenario may paint its starting ownership from shapes (`land.parcels`: owned, land for sale, rights for sale, or not for sale), raise or lower terrain inside shapes (`terrain.shapes`), and fill woods and clearings (`trees.stands`, `trees.clearings`). Owned land must be one connected piece and the gate apron must lie on it, following the RCT2 manual's advice that a park is one continuous piece of land; not-for-sale parcels stay unbuyable, so buying every sale cannot erase a park's outline. Margin-only recipes generate exactly as before. Saves store the map, so loading never regenerates land, terrain or scenery. | | Save format | Current version 31 (see [save/load documentation](../src/save/docs.md) for the format history). Version 10 added guest navigation fields and research work units; version 11 adds ride reliability, mode and mechanic-work columns; version 12 adds guest age, ride count and last-ride fields; version 13 adds recent guest ride history and per-worker task orders; version 14 adds the 60-slot rolling rider history; version 15 adds litter memory/anger, staff sweeps, litter order and climate; version 16 adds the per-worker stopped-vandal counter; version 30 adds ride downtime and mechanic-heading data; version 31 stores scenario average guest cash in the header, defaulting to $50 when absent in older saves. Older saves default new histories and counters to zero or worker-order defaults. Versions 9 and older store research costs and progress in cents, which convert at the old minimum rate (2,500 cents a week = 21 units), so each invention keeps its duration at minimum funding. `difficultRating`, `campaignTarget` and research `priority` are additive and default when absent. | | Guest cadence | Need decay every 128 world ticks; happiness motives every 512 ticks, matching the audited original cadence summary. | | Hunger and thirst | Values count satiation: high means full; low means hungry or thirsty. Loading saves through v11 inverts both bytes. | diff --git a/docs/scenario-remixes.md b/docs/scenario-remixes.md new file mode 100644 index 000000000..79d719724 --- /dev/null +++ b/docs/scenario-remixes.md @@ -0,0 +1,57 @@ +# Hard scenario remixes + +The Challenging and Expert parks are original OpenCoaster designs. Each borrows one idea from a +RollerCoaster Tycoon 2 scenario and rebuilds it with OpenCoaster's map recipe: irregular owned land +(`land.parcels`), shaped terrain (`terrain.shapes`), dense woods and clearings (`trees.stands`, +`trees.clearings`), and the scenario rules in [scenario-restrictions.md](scenario-restrictions.md). +No original map, layout, park name, sprite or scenario file is used. Where a park copies a rule the +source scenario does not have, the matrix says so. + +## Sources + +- RCT2 manual, p. 23 ("Buy Land", "Buy Construction Rights") and pp. 57-62 (scenario editor: + "The land owned by the player is a single continuous piece of land", "A U-shaped park will + confuse your guests", forbidding tree removal, high construction and marketing): + . Page numbers are the + manual's printed pages. +- Scenario prohibitions (only Rainbow Summit uses them among the 15 original RCT2 scenarios; the + Wacky Worlds expansion forbids landscaping in Grand Canyon and others; Rainbow Valley and + Harmonic Hills are RCT1): +- Botany Breakers ("a small island overgrown with trees... the trees provide great scenery at the + expense of removal cost"; monthly ride income; no prohibitions): + +- Rainbow Summit ("Built on a hillside, this park is forbidden from building anything tall", + nothing above 10.5 m, marketing prohibited): +- Gravity Gardens ("No other rides, just roller coasters!", stalls and shops still allowed; repay + loan and park value): +- Alpine Adventures (small mountain ski resort with a lone chairlift; monthly ride income): + +- Fungus Woods ("lots and lots of trees") and Infernal Views (lava channels through the park): + , + +## Design matrix + +| Park | RCT2 idea (cited above) | OpenCoaster design | Owned land at start | Woods and clearance | Rules | Objective | A route to the goal | +| -------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Copper Ridge (Challenging, 96²) | Infernal Views' channels cutting a park apart; Grand Canyon's landscaping ban (Wacky Worlds, an expansion). | Red ridges with a dry gulch across the park. The gate bench (level 8) is reached from the south; a narrow owned trail crosses the gulch (level 5) to the west bench (level 11). East and summit benches are land for sale; the gulch and the ridge saddle are rights only. | 849 tiles: gate bench, trail and west bench (was a 2,916-tile rectangle). | Scattered boulders on the benches; no trees on the dirt ridges. Gate clearing 17×12. | No landscaping (our remix of the expansion rule). | Five coasters of 4.60+ excitement by the end of year 2 (was year 1). | Follow the trail across the gulch and fit coasters on the benches; terrain and nearby rocks lift ratings (the west-bench compact circuit rates 4.98 against 4.67 on flat ground). | +| Tidewater Docks (Challenging, 80²) | Lucky Lake's waterfront; the manual's warning that a U-shaped park confuses guests; construction rights. | An old harbour: a hook of quays round a basin with three finger piers. The basin and inlets are rights only, so they can be bridged but never filled; the third pier and the east breakwater are land for sale. | 966 tiles: west quay, south quay and two piers (was 3,136). | Woods on the banks and beyond the quays; gate clearing 13×10. | None: the shape is the challenge. | Repay the loan and reach $5,500 park value by the end of year 4 (unchanged). | Walk the south quay, buy rights over an inlet and bridge it, and stand narrow rides (a Ferris wheel fits a five-tile pier) along the piers. | +| Thunderhead Mesa (Expert, 96²) | Rainbow Summit's height limit and marketing ban; Extreme Heights' desert. | A scorched mesa top with buttes (level 16) above a dry canyon (level 4), with a narrow cliff trail down to the west shelf (11). East (13) and south (7) shelves are for sale behind steep corridors; the canyon is rights only. | 1,023 tiles: mesa top, cliff trail and west shelf (was 4,356). | Cacti and rock scatter; gate clearing 15×8. | Nothing more than 6 levels above local ground; no marketing (Rainbow Summit's rules, with OpenCoaster's own cap). | 460 guests and rating 700 by the end of year 4 (unchanged). | Build low on the mesa, take the cliff trail to the west shelf, and spread rides over the shelves; patrol handymen by area because the park is long. | +| Glacier Point (Expert, 96²) | Gravity Gardens' coaster-only roster; Alpine Adventures' mountain resort and chairlift. | Mountain shelves above a glacial lake. The gate shelf (12) sits on a saddle; a steep owned trail drops to a lake-shore shelf (6). A forested middle shelf (10) and a summit shelf (18) are for sale; the mountainside between them is rights only. | 589 tiles: gate shelf, trail and shore shelf (was 2,916). | Conifer and birch woods on the slopes and purchasable shelves; gate clearing 11×8. | Only coasters, stalls, toilets and the chairlift: gentle, thrill, water, transport rides other than the chairlift and the observation tower are forbidden (Gravity Gardens' roster is a research list, not a prohibition; here it is a rule). | Five coasters of 4.70+ excitement by the end of year 2 (was six of 4.90+ in about a month and a half). | Keep the woods round each station (nearby scenery lifts excitement), buy the forested middle shelf and clear only the track, and take the trail down to the shore for the fifth coaster; the scripted plan's five coasters rate 5.98 to 6.68. | +| Mossgrove Isle (Challenging, 72², new) | Botany Breakers' tree-covered island and monthly ride income; Fungus Woods' dense trees. | A wooded island reached by a causeway. A flat island core holds four small clearings joined by narrow trails; a protected grove on the knoll is not for sale; shallows to the south are rights only and a wooded islet is for sale. | 1,151 tiles, ellipse with a hole (bounding-box fill 65%). | About half the owned dry land is wooded; clearings of roughly 10×8. | No tree removal (our remix: Botany Breakers has no prohibitions; its trees only cost money to clear). | $350 a month in ride ticket income by the end of year 3 (set from scripted play; see BALANCE.md). | Build in the clearings along the trails, lift track above the trees, and use the shallows for water rides. | + +## How the parks are validated + +- `src/sim/scenario/hard-scenarios.test.ts` checks each park's identity on the generated map: one + connected, non-rectangular owned piece; parcels that stay unbuyable after buying every sale; + a small gate clearing; height variation; and the park's own feature (Copper's benches, + Tidewater's rights-only water, Thunderhead's shelves, Glacier's lake and mountains, Mossgrove's + woods and open trails). +- `bench/hard-parks.test.ts` plays the start of every park with ordinary commands and the park's + real cash: the gate opens onto working stalls and a first ride, the park's defining move is + built and guests use it, and each park refuses the action its rules forbid. +- `pnpm balance -- --scenario ` plays each park with a scripted strategy. The hard parks use + site plans (`bench/strategy/site-plan.ts`, plans in `bench/strategy/plans/`) because the old + flat-apron scripts cannot fit rides on the new ground. Results are in + [BALANCE.md](BALANCE.md#hard-park-remixes). +- Saves keep their own map: a park saved before the remix loads with its old land, terrain and + scenery (`src/save/scenario-remix-saves.test.ts`). diff --git a/e2e/docs.md b/e2e/docs.md index 7a6076f00..ae238f5e4 100644 --- a/e2e/docs.md +++ b/e2e/docs.md @@ -46,6 +46,7 @@ Path: @/e2e - [people-depth.spec.ts](people-depth.spec.ts) checks pixel ownership between a guest and flat, raised, queue and ramp paths, benches, trees and stalls, in WebGL2 and Canvas2D at all four rotations. It loads the dev-only [depth-fixture.html](../depth-fixture.html) ([src/dev/depth-fixture.ts](../src/dev/depth-fixture.ts)), which draws a hand-built map with one guest at a chosen position, and renders each case with and without the guest and on a bare map with the same camera. Pixels the guest owns are those of the bare-map render; pixels the scene owns are those of the scene-only render, so the check does not depend on the art. It asserts that a guest is not covered by the surface it stands on, is behind an object nearer the camera (only where the sprites overlap), and in front of one farther away. - [occlusion-oracle.spec.ts](occlusion-oracle.spec.ts) scores renderer occlusion against the oracle described in [src/render/docs.md](../src/render/docs.md) ("Occlusion model"). For every renderer × seed × rotation × zoom it loads the dev-only [occlusion-fixture.html](../occlusion-fixture.html) ([src/dev/occlusion-fixture.ts](../src/dev/occlusion-fixture.ts)), which renders a seeded fuzz park, captures the renderer's object-ID image and compares it with the oracle's z-buffer over the same placed sprites and terrain. It writes `.local/occlusion/