fudd 0.1.9

Fun with poker. Named after that most famous of rabbit hunters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
use crate::types::arrays::Vectorable;
use crate::types::playing_card::PlayingCard;
use crate::types::playing_cards::PlayingCards;
use crate::types::poker_deck::PokerDeck;
use crate::types::U32Card;
use cardpack::{Pile, Standard52};
use ckc_rs::cards::two::Two;
use ckc_rs::{CKCNumber, CardNumber, CardRank, HandError, PokerCard};
use rand::seq::SliceRandom;
use rand::thread_rng;
use std::fmt;

pub const POSSIBLE_COMBINATIONS: usize = 7937;

#[derive(Clone, Debug, Hash, PartialEq)]
pub struct PokerCards(Vec<U32Card>);

impl PokerCards {
    #[must_use]
    pub fn deck() -> PokerCards {
        PokerDeck::poker_cards()
    }

    /// # Errors
    ///
    /// Will return `CardError::InvalidCard` for an invalid index.
    #[must_use]
    pub fn from_index(index: &'static str) -> Result<PokerCards, HandError> {
        let mut cards = PokerCards::default();

        for s in index.split_whitespace() {
            let card = CKCNumber::from_index(s);
            if card.is_blank() {
                return Err(HandError::InvalidCard);
            }
            cards.push(card);
        }
        Ok(cards)
    }

    /// # Errors
    ///
    /// Will return `CardError::InvalidCard` for an invalid index.
    #[must_use]
    #[allow(clippy::needless_pass_by_value)]
    pub fn from_index_string(index: String) -> Result<PokerCards, HandError> {
        let mut cards = PokerCards::default();

        for s in index.split_whitespace() {
            let card = CKCNumber::from_index(s);
            if card.is_blank() {
                return Err(HandError::InvalidCard);
            }
            cards.push(card);
        }
        Ok(cards)
    }

    /// Appends a clone of the passed in collection of `PokerCards` to the existing one.
    pub fn append(&mut self, other: &PokerCards) {
        self.0.append(&mut other.0.clone());
    }

    #[must_use]
    pub fn combine(self, other: &PokerCards) -> PokerCards {
        let mut r = self;
        r.append(&other.filter_blank());
        r
    }

    #[must_use]
    pub fn contains(&self, card: &U32Card) -> bool {
        self.0.contains(card)
    }

    #[must_use]
    pub fn deal(&mut self, number: usize) -> PokerCards {
        if self.len() >= number {
            let v: Vec<U32Card> = self.0.drain(0..number).collect();
            PokerCards(v)
        } else {
            PokerCards::default()
        }
    }

    /// # Panics
    ///
    /// Will panic if there aren't five cards available in the passed in `Standard52`
    /// deck.
    ///
    /// TODO: Improve me
    #[must_use]
    pub fn deal_from_standard52(standard52: &mut Standard52, number: usize) -> PokerCards {
        let pile = standard52.draw(number).unwrap();
        let mut cards = PokerCards::default();
        for card in pile {
            cards.push(PlayingCard::from(&card).as_u32());
        }
        cards
    }

    #[must_use]
    pub fn deal_from_the_bottom(&mut self, num: usize) -> PokerCards {
        let mut dealt = PokerCards::default();
        for _ in 0..num {
            let popped = self.pop();
            if let Some(card) = popped {
                dealt.push(card);
            }
        }
        dealt.0.reverse();
        dealt
    }

    #[must_use]
    pub fn divisible_by(&self, x: usize) -> bool {
        (self.len() % x) == 0
    }

    #[must_use]
    pub fn filter_blank(&self) -> PokerCards {
        PokerCards::from(
            self.0
                .clone()
                .into_iter()
                .filter(|c| *c != CardNumber::BLANK)
                .collect::<Vec<U32Card>>(),
        )
    }

    #[must_use]
    pub fn filter_eqgt_on_rank(&self, rank: CardRank) -> PokerCards {
        PokerCards::from(
            self.0
                .clone()
                .into_iter()
                .filter(|c| c.get_card_rank() as u8 >= rank as u8)
                .collect::<Vec<U32Card>>(),
        )
    }

    #[must_use]
    pub fn get(&self, index: usize) -> Option<&U32Card> {
        self.0.get(index)
    }

    #[must_use]
    pub fn is_complete_hand(&self) -> bool {
        self.len() == 5
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.len() == PlayingCards::from(self).len()
    }

