cardpack 0.6.11

Generic Deck of Cards
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
use crate::basic::decks::cards::french::FLUENT_KEY_BASE_NAME_FRENCH;
use crate::basic::types::basic_card::BasicCard;
pub use crate::basic::types::basic_pile::BasicPile;
pub use crate::basic::types::card::Card;
use crate::basic::types::combos::Combos;
pub use crate::basic::types::pile::Pile;
use crate::basic::types::pips::Pip;
use crate::prelude::PipType;
use itertools::Itertools;
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::str::FromStr;

pub trait DeckedBase {
    /// And just like that we have a `Pile`.
    #[must_use]
    fn basic_pile() -> BasicPile {
        BasicPile::from(Self::base_vec())
    }

    #[must_use]
    fn basic_pile_cell() -> Cell<BasicPile> {
        Cell::from(BasicPile::from(Self::base_vec()))
    }

    fn base_vec() -> Vec<BasicCard>;

    fn colors() -> HashMap<Pip, colored::Color>;

    fn deck_name() -> String;

    /// Use this to override the fluent keys iside the ftl files
    #[must_use]
    fn fluent_name_base() -> String {
        FLUENT_KEY_BASE_NAME_FRENCH.to_string()
    }

    fn fluent_deck_key() -> String;
}

pub trait Decked<DeckType>: DeckedBase
where
    DeckType: Copy + Default + Ord + DeckedBase + Hash,
{
    /// The method to generate a deck of cards based on specific type parameters.
    ///
    /// ```
    /// use cardpack::prelude::*;
    ///
    /// // Each deck can be evoked in two ways:
    /// let deck_from_type_parameter: Pile<Pinochle> = Pinochle::deck();
    /// let deck_from_generic_pile = Pile::<Pinochle>::deck();
    ///
    /// assert_eq!(deck_from_type_parameter, deck_from_generic_pile);
    /// assert_eq!(
    ///     deck_from_type_parameter.to_string(),
    ///     "A♠ A♠ T♠ T♠ K♠ K♠ Q♠ Q♠ J♠ J♠ 9♠ 9♠ A♥ A♥ T♥ T♥ K♥ K♥ Q♥ Q♥ J♥ J♥ 9♥ 9♥ A♦ A♦ T♦ T♦ K♦ K♦ Q♦ Q♦ J♦ J♦ 9♦ 9♦ A♣ A♣ T♣ T♣ K♣ K♣ Q♣ Q♣ J♣ J♣ 9♣ 9♣"
    /// );
    /// ```
    #[must_use]
    fn deck() -> Pile<DeckType> {
        Pile::<DeckType>::from(Self::deckvec())
    }

    /// Creates x numbers of a specific `Deck` in a single [`Pile`].
    ///
    /// ```
    /// use cardpack::prelude::*;
    ///
    /// let twodecks = Pile::<Standard52>::decks(2);
    ///
    /// assert_eq!(twodecks.len(), 104);
    ///
    /// // Converting it into a `HashSet` will verify that there are only 52 unique cards.
    /// assert_eq!(twodecks.into_hashset().len(), 52);
    /// ```
    ///
    /// This way of doing it from `CoPilot` is an interesting alternative to
    /// my old `pile_up` method:
    ///
    /// ```txt
    /// fn decks(n: usize) -> Pile<RankType, SuitType> {
    ///     Pile::<RankType, SuitType>::pile_up(n, <Self as Decked<RankType, SuitType>>::deck)
    /// }
    /// ```
    #[must_use]
    fn decks(count: usize) -> Pile<DeckType> {
        Pile::<DeckType>::from(Self::deckvec().repeat(count))
    }

    /// Takes the [`BasicCard`] vector for the type parameter and converts it into a vector
    /// of [`Card`]s for the type parameter. This is where the work is done channeling between
    /// the plain and generic enabled versions of the structs.
    #[must_use]
    fn deckvec() -> Vec<Card<DeckType>> {
        let v = Card::<DeckType>::base_vec();
        v.iter().map(|card| Card::<DeckType>::from(*card)).collect()
    }

    /// Used in the `examples/cli.rs` application for showing off the various decks.
    fn demo(verbose: bool) {
        Self::deck().demo_cards(verbose);
    }

    /// Warning on original version of the code.
    /// TODO: I need to understand slices better.
    ///
    /// ```txt
    /// warning: writing `&Vec` instead of `&[_]` involves a new object where a slice will do
    ///   --> src/rev6/traits.rs:22:31
    ///    |
    /// 22 |     fn into_cards(base_cards: &Vec<BaseCard>) -> Vec<Card<DeckType>> {
    ///    |                               ^^^^^^^^^^^^^^ help: change this to: `&[BaseCard]`
    /// ```
    #[must_use]
    fn into_cards(base_cards: &[BasicCard]) -> Vec<Card<DeckType>> {
        base_cards
            .iter()
            .map(|card| Card::<DeckType>::from(*card))
            .collect()
    }

    /// This is the urtest for a deck. If you can do this, you are golden.
    #[must_use]
    fn validate() -> bool {
        let deck = Self::deck();
        Pile::<DeckType>::from_str(&deck.to_string()).is_ok_and(|deckfromstr| {
            deck == deck.clone().shuffled().sorted() && deck == deckfromstr
        })
    }
}

