Sub topic 5
Modeling outcomes as a state machine
Prerequisites and scope
This chapter assumes you know what win, lose, and fail states are (covered in the earlier chapters of this tutorial). It also assumes you can read Python: functions, conditionals, classes, and enums. The goal is to turn those design ideas into explicit logic. The logic should be easy to read, easy to test, and unambiguous when two things happen in the same frame.
Why model outcomes explicitly
Many prototypes scatter outcome logic across the codebase. The enemy script calls game_over(). The pickup script calls victory(). A timer calls game_over() too. Each of these works alone. Together they cause bugs that are hard to reproduce:
- The player collects the last relic on the same frame their health reaches zero, and the screen flashes both "Victory" and "Game Over".
- The game-over screen appears twice because two systems each reported a death.
- The player dies after the win screen is already showing, and a lose sound plays over the credits.
A state machine fixes this by giving the game one place that answers the question "What is the outcome right now?" A state machine is a model with a fixed set of states, exactly one of which is active at a time, and a defined set of transitions between them. For outcomes, the states are things like playing, won, and lost. The transitions are the events that move the game from one to another.
The core states
A minimal outcome model has three states.
| State | Meaning | Can the player still act? |
|---|---|---|
| PLAYING | No end condition has been met | Yes |
| WON | A win condition was met | No (or only in a post-game flow) |
| LOST | A lose condition was met | No (or only in a retry flow) |
WON and LOST are terminal states. Once the machine enters one, nothing in the run moves it back to PLAYING. Starting a new attempt creates a fresh machine instead of reversing the old one. This rule prevents the "died after winning" class of bug.
Fail states usually do not appear as separate states in this top-level machine. A fail state is a setback the player can recover from, so the machine stays in PLAYING while the game handles the setback. The next sections show how.
A first implementation
The simplest version is a pure function. It takes the current game numbers and returns an outcome. It changes nothing, so you can call it from a test with made-up values.
from enum import Enum, auto
class Outcome(Enum):
PLAYING = auto()
WON = auto()
LOST = auto()
def evaluate(health, relics, relics_needed):
# Check the lose condition first, so a simultaneous win and loss
# resolves as a loss. Reverse the order to favor the player.
if health <= 0:
return Outcome.LOST
if relics >= relics_needed:
return Outcome.WON
return Outcome.PLAYING
print(evaluate(health=3, relics=2, relics_needed=5)) # Outcome.PLAYING
print(evaluate(health=0, relics=5, relics_needed=5)) # Outcome.LOST
print(evaluate(health=1, relics=5, relics_needed=5)) # Outcome.WONThe second call is the important one. Health is zero and the relic count is met on the same check. The order of the if statements decides the result. That order is a design decision, not a coding detail.
Precedence: deciding simultaneous outcomes
Precedence is the rule for which outcome wins when more than one condition is true at once. Every game with both a win and a lose condition has this question, even if the code never states an answer.
There are three common answers:
- Loss first. Death beats victory. This is the strictest rule. It suits games where reaching the goal while dying feels like it should not count, such as a race to an exit in a hazard room.
- Win first. Victory beats death. This favors the player. It suits games where the last action is the goal, such as a boss fight where trading a final blow for your own life should still count as a win.
- Declared tie or special outcome. The game has a third result for the overlap, such as a draw or a "pyrrhic victory" ending. This is common in competitive games.
Whichever you choose, apply three rules:
- Decide it on purpose and write it in the design document.
- Put the decision in one function, not in several scripts.
- Write a test for the overlap case.
Adding fail states without breaking the model
Now consider a game with lives and checkpoints. Death is no longer always a loss. It costs one life and returns the player to the last checkpoint. The same event is a recoverable fail state while lives remain, and a lose state when they run out.
class Run:
def __init__(self, lives, checkpoint):
self.lives = lives
self.checkpoint = checkpoint
self.position = checkpoint
def on_player_death(self):
# A death is a fail state while lives remain and a lose state when they run out.
self.lives -= 1
if self.lives == 0:
return Outcome.LOST
self.position = self.checkpoint
return Outcome.PLAYINGThis code shows the key idea of the chapter. The event "player died" is not an outcome. It is an input to the state machine. The machine looks at the resources behind it (here, lives) and decides which transition applies. The same input produces different results depending on the data.
The Run class has one weakness. If on_player_death is called twice in one frame, for example because two enemies hit the player at once, lives drop by two. With lives == 1, the second call makes lives equal to -1, and the == 0 check never triggers. A safer version uses <= 0 and ignores events after a terminal state. The next section builds that guard.
A complete outcome machine
The full version combines the pieces. It owns the current state, accepts events, applies precedence, and refuses to leave a terminal state.
from enum import Enum, auto
class Outcome(Enum):
PLAYING = auto()
WON = auto()
LOST = auto()
class OutcomeMachine:
def __init__(self, lives, relics_needed, checkpoint):
self.state = Outcome.PLAYING
self.lives = lives
self.relics = 0
self.relics_needed = relics_needed
self.checkpoint = checkpoint
self.position = checkpoint
self.pending_death = False
def report_death(self):
# Record the event. Do not change state yet.
if self.state is Outcome.PLAYING:
self.pending_death = True
def report_relic(self):
if self.state is Outcome.PLAYING:
self.relics += 1
def end_of_frame(self):
# Resolve everything that happened this frame in one place.
if self.state is not Outcome.PLAYING:
return self.state
if self.pending_death:
self.lives -= 1 # at most one life lost per frame
self.pending_death = False
if self.lives <= 0:
self.state = Outcome.LOST # loss precedes win
return self.state
self.position = self.checkpoint # recoverable fail state
if self.relics >= self.relics_needed:
self.state = Outcome.WON
return self.state
run = OutcomeMachine(lives=1, relics_needed=2, checkpoint=(0, 0))
run.report_relic()
run.report_relic()
run.report_death()
print(run.end_of_frame()) # Outcome.LOST, because loss takes precedenceThree design choices in this code are worth naming.
- Events are recorded, then resolved.
report_deathandreport_reliconly note what happened.end_of_framemakes the decision. This keeps precedence in one place. - Terminal states ignore input. Every method checks
self.state. A late event after the game ended cannot change anything. - One life per frame. Several hits in one frame count as one death. This is also a fairness choice: it stops a single burst of damage from consuming multiple lives.
If your design says a fail state should give the player a brief grace period, you can add an INVULNERABLE timer inside PLAYING. Keep the top-level outcome machine small. Put per-feature detail in the feature that needs it.
Choosing where fail states live
There are two common ways to represent fail states, and both are valid.
| Approach | How it works | Good for | Cost |
|---|---|---|---|
| Fail as a transition | The machine stays in PLAYING and handles setbacks as data changes (lives, position) | Most games, small outcome logic | The setback is invisible in the state diagram |
| Fail as a state | Add a state such as RESPAWNING between PLAYING and either PLAYING or LOST | Games with a visible respawn flow, animations, or timed recovery | More states and transitions to test |
Use a separate state when the setback has its own duration or its own rules. A respawn that takes three seconds, during which the player cannot act but the world keeps running, is a real phase of the game. Modeling it as a state lets you say exactly what is allowed during it.
Common errors
- Checking conditions in many places. Each extra check is a chance for two systems to disagree. Keep one evaluation point.
- Letting terminal states be reversible. If WON can return to PLAYING, a late hit can erase a victory. Make terminal states final within a run.
- Unspecified precedence. If the code order is the only record of the rule, the next person to edit it may flip the behavior without noticing.
- Using
== 0instead of<= 0. Damage and life changes can skip over zero. Compare with<=. - Firing presentation from the logic. The state machine should report a state. Sounds, screens, and animations should react to the change. This keeps the logic testable without a screen, and the later chapter on feedback builds on it.
- Forgetting restart. Build a new machine for a new run. Reusing one with stale counters carries old relics and lives into the next attempt.
Summary of the model
An outcome state machine has a short list of states, one place where transitions are decided, a declared precedence rule, and terminal states that ignore further input. Fail states fit in either as data changes inside PLAYING or as a separate state when the setback has its own phase. The design questions from earlier chapters (what counts as a win, what counts as a loss, what is recoverable) become the exact conditions and transitions in this machine.
Exercise
In the OutcomeMachine, the player has 2 lives, collects the final relic, and is hit by two enemies, all in the same frame. Both hits call reportdeath. What state does endof_frame return, how many lives remain, and how would you change the code if the design said each hit should cost a life?
Show answer
The machine returns WON and 1 life remains. The two reportdeath calls only set the pendingdeath flag to True, so endofframe subtracts one life (2 to 1), sees lives above zero, moves the player to the checkpoint, and then checks relics, which meet the goal. To make each hit cost a life, replace the boolean flag with a counter. Increment it in reportdeath, subtract the counter from lives in endof_frame, then reset it. With that change, two hits would take lives from 2 to 0, so the machine would return LOST because the loss check comes before the win check.
Exercise
A designer wants a boss fight where killing the boss while the player's health reaches zero on the same frame counts as a win. Which part of the code do you change, and what test do you add?
Show answer
Change the precedence in the single evaluation point so the win condition is checked before the lose condition. In the evaluate function, move the relics check above the health check, or in OutcomeMachine, check the win goal before the life check. Add a test where health is zero and the win condition is met together, and assert that the result is WON. Also keep a test where health is zero and the win condition is not met, and assert LOST.