    pub fn iter(&self) -> impl Iterator<Item = &U32Card> {
        self.0.iter()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn pop(&mut self) -> Option<U32Card> {
        self.0.pop()
    }

    /// Returns a vector of all the prime bits of the CKC.
    #[must_use]
    pub fn primes(&self) -> Vec<u32> {
        let mut v: Vec<u32> = Vec::new();
        for c in self.iter() {
            v.push(c & 0xff);
        }
        v
    }

    pub fn pull(&mut self) -> U32Card {
        if self.is_empty() {
            return CardNumber::BLANK;
        }
        self.0.remove(0)
    }

    /// Appends an `PokerCard` to the back of a collection..
    pub fn push(&mut self, ckc: U32Card) {
        self.0.push(ckc);
    }

    #[must_use]
    pub fn shuffle(&self) -> PokerCards {
        let mut shuffled = self.clone();
        shuffled.shuffle_in_place();
        shuffled
    }

    pub fn shuffle_in_place(&mut self) {
        self.0.shuffle(&mut thread_rng());
    }

    #[must_use]
    pub fn sort(&self) -> PokerCards {
        let mut cards = self.clone();
        cards.sort_in_place();
        cards
    }

    pub fn sort_in_place(&mut self) {
        self.0.sort_unstable();
        self.0.reverse();
    }

    /// Converts a `PokerCards` collection to a `cardpack::Pile` collection
    /// of `cardpack::Card` entities.
    #[must_use]
    pub fn to_pile(&self) -> Pile {
        let mut pile = Pile::default();

        for card in &self.0 {
            pile.push(PlayingCard::from(*card).as_card());
        }

        pile
    }

    /// # Errors
    ///
    /// Will return `CardError::InvalidCardCount` for an invalid index.
    #[must_use]
    pub fn try_into_twos(&self) -> Result<Vec<Two>, HandError> {
        if !self.divisible_by(2) {
            return Err(HandError::InvalidCardCount);
        }
        let mut v: Vec<Two> = Vec::new();
        let mut cards = self.clone();
        loop {
            let c1 = cards.pull();
            if c1.is_blank() {
                break;
            }
            v.push(Two::new(c1, cards.pull()));
        }
        Ok(v)
    }
}

impl Default for PokerCards {
    fn default() -> Self {
        PokerCards::from(Vec::new())
    }
}

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

impl From<Pile> for PokerCards {
    fn from(value: Pile) -> Self {
        let mut pcks = PokerCards::default();
        for card in value {
            pcks.push(PlayingCard::from(&card).as_u32());
        }
        pcks
    }
}

impl From<&PlayingCards> for PokerCards {
    fn from(cards: &PlayingCards) -> Self {
        PokerCards(cards.iter().map(PlayingCard::as_u32).collect())
    }
}

impl From<Vec<U32Card>> for PokerCards {
    fn from(value: Vec<U32Card>) -> Self {
        PokerCards(value)
    }
}

impl TryFrom<&'static str> for PokerCards {
    type Error = HandError;

    /// # Errors
    ///
    /// Will return `CardError::InvalidCard` for an invalid index.
    #[allow(clippy::missing_panics_doc)]
    fn try_from(value: &'static str) -> Result<Self, Self::Error> {
        PokerCards::from_index(value)
    }
}

impl TryFrom<String> for PokerCards {
    type Error = HandError;

    /// # Errors
    ///
    /// Will return `CardError::InvalidCard` for an invalid index.
    #[allow(clippy::missing_panics_doc)]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        PokerCards::from_index_string(value)
    }
}

impl Vectorable for PokerCards {
    #[must_use]
    fn to_vec(&self) -> Vec<U32Card> {
        self.0.clone()
    }
}

#[cfg(test)]
#[allow(non_snake_case)]
mod poker_cards_tests {
    use super::*;
    use crate::types::poker_deck::PokerDeck;

    #[test]
    fn append() {
        let standard52 = &mut Standard52::new_shuffled();
        let hole_cards = PokerCards::deal_from_standard52(standard52, 2);
        let flop = PokerCards::deal_from_standard52(standard52, 3);

        let mut five_cards = hole_cards.clone();
        five_cards.append(&flop);

        assert_eq!(
            format!("{}", five_cards),
            format!("{} {}", hole_cards, flop)
        );
    }

    #[test]
    fn combine() {
        let standard52 = &mut Standard52::new_shuffled();
        let hole_cards = PokerCards::deal_from_standard52(standard52, 2);
        let flop = PokerCards::deal_from_standard52(standard52, 3);

        let five_cards = hole_cards.clone().combine(&flop);

        assert_eq!(
            format!("{}", five_cards),
            format!("{} {}", hole_cards, flop)
        );
    }

    #[test]
    fn contains() {
        let poker_cards = PokerCards::try_from("AS KS").unwrap();

        assert!(poker_cards.contains(&CardNumber::ACE_SPADES));
        assert!(poker_cards.contains(&CardNumber::KING_SPADES));
        assert!(!poker_cards.contains(&CardNumber::QUEEN_SPADES));
    }

