gametools 0.8.0

Toolkit for game-building in Rust: cards, dice, dominos, spinners, refillable pools, and ordering helpers.
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! # Standard Playing Cards
//!
//! Helpers for working with the canonical 52-card deck (plus optional Jokers).
//! The [`StandardCard`] type implements [`CardFaces`] so it can be
//! wrapped in a [`Card`] and used with [`Deck`](crate::cards::Deck),
//! [`Hand`], or [`Pile`](crate::cards::Pile).
//!
//! ```
//! use gametools::{Card, CardCollection, Deck};
//! use gametools::cards::std_playing_cards::{standard_52, Rank, StandardCard, Suit};
//!
//! // Create a full deck and wrap each face in a Card.
//! let cards = standard_52()     // or standard_52_with_jokers() for added 2 Jokers / wildcards
//!     .into_iter()
//!     .map(Card::new_card)
//!     .collect::<Vec<_>>();
//!
//! let mut deck = Deck::from_cards("standard", cards);
//! assert_eq!(deck.size(), 52);
//!
//! // Create an individual card by rank and suit.
//! let ace_spades = StandardCard::new_card(Rank::Ace, Suit::Spades);
//! assert_eq!(ace_spades.rank, Rank::Ace);
//! assert_eq!(ace_spades.suit, Suit::Spades);
//! ```
use crate::{
    CardCollection as _,
    cards::{Card, CardFaces, Hand},
};
use std::collections::BTreeMap;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// A standard playing card from a regular deck (52 cards, or 54 with Jokers).
#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct StandardCard {
    /// Numeric value used for comparisons (ace high by default).
    pub value: u8,
    /// The suit (♣, ♦, ♥, ♠, or `Wild` for Jokers).
    pub suit: Suit,
    /// The rank, including face cards and optional joker.
    pub rank: Rank,
}
impl StandardCard {
    /// Create a new standard playing card face.
    ///
    /// ```
    /// use gametools::cards::std_playing_cards::{Rank, StandardCard, Suit};
    ///
    /// let card = StandardCard::new_card(Rank::Queen, Suit::Hearts);
    /// assert_eq!(card.rank, Rank::Queen);
    /// assert_eq!(card.suit, Suit::Hearts);
    /// ```
    #[must_use]
    pub fn new_card(rank: Rank, suit: Suit) -> Self {
        Self {
            rank,
            suit,
            value: rank as u8,
        }
    }
}
impl CardFaces for StandardCard {
    fn display_front(&self) -> String {
        format!("{}.{}", self.rank, self.suit)
    }

    fn display_back(&self) -> Option<String> {
        None
    }

    fn matches(&self, other: &Self) -> bool {
        self.rank == other.rank && self.suit == other.suit
    }

    fn compare(&self, other: &Self) -> std::cmp::Ordering {
        self.value.cmp(&other.value)
    }
}

/// Card ranks from two through ace, plus an optional joker.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Rank {
    Two = 2,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
    Ace,
    Joker = 255,
}
impl std::fmt::Display for Rank {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Rank::Two => write!(f, "2"),
            Rank::Three => write!(f, "3"),
            Rank::Four => write!(f, "4"),
            Rank::Five => write!(f, "5"),
            Rank::Six => write!(f, "6"),
            Rank::Seven => write!(f, "7"),
            Rank::Eight => write!(f, "8"),
            Rank::Nine => write!(f, "9"),
            Rank::Ten => write!(f, "10"),
            Rank::Jack => write!(f, "J"),
            Rank::Queen => write!(f, "Q"),
            Rank::King => write!(f, "K"),
            Rank::Ace => write!(f, "A"),
            Rank::Joker => write!(f, "*"),
        }
    }
}
impl Rank {
    /// Return the thirteen ranks used in a standard 52-card deck.
    ///
    /// ```
    /// use gametools::cards::std_playing_cards::{Rank, Suit};
    ///
    /// let mut ranks = Rank::normal_ranks();
    /// assert_eq!(ranks.len(), 13);
    /// assert!(ranks.contains(&Rank::Ace));
    /// assert!(!ranks.contains(&Rank::Joker));
    /// ```
    #[must_use]
    pub fn normal_ranks() -> Vec<Rank> {
        vec![
            Rank::Two,
            Rank::Three,
            Rank::Four,
            Rank::Five,
            Rank::Six,
            Rank::Seven,
            Rank::Eight,
            Rank::Nine,
            Rank::Ten,
            Rank::Jack,
            Rank::Queen,
            Rank::King,
            Rank::Ace,
        ]
    }
    /// Return the standard ranks plus the optional `Rank::Joker`.
    #[must_use]
    pub fn all_ranks() -> Vec<Rank> {
        let mut all_ranks = Rank::normal_ranks();
        all_ranks.push(Rank::Joker);
        all_ranks
    }