/// Trait of convenience to organize what needs to be done in order to create a revised
/// [Cactus Kev](https://suffe.cool/poker/evaluator.html) number.
///
/// I like having functional blocks
/// like this organized in a functional way. Traits feel like a good way to do it.
pub trait CKCRevised {
    #[must_use]
    fn get_ckc_number(&self) -> usize;

    #[must_use]
    fn ckc_rank_number(&self) -> usize;

    #[must_use]
    fn ckc_suit_number(&self) -> usize;

    #[must_use]
    fn ckc_rank_bits(&self) -> usize;

    #[must_use]
    fn ckc_get_prime(&self) -> usize;

    #[must_use]
    fn ckc_rank_shift8(&self) -> usize;
}

/// Proof of concept for how easy it would be to lay a foundation for creating
/// a [GTO (Game Theory Optimal)](https://www.888poker.com/magazine/strategy/beginners-guide-gto-poker)
/// style poker solver.
///
/// A foundation to that is around what they call poker ranges. Where, instead
/// of trying to figure out exactly what hand an opponent has, you base your moves on what you
/// believe is the range of hands that they player could have given their particular style.
pub trait Ranged {
    /// This is the starting point for any entity enabling the `Ranged` trait. Since none of the
    /// logic behind any of these methods requires the boundary provided by the generic [`Pile`] struct,
    /// since it is based entirely on the raw data in the collection of [`BasicCard`]s in a
    /// [`BasicPile`]. [`Pile`] is very useful for getting us to where we want to be, re a specific
    /// collection of cards, but once there we can rid ourselves of its confinements and focus on
    /// data.
    ///
    /// This started out passing a reference, but that didn't work when trying to implement it
    /// with Pile, because the reference vanishes at the end of the call.
    fn my_basic_pile(&self) -> BasicPile;

    fn combos(&self, k: usize) -> Combos {
        let mut hs: HashSet<BasicPile> = HashSet::new();

        for combo in self.my_basic_pile().into_iter().combinations(k) {
            let pile = BasicPile::from(combo).sorted_by_rank();
            hs.insert(pile);
        }

        let mut combos = hs.into_iter().collect::<Vec<_>>();

        combos.sort();
        Combos::from(combos)
    }

    fn combos_with_dups(&self, k: usize) -> Combos {
        let mut combos = Combos::default();

        for combo in self.my_basic_pile().into_iter().combinations(k) {
            let pile = BasicPile::from(combo).sorted_by_rank();
            combos.push(pile);
        }

        combos.sort();
        combos.reverse();
        combos
    }

    fn all_of_rank(&self, rank: Pip) -> bool {
        self.my_basic_pile().iter().all(|card| card.rank == rank)
    }

    fn all_of_same_rank(&self) -> bool {
        self.my_basic_pile().v().first().is_none_or(|first_card| {
            self.my_basic_pile()
                .iter()
                .all(|card| card.rank == first_card.rank)
        })
    }

    fn all_of_same_suit(&self) -> bool {
        self.my_basic_pile().v().first().is_none_or(|first_card| {
            self.my_basic_pile()
                .iter()
                .all(|card| card.suit == first_card.suit)
        })
    }