    #[test]
    fn deal() {
        let mut deck = PokerDeck::poker_cards_shuffled();
        let hand1 = deck.deal(5);
        let hand2 = deck.deal(5);

        assert_eq!(deck.len(), 42);
        assert_eq!(hand1.len(), 5);
        assert_eq!(hand2.len(), 5);
    }

    #[test]
    fn deal_overflow() {
        let mut deck = PokerDeck::poker_cards_shuffled();
        let hand1 = deck.deal(25);
        let hand2 = deck.deal(25);
        let hand3 = deck.deal(3);

        assert_eq!(deck.len(), 2);
        assert_eq!(hand1.len(), 25);
        assert_eq!(hand2.len(), 25);
        assert!(hand3.is_empty());
    }

    #[test]
    fn filter_blank() {
        let mut poker_cards = PokerCards::try_from("AS KS").unwrap();
        poker_cards.push(CardNumber::BLANK);
        poker_cards.push(CardNumber::BLANK);
        poker_cards.push(CardNumber::TEN_SPADES);

        assert_eq!(poker_cards.len(), 5);
        assert_eq!("A♠ K♠ T♠", poker_cards.filter_blank().to_string());
        assert_eq!("A♠ K♠ __ __ T♠", poker_cards.to_string());
    }

    #[test]
    fn filter_gt_on_rank() {
        let deck = PokerCards::deck();

        let filtered = deck.filter_eqgt_on_rank(CardRank::KING);

        assert_eq!(filtered.len(), 8);
        // for card in filtered.iter() {
        //     println!("{}", card.to_string());
        // }
    }

    #[test]
    fn deal_from_the_bottom() {
        let mut hand = PokerCards::try_from("A♠ A♠ Q♠ J♠ T♠").unwrap();

        let dealt = hand.deal_from_the_bottom(3);

        assert_eq!("Q♠ J♠ T♠", dealt.to_string());
        assert_eq!("A♠ A♠", hand.to_string());
    }

    #[test]
    fn deal_from_the_bottom__some() {
        let mut hand = PokerCards::try_from("J♠ T♠").unwrap();

        let dealt = hand.deal_from_the_bottom(3);

        assert_eq!(dealt.len(), 2);
        assert_eq!("J♠ T♠", dealt.to_string());
        assert!(hand.is_empty());
    }

    #[test]
    fn deal_from_the_bottom__none() {
        let mut hand = PokerCards::default();

        let dealt = hand.deal_from_the_bottom(3);

        assert_eq!(dealt, hand);
        assert!(dealt.is_empty());
    }

    #[test]
    fn is_valid() {
        assert!(PokerCards::try_from("  A♠ Q♠   J♠    T♠ ")
            .unwrap()
            .is_valid());
        assert!(!PokerCards::try_from("A♠ A♠ Q♠ J♠ T♠").unwrap().is_valid());
    }

    #[test]
    fn pop() {
        let mut hand = PokerCards::try_from("A♠ A♠ Q♠ J♠ T♠").unwrap();

        let last = hand.pop().unwrap();

        assert_eq!(last, CardNumber::TEN_SPADES);
        assert_eq!("A♠ A♠ Q♠ J♠", hand.to_string());
    }

    #[test]
    fn pop__empty() {
        let mut hand = PokerCards::default();

        let last = hand.pop();

        assert!(last.is_none());
    }

    #[test]
    #[ignore]
    fn sort() {
        let hand = PokerCards::try_from("KC AD KH KD AS").unwrap();
        let sorted = hand.sort();
        println!("{}", sorted);

        let hand = PokerCards::try_from("KC AD KH KD AS").unwrap();
        let sorted = hand.sort();
        println!("{}", sorted);
    }

    #[test]
    fn try_into_twos() {
        let two = vec![
            Two::try_from("J♠ T♠").unwrap(),
            Two::try_from("A♠ K♠").unwrap(),
        ];

        let cards = PokerCards::try_from("JS TS AS KS")
            .unwrap()
            .try_into_twos()
            .unwrap();

        assert_eq!(two, cards);
    }

    #[test]
    fn try_into_twos__not_divisible_into_two() {
        let cards = PokerCards::try_from("KC AD KH KD AS")
            .unwrap()
            .try_into_twos();

        assert!(cards.is_err());
    }

    #[test]
    fn try_from__index_str() {
        assert_eq!(
            "K♣ A♦ K♥ K♦ A♠",
            PokerCards::try_from("KC AD KH KD AS").unwrap().to_string()
        );
    }

    #[test]
    fn try_from__index_str__invalid() {
        let cards = PokerCards::try_from("KX AD KH KD AS");
        assert!(cards.is_err());
        assert_eq!(HandError::InvalidCard, cards.unwrap_err());
    }
}