Tag: gameplay programming

  • Game State Management: Choose Ownership Before a State Machine

    Game State Management: Choose Ownership Before a State Machine

    “Game state” can mean the current menu, a character's movement mode, the world simulation, a save file, interface selection or an authoritative multiplayer snapshot. Combining all of these in one global state manager creates hidden dependencies and transitions that are difficult to test.

    Begin with ownership and lifecycle. A state machine is a useful implementation tool only after the team knows which subsystem owns each fact, who may change it and what must happen when it changes.

    Article map for Game State Management: Choose Ownership Before a State Machine, covering Divide state by responsibility, Use the smallest state model that fits, Make transitions explicit and related review points.
    Article map: Divide state by responsibility; Use the smallest state model that fits; Make transitions explicit; Keep side effects at boundaries.

    Divide state by responsibility

    A practical inventory distinguishes at least:

    State family Examples Likely owner
    Application flow boot, title, loading, gameplay, results flow coordinator
    Entity behaviour idle, moving, stunned, attacking entity or behaviour component
    Interface active screen, focus, modal stack UI layer
    Persistent progress settings, unlocks, save slots persistence service
    Network truth match phase, player inventory, scores authoritative server or replication layer
    Presentation animation blend, camera shake, transient effects presentation systems

    Do not duplicate one concept across owners without a synchronisation rule. An animation parameter can present an entity state, but it should not silently become a second authority for whether the character can attack.

    Separate durable data from transient runtime handles. A save file should contain a versioned representation that can be validated and migrated, not pointers to scene objects. A network snapshot should contain replicated facts, not every private presentation variable.

    Use the smallest state model that fits

    A finite state machine has a finite set of states, events and allowed transitions. It works well when one region of behaviour is mutually exclusive: a door can be closed, opening, open or closing. Put entry, update and exit behaviour with the state or transition rather than distributing checks across unrelated scripts.

    The State chapter in Game Programming Patterns explains three useful forms: a basic finite state machine, hierarchical state machines that share behaviour and pushdown automata that keep a stack so a temporary state can return to the state beneath it (Game Programming Patterns — State).

    Choose deliberately:

    • basic FSM: small, mutually exclusive behaviour;
    • hierarchical state machine: shared parent behaviour and nested refinement;
    • state stack or pushdown model: pause, overlay or temporary actions that must resume prior context;
    • parallel regions: independent dimensions, such as locomotion and equipped-item state; or
    • data-oriented rules or planner: numerous interacting facts where enumerating combined states would explode.

    Do not create one state for every combination of movement, weapon, status, camera and interface. Split orthogonal responsibilities and define their interaction.

    Make transitions explicit

    Each transition should have:

    • a source and destination;
    • an event or evaluated condition;
    • a guard that can accept or reject it;
    • ordered exit, transition and entry actions;
    • a policy for re-entry and interruption; and
    • observable reason data for debugging.

    Prefer events such as LoadSucceeded, HealthReachedZero or PauseRequested over repeated polling of unrelated globals. Events should carry the minimum validated data needed by the owner. Avoid an unconstrained global event bus where any system can mutate any other system.

    Specify conflict handling. If PauseRequested and PlayerDefeated arrive in the same update, which transition wins? Are events queued, coalesced or discarded after a transition? Can entry actions emit new events? Guard against unbounded re-entrant transitions.

    W3C's SCXML Recommendation provides a formal vocabulary for event-driven state machines, including compound and parallel states. A game does not need to implement SCXML, but its processing model is a useful reference when defining event queues, guards and entry/exit order (W3C — SCXML).

    Decision path for Game State Management: Choose Ownership Before a State Machine, covering Make transitions explicit, Keep side effects at boundaries, Define multiplayer authority and persistence separately and related…
    Decision path: Make transitions explicit; Keep side effects at boundaries; Define multiplayer authority and persistence separately; Test models as transition tables.

    Keep side effects at boundaries

    A state transition can request audio, animation, loading or analytics, but the state model should not own every implementation. Use narrow interfaces so the model can run in a headless test. For example, an application-flow state can request LoadLevel(id) through a service and wait for a success or failure event.

    Make cancellation explicit. Leaving a loading state should cancel or safely ignore the outstanding result. Entry and exit must be idempotent enough to handle retries, scene teardown and error recovery. Dispose subscriptions and timers when ownership ends.

    Avoid long blocking work inside a transition. Start asynchronous work, store a bounded operation identifier and handle completion as an event. Late results must be checked against the current owner and operation.

    Define multiplayer authority and persistence separately

    In multiplayer, a local state machine can predict presentation, but the server remains authoritative for consequential state. A client entering Attack does not prove the server accepted the attack. Model requested, predicted, confirmed and rejected outcomes where the distinction matters.

    For save data, write schema versions and migration tests. Validate enum or state identifiers read from disk; removed states need a defined fallback. Capture enough stable data to reconstruct runtime state, but do not serialise temporary callbacks, pooled-object identifiers or network connections.

    Test models as transition tables

    The state model should run without a rendered scene. Create tests for:

    • every allowed transition and important rejected transition;
    • entry and exit order;
    • repeated, missing and out-of-order events;
    • interruption and return for stacked states;
    • guard boundaries and simultaneous conditions;
    • asynchronous success, failure, timeout and late completion;
    • save migration and invalid state identifiers; and
    • server correction of predicted client state.

    A table-driven test can describe start state, event, context, expected state and expected effects. Property tests can assert invariants such as “only one application-flow leaf is active” or “a dead player cannot become attacking without respawn.”

    Add a runtime inspector that shows active states, queued events, last transition, guard result and time in state. Log structured transitions with a session or entity identifier while avoiding personal or secret data. A visual graph is useful only if it reflects the runtime model rather than becoming an undocumented second implementation.

    Control and evidence map for Game State Management: Choose Ownership Before a State Machine, covering Define multiplayer authority and persistence separately, Test models as transition tables, Review signs of an overloa…
    Control and evidence map: Define multiplayer authority and persistence separately; Test models as transition tables; Review signs of an overloaded design; General-information disclaimer.

    Review signs of an overloaded design

    Reconsider the architecture when:

    • a state knows about most systems in the project;
    • transitions are hidden in setters or animation callbacks;
    • adding one weapon multiplies locomotion states;
    • UI code changes server authority;
    • a save file contains scene-object references;
    • tests require the full rendered game; or
    • no one can explain which state owns a fact.

    Refactor one responsibility at a time. Introduce a boundary and regression tests before moving data; a large “state manager rewrite” without behavioural evidence can create more risk than it removes.

    For help scoping a gameplay architecture or testable state model, see Ozlin Info's game-development services or contact Ozlin Info.

    Related reading: Multiplayer game networking and authority.


    General-information disclaimer

    This article provides general technical information. The correct state model depends on the game's behaviour, engine, persistence and network architecture; the patterns described are not a universal design prescription.

    AI-assistance disclosure

    AI tools assisted with source discovery, outlining and copyediting. A human reviewer must validate ownership, transition semantics, tests and current engine behaviour before publication or implementation.

    Practical checklist for Game State Management: Choose Ownership Before a State Machine, covering Review signs of an overloaded design, General-information disclaimer, AI-assistance disclosure and related review points.
    Practical checklist: Review signs of an overloaded design; General-information disclaimer; AI-assistance disclosure; Primary sources checked.

    Primary sources checked

    Source access date: 29 August 2026.