RustDeck

mail@pastecode.io avatar
unknown
rust
a year ago
1.9 kB
2
Indexable
Never
use std::fmt;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use rand::seq::SliceRandom;

#[derive(Debug, EnumIter, Clone, Copy)]
enum Face {
    Hearts,
    Diamonds,
    Clubs,
    Spades,
}

impl fmt::Display for Face {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[derive(Debug, EnumIter, Clone, Copy)]
enum Suit {
    Ace,
    Due,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
}

impl fmt::Display for Suit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[derive(Debug)]
struct Card {
    face: Face,
    suit: Suit,
}

impl Card {
    pub fn new(f: Face, s: Suit) -> Card {
        Card { face: f, suit: s }
    }
}

impl fmt::Display for Card {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{}", self.face, self.suit)
    }
}

struct Deck {
    list: Vec<Card>,
}

impl Deck {
    fn new() -> Deck {
        let mut list = Vec::new();
        for f in Face::iter() {
            for s in Suit::iter() {
                list.push(Card::new(f, s))
            }
        }

        Deck { list: list }
    }

    fn shuffle(&mut self) {
        let mut rng = rand::thread_rng();
        self.list.shuffle(&mut rng);
    }

    fn draw(&mut self) -> Card {
        if !self.list.is_empty() {
            return self.list.remove(0);
        }
        panic!("No Cards in Deck")
    }
}

fn main() {
    let mut d = Deck::new();
    d.shuffle();
    for i in 0..d.list.len() {
        if i != 0 && (i + 1) % 5 == 0 {
            println!("{}\n", d.draw());
        } else {
            println!("{}", d.draw());
        }
    }
}