    /// Convert an integer value into a rank (treating 1 and 14 as aces).
    ///
    /// ```
    /// use gametools::cards::std_playing_cards::Rank;
    ///
    /// assert_eq!(Rank::from_value(12), Some(Rank::Queen));
    /// assert_eq!(Rank::from_value(1), Some(Rank::Ace));
    /// assert_eq!(Rank::from_value(42), None);
    /// ```
    #[must_use]
    pub fn from_value(value: u8) -> Option<Rank> {
        match value {
            1 | 14 => Some(Rank::Ace),
            2 => Some(Rank::Two),
            3 => Some(Rank::Three),
            4 => Some(Rank::Four),
            5 => Some(Rank::Five),
            6 => Some(Rank::Six),
            7 => Some(Rank::Seven),
            8 => Some(Rank::Eight),
            9 => Some(Rank::Nine),
            10 => Some(Rank::Ten),
            11 => Some(Rank::Jack),
            12 => Some(Rank::Queen),
            13 => Some(Rank::King),
            _ => None,
        }
    }
}

/// The four standard suits plus `Wild` for Jokers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Suit {
    Clubs,
    Hearts,
    Diamonds,
    Spades,
    Wild,
}
impl std::fmt::Display for Suit {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Suit::Clubs => write!(f, ""),
            Suit::Hearts => write!(f, ""),
            Suit::Diamonds => write!(f, ""),
            Suit::Spades => write!(f, ""),
            Suit::Wild => write!(f, "?"),
        }
    }
}
impl Suit {
    /// Return the four standard suits.
    ///
    /// ```
    /// use gametools::cards::std_playing_cards::Suit;
    ///
    /// let suits = Suit::normal_suits();
    /// assert_eq!(suits.len(), 4);
    /// assert!(suits.contains(&Suit::Hearts));
    /// ```
    #[must_use]
    pub fn normal_suits() -> Vec<Suit> {
        vec![Suit::Clubs, Suit::Hearts, Suit::Diamonds, Suit::Spades]
    }
    /// Return the four suits plus `Suit::Wild`.
    #[must_use]
    pub fn all_suits() -> Vec<Suit> {
        let mut all_suits = Suit::normal_suits();
        all_suits.push(Suit::Wild);
        all_suits
    }
}

/*
 *
 *  DEFINITION OF COMMON DECK SETUPS WITH STANDARD CARDS TO SIMPLIFY DECK BUILDING
 *
 */

/// Create a set of all 52 "normal" card faces for a standard deck of playing cards.
///
/// ```
/// use gametools::cards::std_playing_cards::standard_52;
///
/// let deck = standard_52();
/// assert_eq!(deck.len(), 52);
/// ```
#[must_use]
pub fn standard_52() -> Vec<StandardCard> {
    let mut deck = Vec::new();
    for suit in Suit::normal_suits() {
        for rank in Rank::normal_ranks() {
            deck.push(StandardCard::new_card(rank, suit));
        }
    }
    deck
}

/// Trait that extends a `Vec<StandardCard>` to assist in building modified decks.
pub trait DeckModifier {
    #[must_use]
    fn add_jokers(self, count: u8) -> Self;
    #[must_use]
    fn remove_ranks(self, ranks: &[Rank]) -> Self;
    #[must_use]
    fn remove_suits(self, suits: &[Suit]) -> Self;
    #[must_use]
    fn add_cards(self, cards: impl Iterator<Item = StandardCard>) -> Self;
    #[must_use]
    fn duplicate(self, times: usize) -> Self;
}
impl DeckModifier for Vec<StandardCard> {
    fn add_jokers(mut self, count: u8) -> Self {
        for _ in 0..count {
            self.push(StandardCard::new_card(Rank::Joker, Suit::Wild));
        }
        self
    }
    fn remove_ranks(self, ranks: &[Rank]) -> Self {
        self.into_iter()
            .filter(|c| !ranks.contains(&c.rank))
            .collect()
    }

    fn remove_suits(self, suits: &[Suit]) -> Self {
        self.into_iter()
            .filter(|c| !suits.contains(&c.suit))
            .collect()
    }

