Game Dev Advanced

24  Game states

Games are state machines: a screen enum plus rules for legal transitions. Drive the transitions with a match on (state, event), then build the other gamedev staple -- a cooldown timer.

Step 1 / 2

Implement next: apply the legal transitions, leave the state unchanged otherwise.

Hints
  • Match on both at once: match (state, event) { ... }.
  • Five legal arms, then _ => state keeps everything else where it is.
24_state_machine.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
#[derive(Clone, Copy, PartialEq, Debug)]
enum State { Menu, Playing, Paused, GameOver }
#[derive(Clone, Copy)]
enum Event { Start, Pause, Resume, Die, Restart }

fn next(state: State, event: Event) -> State {
    match (state, event) {
        (State::Menu, Event::Start) => State::Playing,
        (State::Playing, Event::Pause) => State::Paused,
        (State::Paused, Event::Resume) => State::Playing,
        (State::Playing, Event::Die) => State::GameOver,
        (State::GameOver, Event::Restart) => State::Menu,
        _ => state,
    }
}