Skip to main content

MoveType

Enum MoveType 

Source
pub enum MoveType {
    Rock,
    Paper,
    Scissors,
    None,
}
Expand description

§MoveType Enum

Represents the possible moves in the game, providing safety and clarity in game logic. Now includes a None variant for uninitialized or invalid move states.

§Variants

  • MoveType::Rock: The “Rock” move.
  • MoveType::Paper: The “Paper” move.
  • MoveType::Scissors: The “Scissors” move.
  • MoveType::None: A default state to handle uninitialized or invalid moves.

§Key Features

  • Randomized Moves: Generates a random move using random_move().
  • String Conversion: Converts moves to a user-friendly String using convert_to_string().
  • Controlled User Input: Converts valid input into a MoveType using from_user_input().

§Examples

§Create a MoveType

use rock_paper_scissors::MoveType;

let move_type = MoveType::Rock;
assert_eq!(move_type.convert_to_string(), "Rock");

§Generate a Random Move

use rock_paper_scissors::MoveType;

let random_move = MoveType::random_move();
assert!(matches!(random_move, MoveType::Rock | MoveType::Paper | MoveType::Scissors));

§Handle Uninitialized Moves

The None variant is helpful when moves are not immediately set:

use rock_paper_scissors::MoveType;

let move_type = MoveType::None;
assert_eq!(move_type.convert_to_string(), "None");

§Convert User Input

use rock_paper_scissors::MoveType;

println!("Enter your move: 1 (Rock), 2 (Paper), or 3 (Scissors)");
let user_move = MoveType::from_user_input();

match user_move {
    Ok(move_type) => println!("You chose: {}", move_type.convert_to_string()),
    Err(err) => println!("Error: {}", err),
}

Variants§

§

Rock

§

Paper

§

Scissors

§

None

Implementations§

Source§

impl MoveType

Source

pub fn random_move() -> MoveType

Generates a random MoveType (one of Rock, Paper, or Scissors).

§Examples
use rock_paper_scissors::MoveType;

let random_move = MoveType::random_move();
assert!(matches!(random_move, MoveType::Rock | MoveType::Paper | MoveType::Scissors));
Examples found in repository?
examples/sim.rs (line 11)
3fn main() {
4    let loops: u8 = 255;
5
6    let mut scores = Scores::new();
7
8    let mut player_moves = PlayerMoves::new();
9
10    for _ in 0..=loops {
11        (player_moves.user_move, player_moves.enemy_move) = (MoveType::random_move(), MoveType::random_move());
12
13        let winner = player_moves.check_who_wins_round();
14
15        match winner {
16            Winner::User => scores.user_wins += 1,
17            Winner::Enemy => scores.enemy_wins += 1,
18            Winner::Tie => (),
19        }
20    }
21
22    println!("{:?}", scores);
23}
Source

pub fn convert_to_string(&self) -> String

Converts the MoveType to a human-readable String.

§Examples
use rock_paper_scissors::MoveType;

