skip to content

A boss's state machine needs Stunned and Dead reachable from every combat state; how does a hierarchical state machine avoid duplicating those transitions?

level: seniorimportance: should knowfreq 52%

answer

  1. states inside states
  2. parent transitions apply to children
  3. exit up to the common ancestor
  4. initial versus history substate

basics

~10 s

A hierarchical state machine nests states in superstates, and a transition declared on a superstate applies from every state inside it. One Combat-to-Stunned and one Alive-to-Dead transition replace a copy on each combat state.

solid answer

~50 s

In a **hierarchical state machine (HFSM)** a state can contain substates. For the boss: `Alive` contains `Combat` (with `Idle`, `Attack`, `Enraged`) and `Stunned`, and `Dead` sits beside `Alive`. A transition on `Alive` to `Dead` applies from every state nested inside it, and one on `Combat` to `Stunned` from every combat state, so adding a combat state adds no copies. Firing a transition exits from the active innermost state up to the **least common ancestor** of source and target, then enters down to the target and its initial substate: `Attack` to `Stunned` exits `Attack` and `Combat`, keeps `Alive` and enters `Stunned`. Two decisions need stating: whether inner or outer transitions win when both pass, and whether re-entering `Combat` after a stun starts its initial substate or a **history** state, or the boss forgets it was enraged.

code

pseudocode · 13 lines
pseudocode
function fireTransition(machine, source, target):
    lca = lowestCommonAncestor(source, target)
    s = machine.activeLeaf
    while s != lca:                      # exit innermost first, stop at the LCA
        s.exit()
        s = s.parent
    for t in pathBelow(lca, target):     # outermost first, ends at target
        t.enter()
    leaf = target
    while leaf.hasSubstates():           # descend into the initial or history substate
        leaf = leaf.historyOrInitial()
        leaf.enter()
    machine.activeLeaf = leaf

go deeper

for a junior

Recall that a hierarchical machine nests states, and a transition on a parent state applies from every child inside it.

for a middle

Walk the exit and enter order for a transition using the least common ancestor, and explain initial versus history substates.

for a senior

Spot the lost-enrage bug after a stun, choose and enforce an inner-versus-outer priority rule, and say when a hierarchy stops helping and concurrent machines are needed.

for a principal

For a lead, the question is standardising one hierarchy convention, priority and history rules included, so every gameplay programmer and tool reads machines the same way.

## The duplication problem In a flat state machine, a transition belongs to one source state. The boss has three combat states, `Idle`, `Attack` and `Enraged`, plus `Stunned` and `Dead`. If a heavy hit can stun the boss from any combat state and death can happen from any living state, the flat machine needs: - three copies of the stun transition, one per combat state; - four copies of the death transition, one per living state. That is seven transitions encoding two rules. Each new combat state adds two more, and each copy is a place to forget a guard change. This duplication is one of the main drivers of **state explosion** in flat machines. ## Superstates and substates A **hierarchical state machine (HFSM)**, close to the statechart formalism, lets a state contain a machine of its own: - `Alive` (superstate) - `Combat` (superstate) - `Idle`, `Attack`, `Enraged` - `Stunned` - `Dead` At any moment the active configuration is a path from the root to a leaf, such as `Alive > Combat > Attack`. Two rules make it work: 1. A transition declared on a superstate is available from every state inside it. `Alive -> Dead` and `Combat -> Stunned` are declared once. 2. Entering a superstate enters one of its substates as well, normally its declared **initial substate**. With the hierarchy, the two rules take two transitions, and adding a fourth combat state adds none. ## What runs when a transition fires The hooks run along the path through the hierarchy, determined by the **least common ancestor (LCA)** of the transition's source and target: 1. Exit from the active leaf upwards, innermost first, until reaching the LCA. The LCA itself is not exited. 2. Enter from just below the LCA down to the target, outermost first. 3. If the target is a superstate, keep entering its initial (or history) substate until a leaf is active. | Transition | LCA | Exits | Enters | |---|---|---|---| | `Combat -> Stunned` while in `Attack` | `Alive` | `Attack`, `Combat` | `Stunned` | | `Alive -> Dead` while in `Enraged` | root | `Enraged`, `Combat`, `Alive` | `Dead` | | `Stunned -> Combat` | `Alive` | `Stunned` | `Combat`, then its initial or history substate | Because `Alive` is not exited on a stun, anything `Alive` owns, such as a health bar shown on screen, stays up throughout. ## Two decisions every HFSM must make **Which transition wins when an inner and an outer guard both pass.** Some statechart semantics give the innermost state priority, so a substate can override a parent's rule. Other semantics, and many game implementations, test outer levels first, so `Dead` on `Alive` wins over anything a combat state wants. Both are coherent; mixing them is not. If inner wins, a combat substate's transition can delay death by a tick. **What re-entering a superstate restores.** After the stun, `Stunned -> Combat` enters `Combat`'s initial substate, `Idle`. If the boss was `Enraged` before the stun, it silently loses the enrage. Remedies: - a **history** substate, which re-enters whichever substate was last active in `Combat`; - modelling the phase as structure, such as `Combat` containing `PhaseOne` and `PhaseTwo` superstates, with the stun returning to the right phase; - keeping a fact such as `enragedYet` as data and letting `Combat`'s initial transition read it. ## Costs and pitfalls - **Depth hurts readability.** Two or three levels are easy to follow; beyond that, working out which transition applies means walking several parents. - **Updates at several levels.** If superstates also have `update`, define the order, usually outer to inner, and keep each level's work separate. - **Cross-level transitions.** A transition from deep inside one branch to deep inside another exits and enters many states; log the whole exit and enter path when debugging. - **Not a cure for independent concerns.** A hierarchy groups states that share exits. It does not help when two unrelated concerns, such as alertness and weapon state, are multiplied together; separate concurrent machines do. ## Debugging a hierarchy Hierarchical bugs are usually bugs of path, not of a single state, so the tooling should show paths: - Log the full active path, such as `Alive > Combat > Enraged`, every time it changes, not just the leaf. - Log the exit and enter sequence of each fired transition together with the level the transition was declared on. - When a transition fires unexpectedly, check which level declared it before reading any guard code; a parent's rule firing over a child's is the most common surprise.

  • How does a history substate differ from a pushdown stack?
    A history substate belongs to one superstate and remembers its last active substate, restored when that superstate is re-entered. A pushdown stack is one stack for the whole machine: an interrupting state is pushed on top and popped to resume whatever was underneath. History restores a position in the hierarchy; a stack restores an arbitrary previous state and can nest interruptions.
  • When is a flat machine better than a hierarchy?
    When there are only a few states and few shared transitions, such as a door or a simple ambient creature. A hierarchy adds rules about exit and enter order, priority between levels and history, which cost more to learn and debug than they save on a five-state machine with no repeated edges.

  • A superstate transition fires only from the superstate's initial substate.
  • Firing Attack to Stunned exits and re-enters the Alive superstate.
  • Re-entering a superstate always restores its last active substate.
  • Hierarchy fixes state explosion from independent concerns such as alertness and weapon state.
  • Inner and outer transition priority is fixed, so it never needs choosing.