We are going to explain what a finite state machine (FSM) is, provide a real-world example, and then give a simple implementation.
Definition:
A finite state machine (FSM) is a computational model used to design systems that can be in one of a finite number of states at any given time. The FSM can change from one state to another in response to external inputs; the change from one state to another is called a transition. An FSM is defined by:
- A set of states
- A set of inputs (events)
- A set of transitions (which state to move to given a current state and an input)
- A start state (initial state)
- A set of final states (optional, for accepting states in automata theory)
In practice, FSMs are used in many fields such as computer science, electrical engineering, linguistics, and biology. They are particularly useful for modeling behavior that is event-driven and can be broken down into distinct states.
Real-world example:
Consider a simple traffic light. It has three states: Green, Yellow, Red. The transitions are triggered by timers (or sensors) that change the light after a certain interval. The sequence is:
- Green -> Yellow (after a time)
- Yellow -> Red (after a short time)
- Red -> Green (after a time)
This is a classic example of a finite state machine with cyclic behavior.
Simple implementation:
We'll implement a traffic light FSM in Python. We'll have:
- States: 'GREEN', 'YELLOW', 'RED'
- Inputs: 'timer_expired' (we assume a timer triggers the change)
- Transitions:
GREEN -timer_expired-> YELLOW
YELLOW -timer_expired-> RED
RED -timer_expired-> GREEN
We'll create a class that holds the current state and has a method to process an event (in this case, the timer expiration). We'll also have a method to get the current state.
Note: In a real traffic light, there might be pedestrian buttons or other inputs, but for simplicity we stick to the timer.
Let's code accordingly.
A finite state machine (FSM) is a computational model used to design systems that can be in exactly one of a finite number of states at any given time. Transitions between states occur based on inputs/events, following predefined rules. FSMs are widely used in software engineering, electronics, game AI, protocol design, and more.
Key Components:
- States: Distinct modes/conditions (e.g.,
locked, unlocked).
- Events/Inputs: Triggers that cause transitions (e.g.,
coin_inserted, button_pressed).
- Transitions: Rules mapping
(current_state, event) → next_state.
- Initial State: Starting state.
- Actions (optional): Side effects during transitions or in states (e.g., output a signal).
Real-World Example: Turnstile
A subway turnstile has two states:
- Locked: Arms block entry. Valid events:
coin (unlocks), push (denied).
- Unlocked: Arms allow one entry. Events:
push (resets to locked), coin (ignored).
Transitions:
| Current State | Event | Next State | Action |
|---|
| Locked | coin | Unlocked | unlock arm |
| Locked | push | Locked | alarm (optional) |
| Unlocked | push | Locked | lock arm, count entry |
| Unlocked | coin | Unlocked | ignore (no change) |
Simple Implementation (Python)
Below is a class-based FSM for the turnstile:
class TurnstileFSM:
def __init__(self):
self.state = "LOCKED"
self.coins = 0 # Optional: track coins
def process_event(self, event):
if self.state == "LOCKED":
if event == "COIN":
self.state = "UNLOCKED"
self.coins += 1
print("Turnstile unlocked. Accepting entry.")
elif event == "PUSH":
print("Alarm! Turnstile is locked.")
elif self.state == "UNLOCKED":
if event == "PUSH":
self.state = "LOCKED"
print("Entry accepted. Turnstile locked.")
elif event == "COIN":
print("Coin ignored. Already unlocked.")
def get_state(self):
return self.state
# Example usage
turnstile = TurnstileFSM()
turnstile.process_event("COIN") # Unlocks
turnstile.process_event("PUSH") # Enters, relocks
turnstile.process_event("PUSH") # Alarm (locked)
Output:
Turnstile unlocked. Accepting entry.
Entry accepted. Turnstile locked.
Alarm! Turnstile is locked.
Why Use FSMs?
- Clarity: Explicit state/event logic simplifies complex systems.
- Reliability: Prevents illegal transitions (e.g., pushing without a coin).
- Maintainability: Easy to modify/add states/events.
FSMs scale from simple designs (like the turnstile) to complex systems (network protocols, game NPC behavior). For larger projects, tools like Statecharts (hierarchical FSMs) or libraries (e.g., python-transitions) provide advanced features.