Learn about structs, implimentations

This commit is contained in:
Dylan Smith
2024-03-22 12:02:37 -04:00
commit 5398e2b443
4 changed files with 166 additions and 0 deletions

81
src/main.rs Normal file
View File

@@ -0,0 +1,81 @@
use rand::Rng;
use std::fmt;
use std::vec;
#[derive(Clone, Copy)]
enum CardSuit {
Diamonds,
Clubs,
Hearts,
Spades,
}
struct PlayingCard {
value: u8,
suit: CardSuit,
}
impl fmt::Display for PlayingCard {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let val = match self.value {
2 => "Two",
3 => "Three",
4 => "Four",
5 => "Five",
6 => "Six",
7 => "Seven",
8 => "Eight",
9 => "Nine",
10 => "Ten",
11 => "Jack",
12 => "King",
13 => "Queen",
14 => "Ace",
_ => "???",
};
let suit = match self.suit {
CardSuit::Clubs => "Clubs",
CardSuit::Diamonds => "Diamonds",
CardSuit::Hearts => "Hearts",
CardSuit::Spades => "Spades",
};
write!(f, "{} of {}", val, suit)
}
}
fn draw_card(deck: &mut Vec<PlayingCard>) -> PlayingCard {
let num = rand::thread_rng().gen_range(0..deck.len());
let card = deck.remove(num);
card
}
fn create_deck() -> Vec<PlayingCard> {
let mut deck: Vec<PlayingCard> = vec![];
for s in [
CardSuit::Diamonds,
CardSuit::Clubs,
CardSuit::Hearts,
CardSuit::Spades,
] {
for i in 2..14 {
let card = PlayingCard { suit: s, value: i };
deck.insert(0, card);
}
}
deck
}
fn main() {
let mut deck = create_deck();
let card1 = draw_card(&mut deck);
let card2 = draw_card(&mut deck);
println!("Card 1: {}", card1);
println!("Card 2: {}", card2);
}