    fn add_cards(mut self, cards: impl Iterator<Item = StandardCard>) -> Self {
        self.extend(cards);
        self
    }

    fn duplicate(mut self, times: usize) -> Self {
        for _ in 0..times {
            self.extend_from_within(..);
        }
        self
    }
}

/// Create a full 52-card deck plus two jokers.
///
/// ```
/// use gametools::cards::std_playing_cards::standard_52_with_jokers;
///
/// let deck = standard_52_with_jokers();
/// assert_eq!(deck.len(), 54);
/// ```
#[must_use]
pub fn standard_52_with_jokers() -> Vec<StandardCard> {
    standard_52().add_jokers(2)
}

/// Create a Piquet deck (32 cards, ranks 2-6 excluded.)
///
/// ```
/// use gametools::cards::std_playing_cards::piquet_deck;
///
/// let deck = piquet_deck();
/// assert_eq!(deck.len(), 32);
/// ```
#[must_use]
pub fn piquet_deck() -> Vec<StandardCard> {
    standard_52().remove_ranks(&[Rank::Two, Rank::Three, Rank::Four, Rank::Five, Rank::Six])
}

/// Create a Euchre deck (24 cards, ranks 2-8 excluded.
///
/// ```
/// use gametools::cards::std_playing_cards::euchre_deck;
///
/// let deck = euchre_deck();
/// assert_eq!(deck.len(), 24);
/// ```
#[must_use]
pub fn euchre_deck() -> Vec<StandardCard> {
    standard_52().remove_ranks(&[
        Rank::Two,
        Rank::Three,
        Rank::Four,
        Rank::Five,
        Rank::Six,
        Rank::Seven,
        Rank::Eight,
    ])
}

impl Hand<StandardCard> {
    /// Check whether a card matching a rank and suit is in the `Hand`.
    ///
    /// ```
    /// use gametools::{AddCard, Card, Hand};
    /// use gametools::cards::std_playing_cards::{Rank, StandardCard, Suit};
    ///
    /// let mut hand = Hand::<StandardCard>::new("player");
    /// hand.add_card(Card::new_card(StandardCard::new_card(Rank::Ace, Suit::Spades)));
    /// assert!(hand.contains(Rank::Ace, Suit::Spades));
    /// assert!(!hand.contains(Rank::Queen, Suit::Hearts));
    /// ```
    #[must_use]
    pub fn contains(&self, rank: Rank, suit: Suit) -> bool {
        let search = StandardCard::new_card(rank, suit);
        self.cards().iter().any(|card| card.faces.matches(&search))
    }

    /// Count how many cards in the hand have a specific rank.
    ///
    /// ```
    /// use gametools::{AddCard, Card, Hand};
    /// use gametools::cards::std_playing_cards::{Rank, StandardCard, Suit};
    ///
    /// let mut hand = Hand::<StandardCard>::new("player");
    /// hand.add_card(Card::new_card(StandardCard::new_card(Rank::Ace, Suit::Spades)));
    /// hand.add_card(Card::new_card(StandardCard::new_card(Rank::Ace, Suit::Hearts)));
    /// hand.add_card(Card::new_card(StandardCard::new_card(Rank::King, Suit::Clubs)));
    /// assert_eq!(hand.count_rank(Rank::Ace), 2);
    /// ```
    #[must_use]
    pub fn count_rank(&self, rank: Rank) -> usize {
        self.cards().iter().filter(|c| c.faces.rank == rank).count()
    }

    /// Create a map of `Rank` counts for the current `Hand`.
    ///
    /// ```
    /// use gametools::{AddCard, Card, Hand};
    /// use gametools::cards::std_playing_cards::{Rank, StandardCard, Suit};
    ///
    /// let mut hand = Hand::<StandardCard>::new("player");
    /// hand.add_card(Card::new_card(StandardCard::new_card(Rank::Three, Suit::Spades)));
    /// hand.add_card(Card::new_card(StandardCard::new_card(Rank::Three, Suit::Clubs)));
    /// hand.add_card(Card::new_card(StandardCard::new_card(Rank::Ace, Suit::Hearts)));
    ///
    /// let ranks = hand.rank_map();
    /// assert_eq!(ranks.get(&Rank::Three), Some(&2));
    /// assert_eq!(ranks.get(&Rank::Ace), Some(&1));
    /// ```
    #[must_use]
    pub fn rank_map(&self) -> BTreeMap<Rank, usize> {
        let mut rank_map = BTreeMap::new();
        for card in self.cards() {
            rank_map
                .entry(card.faces.rank)
                .and_modify(|count| *count += 1)
                .or_insert(1);
        }
        rank_map
    }

