go-fish 0.2.0

A core engine for the classic Go Fish card game, providing game logic, deck management, and player interactions.
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
//! # go-fish
//!
//! `go-fish` is a library providing core engine functionality for the classic [Go Fish card game](https://en.wikipedia.org/wiki/Go_Fish).
//!
//! It provides types for cards, decks, and players, and manages the game logic including turns, drawing, and completing books.
//!
//! ## Example
//!
//! ```rust
//! use go_fish::{Game, Deck, Hook, PlayerId, Rank};
//!
//! // Initialize a new game with 3 players
//! let deck = Deck::new().shuffle();
//! let mut game = Game::new(deck, 3);
//!
//! // Current player takes a turn
//! let hook = Hook {
//!     target: PlayerId::new(1),
//!     rank: Rank::Ace,
//! };
//!
//! match game.take_turn(hook) {
//!     Ok(result) => println!("Turn result: {:?}", result),
//!     Err(e) => eprintln!("Error: {:?}", e),
//! }
//! ```

use enum_iterator::{all, Sequence};
use rand::prelude::SliceRandom;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use tracing::debug;
use tracing::warn;

/// A playing card
#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
pub struct Card {
    pub suit: Suit,
    pub rank: Rank,
}

/// The suit of a [Card]
#[derive(Debug, PartialEq, Sequence, Clone, Copy, Serialize, Deserialize)]
pub enum Suit {
    Clubs,
    Diamonds,
    Hearts,
    Spades,
}

/// The rank (or value) of a [Card]
#[derive(
    Debug,
    PartialEq,
    Eq,
    Hash,
    Sequence,
    Clone,
    Copy,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize
)]
pub enum Rank {
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
    Ace,
}

impl Display for Rank {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let s = match self {
            Rank::Two => "Two",
            Rank::Three => "Three",
            Rank::Four => "Four",
            Rank::Five => "Five",
            Rank::Six => "Six",
            Rank::Seven => "Seven",
            Rank::Eight => "Eight",
            Rank::Nine => "Nine",
            Rank::Ten => "Ten",
            Rank::Jack => "Jack",
            Rank::Queen => "Queen",
            Rank::King => "King",
            Rank::Ace => "Ace",
        };
        write!(f, "{}", s)
    }
}

/// A deck of [Cards](Card)
#[derive(Debug, Serialize, Deserialize)]
pub struct Deck {
    pub cards: Vec<Card>,
}

/// A collection of three or fewer [Cards](Card) of the same [Rank]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct IncompleteBook {
    pub rank: Rank,
    pub cards: Vec<Card>,
}

/// A collection of four [Cards](Card) of the same [Rank]
#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
pub struct CompleteBook {
    pub rank: Rank,
    pub cards: [Card; 4],
}

/// A players hand
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Hand {
    pub books: Vec<IncompleteBook>,
}

/// A player actively trying to win the game
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Player {
    pub id: PlayerId,
    pub hand: Hand,
    pub completed_books: Vec<CompleteBook>,
}

/// A player who no longer has any viable moves. They can still win the game, if they have
/// more [Completed Books](CompleteBook) than any other player at the end of the game
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InactivePlayer {
    pub id: PlayerId,
    pub completed_books: Vec<CompleteBook>,
}

#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Hash)]
pub struct PlayerId(u8);

impl PlayerId {
    pub fn new(id: u8) -> PlayerId {
        PlayerId(id)
    }
}

/// A request for another players cards
/// > Player 2, got any three's?
#[derive(Debug, Serialize, Deserialize)]
pub struct Hook {
    pub target: PlayerId,
    pub rank: Rank,
}

#[derive(Debug)]
pub enum TurnError {
    /// The [Hooks](Hook) target is not a player in the game
    TargetNotFound(PlayerId),
    GameIsFinished
}

/// Handling for a game of Go Fish
#[derive(Debug, Serialize, Deserialize)]
pub struct Game {
    pub deck: Deck,
    pub players: Vec<Player>,
    pub inactive_players: Vec<InactivePlayer>,
    pub is_finished: bool,
    player_turn: usize,
}

