1use cards::Card;
2use cards::Suit::*;
3use cards::Value::*;
4use rand::{thread_rng, Rng};
5use std::ops::Deref;
6use std::slice::{Iter, IterMut};
7use std::vec::IntoIter;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Deck {
11 cards: Vec<Card>,
12}
13
14impl Default for Deck {
15 fn default() -> Self {
16 let mut deck = Self::new();
17 deck.shuffle();
18 deck
19 }
20}
21
22impl Into<Vec<Card>> for Deck {
23 fn into(self) -> Vec<Card> {
24 self.cards
25 }
26}
27
28impl Deck {
29 pub fn new() -> Deck {
32 let mut cards: Vec<Card> = Vec::with_capacity(52);
33 let suits = [Hearts, Spades, Diamonds, Clubs];
34 let values = [
35 Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King,
36 ];
37 for &suit in &suits {
38 for &value in &values {
39 let card = Card { suit, value };
40 cards.push(card);
41 }
42 }
43 Deck { cards }
44 }
45
46 pub fn new_empty() -> Deck {
48 let cards: Vec<Card> = Vec::with_capacity(52);
49 Deck { cards }
50 }
51
52 pub fn clear(&mut self) {
54 self.cards.clear();
55 }
56
57 pub fn len(&self) -> usize {
59 self.cards.len()
60 }
61
62 pub fn is_empty(&self) -> bool {
64 self.cards.is_empty()
65 }
66
67 pub fn show(&self, idx: usize) -> Option<&Card> {
69 self.cards.get(idx)
70 }
71
72 pub fn add(&mut self, card: Card) {
74 self.cards.push(card);
75 }
76
77 pub fn add_bottom(&mut self, card: Card) {
79 self.cards.insert(0, card);
80 }
81
82 pub fn add_deck(&mut self, deck: &mut Deck) {
84 while !deck.is_empty() {
85 self.cards.push(deck.draw().unwrap());
86 }
87 }
88
89 pub fn draw(&mut self) -> Option<Card> {
91 match self.cards.len() {
92 0 => None,
93 _ => Some(self.cards.remove(0)),
94 }
95 }
96
97 pub fn draw_bottom(&mut self) -> Option<Card> {
99 match self.cards.len() {
100 0 => None,
101 _x => Some(self.cards.remove(_x - 1)),
102 }
103 }
104
105 pub fn shuffle(&mut self) {
107 let mut rng = thread_rng();
108 rng.shuffle(&mut self.cards);
109 }
110
111 pub fn drain_into(&mut self, deck: &mut Deck) {
113 deck.add_deck(self);
114 }
115}
116
117impl IntoIterator for Deck {
118 type Item = Card;
119 type IntoIter = IntoIter<Card>;
120
121 fn into_iter(self) -> Self::IntoIter {
122 self.cards.into_iter()
123 }
124}
125
126impl<'a> IntoIterator for &'a Deck {
127 type Item = &'a Card;
128 type IntoIter = Iter<'a, Card>;
129
130 fn into_iter(self) -> Self::IntoIter {
131 self.cards.iter()
132 }
133}
134
135impl<'a> IntoIterator for &'a mut Deck {
136 type Item = &'a mut Card;
137 type IntoIter = IterMut<'a, Card>;
138
139 fn into_iter(self) -> Self::IntoIter {
140 self.cards.iter_mut()
141 }
142}
143
144impl Deref for Deck {
145 type Target = [Card];
146
147 fn deref(&self) -> &Self::Target {
148 &self.cards
149 }
150}