Skip to main content

games/rps/
game.rs

1use crate::rps::Weapon;
2use core::cmp::Ordering;
3
4/// Result of `RpsGame`
5#[repr(C)]
6#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
7pub enum GameResult {
8    /// Player has won the game
9    Win {
10        /// The weapon the player chose
11        player: Weapon,
12        /// The weapon the robot chose
13        robo: Weapon,
14    },
15    /// Player has lost the game
16    Lose {
17        /// The weapon the player chose
18        player: Weapon,
19        /// The weapon the robot chose
20        robo: Weapon,
21    },
22    /// It is a draw
23    Draw {
24        /// The weapon the player chose
25        player: Weapon,
26        /// The weapon the robot chose
27        robo: Weapon,
28    },
29}
30
31/// Rock Paper scissors Game
32#[repr(C)]
33#[derive(
34    Copy, Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash,
35)]
36pub struct RpsGame {
37    // Player's chosen weapon
38    pub(crate) player: Weapon,
39    // Bot's chosen Weapon
40    pub(crate) robo: Weapon,
41}
42
43impl RpsGame {
44    /// Create a new game of rock paper scissors
45    /// weapon: Weapon you chose to use (Rock/Paper/Scissors)
46    pub fn new_game(weapon: Weapon) -> Self {
47        Self {
48            player: weapon,
49
50            robo: Weapon::rand(),
51        }
52    }
53    /// convert the struct into a result of the game
54    pub fn result(self) -> GameResult {
55        self.into()
56    }
57}
58
59impl From<RpsGame> for GameResult {
60    fn from(val: RpsGame) -> Self {
61        match val.player.cmp(&val.robo) {
62            Ordering::Greater => GameResult::Win {
63                player: val.player,
64                robo: val.robo,
65            },
66            Ordering::Equal => GameResult::Draw {
67                player: val.player,
68                robo: val.robo,
69            },
70            Ordering::Less => GameResult::Lose {
71                player: val.player,
72                robo: val.robo,
73            },
74        }
75    }
76}