Created
September 15, 2019 18:31
-
-
Save matthewjberger/46792339f8adcf52ee422f6a6a95dd67 to your computer and use it in GitHub Desktop.
Simple state machine pattern in Rust (https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f66b41f93d7a9a2ef704d4aa5b5b0a44)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug, PartialEq)] | |
pub enum State { | |
Intro, | |
StartScreen, | |
PlayGame, | |
Paused, | |
Faulted, | |
} | |
#[derive(Debug, Clone, Copy)] | |
pub enum Event { | |
IntroFinished, | |
GameStartRequested, | |
PauseRequested, | |
UnpauseRequested, | |
} | |
pub struct GameplayStateMachine { | |
state: State, | |
} | |
impl GameplayStateMachine { | |
pub fn new() -> Self { | |
GameplayStateMachine { | |
state: State::Intro, | |
} | |
} | |
pub fn handle_events(&mut self, events: Vec<Event>) { | |
for event in events.iter() { | |
self.handle_event(&event); | |
} | |
} | |
pub fn handle_event(&mut self, event: &Event) { | |
self.state = match (&self.state, event) { | |
(State::Intro, Event::IntroFinished) => { | |
println!("Introducing the game!"); | |
State::StartScreen | |
} | |
(State::StartScreen, Event::GameStartRequested) => { | |
println!("Starting the game!"); | |
State::PlayGame | |
} | |
(State::PlayGame, Event::PauseRequested) => { | |
println!("Paused."); | |
State::Paused | |
} | |
(State::Paused, Event::UnpauseRequested) => { | |
println!("Unpaused"); | |
State::PlayGame | |
} | |
_ => { | |
println!("Faulted!"); | |
State::Faulted | |
} | |
}; | |
} | |
} | |
fn main() { | |
let mut machine = GameplayStateMachine::new(); | |
let events = vec![ | |
Event::IntroFinished, | |
Event::GameStartRequested, | |
Event::PauseRequested, | |
Event::UnpauseRequested, | |
Event::PauseRequested, | |
Event::UnpauseRequested, | |
]; | |
for event in events.iter() { | |
machine.handle_event(&event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment