Simulation: Energy System (BETA)
Add a regenerating energy/stamina system to your game. Players spend energy to take actions (start battles, enter dungeons) and it refills automatically over time, even while offline.
This is a self-contained recipe. Everything you need, config, client code, and patterns, is on this page.
Where Config Goes
All JSON config on this page is simulation config: server-authoritative state, actions, and rewards. The CLI uploads it automatically when you rundot deploy.
Recommended: rundot/simulation/
Place simulation config in the rundot/simulation/ directory, one file per system. Each file holds raw simulation content with no {"simulation": {...}} wrapper (the directory implies it). Files are deep-merged alphabetically at deploy time with collision detection.
my-game/
├── rundot/
│ └── simulation/
│ └── energy-system.json ← raw content, no "simulation" wrapper
├── game.config.prod.json ← game ID + build settings only (separate)
└── package.jsonCommit
rundot/to your repo; it's project config likepackage.json, not a build artifact. It's env-agnostic and takes priority over legacyconfig.{local,staging}.json.game.config.prod.jsonis for CLI metadata only; simulation config does not go there.
Also supported: legacy config.json / config/
Legacy layouts keep working indefinitely. Run rundot migrate-config (with --dry-run to preview) to move them into rundot/simulation/ automatically.
What You'll Build
Energy that regenerates 1 point every N minutes, up to a maximum
Actions that cost energy (e.g., starting a battle costs 5 energy)
Automatic offline catch-up (player returns after 2 hours → energy has regenerated)
A cap so energy stops regenerating at max
Server Configuration
Entities
Define the energy state:
energy_current
The player's current energy. Consumed by actions, refilled by regen.
energy_max
Maximum energy capacity. Use this if max energy can increase (e.g., through upgrades).
Regeneration Recipe
This is the core of the energy system: a timed recipe that auto-restarts to produce 1 energy every cycle:
duration
600000
10 minutes per energy point (in milliseconds).
autoRestart
true
Restarts immediately after granting energy.
concurrency
"single"
Only one regen timer runs at a time.
maxOfflineExecutionPeriod
604800000
Catch up to 7 days of offline regen.
maxRestartCondition
energy_current ≤ 20
Stops regenerating when energy is full.
inputs
{}
Regen is free: no cost to the player.
outputs
energy_current: 1
Grants 1 energy per cycle.
Energy-Spending Recipes
Define actions that consume energy:
Key patterns:
battle_startcosts 5 energy and sets abattle_pendingflagbattle_start_freeis an alternative for tutorials with no energy costbattle_resolve_forfeitrefunds energy if the player cancels before the battle starts
Initialization
Start the regen timer when a new player opens the game for the first time:
The onStart lifecycle hook fires the initial_player_state recipe once. It sets energy to full and kicks off the regen timer.
Client-Side Implementation
Step 1: Read Energy State
Step 2: Subscribe to Real-Time Updates
Subscribe to activeRuns: true to get the regen timer's progress. Each active run includes an expiresAt timestamp you can use to show a countdown.
You can also target entities by tag instead of listing ids, and scope the subscription to a room:
entities
string[]
No
-
Entity ids to watch (e.g. ['energy_current']).
tags
string[]
No
-
Entity tags to watch (e.g. ['energy']); an alternative to listing ids.
activeRuns
boolean
No
false
When true, emit 'activeRuns' updates for in-flight timers.
roomId
string
No
-
Scope the subscription to a room's shared state.
onUpdate
(update) => void
Yes
-
Receives 'snapshot', 'entity', and 'activeRuns' updates.
Step 3: Display Regen Countdown
Seed the timer on mount with getActiveRunsAsync
The subscription's 'activeRuns' deltas only fire when a timer changes, so on screen mount you may want the current timer immediately. getActiveRunsAsync does a one-shot fetch:
getActiveRunsAsync(options?)
Promise<SimulationRunSummary[]>
Fetch the player's current active runs once. options is { roomId?: string } to scope to a room. Pair it with the 'snapshot' subscription update to seed the regen countdown before deltas arrive.
Step 4: Spend Energy with Optimistic UI
executeRecipeAsync resolves to more than success / message. The full ExecuteRecipeResponse reports what the server actually did:
success
boolean
Whether the recipe ran.
message
string?
Human-readable result or error.
outputs
Record<string, number | string>?
Entities granted or consumed (e.g. confirm the 5 energy spent).
runId
string?
Id of the started run (for timed recipes).
expiresAt
string?
When a timed run completes.
queuePosition
number?
Position if the recipe was queued.
amountRequested
number?
Batch quantity requested.
amountFulfilled
number?
Batch quantity actually granted.
partialSuccess
boolean?
true when only part of a batch spend succeeded.
randomSeed
string?
Seed for recipes with randomized outputs.
status
string?
Server status code for the run.
data
Record<string, unknown>?
Extra recipe-specific payload.
For batched spends (batchAmount in ExecuteRecipeOptions), check partialSuccess and amountFulfilled to learn how many copies actually went through, and read outputs to reconcile your optimistic UI with the authoritative result.
Step 5: Check Requirements Before Showing UI
getRecipeRequirementsAsync takes a single Recipe object: { recipeId: string; entity?: string; nonce?: string; batchAmount?: number }. Pass batchAmount to check the cost of spending several copies at once (e.g. { recipeId: 'battle_start', batchAmount: 3 }). It resolves to a RecipeRequirementResult with canAfford, inputs, disabled, and the resolved amount.
How Offline Catch-Up Works
Player closes the game with 5/20 energy
Player returns 3 hours later (180 minutes)
Regen is 1 energy per 10 minutes → 18 cycles would have completed
But
maxRestartConditioncaps at 20, so only 15 energy is granted (5 + 15 = 20)Player sees 20/20 energy on return
The maxOfflineExecutionPeriod of 7 days means if a player is away for a month, only 7 days of catch-up are calculated.
Common Variations
Dynamic Regen Rate
If regen speed increases with level, use a formula for duration:
Premium Energy Refill
Let players buy energy with premium currency:
Ad-Rewarded Energy
Grant energy for watching an ad: call the recipe after a successful ad view:
Resetting State During Development
While building and testing an energy system, resetStateAsync wipes the current player's simulation state: it clears entities, cancels all active runs (including the regen timer), and removes slot assignments. Pass initializeRecipe to re-seed full energy in the same call.
resetStateAsync(options?)
Promise<ResetStateResult>
Clears all simulation state for the current player. options is { initializeRecipe?: string }. Resolves to { success, clearedRuns, clearedSlots, recipeExecuted }.
Best Practices
Always validate energy client-side before calling
executeRecipeAsyncfor responsive UX, but trust the server result as authoritative.Use optimistic updates with rollback: deduct energy immediately, restore on server failure.
Subscribe to
activeRunsto power countdown timers instead of calculating client-side.Set
maxOfflineExecutionPeriodto prevent unlimited offline accumulation.Consider a
battle_resolve_forfeitrecipe to refund energy when players cancel actions.Keep
energy_regenerationmetadatahidden: trueso it doesn't appear in player-facing recipe lists.
Last updated