Skip to content

Instantly share code, notes, and snippets.

@ilopX
Last active April 29, 2023 11:14
Show Gist options
  • Save ilopX/44ff122e43b2aba9ecbe5faf21c70ff2 to your computer and use it in GitHub Desktop.
Save ilopX/44ff122e43b2aba9ecbe5faf21c70ff2 to your computer and use it in GitHub Desktop.
use std::mem;
use self::State::*;
use self::Transaction::*;
fn main() {
let mut player = Player::new();
println!("{:?}", player); // state == One
player.collision(Run); // state == Two
println!("{:?}", player);
player.collision(Go); // state = Three
println!("{:?}", player);
player.collision(Jump); // state = One
println!("{:?}", player);
if let One { active: true, name } = player.state {
println!("State is One and active = true, name: {name}");
}
}
#[derive(Debug)]
struct Player {
state: State,
}
impl Player {
fn new() -> Self {
Self {
state: One { active: true, name: "rust" },
}
}
fn collision(&mut self, transaction: Transaction) {
self.state(|state| {
match (state, &transaction) {
(One { .. }, Run) => Two,
(Two, Go) => Three,
(Three, Jump) => One { active: true, name: "rust collision" },
(state, _) => state,
}
});
}
fn state(&mut self, mut call: impl FnMut(State) -> State) {
let default_state = One { active: false, name: "" };
let curr_state = mem::replace(&mut self.state, default_state);
self.state = call(curr_state);
}
}
#[derive(Debug)]
enum State {
One { active: bool, name: &'static str },
Two,
Three,
}
enum Transaction {
Go,
Run,
Jump,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment