Mini Business Sim · under the hood

How the Simulation Works

The game runs two ways. On its own, everything happens in the browser: the economy engine, the save file and the access gate, with no server at all. In a classroom, the same player connects to an Express and MongoDB server. At the end of each round, that server scores every team against the others.

90 days
in 3 phases of 30, one batch per phase
13 steps
run for every simulated day
1 store
every change goes through apply()
v10
save format, with a migration chain
22
MongoDB collections in the classroom server
1
database transaction to close and score a round
1 · Overview

Two Ways to Play, One Player

The standalone build is a static site: the whole economy runs in the browser and saves to local storage. The classroom build swaps the pass-key check for a real login and sends each round's decisions to the server.

Runs in the browserServerStored dataHosting and outside services
Standalone · no server
VercelStatic build from main. Images cached for a year, so new art gets a new _vNN name
React playerProduct page, Business page, Results. Pass key checked in the browser
Economy engineDemand, cost, production, cash flow, events, scoring. Pure functions over one game state
localStorageintlabs:sim:state:v1, the whole run as one save, schema v10
Classroom · many teams, one market
Player, per teamThe same game, with a src/gamesim layer around it
Sync layerPasskey login, polls every 20 s, posts decisions, heartbeat
Operator consoleReact, Radix, Tailwind, TanStack Query. Starts and ends rounds, watches who is in the room
APIExpress on NodeTypeScript, every route under /api, JWT on every request, scores each round
MongoDB Atlas22 collections: game design, rounds, decisions, results
Supabase StorageImage assets, with a local folder fallback
Both builds share the same player code. The classroom build adds the sync layer and the server; the standalone build needs neither.
2 · The engine

What Happens in One Simulated Day

Decisions never move time. Only confirming a phase does: the game then runs the rest of the phase as one batch of days, stopping at the first interrupt (a market event or a phase review) and resuming after it. Each day runs the same 13 steps across every notebook line in the portfolio.

1Phase rolloverDay 31 and 61 start a new phase
2Cash landsReceivables and payables due today, by each channel's payment terms
3Expire effectsEvent modifiers that ran out
4FitHow well each notebook suits each audience
5Roll demandOne seeded random stream for the whole portfolio
10Pay opexDaily running costs
9SellDemand × sales conversion, capped by that line's own stock
8ProduceFinished notebooks, minus defects
7Plan productionShared capacity split across lines; more lines, more complexity penalty
6Auto-buy materialsJust in time, only if cash allows
11Brand and retentionSatisfaction feeds next demand
12Record the dayInventory roll-up and the daily series for charts
13Fire interruptsEvents on days 15, 30, 45, 60, 75, 89. Reviews on 30, 60, 90. Day 90 settles any debt
Interrupt: pause the batchShow the event or review inline, then carry on
No interrupt: next dayBack to step 1 until the phase ends
The steps of dayTick in src/engine/simulationEngine.ts. advanceDay(state, n) calls it n times and stops early at any interrupt.

One Import Surface

The UI imports game logic from one facade, engine/mockEngine.ts. Behind it sit small modules: demand, cost, production, quality, complexity, cash flow, events, scoring and projections.

Same Seed, Same Run

Every random roll comes from a seeded generator with its own key: <seed>-<day> for the real day, and <seed>:preview:<day> for forecasts. A preview can never change the real outcome, and a replay with the same decisions gives the same numbers.

No NaN, Ever

Numbers pass through small guards (finite, clamp01, safeDiv) at the engine's edges, so a bad input can't reach the save file or the charts.

Score Out of 100

Net profit counts for 50 points, a clean inventory (no stockouts, no overstock) for 25, and the three end-of-phase insight questions for 25. The questions are built from the player's own ledger, so the answers can't be memorised.

3 · State

One Store, One Way to Change It

All game state lives in a single Zustand store with Immer. Components never change it directly: they call apply(fn) with an engine mutator. That one path makes the profit and loss statement, the decision timeline and undo fall out of the same records.

A controlPrice slider, add-on drop, Confirm phase
storeapply(fn)The only way in
Engine mutatore.g. setPrice(s, 12), a pure function over the draft
GameStateLines, channels, cash, stock, phase, day
persistSaves the game, not the passing UI state
localStorageintlabs:sim:state:v1
Undo / redoKeeps a step only when the change wrote history. Slider drags merge into one step. Never saved
Seeded RNGmulberry32, one stream per key
ledger[ ]Every money movement, tagged with a cause
history[ ]Every decision the player made
Migrate + mergeSchema v10 with a migration chain. Nested settings deep-merged, so new fields get defaults
Profit and lossA view over the ledger, line by cause
Decision timelineRead straight from history
The ledger and history are the source; the P&L, the timeline and undo are views of them. A change that writes no history can't be undone, which is why every decision goes through a mutator.
4 · Classroom system

The Parts and How They Connect

A game is data, not code. Each simulation type is a set of database rows: its products (whose fields are the decision form), audience segments, global inputs and market data. That is why most of the operator console is editing screens over those collections.

