Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created September 15, 2019 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewjberger/46792339f8adcf52ee422f6a6a95dd67 to your computer and use it in GitHub Desktop.
Save matthewjberger/46792339f8adcf52ee422f6a6a95dd67 to your computer and use it in GitHub Desktop.
#[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