Created
March 27, 2023 17:44
-
-
Save AlJohri/94af45b05fb6b2fe1db7e3b66a13b7f1 to your computer and use it in GitHub Desktop.
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
use std::error::Error; | |
#[derive(PartialEq)] | |
enum MyGameResult { | |
Win, | |
Lose, | |
Tie | |
} | |
#[derive(Debug, PartialEq, Clone, Copy)] | |
enum Shape { | |
Rock = 0, | |
Paper = 1, | |
Scissors = 2, | |
} | |
impl Shape { | |
fn get_winning_move_for_opponent(&self) -> Self { | |
let self_u8 = *self as u8; | |
Shape::try_from((&self_u8 + 2) % 3).unwrap() | |
} | |
fn get_losing_move_for_opponent(&self) -> Self { | |
let self_u8 = *self as u8; | |
Shape::try_from((self_u8 + 1) % 3).unwrap() | |
} | |
} | |
impl std::convert::TryFrom<u8> for Shape { | |
type Error = Box<dyn Error>; | |
fn try_from(value: u8) -> Result<Self, Self::Error>{ | |
match value { | |
0 => Ok(Shape::Rock), | |
1 => Ok(Shape::Paper), | |
2 => Ok(Shape::Scissors), | |
_ => Err(format!("invalid shape: {}", value).into()), | |
} | |
} | |
} | |
fn vs(me: Shape, opponent: Shape) -> MyGameResult { | |
let winning_move_for_opponent = me.get_winning_move_for_opponent(); | |
let losing_move_for_opponent = me.get_losing_move_for_opponent(); | |
println!("me: {me:?}, opponent: {opponent:?}, winning_move_for_opponent: {winning_move_for_opponent:?}, losing_move_for_opponent: {losing_move_for_opponent:?}"); | |
match opponent { | |
x if x == losing_move_for_opponent => MyGameResult::Lose, | |
x if x == winning_move_for_opponent => MyGameResult::Win, | |
x if x == me => MyGameResult::Tie, | |
_ => unreachable!() | |
} | |
} | |
fn main() { | |
// Wins | |
assert!(vs(Shape::Scissors, Shape::Paper) == MyGameResult::Win); // "Scissors cuts Paper" | |
assert!(vs(Shape::Paper, Shape::Rock) == MyGameResult::Win); // "Paper covers Rock" | |
assert!(vs(Shape::Rock, Shape::Scissors) == MyGameResult::Win); // "Rock crushes Scissors" | |
// Ties | |
assert!(vs(Shape::Rock, Shape::Rock) == MyGameResult::Tie); | |
assert!(vs(Shape::Paper, Shape::Paper) == MyGameResult::Tie); | |
assert!(vs(Shape::Scissors, Shape::Scissors) == MyGameResult::Tie); | |
// One Example Loss | |
assert!(vs(Shape::Scissors, Shape::Rock) == MyGameResult::Lose); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment