Skip to content

Instantly share code, notes, and snippets.

@mhtocs
Created September 29, 2023 06:51
Show Gist options
  • Save mhtocs/de8540b7abd1429c11f31d97f81a4bff to your computer and use it in GitHub Desktop.
Save mhtocs/de8540b7abd1429c11f31d97f81a4bff to your computer and use it in GitHub Desktop.
Mario
// SUPER-MARIO STATE MACHINE IN RUST
#[derive(Debug, PartialEq)]
enum State {
Mario,
SuperMario,
FireMario,
CapeMario,
}
use State::*;
#[derive(Debug)]
enum Transition {
Feather,
Flower,
Mushroom,
}
use Transition::*;
#[derive(Debug)]
struct Player {
state: State
}
impl Player {
fn new () -> Self {
Self {state: Mario}
}
fn collect(&mut self, power: Transition) {
match (&self.state, power) {
(Mario, Mushroom) => self.state = SuperMario,
(_, Feather) => self.state = CapeMario,
(_, Flower) => self.state = FireMario,
(_, Mushroom) => {}
}
}
}
fn main() {
let mut player = Player::new();
player.collect(Mushroom); // Mario -> SuperMario
player.collect(Flower); // SuperMario -> FireMario
player.collect(Feather); // FireMario -> CapeMario
player.collect(Mushroom); // No Effect
player.collect(Mushroom); // No Effect
assert!(player.state == CapeMario)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment