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.
Implement next: apply the legal transitions, leave the state unchanged otherwise.
Hints
- Match on both at once:
match (state, event) { ... }. - Five legal arms, then
_ => statekeeps everything else where it is.
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,
}
}