impl Deck {
    /// Creates a new, ordered deck of [Cards](Card)
    pub fn new() -> Deck {
        let cards = Self::ordered_cards();
        Deck { cards }
    }

    /// Shuffles the remaining cards and returns the deck
    pub fn shuffle(mut self) -> Self {
        let mut rng = rand::rng();
        self.cards.shuffle(&mut rng);
        self
    }

    pub fn is_empty(&self) -> bool {
        self.cards.is_empty()
    }

    pub fn len(&self) -> usize {
        self.cards.len()
    }

    /// Draws a card from the deck´
    /// ```
    /// use go_fish::Deck;
    /// let mut deck = Deck::new();
    /// let card = deck.draw();
    /// assert!(card.is_some())
    /// ```
    pub fn draw(&mut self) -> Option<Card> {
        self.cards.pop()
    }

    fn ordered_cards() -> Vec<Card> {
        let cards_from_suit = |suit| {
            all::<Rank>()
                .map(|rank| Card { suit, rank })
                .collect::<Vec<_>>()
        };
        all::<Suit>().flat_map(cards_from_suit).collect::<Vec<_>>()
    }
}

impl Default for Deck {
    fn default() -> Self {
        Self::new()
    }
}

impl IncompleteBook {
    /// Try to combine one [IncompleteBook] with another. This can result in a [CompleteBook].
    pub(crate) fn combine(self, other: IncompleteBook) -> CombineBookResult {
        if self.rank != other.rank {
            return CombineBookResult::NotCombined(self, other);
        }

        let rank = self.rank;
        let combined_cards = self
            .cards
            .into_iter()
            .chain(other.cards)
            .collect::<Vec<_>>();

        if combined_cards.len() == 4 {
            let cards = [
                combined_cards[0],
                combined_cards[1],
                combined_cards[2],
                combined_cards[3],
            ];
            let complete_book = CompleteBook { rank, cards };
            return CombineBookResult::Completed(complete_book);
        }

        let combined_book = IncompleteBook {
            rank,
            cards: combined_cards,
        };
        CombineBookResult::Combined(combined_book)
    }
}