let move_type = MoveType::Scissors;
assert_eq!(move_type.convert_to_string(), "Scissors");
Examples found in repository?
examples/interactive.rs (line 17)
3fn main() {
4    let mut scores = Scores::new();
5
6    let game_settings = GameSettings::from_first_to(3);
7
8    println!("Welcome to Rock-Paper-Scissors!");
9
10    // Game loop
11    while scores.check_for_winner(&game_settings).is_err() {
12        let player_moves = PlayerMoves::build_from_input();
13
14        let round_winner = player_moves.check_who_wins_round();
15        println!(
16            "You chose {}. Enemy chose {}.",
17            player_moves.user_move.convert_to_string(),
18            player_moves.enemy_move.convert_to_string(),
19        );
20        println!("Result: {}", round_winner.convert_to_string());
21
22        // Update scores
23        match round_winner {
24            Winner::User => scores.user_wins += 1,
25            Winner::Enemy => scores.enemy_wins += 1,
26            Winner::Tie => (),
27        }
28
29        println!(
30            "Current Scores -> You: {}, Enemy: {}",
31            scores.user_wins, scores.enemy_wins
32        );
33    }
34
35    // Display final results
36    let game_winner = scores.check_for_winner(&game_settings).unwrap();
37    println!("Game over! {}", game_winner.convert_to_string());
38}
More examples
Hide additional examples
examples/configurable.rs (line 23)
3fn main() {
4    let mut scores = Scores::new();
5
6    println!("Welcome to the Rock-Paper-Scissors game!");
7    println!("Please enter what you want to play to: ");
8
9    let game_settings = loop {
10        match GameSettings::from_user_input() {
11            Ok(game_settings) => break game_settings,
12            Err(err) => println!("Error: {}", err),
13        }
14    };
15
16    println!();
17    let mut round_counter = 0;
18    while scores.check_for_winner(&game_settings).is_err() {
19        round_counter += 1;
20        println!("Round {}:", round_counter);
21        let player_moves = PlayerMoves::build_from_input();
22        println!();
23        println!("User: {}", player_moves.user_move.convert_to_string());
24        println!("Enemy: {}", player_moves.enemy_move.convert_to_string());
25
26        let round_winner = player_moves.check_who_wins_round();
27        println!();
28        match round_winner {
29            Winner::Tie => {
30                println!("Tie!");
31                round_counter -= 1
32            },
33            Winner::User => {
34                println!("User win");
35                scores.user_wins += 1;
36            },
37            Winner::Enemy => {
38                println!("Enemy win");
39                scores.enemy_wins += 1;
40            }
41        }
42
43        println!("Current Scores -> User: {} :: Enemy: {}", scores.user_wins, scores.enemy_wins);
44    }
45
46    let game_winner = scores.check_for_winner(&game_settings).unwrap(); // can use unwrap here because the while loop
47    // will only break if the return is Ok()
48
49
50    println!("Game Winner: {}", game_winner.convert_to_string());
51}
examples/colored.rs (line 31)
4fn main() {
5    println!("{}", "Welcome to rock paper scissors!".blue().bold());
6
7    // create game_settings struct with 3.
8    let game_settings = GameSettings::from_first_to(3);
9
10    println!("{}", "Game will be first to 3 rounds.".blue().bold());
11
12    let mut scores = Scores::new(); // instantiate Scores struct
13
14    let mut round_counter = 0;
15
16    while scores.check_for_winner(&game_settings).is_err() { // checking to see if there has been a winner yet.
17        round_counter += 1;
18        let player_moves = PlayerMoves::build_from_input(); // build a PlayerMoves struct from input
19        let round_winner = player_moves.check_who_wins_round(); // check who wins round based on moves.
20
21        println!(
22            "{}{}{}",
23            "-----Round ".magenta(),
24            round_counter.to_string().magenta(),
25            "-----".magenta()
26        );
27
28        println!(
29            "{}{}{}{}{}",
30            "User: ".italic(),
31            player_moves.user_move.convert_to_string().italic(),
32            " :: ".italic(),
33            "Enemy: ".italic(),
34            player_moves.enemy_move.convert_to_string().italic()
35        );
36
37
38        match round_winner {
39            Winner::Tie => {
40                println!("{}", "It's a tie!".blue());
41                round_counter -= 1;
42            },
43            Winner::User => {
44                println!("{}", "You win!".green());
45                scores.user_wins += 1;
46            },
47            Winner::Enemy => {
48                println!("{}", "Enemy wins!".red());
49                scores.enemy_wins += 1;
50            }
51        }
52
53        // print scores
54        println!("{}", "[Scores]".magenta().bold());
55        println!("{}{}", "User: ".magenta(), scores.user_wins.to_string().magenta());
56        println!("{}{}", "Enemy: ".magenta(), scores.enemy_wins.to_string().magenta());
57    }
58
59
60    if scores.check_for_winner(&game_settings) == Ok(Winner::User) {
61        println!("{}", "You won the game!".green());
62    } else {
63        println!("{}", "You lost the game!".red());
64    }
65
66}
Source

pub fn from_user_input() -> Result<MoveType, String>

§Gets the User’s Move

Handles user input from the console, validates it, and converts it into a MoveType.

The user is prompted to enter a number corresponding to their move:

  • 1 for Rock
  • 2 for Paper
  • 3 for Scissors

The function will ensure valid input by repeatedly asking for input until a valid value is provided.

§Examples
use rock_paper_scissors::MoveType;

println!("Enter your move: (1 = Rock, 2 = Paper, 3 = Scissors)");
let user_move = MoveType::from_user_input();

assert!(matches!(user_move, Ok(MoveType::Rock) | Ok(MoveType::Paper) | Ok(MoveType::Scissors)));
§Behavior

When the user provides invalid input (e.g., letters or numbers outside the valid range), the function will re-prompt for valid input until it is received

Trait Implementations§

Source§

impl Debug for MoveType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for MoveType

Source§

fn eq(&self, other: &MoveType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for MoveType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V