use crate::core::card::Card;
use crate::core::deck::Deck;
use std::ops::{Index, Range, RangeFrom, RangeFull, RangeTo};
extern crate rand;
use rand::seq::*;
use rand::thread_rng;
#[derive(Debug)]
pub struct FlatDeck {
cards: Vec<Card>,
}
impl FlatDeck {
pub fn len(&self) -> usize {
self.cards.len()
}
pub fn is_empty(&self) -> bool {
self.cards.is_empty()
}
pub fn sample(&self, n: usize) -> Vec<Card> {
let mut rng = thread_rng();
self.cards.choose_multiple(&mut rng, n).cloned().collect()
}
pub fn shuffle(&mut self) {
let mut rng = thread_rng();
self.cards.shuffle(&mut rng)
}
pub fn deal(&mut self) -> Option<Card> {
self.cards.pop()
}
}
impl Index<usize> for FlatDeck {
type Output = Card;
fn index(&self, index: usize) -> &Card {
&self.cards[index]
}
}
impl Index<Range<usize>> for FlatDeck {
type Output = [Card];
fn index(&self, index: Range<usize>) -> &[Card] {
&self.cards[index]
}
}
impl Index<RangeTo<usize>> for FlatDeck {
type Output = [Card];
fn index(&self, index: RangeTo<usize>) -> &[Card] {
&self.cards[index]
}
}
impl Index<RangeFrom<usize>> for FlatDeck {
type Output = [Card];
fn index(&self, index: RangeFrom<usize>) -> &[Card] {
&self.cards[index]
}
}
impl Index<RangeFull> for FlatDeck {
type Output = [Card];
fn index(&self, index: RangeFull) -> &[Card] {
&self.cards[index]
}
}
impl From<Vec<Card>> for FlatDeck {
fn from(value: Vec<Card>) -> Self {
Self { cards: value }
}
}
impl From<Deck> for FlatDeck {
fn from(value: Deck) -> Self {
Self {
cards: value.into_iter().collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::card::{Suit, Value};
#[test]
fn test_deck_from() {
let fd: FlatDeck = Deck::default().into();
assert_eq!(52, fd.len());
}
#[test]
fn test_from_vec() {
let c = Card {
value: Value::Nine,
suit: Suit::Heart,
};
let v = vec![c];
let mut flat_deck: FlatDeck = v.into();
assert_eq!(1, flat_deck.len());
assert_eq!(c, flat_deck.deal().unwrap());
}
}