    /// Count how many cards in the hand have a specific suit.
    #[must_use]
    pub fn count_suit(&self, suit: Suit) -> usize {
        self.cards().iter().filter(|c| c.faces.suit == suit).count()
    }

    /// Create a map of `Suit` counts for the current `Hand`.
    #[must_use]
    pub fn suit_map(&self) -> BTreeMap<Suit, usize> {
        let mut suit_map = BTreeMap::new();
        for card in self.cards() {
            suit_map
                .entry(card.faces.suit)
                .and_modify(|count| *count += 1)
                .or_insert(1);
        }
        suit_map
    }

    /// Returns true if every card in the hand belongs to the same `Suit`.
    #[must_use]
    pub fn is_flush(&self) -> bool {
        let total_cards = self.size();
        if total_cards == 0 {
            return false;
        }

        let mut suit_map = self.suit_map();
        let wildcards = suit_map.remove(&Suit::Wild).unwrap_or(0);

        if suit_map.is_empty() {
            return wildcards >= total_cards;
        }

        suit_map
            .values()
            .any(|count| *count + wildcards >= total_cards)
    }

    /// Check for N cards of a kind.
    ///
    /// Returns `None` if none reach N, or `Some` cards if there are any.
    #[must_use]
    pub fn find_n_of_a_kind(&self, count: usize) -> Option<Vec<&StandardCard>> {
        if count == 0 {
            return Some(Vec::new());
        }
        if self.size() < count {
            return None;
        }

        let mut rank_groups: BTreeMap<Rank, Vec<&Card<StandardCard>>> = BTreeMap::new();
        for card in self.cards() {
            rank_groups.entry(card.faces.rank).or_default().push(card);
        }

        let jokers = rank_groups.remove(&Rank::Joker).unwrap_or_default();
        let mut groups: Vec<(Rank, Vec<&Card<StandardCard>>)> = rank_groups.into_iter().collect();
        groups.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));

        for (_rank, cards) in groups {
            let mut result: Vec<&StandardCard> =
                cards.iter().take(count).map(|card| &card.faces).collect();
            if result.len() == count {
                return Some(result);
            }

            let missing = count - result.len();
            if !jokers.is_empty() && jokers.len() >= missing {
                result.extend(jokers.iter().take(missing).map(|card| &card.faces));
                return Some(result);
            }
        }

        if jokers.len() >= count {
            return Some(jokers.iter().take(count).map(|card| &card.faces).collect());
        }

        None
    }

    /// Returns `Some` ordered cards that form a straight of the requested length, or `None` if no straight exists.
    ///
    /// Jokers serve as wild cards and may fill any missing rank. Aces may be used high or low.
    #[must_use]
    pub fn find_n_straight(&self, count: usize) -> Option<Vec<&StandardCard>> {
        // handle edge cases with obvious results
        if count == 0 {
            return Some(Vec::new());
        }
        if self.size() < count || count > 14 {
            return None;
        }

        // group cards according their ranks
        let mut rank_groups: BTreeMap<Rank, Vec<&Card<StandardCard>>> = BTreeMap::new();
        for card in self.cards() {
            rank_groups.entry(card.faces.rank).or_default().push(card);
        }

        // pull the wildcards out of the rank groups, counting them for later insertion if
        // needed to complete a straight
        let jokers = rank_groups.remove(&Rank::Joker).unwrap_or_default();

        // if all of the cards were wild, we have a straight if we have enough cards
        if rank_groups.is_empty() {
            return (jokers.len() >= count)
                .then(|| jokers.iter().take(count).map(|card| &card.faces).collect());
        }

        // any sequence starting after this will run out of ranks before we have enough
        let max_start = 14usize.saturating_sub(count).saturating_add(1);

        // try to pull a card from `count` consecutive rank groups, inserting Jokers
        // as needed and if available
        for start in 1..=max_start {
            let mut available = rank_groups.clone();
            let mut jokers_left = jokers.clone();
            let mut straight_cards: Vec<&Card<StandardCard>> = Vec::with_capacity(count);
            let mut success = true;

            for offset in 0..count {
                #[allow(clippy::cast_possible_truncation)]
                let value = (start + offset) as u8;
                let Some(rank) = Rank::from_value(value) else {
                    success = false;
                    break;
                };

                // if there's a natural card to fill this rank slot, use it and move on
                if let Some(cards) = available.get_mut(&rank)
                    && let Some(card) = cards.pop()
                {
                    straight_cards.push(card);
                    continue;
                }

                // if there's Joker to fill this rank slot, use it and move on
                if let Some(joker_card) = jokers_left.pop() {
                    straight_cards.push(joker_card);
                } else {
                    success = false;
                    break;
                }
            }

            if success {
                let straight_faces = straight_cards.iter().map(|card| &card.faces).collect();
                return Some(straight_faces);
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AddCard, cards::Card};
    use std::collections::BTreeSet;

    #[test]
    fn piquet_deck_includes_only_expected_cards() {
        let cards = piquet_deck();
        assert_eq!(cards.len(), 32);
        assert!(cards.iter().all(|card| matches!(
            card.rank,
            Rank::Seven
                | Rank::Eight
                | Rank::Nine
                | Rank::Ten
                | Rank::Jack
                | Rank::Queen
                | Rank::King
                | Rank::Ace
        )));
    }

    #[test]
    fn remove_ranks_removes_expected_cards() {
        let std_minus_two_ranks = standard_52().remove_ranks(&[Rank::Two, Rank::Jack]);
        assert_eq!(std_minus_two_ranks.len(), 44);
        assert!(
            !std_minus_two_ranks
                .iter()
                .any(|c| matches!(c.rank, Rank::Two | Rank::Jack))
        );
    }

    #[test]
    fn add_jokers_adds_expected_cards() {
        let joker_deck: Vec<StandardCard> = Vec::new().add_jokers(10);
        assert_eq!(joker_deck.len(), 10);

        let full_plus_four: Vec<StandardCard> = standard_52().add_jokers(4);
        assert_eq!(full_plus_four.len(), 52 + 4);

        let wild_count = full_plus_four
            .iter()
            .filter(|c| c.suit == Suit::Wild)
            .count();
        assert_eq!(wild_count, 4);

        let joker_count = full_plus_four
            .iter()
            .filter(|c| c.rank == Rank::Joker)
            .count();
        assert_eq!(joker_count, 4);
    }

    #[test]
    fn standard_card_constructor_sets_rank_suit_and_value() {
        let card = StandardCard::new_card(Rank::Ace, Suit::Spades);

        assert_eq!(card.rank, Rank::Ace);
        assert_eq!(card.suit, Suit::Spades);
        assert_eq!(card.value, Rank::Ace as u8);
    }

    #[test]
    fn standard_card_display_and_faces_behave_as_expected() {
        let card = StandardCard::new_card(Rank::Ten, Suit::Hearts);

        assert_eq!(card.display_front(), "10.♥");
        assert!(card.display_back().is_none());
    }

    #[test]
    fn matches_and_compare_follow_rank_and_suit() {
        let low = StandardCard::new_card(Rank::Five, Suit::Clubs);
        let high = StandardCard::new_card(Rank::Seven, Suit::Clubs);
        let different_suit = StandardCard::new_card(Rank::Five, Suit::Hearts);

        assert!(low.matches(&StandardCard::new_card(Rank::Five, Suit::Clubs)));
        assert!(!low.matches(&different_suit));
        assert_eq!(low.compare(&high), std::cmp::Ordering::Less);
        assert_eq!(high.compare(&low), std::cmp::Ordering::Greater);
        assert_eq!(low.compare(&low), std::cmp::Ordering::Equal);
    }

    #[test]
    fn normal_ranks_and_suits_return_expected_sets() {
        let ranks = Rank::normal_ranks();
        let suits = Suit::normal_suits();

        assert_eq!(ranks.len(), 13);
        assert!(ranks.iter().all(|rank| *rank != Rank::Joker));
        assert_eq!(suits.len(), 4);
        assert!(!suits.contains(&Suit::Wild));
    }

    #[test]
    fn full_deck_contains_all_rank_suit_combinations() {
        let deck = standard_52();

        assert_eq!(deck.len(), 52);
        let unique: BTreeSet<(Rank, Suit)> = deck.iter().map(|c| (c.rank, c.suit)).collect();
        assert_eq!(unique.len(), 52);
    }

    #[test]
    fn full_deck_with_jokers_adds_two_wild_cards() {
        let deck = standard_52_with_jokers();

        assert_eq!(deck.len(), 54);
        let joker_count = deck
            .iter()
            .filter(|c| c.rank == Rank::Joker && c.suit == Suit::Wild)
            .count();
        assert_eq!(joker_count, 2);
    }

    #[test]
    fn hand_detects_ace_low_straight() {
        let mut hand = Hand::new("player");
        let cards = [
            (Rank::Ace, Suit::Spades),
            (Rank::Two, Suit::Clubs),
            (Rank::Three, Suit::Diamonds),
            (Rank::Four, Suit::Hearts),
            (Rank::Five, Suit::Spades),
        ];

        for (rank, suit) in cards {
            hand.add_card(Card::new_card(StandardCard::new_card(rank, suit)));
        }

        let straight = hand.find_n_straight(5).expect("expected ace-low straight");
        let ranks: Vec<Rank> = straight.iter().map(|card| card.rank).collect();
        assert_eq!(
            ranks,
            vec![Rank::Ace, Rank::Two, Rank::Three, Rank::Four, Rank::Five]
        );
    }

    #[test]
    fn hand_detects_straight_with_joker() {
        let mut hand = Hand::new("player");
        let cards = [
            (Rank::Ten, Suit::Hearts),
            (Rank::Queen, Suit::Diamonds),
            (Rank::King, Suit::Clubs),
            (Rank::Ace, Suit::Spades),
        ];

        for (rank, suit) in cards {
            hand.add_card(Card::new_card(StandardCard::new_card(rank, suit)));
        }
        hand.add_card(Card::new_card(StandardCard::new_card(
            Rank::Joker,
            Suit::Wild,
        )));

        let straight = hand
            .find_n_straight(5)
            .expect("expected straight with joker");
        assert_eq!(straight.len(), 5);
        assert_eq!(
            straight
                .iter()
                .filter(|card| card.rank == Rank::Joker)
                .count(),
            1
        );
        let mut ranks: Vec<_> = straight.iter().map(|card| card.rank).collect();
        ranks.sort();
        assert!(ranks.contains(&Rank::Ten));
        assert!(ranks.contains(&Rank::Queen));
        assert!(ranks.contains(&Rank::King));
        assert!(ranks.contains(&Rank::Ace));
    }

    #[test]
    fn hand_requires_enough_jokers_to_fill_gaps() {
        let mut hand = Hand::new("player");
        let cards = [
            (Rank::Two, Suit::Diamonds),
            (Rank::Four, Suit::Clubs),
            (Rank::Six, Suit::Spades),
        ];
        for (rank, suit) in cards {
            hand.add_card(Card::new_card(StandardCard::new_card(rank, suit)));
        }
        hand.add_card(Card::new_card(StandardCard::new_card(
            Rank::Joker,
            Suit::Wild,
        )));

        assert!(hand.find_n_straight(4).is_none());
    }

    #[test]
    fn hand_finds_three_of_a_kind_using_joker() {
        let mut hand = Hand::new("player");
        let cards = [
            (Rank::Ten, Suit::Hearts),
            (Rank::Ten, Suit::Clubs),
            (Rank::Joker, Suit::Wild),
        ];
        for (rank, suit) in cards {
            hand.add_card(Card::new_card(StandardCard::new_card(rank, suit)));
        }

        let trio = hand
            .find_n_of_a_kind(3)
            .expect("expected three of a kind with joker support");
        assert_eq!(trio.len(), 3);
        assert_eq!(trio.iter().filter(|card| card.rank == Rank::Ten).count(), 2);
        assert_eq!(
            trio.iter().filter(|card| card.rank == Rank::Joker).count(),
            1
        );
    }

    #[test]
    fn hand_allows_flush_with_joker() {
        let mut hand = Hand::new("player");
        let cards = [
            (Rank::Two, Suit::Hearts),
            (Rank::Four, Suit::Hearts),
            (Rank::Six, Suit::Hearts),
            (Rank::Nine, Suit::Hearts),
            (Rank::Joker, Suit::Wild),
        ];
        for (rank, suit) in cards {
            hand.add_card(Card::new_card(StandardCard::new_card(rank, suit)));
        }

        assert!(hand.is_flush());
    }

    #[test]
    fn hand_of_only_jokers_counts_as_flush_and_of_a_kind() {
        let mut hand = Hand::new("player");
        for _ in 0..3 {
            hand.add_card(Card::new_card(StandardCard::new_card(
                Rank::Joker,
                Suit::Wild,
            )));
        }

        assert!(hand.is_flush());
        let wild_trio = hand
            .find_n_of_a_kind(3)
            .expect("expected jokers to satisfy kind");
        assert_eq!(wild_trio.len(), 3);
        assert!(wild_trio.iter().all(|card| card.rank == Rank::Joker));
    }
}