People
Player teamsOne passkey per team
Facilitators and adminsEmail and password
Frontends
PlayerVite, React 18, Zustand, Tailwind. REST with a JWT; polls every 20 s
Operator consoleVite, React 18, Radix, Tailwind 4, TanStack Query. REST with a JWT; polls every 15 s
One Node container
/apiExpress APITypeScript and Mongoose. Auth middleware, role checks, round scoring. Live at api.int-labs.site
Static hostingServes the console's build, with a single-page fallback
socket.ioSet up, not used for game events yet: polling does the live work
Data and services
MongoDB AtlasEvery collection; transactions for round closing
Supabase StorageBucket imageAsset
DiceBearTeam avatars, made once
Render previewsEach pull request gets its own seeded Atlas database
The player and the console read the API address from one build variable, so the same builds run against local, preview and live servers.
5 · One round

From a Team's Decision to the Official Result

The browser runs the game so it feels instant. The server holds the official numbers: when the facilitator ends the round, it scores every team against the others in one database transaction.

Order of operations from PhaseSequenceModal, src/gamesim/sync.ts, roundControllers.endRound and services/roundCalculation.ts.
6 · Scoring

How the Server Splits the Market

For each audience segment and product, the server compares every team's decisions with everyone else's. Your share depends on where your choices sit among the other teams', not on hitting a fixed target.

DecisionsEvery team's inputs for this round, field by field
Base dataMarket size per round; which fields count, and how much
ProductsEach field's direction, range and cost
calcMarketModelWeighted score per teamFor each field: where the team's value sits on a normal curve of all teams' values, times the field's direction, times its weight for this round
Competed shareYour weighted score over the total, scaled by your forecast share and the number of teams, capped at 100%
calcFinancialsEach team's moneyCustomers = share × this round's market size × pricing score. Revenue = what you could actually supply × price. Costs cover the whole production run
ResultsWeighted scores and shares, per product and segment
ProjectionsEach team's revenue, COGS and profit
Runs once per segment × product inside runRoundCalculation. The player then shows rank, leaderboard and official revenue, COGS and customers.
7 · Data model

The Core Collections

Twelve of the twenty-two MongoDB collections. Blue is a session's spine, amber is game design, green is live telemetry. Rounds link to decisions, results and projections by round number, not by id.

BaseData

  • _id
  • simulationTypeId
  • marketData
  • marketModel

SimulationType

  • _id
  • name
  • outputs[ ]
  • yearRange

Segment

  • _id
  • simulationTypeId
  • key
  • fields[ ]

Product

  • _id
  • simulationTypeId, segmentId
  • productName
  • fields[ ] (the decision form)

Simulation

  • _id
  • simulationTypeId
  • status
  • config.totalRounds

Round

  • _id
  • simulationId
  • roundNumber, status
  • timer

User

  • _id
  • teamId
  • role
  • passkey

Team

  • _id
  • simulationId
  • teamName
  • members[ ]

Decision

  • _id
  • simulationId, teamId
  • roundNumber
  • inputs[ ] by product

Results

  • _id
  • productId, segmentId
  • roundNumber
  • weightedScores, marketShares

TeamProgress

  • _id
  • teamId
  • day, phase, cash
  • lastSeenAt

Projections

  • _id
  • teamId
  • roundNumber
  • projections.<product>
Also in the database: global inputs, player config (the game's published content), run reports, round notes, debriefs, image assets, parameter lists, drivers, initiatives and refresh tokens.
8 · Sign-in

Two Doors, One Token

Staff sign in with email and password; teams sign in with a passkey alone. Both get a 12-hour JSON Web Token. Every request carries it, and the server checks it before any handler runs.

Console sign-inEmail and password
POST /users/loginbcrypt check, staff only. Same timing whether or not the account exists
JWT, 12 hrole + userId, kept in the console
Player sign-inThe pass-key screen, now a real login
POST /users/login-passkeyFinds the team by its passkey, unique per simulation
JWT, 12 hrole team + teamId + simulationId
Every requestAuthorization: Bearer token
authenticateVerifies the signature
authorize(roles)e.g. only staff can end a round
401 or 403No token, a bad one, or the wrong role. The client clears it and shows sign-in again
HandlerTeam identity comes from the token
In the standalone build there is no server: the pass key is compared in the browser, a light gate that keeps casual visitors out. The classroom build replaces it with this flow.
9 · Credits and checks

Who Built What

The Player and Its Engine

Designed and built by me with Claude Code: the game, the economy engine, the store and saves, Amelia, the art direction and the booth mode for events.

The Classroom Server

The core API, its data model and both scoring calculators are the IntLabs development team's work. On top of it I rebuilt the operator console, wrote the service that closes and scores a round in one transaction, and added the live progress, run report, debrief and content models.

How It Is Checked

  • The game's type check runs on every build.
  • The server has unit tests for the market model, the config validators, and a parity test proving the server's copy of the engine matches the game's, value by value and file by file.
  • The console has a Playwright suite: sign-in, every page, and access checks between teams.