Designing an idle game economy in TypeScript
Keep the tick, the cost curve, and the display in different places, and store currency in a way that will not drift after a long offline stretch of time.
An idle game lives or dies on its economy, and the economy should live in a TypeScript module, not in the React tree. I learned that while shipping Zero Space Radio, an idle tycoon. The lesson is not a design manifesto. It is a set of boundaries I would keep on any similar game.
The display can be pretty. The tick, the cost curve, and the currency have to be boring and testable.
One clock, one state
The game has a state object and a function that advances that state by a number of milliseconds. Everything that earns, spends, or unlocks goes through that function. Buttons in the UI do not add coins on their own. They ask the economy module to buy a generator, and they render whatever state comes back.
export type GeneratorId = "relay" | "tower" | "array";
export type Generator = {
id: GeneratorId;
owned: number;
};
export type EconomyState = {
credits: bigint;
generators: Record<GeneratorId, Generator>;
lastTickAt: number;
};
export type EconomyConfig = {
ratePerSecond: Record<GeneratorId, bigint>;
baseCost: Record<GeneratorId, bigint>;
// Geometric growth as a rational, e.g. 115n / 100n for 1.15.
costGrowthNum: Record<GeneratorId, bigint>;
costGrowthDen: Record<GeneratorId, bigint>;
};
export function tick(
state: EconomyState,
config: EconomyConfig,
now: number,
): EconomyState {
const elapsedMs = Math.max(0, now - state.lastTickAt);
const credits = state.credits + incomeFor(state, config, elapsedMs);
return { ...state, credits, lastTickAt: now };
}
`lastTickAt` is wall-clock time, usually `Date.now()`. The render loop can call `tick` once a frame, or a store can call it when the tab becomes visible again. I do not keep a second unofficial clock in a `useEffect` that also increments a counter. Two clocks will drift, and then you will spend a week asking why the on-screen rate does not match the banked total.
The config is data. Rates and costs do not belong in JSX, and they do not belong in a CSS animation that "looks like" income. When I want to change the feel of a generator, I change the config and I run the tests. I do not hunt through components for a hardcoded `100`.
Offline progress is a formula
Players will leave the tab open, put the phone in a pocket, and come back later. The worst way to catch up is a loop that runs one tick per missing second. After a weekend, that loop is a loading screen, and it is also a way to hit floating-point and rounding bugs you would never see in an ordinary session.
Catch-up should be the same function as a live tick, called with a larger `elapsedMs`, with a cap if you have one:
const MAX_OFFLINE_MS = 1000 * 60 * 60 * 8;
export function catchUp(
state: EconomyState,
config: EconomyConfig,
now: number,
): EconomyState {
const elapsed = Math.min(Math.max(0, now - state.lastTickAt), MAX_OFFLINE_MS);
return tick({ ...state, lastTickAt: now - elapsed }, config, now);
}
export function incomeFor(
state: EconomyState,
config: EconomyConfig,
elapsedMs: number,
): bigint {
let total = 0n;
for (const generator of Object.values(state.generators)) {
const rate = config.ratePerSecond[generator.id] * BigInt(generator.owned);
total += (rate * BigInt(elapsedMs)) / 1000n;
}
return total;
}
I have used an eight-hour cap in the example because a cap is a design choice you should make on purpose. Some games pay the full away time. Some games cap it and tell the player why. What I will not do is leave it uncapped and also loop.
If a bonus, a seasonal modifier, or a decay changes mid-away, the honest approach is to split the interval at the change, not to apply the later modifier to the whole stretch. That is more code. It is also the only way the catch-up and a player who stayed on the page will agree.
Costs have to grow, and they have to be reversible to look at
A generator that always costs the same amount is a machine for breaking the mid-game. The usual curve is geometric: `base * growth^owned`. I keep that math in one function, and I keep `growth` in the config so I can feel it without rewriting the formula.
export function costOfNext(
state: EconomyState,
config: EconomyConfig,
id: GeneratorId,
): bigint {
const owned = state.generators[id].owned;
const base = config.baseCost[id];
const numerator = config.costGrowthNum[id];
const denominator = config.costGrowthDen[id];
let cost = base;
for (let i = 0; i < owned; i += 1) {
cost = (cost * numerator) / denominator;
}
return cost < 1n ? 1n : cost;
}
export function buy(
state: EconomyState,
config: EconomyConfig,
id: GeneratorId,
now: number,
): EconomyState {
const current = tick(state, config, now);
const cost = costOfNext(current, config, id);
if (current.credits < cost) return current;
return {
...current,
credits: current.credits - cost,
generators: {
...current.generators,
[id]: { id, owned: current.generators[id].owned + 1 },
},
};
}
The sample keeps the curve as a numerator and a denominator so the arithmetic stays in `bigint`. I would do the same in a real config, or I would use a decimal library, and I would never go back to `Math.pow` for a price the player will pay. `Math.pow(1.15, owned)` looks fine at twelve generators. It does not look fine at a few hundred, and idle games will get there.
I also test the inverse question: given a bank, how many of this generator can I afford. Bulk-buy is not a UI trick. It is the same cost function, summed, with a test that buying four one at a time matches buying four at once.
Currency is not a `number`
I use `bigint` in the sample, and I would use `bigint` or a decimal type in a real bank. I would not use a JavaScript `number` for the thing the player is accumulating. IEEE floats are fine for a camera. They are not fine for a balance that has to survive a long offline stretch and a lot of multiplies.
Display is a separate step. The bank can be `93120488221n` and the label can be `93.12B`. Once you start storing `93.12B` as the value, you have already lost. Rounding belongs at the edge, the same way I like to [validate API data at the boundary](/journal/validate-api-responses-at-the-boundary-in-typescript).
export function formatCredits(value: bigint): string {
if (value < 1_000n) return value.toString();
const units = [
[1_000_000_000_000n, "T"],
[1_000_000_000n, "B"],
[1_000_000n, "M"],
[1_000n, "K"],
] as const;
for (const [cut, suffix] of units) {
if (value >= cut) {
const whole = value / cut;
const frac = (value % cut) / (cut / 100n);
return `${whole}.${frac.toString().padStart(2, "0")}${suffix}`;
}
}
return value.toString();
}
That formatter is deliberately simple. A real game may want more units and a locale. What it should not want is to parse the formatted string back into a balance.
What I test, and what I leave out of the UI
I test income over a known interval, the cost of the nth generator, a purchase that should fail, a purchase that should succeed, catch-up at the cap, and bulk-buy against a loop of single buys. Those tests do not mount a component. They run against the economy module, and they are the tests I trust when I change a rate.
I do not test that a button is green. I do not put prestige, seasons, or a daily gift inside `tick` until I can say what they do to catch-up. I do not let a UI animation award currency if the player closes the tab mid-animation. If the award is real, it is already in the state.
Zero Space Radio is a much larger game than the snippet above, and it has its own rules about when a modal should appear and when it should not. The part I would repeat on a new idle project is the split: config is data, time is an input, currency is exact, the UI is a view. The moment those four collapse into one component, the economy becomes a story you tell about the screen instead of a function you can test.
I would rather tune a config object than debug a render loop that also happens to be the bank.