impl From<Card> for IncompleteBook {
    fn from(card: Card) -> Self {
        let rank = card.rank;
        let cards = vec![card];
        IncompleteBook { rank, cards }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GameResult {
    pub winners: Vec<InactivePlayer>,
    pub losers: Vec<InactivePlayer>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum HookResult {
    Catch(IncompleteBook),
    GoFish,
}

/// The full outcome of a [take_turn](Game::take_turn) call, including who fished, who was targeted, what rank was requested, and whether the catch succeeded.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HookOutcome {
    pub fisher: PlayerId,
    pub target: PlayerId,
    pub rank: Rank,
    pub result: HookResult,
}

impl Hand {
    /// Create a new, empty Hand.
    pub fn empty() -> Hand {
        let books = vec![];
        Hand { books }
    }

    /// Add an [IncompleteBook] to the Hand. This may produce an [CompleteBook].
    pub fn add_book(&mut self, book: IncompleteBook) -> Option<CompleteBook> {
        let position = self.books.iter().position(|b| b.rank == book.rank);
        let position = match position {
            Some(position) => position,
            None => {
                self.books.push(book);
                return None;
            }
        };

        let existing_book = self.books.remove(position);
        let combined_result = existing_book.combine(book);

        match combined_result {
            CombineBookResult::NotCombined(a, b) => {
                warn!("Books {:?} and {:?} failed to combine, but we expect them to have the same rank", a, b);
                None
            }
            CombineBookResult::Combined(combined_book) => {
                self.books.push(combined_book);
                None
            }
            CombineBookResult::Completed(completed_book) => Some(completed_book),
        }
    }

    pub(crate) fn receive_hook(&mut self, rank: Rank) -> HookResult {
        let position = self.books.iter().position(|b| b.rank == rank);
        let position = match position {
            None => return HookResult::GoFish,
            Some(pos) => pos,
        };

        let catch = self.books.remove(position);
        HookResult::Catch(catch)
    }
}

impl Player {
    pub(crate) fn add_book(&mut self, book: IncompleteBook) {
        let completed_book = self.hand.add_book(book);

        if let Some(completed_book) = completed_book {
            self.completed_books.push(completed_book);
        }
    }

    pub(crate) fn receive_hook(&mut self, rank: Rank) -> HookResult {
        self.hand.receive_hook(rank)
    }
}

impl Game {
    /// Create a new Game of Go Fish, with the given [Deck] and number of players
    pub fn new(deck: Deck, player_count: u8) -> Game {
        debug!(?deck, player_count, "Creating new Game");
        let hand_size = match player_count {
            2 | 3 => 7,
            _ => 5,
        };

        let mut players: Vec<Player> = vec![];
        let mut deck = deck;
        for n in 0..player_count {
            let player = Self::deal_player(PlayerId(n), hand_size, &mut deck);
            players.push(player);
        }

        Game {
            deck,
            players,
            is_finished: false,
            inactive_players: vec![],
            player_turn: 0,
        }
    }

    /// Take a turn in the game
    pub fn take_turn(&mut self, hook: Hook) -> Result<HookOutcome, TurnError> {
        debug!(game.players = ?self.players,
            game.inactive_players = ?self.inactive_players,
            game.is_deck_empty = self.deck.is_empty(),
            game.player_turn = self.player_turn,
            game.is_finished = self.is_finished,
            ?hook,
            "Taking turn");
        if self.is_finished {
            warn!("Taking turn when game is finished");
            return Err(TurnError::GameIsFinished);
        }

        let player_order = self.players.iter().map(|p| p.id).collect::<Vec<PlayerId>>();

        let (mut fisher, target) =
            Self::find_hook_players(&mut self.players, self.player_turn, hook.target);
        let fisher_id = fisher.id;

        let mut target = match target {
            Some(target) => target,
            None => {
                self.players.push(fisher);
                Self::reorder_players(&mut self.players, &player_order);
                debug!(hook.target = hook.target.0, "Target player was not found");
                return Err(TurnError::TargetNotFound(hook.target));
            }
        };

        let result = target.receive_hook(hook.rank);
        debug!(?target, ?hook, ?result, "Target received hook");

        match result.clone() {
            HookResult::Catch(catch) => {
                fisher.add_book(catch);
                let fisher = match fisher.hand.books.is_empty() {
                    true => Self::handle_active_player_has_empty_hand(fisher, &mut self.deck),
                    false => PlayerEmptyHandOutcome::Active(fisher),
                };

                debug!(?fisher, "Handled fisher hand state");
                match fisher {
                    PlayerEmptyHandOutcome::Active(fisher) => {
                        self.players.push(fisher);
                        self.players.push(target);
                        Self::reorder_players(&mut self.players, &player_order);
                    }
                    PlayerEmptyHandOutcome::Inactive(fisher) => {
                        self.players.push(target);
                        Self::reorder_players(&mut self.players, &player_order);
                        self.inactive_players.push(fisher);
                        self.player_turn = match self.player_turn {
                            0 => self.players.len() - 1,
                            n => n - 1,
                        };

                        self.advance_player_turn()
                    }
                }
            }
            HookResult::GoFish => {
                let draw = self.deck.draw();
                if let Some(card) = draw {
                    fisher.add_book(card.into())
                }

                self.players.push(fisher);
                self.players.push(target);
                Self::reorder_players(&mut self.players, &player_order);
                self.advance_player_turn()
            }
        };

        if self.players.is_empty() {
            self.is_finished = true;
        }

        debug!(game.players = ?self.players,
            game.inactive_players = ?self.inactive_players,
            game.is_deck_empty = self.deck.is_empty(),
            game.player_turn = self.player_turn,
            game.is_finished = self.is_finished,
            "Finished taking turn");

        Ok(HookOutcome { fisher: fisher_id, target: hook.target, rank: hook.rank, result })
    }

    /// Get the current player
    pub fn get_current_player(&self) -> Option<&Player> {
        if self.is_finished {
            return None;
        }
        if self.players.is_empty() {
            warn!("Current game has no current player, is not finished");
            return None;
        }

        let player = self.players.get(self.player_turn);
        if player.is_none() {
            warn!(player_turn = self.player_turn, players = ?self.players, "player_turn index is out of bounds");
        }

        player
    }

    pub fn get_game_result(&self) -> Option<GameResult> {
        if !self.is_finished {
            return None;
        }

        let max_books = self.inactive_players.iter().map(|p| p.completed_books.len()).max().unwrap();
        let mut winners = vec![];
        let mut losers = vec![];
        for player in self.inactive_players.clone().into_iter() {
            if player.completed_books.len() == max_books {
                winners.push(player);
            } else {
                losers.push(player);
            }
        };
        Some(GameResult { winners, losers })
    }

    fn deal_player(id: PlayerId, hand_size: usize, deck: &mut Deck) -> Player {
        let mut hand = Hand::empty();
        let mut completed_books = vec![];

        for _ in 0..hand_size {
            let draw = deck.draw();
            let book = IncompleteBook::from(draw.unwrap());
            let completed_book = hand.add_book(book);
            if let Some(c) = completed_book {
                completed_books.push(c);
            }
        }

        Player {
            id,
            hand,
            completed_books,
        }
    }

    fn advance_player_turn(&mut self) {
        if self.players.is_empty() {
            return;
        }

        if self.players.len() == 1 {
            let player = self.players.remove(0);
            if !player.hand.books.is_empty() {
                panic!("Shouldn't get here I don't think")
            }
            let player = InactivePlayer { id: player.id, completed_books: player.completed_books };
            self.inactive_players.push(player);
            return;
        }

        let mut new_turn = (self.player_turn + 1) % self.players.len();
        let player_order = self.players.iter().map(|p| p.id).collect::<Vec<PlayerId>>();

        for _ in 1..self.players.len() {
            let current_player = self.players.remove(new_turn);
            let result = match current_player.hand.books.is_empty() {
                true => Self::handle_active_player_has_empty_hand(current_player, &mut self.deck),
                false => PlayerEmptyHandOutcome::Active(current_player),
            };
            let found_new_player = match result {
                PlayerEmptyHandOutcome::Active(player) => {
                    self.players.push(player);
                    Self::reorder_players(&mut self.players, &player_order);
                    true
                }
                PlayerEmptyHandOutcome::Inactive(player) => {
                    self.inactive_players.push(player);
                    Self::reorder_players(&mut self.players, &player_order);
                    false
                }
            };

            if found_new_player {
                break;
            }

            new_turn = (new_turn + 1) % self.players.len();
        }

        if self.players.len() == 1 {
            let player = self.players.remove(0);
            if !player.hand.books.is_empty() {
                panic!("Shouldn't get here I don't think")
            }
            let player = InactivePlayer { id: player.id, completed_books: player.completed_books };
            self.inactive_players.push(player);
            return;
        }

        self.player_turn = new_turn;
    }

    fn handle_active_player_has_empty_hand(
        mut player: Player,
        deck: &mut Deck,
    ) -> PlayerEmptyHandOutcome {
        let draw = deck.draw();
        match draw {
            Some(card) => {
                player.add_book(IncompleteBook::from(card));
                PlayerEmptyHandOutcome::Active(player)
            }
            None => PlayerEmptyHandOutcome::Inactive(InactivePlayer {
                id: player.id,
                completed_books: player.completed_books,
            }),
        }
    }

    fn find_hook_players(
        players: &mut Vec<Player>,
        current_player_index: usize,
        target_id: PlayerId,
    ) -> (Player, Option<Player>) {
        let fisher = players.remove(current_player_index);

        let target_index = players.iter().position(|p| p.id == target_id);
        let target = match target_index {
            Some(index) => players.remove(index),
            None => return (fisher, None),
        };

        (fisher, Some(target))
    }

    fn reorder_players(players: &mut [Player], order: &[PlayerId]) {
        players.sort_by_key(|p| order.iter().position(|pos| &p.id == pos).unwrap());
    }
}

#[derive(Debug)]
pub(crate) enum CombineBookResult {
    Combined(IncompleteBook),
    NotCombined(IncompleteBook, IncompleteBook),
    Completed(CompleteBook),
}

#[derive(Debug)]
enum PlayerEmptyHandOutcome {
    Active(Player),
    Inactive(InactivePlayer),
}

#[cfg(feature = "bots")]
pub mod bots;

#[cfg(test)]
mod game_tests;