Created
September 29, 2023 06:51
-
-
Save mhtocs/de8540b7abd1429c11f31d97f81a4bff to your computer and use it in GitHub Desktop.
Mario
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
// 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