    /// I love how `CoPilot` can have the earlier version of the function from Pile and
    /// completely ignore it and instead provide stuff with absolutely no rational:
    ///
    /// ```txt
    /// pub fn is_connector(&self) -> bool {
    ///     if self.len() < 3 {
    ///         return false;
    ///     }
    ///
    ///     let mut cards = self.0.clone();
    ///     cards.sort();
    ///
    ///     for i in 1..cards.len() {
    ///         if cards[i].rank as i32 - cards[i - 1].rank as i32 != 1 {
    ///             return false;
    ///         }
    ///     }
    ///
    ///     true
    /// }
    /// ```
    ///
    /// I mean, why 3 for length? I don't even want to try to figure out why this code is.
    ///
    /// OK, the `core::slice::windows()` function is officially cool.
    fn is_connector(&self) -> bool {
        let mut pile = self.my_basic_pile();
        pile.sort_by_rank();
        pile.v()
            .windows(2)
            .all(|w| w[0].rank.weight == w[1].rank.weight + 1)
    }

    fn of_same_or_greater_rank(&self, rank: Pip) -> bool {
        self.my_basic_pile().iter().all(|card| card.rank >= rank)
    }

    //\\//\\//\\//\\
    // Pips
    #[must_use]
    fn filter_cards<F>(&self, filter: F) -> BasicPile
    where
        F: Fn(&BasicCard) -> bool,
    {
        self.my_basic_pile()
            .iter()
            .filter(|&card| filter(card))
            .copied()
            .collect()
    }

    /// Returns a [`BasicPile`] filtering on rank [`PipType`].
    ///
    /// TODO: Mark this as an example of the abstraction pushing the limits.
    ///
    /// This example verifies that there are two `Jokers` in the
    /// [`French`](crate::basic::decks::french::French) [`Pile`]
    ///
    /// ```
    /// use cardpack::prelude::*;
    ///
    /// let mut deck = French::deck();
    ///
    /// assert_eq!(deck.cards_of_rank_pip_type(PipType::Joker).len(), 2);
    /// ```
    ///
    /// Here's the original code before being refactored into using the `filter_cards` closure,
    ///
    /// ```txt
    /// #[must_use]
    /// pub fn cards_of_rank_pip_type(&self, pip_type: PipType) -> Self {
    ///     self.iter()
    ///         .filter(|card| card.rank.pip_type == pip_type)
    ///         .cloned()
    ///         .collect()
    /// }
    /// ```
    #[must_use]
    fn cards_of_rank_pip_type(&self, pip_type: PipType) -> BasicPile {
        let rank_types_filter = |basic_card: &BasicCard| basic_card.rank.pip_type == pip_type;
        self.filter_cards(rank_types_filter)
    }

    /// Returns a [`BasicPile`] filtering on suit [`PipType`].
    ///
    /// This example verifies how many `Special` (`Major Arcana`) cards are in the
    /// [`Tarot`](crate::basic::decks::tarot::Tarot) deck.
    ///
    /// ```
    /// use cardpack::prelude::*;
    ///
    /// let mut deck = Tarot::deck();
    ///
    /// assert_eq!(deck.cards_of_suit_pip_type(PipType::Special).len(), 22);
    /// ```
    #[must_use]
    fn cards_of_suit_pip_type(&self, pip_type: PipType) -> BasicPile {
        let rank_types_filter = |basic_card: &BasicCard| basic_card.suit.pip_type == pip_type;
        self.filter_cards(rank_types_filter)
    }

    /// Returns a [`BasicPile`] where either the suit or rank [`Pip`] have the specified [`PipType`].\
    ///
    /// ```
    /// use cardpack::prelude::*;
    ///
    /// assert_eq!(Tarot::deck().cards_with_pip_type(PipType::Special).len(), 22);
    /// assert_eq!(French::deck().cards_with_pip_type(PipType::Joker).len(), 2);
    /// assert!(French::deck().cards_with_pip_type(PipType::Special).is_empty());
    /// ```
    #[must_use]
    fn cards_with_pip_type(&self, pip_type: PipType) -> BasicPile {
        let rank_types_filter = |basic_card: &BasicCard| {
            basic_card.rank.pip_type == pip_type || basic_card.suit.pip_type == pip_type
        };
        self.filter_cards(rank_types_filter)
    }

    fn extract_pips<F>(&self, f: F) -> Vec<Pip>
    where
        F: Fn(&BasicCard) -> Pip,
    {
        let set: HashSet<Pip> = self.my_basic_pile().iter().map(f).collect();
        let mut vec: Vec<Pip> = set.into_iter().collect::<Vec<_>>();
        vec.sort();
        vec.reverse();
        vec
    }

