4
|
1 |
/*** Deck ****/ |
|
2 |
use std::collections::VecDeque; |
|
3 |
|
|
4 |
use rand::Rng; |
|
5 |
|
|
6 |
use crate::card::Card; |
|
7 |
|
|
8 |
#[derive(Debug)] |
|
9 |
pub(crate) struct Deck { |
|
10 |
content: VecDeque<Card>, |
|
11 |
} |
|
12 |
|
|
13 |
impl Deck { |
|
14 |
/// Creates an empty [`Deck`] of undefined size |
|
15 |
pub(crate) fn new_empty() -> Self { |
|
16 |
debug!("Empty deck generated"); |
|
17 |
Deck { |
|
18 |
content: VecDeque::new(), |
|
19 |
} |
|
20 |
} |
|
21 |
|
|
22 |
/// Creates a new full [`Deck`] with 104 cards. |
|
23 |
pub(crate) fn new() -> Self { |
|
24 |
debug!("Full deck generated"); |
|
25 |
let content = (1..=104).into_iter().map( |n| Card::new(n) ).collect(); |
|
26 |
Deck { |
|
27 |
content, |
|
28 |
} |
|
29 |
} |
|
30 |
|
|
31 |
/// Shuffles this [`Deck`] (using its default method) |
|
32 |
pub(crate) fn shuffle( &mut self ) { |
|
33 |
let mut rng = rand::thread_rng(); |
|
34 |
|
|
35 |
trace!("Deck before shuffle: len {}, {:?}", self.content.len(), self); |
|
36 |
debug!("Deck shuffled"); |
|
37 |
// shufflers: |
|
38 |
// * naive: swap cards n times |
|
39 |
// * kgb: half the deck, take 1..4 cards sequentially from each |
|
40 |
// * grin: take 1..6 from front and put at bottom |
|
41 |
|
|
42 |
// naive shuffle: exchange random cards |
|
43 |
for _i in 1..=500 { |
|
44 |
let c1 = rng.gen_range(0 .. self.content.len()); |
|
45 |
let c2 = rng.gen_range(0 .. self.content.len()); |
|
46 |
if c1 != c2 { |
|
47 |
self.content.swap(c1, c2); |
|
48 |
} |
|
49 |
} |
|
50 |
trace!("Deck after shuffle: len {}, {:?}", self.content.len(), self); |
|
51 |
} |
|
52 |
|
|
53 |
/// Returns the top card of this [`Deck`]. |
|
54 |
pub(crate) fn pop( &mut self ) -> Option<Card> { |
|
55 |
self.content.pop_front() |
|
56 |
} |
|
57 |
|
|
58 |
/// Put a card into the bottom of the [`Deck`] |
|
59 |
pub(crate) fn push( &mut self, c: Card ) { |
|
60 |
self.content.push_back(c); |
|
61 |
} |
|
62 |
|
|
63 |
/// Push multiple cards to the bottom of the [`Deck`] |
|
64 |
pub(crate) fn push_cards( &mut self, cards: VecDeque<Card> ) { |
|
65 |
trace!("Collecting back, deck len is {}, cards {}", self.content.len(), cards.len()); |
|
66 |
cards.into_iter().for_each( |card| self.push(card) ); |
|
67 |
trace!("Deck len is {}", self.content.len()); |
|
68 |
} |
|
69 |
|
|
70 |
/// Returns the length of this [`Deck`]. |
|
71 |
pub(crate) fn len( &self ) -> usize { |
|
72 |
self.content.len() |
|
73 |
} |
|
74 |
|
|
75 |
fn _get_nth( &mut self, n: usize ) -> Card { |
|
76 |
if let Some(c) = self.content.remove(n) { |
|
77 |
c |
|
78 |
} else { |
|
79 |
panic!("get_nth: index {} out of bounds ({})!", n, self.content.len()); |
|
80 |
} |
|
81 |
} |
|
82 |
} |