go-fish 0.1.1

The classic Go Fish card game
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
//! # go-fish
//!
//! `go-fish` is a library providing core functionality for the classic [Go Fish card game](https://en.wikipedia.org/wiki/Go_Fish).

use enum_iterator::{all, Sequence};
use rand::prelude::SliceRandom;
use serde::{Deserialize, Serialize};

/// 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, Sequence, Clone, Copy, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Rank {
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
    Ace,
}

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

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

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

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

/// A player actively trying to win the game
#[derive(Debug, Serialize, Deserialize)]
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)]
pub struct InactivePlayer {
    pub id: PlayerId,
    pub completed_books: Vec<CompleteBook>,
}

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

/// 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),
}

/// 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>,
    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
    pub fn shuffle(&mut self) {
        let mut rng = rand::rng();
        self.cards.shuffle(&mut rng);
    }

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

    /// 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 }
    }
}

pub(crate) enum HookResult {
    Catch(IncompleteBook),
    GoFish,
}

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.swap_remove(position);
        let combined_result = existing_book.combine(book);

        match combined_result {
            CombineBookResult::NotCombined(a, b) => {
                panic!(
                    "Books {:?} and {:?} failed to combine, but we expect them to have the same rank",
                    a, b
                )
            }
            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.swap_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 {
        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,
            inactive_players: vec![],
            player_turn: 0,
        }
    }

    /// Take a turn in the game
    pub fn take_turn(&mut self, hook: Hook) -> Result<(), TurnError> {
        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 mut target = match target {
            Some(target) => target,
            None => {
                self.players.push(fisher);
                Self::reorder_players(&mut self.players, &player_order);
                return Err(TurnError::TargetNotFound(hook.target));
            }
        };

        let result = target.receive_hook(hook.rank);

        match result {
            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),
                };

                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()
            }
        };

        Ok(())
    }

    /// Get the current player
    pub fn get_current_player(&self) -> &Player {
        &self.players[self.player_turn]
    }

    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;
        }
        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.swap_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();
        }

        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.swap_remove(current_player_index);

        let target_index = players.iter().position(|p| p.id == target_id);
        let target = match target_index {
            Some(index) => players.swap_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());
    }
}

pub(crate) enum CombineBookResult {
    Combined(IncompleteBook),
    NotCombined(IncompleteBook, IncompleteBook),
    Completed(CompleteBook),
}

enum PlayerEmptyHandOutcome {
    Active(Player),
    Inactive(InactivePlayer),
}

#[cfg(test)]
mod game_tests;