    fn map_by_rank(&self) -> HashMap<Pip, BasicPile> {
        let mut mappy: HashMap<Pip, BasicPile> = HashMap::new();

        for card in &self.my_basic_pile() {
            let rank = card.rank;

            if let std::collections::hash_map::Entry::Vacant(e) = mappy.entry(rank) {
                let pile = BasicPile::from(vec![*card]);
                e.insert(pile);
            } else if let Some(pile) = mappy.get_mut(&rank) {
                pile.push(*card);
            }
        }

        mappy
    }

    /// Takes the `BasicPiles` and sorts them based on their length.
    ///
    /// **DIARY**: Don't really care that much that ten of spades comes before jack of spades in
    /// our unit tests. It's annoying but not enough to solve the problem.
    fn combos_by_rank(&self) -> Combos {
        let mappy = self.map_by_rank();

        let v: Vec<BasicPile> = mappy.values().map(Clone::clone).collect::<Vec<_>>();

        let mut combos = Combos::from(v);
        combos.sort_by_length();
        combos.reverse();
        combos
    }

    fn pip_index<F>(&self, f: F, joiner: &str) -> String
    where
        F: Fn(&BasicCard) -> Pip,
    {
        self.extract_pips(f)
            .iter()
            .map(|pip| pip.index.to_string())
            .collect::<Vec<String>>()
            .join(joiner)
    }

    #[must_use]
    fn ranks(&self) -> Vec<Pip> {
        self.extract_pips(|card| card.rank)
    }

    #[must_use]
    fn ranks_index(&self, joiner: &str) -> String {
        self.pip_index(|card| card.rank, joiner)
    }

    /// TODO RF: Wouldn't it be easier to just return a vector, and if it's empty you know
    /// there were none in the `Pile`.
    #[must_use]
    fn ranks_by_suit(&self, suit: Pip) -> Option<Vec<Pip>> {
        let ranks: Vec<Pip> = self
            .my_basic_pile()
            .iter()
            .filter(|card| card.suit == suit)
            .map(|card| card.rank)
            .collect();

        match ranks.len() {
            0 => None,
            _ => Some(ranks),
        }
    }

    #[must_use]
    fn ranks_index_by_suit(&self, suit: Pip, joiner: &str) -> Option<String> {
        self.ranks_by_suit(suit).map(|ranks| {
            ranks
                .iter()
                .map(|pip| pip.index.to_string())
                .collect::<Vec<String>>()
                .join(joiner)
        })
    }

    #[must_use]
    fn suits(&self) -> Vec<Pip> {
        self.extract_pips(|card| card.suit)
    }

    #[must_use]
    fn suits_index(&self, joiner: &str) -> String {
        self.pip_index(|card| card.suit, joiner)
    }

    #[must_use]
    fn suit_symbol_index(&self, joiner: &str) -> String {
        self.suits()
            .iter()
            .map(|pip| pip.symbol.to_string())
            .collect::<Vec<String>>()
            .join(joiner)
    }
}

#[cfg(test)]
#[allow(non_snake_case, unused_imports)]
mod basic__types__traits_tests {
    use super::*;
    use crate::basic::decks::standard52::Standard52;
    use crate::prelude::{Decked, DeckedBase, FrenchBasicCard};

    #[test]
    fn basic_pile_cell__not_default() {
        let cell = Standard52::basic_pile_cell();
        let pile = cell.take();
        assert_eq!(pile.len(), Standard52::DECK_SIZE);
        assert_ne!(pile.len(), 0);
    }

    #[test]
    fn into_cards__correct_length() {
        let base_cards = Standard52::DECK.as_slice();
        let cards = Standard52::into_cards(base_cards);
        assert_eq!(cards.len(), Standard52::DECK_SIZE);
        assert!(!cards.is_empty());
    }

    #[test]
    fn into_cards__not_empty_collection() {
        // Catches vec![] and vec![Card::new(Default::default())] mutations
        let single = &[FrenchBasicCard::ACE_SPADES];
        let cards = Standard52::into_cards(single);
        assert_eq!(cards.len(), 1);
        assert_ne!(cards[0].base(), FrenchBasicCard::DEUCE_CLUBS);
    }

    #[test]
    fn demo__does_not_panic() {
        Standard52::demo(false);
    }

    #[test]
    fn validate__true_for_valid_deck() {
        // This also catches the validate -> true mutation because the test
        // demonstrates validate returns the correct value, not always true.
        // The && -> || mutation is caught by the fact that both conditions must hold.
        assert!(Standard52::validate());
    }
}