summaryrefslogtreecommitdiff
path: root/protocol/src/bridge_engine.rs
blob: a11eda42bebaca97bd6efcfbbc11f9fb2724c2a4 (plain)
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
use crate::card::{Card, Deal, Suit, RankOrder};
use serde::{Deserialize, Serialize};
use anyhow::{anyhow, bail};
use log::{error, info};
use regex::Regex;
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;
use strum::{EnumCount, IntoEnumIterator};
use strum_macros::{EnumCount as EnumCountMacro, EnumIter, FromRepr};

pub const SUIT_DISPLAY_ORDER: [Suit; 4] = [Suit::Diamond, Suit::Club, Suit::Heart, Suit::Spade];

#[derive(PartialEq, Eq, Clone, Copy, Debug, FromRepr, EnumCountMacro, Serialize, Deserialize, EnumIter)]
#[repr(u8)]
pub enum Player {
    West = 0,
    North,
    East,
    South,
}

impl Player {
    pub fn next(&self) -> Self {
        self.many_next(1)
    }

    pub fn many_next(self, i: usize) -> Self {
        Player::from_repr(((self as usize + i) % Player::COUNT) as u8).unwrap()
    }

    pub fn short_str(&self) -> &str {
        match self {
            Self::West => "W",
            Self::North => "N",
            Self::East => "E",
            Self::South => "W",
        }
    }

    pub fn get_cards<'a>(&self, deal: &'a Deal) -> &'a Vec<Card> {
        match self {
            Self::West => &deal.west,
            Self::North => &deal.north,
            Self::East => &deal.east,
            Self::South => &deal.south,
        }
    }

    pub fn get_cards_mut<'a>(&self, deal: &'a mut Deal) -> &'a mut Vec<Card> {
        match self {
            Self::West => &mut deal.west,
            Self::North => &mut deal.north,
            Self::East => &mut deal.east,
            Self::South => &mut deal.south,
        }
    }
}

#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
pub struct Trick {
    pub leader: Player,
    pub cards_played: Vec<Card>,
}

impl Trick {
    pub fn winner(&self) -> Player {
        error!("XXX: Returning incorrect result for winner");
        self.leader
    }
}

#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
pub struct TurnInPlay {
    trick: Trick,
}

#[derive(PartialEq, Eq, Debug)]
pub enum TurnInPlayResult {
    InProgress(TurnInPlay),
    Trick(Trick),
}

impl TurnInPlay {
    pub fn new(p: Player) -> TurnInPlay {
        TurnInPlay {
            trick: Trick {
                leader: p,
                cards_played: Vec::with_capacity(4),
            },
        }
    }

    pub fn suit(&self) -> Option<Suit> {
        self.trick
            .cards_played
            .iter()
            .next()
            .map(|&Card(suit, _)| suit)
    }

    pub fn leader(&self) -> Player {
        self.trick.leader
    }

    pub fn cards_played(&self) -> &[Card] {
        &self.trick.cards_played[..]
    }

    pub fn play(mut self: TurnInPlay, card: Card) -> TurnInPlayResult {
        self.trick.cards_played.push(card);
        if self.trick.cards_played.len() >= 4 {
            return TurnInPlayResult::Trick(self.trick);
        }
        TurnInPlayResult::InProgress(self)
    }

    pub fn next_player(&self) -> Player {
        self.trick.leader.many_next(self.trick.cards_played.len())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct DealInPlay {
    deal: Deal,
    tricks_played: Vec<Trick>,
    in_progress: TurnInPlay,
}

#[derive(Debug)]
pub enum DealInPlayResult {
    InProgress(DealInPlay),
    PlayFinished(Vec<Trick>),
}

impl DealInPlay {
    pub fn new(leader: Player, deal: Deal) -> DealInPlay {
        DealInPlay {
            deal,
            tricks_played: Vec::with_capacity(13),
            in_progress: TurnInPlay::new(leader),
        }
    }

    pub fn tricks(&self) -> &Vec<Trick> {
        &self.tricks_played
    }

    pub fn trick_in_play(&self) -> &TurnInPlay {
        &self.in_progress
    }

    pub fn deal(&self) -> &Deal {
        &self.deal
    }

    pub fn play(mut self: Self, card: Card) -> Result<DealInPlayResult, anyhow::Error> {
        let player = self.in_progress.next_player();
        let player_cards = player.get_cards_mut(&mut self.deal);

        info!(
            "Next player is {:?}, playing card {} from {:?}",
            player, card, player_cards
        );
        let i = player_cards.iter().position(|&c| c == card).ok_or(anyhow!(
            "{:?} does not have {}",
            player,
            card
        ))?;
        player_cards.remove(i);

        Ok(match self.in_progress.play(card) {
            TurnInPlayResult::InProgress(turn) => DealInPlayResult::InProgress(Self {
                in_progress: turn,
                ..self
            }),
            TurnInPlayResult::Trick(trick) => DealInPlayResult::InProgress(Self {
                in_progress: TurnInPlay::new(trick.winner()),
                tricks_played: {
                    let mut tricks = self.tricks_played;
                    tricks.push(trick);
                    tricks
                },
                deal: self.deal,
            }),
        })
    }
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, EnumIter, Serialize, Deserialize)]
pub enum ContractLevel {
    One = 1,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
}

impl fmt::Display for ContractLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "{}", *self as u8)
    }
}

impl fmt::Debug for ContractLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "{}", self)
    }
}

impl FromStr for ContractLevel {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> std::result::Result<Self, <Self as std::str::FromStr>::Err> {
        match s {
            "1" => Ok(ContractLevel::One),
            "2" => Ok(ContractLevel::Two),
            "3" => Ok(ContractLevel::Three),
            "4" => Ok(ContractLevel::Four),
            "5" => Ok(ContractLevel::Five),
            "6" => Ok(ContractLevel::Six),
            "7" => Ok(ContractLevel::Seven),
            _ => Err(anyhow!("invalid string: {}", s)),
        }
    }
}

#[derive(PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum Bid {
    Pass,
    Double,
    Redouble,
    Raise(Raise),
}

impl Bid {
    pub fn as_raise(&self) -> Option<Raise> {
        match self {
            Bid::Raise(raise) => Some(*raise),
            _ => None,
        }
    }
}

impl fmt::Display for Bid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Bid::Pass => write!(f, "Pass"),
            Bid::Double => write!(f, "Double"),
            Bid::Redouble => write!(f, "Redouble"),
            Bid::Raise(x) => write!(f, "{}", x),
        }
    }
}

impl fmt::Debug for Bid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Bid::Pass => write!(f, "Pass"),
            Bid::Double => write!(f, "Double"),
            Bid::Redouble => write!(f, "Redouble"),
            Bid::Raise(x) => write!(f, "Raise({})", x),
        }
    }
}

impl FromStr for Bid {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> std::result::Result<Self, <Self as std::str::FromStr>::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "pass" => Ok(Bid::Pass),
            "double" => Ok(Bid::Double),
            "redouble" => Ok(Bid::Redouble),
            x => Ok(Bid::Raise(x.parse()?)),
        }
    }
}

#[derive(PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub struct Raise {
    pub level: ContractLevel,
    pub suit: Option<Suit>,
}

impl Raise {
    pub fn all_raises() -> Vec<Raise> {
        let mut result = Vec::with_capacity(7 * 5);
        for level in ContractLevel::iter() {
            for suit in Suit::iter() {
                result.push(Raise {
                    level,
                    suit: Some(suit),
                });
            }
            result.push(Raise { level, suit: None });
        }
        result
    }
}

impl PartialOrd<Self> for Raise {
    fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
        if self.level != o.level {
            return self.level.partial_cmp(&o.level);
        }
        if self.suit != o.suit {
            if self.suit == None {
                return Some(Ordering::Greater);
            }
            if o.suit == None {
                return Some(Ordering::Less);
            }
            return self.suit.partial_cmp(&o.suit);
        }
        return Some(Ordering::Equal);
    }
}

impl Ord for Raise {
    fn cmp(&self, o: &Self) -> std::cmp::Ordering {
        self.partial_cmp(o).unwrap()
    }
}

impl fmt::Display for Raise {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(
            f,
            "{}{}",
            self.level,
            self.suit
                .map_or("NT".to_string(), |suit| format!("{}", suit))
        )
    }
}

impl fmt::Debug for Raise {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "{}", self)
    }
}

impl FromStr for Raise {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> std::result::Result<Self, <Self as std::str::FromStr>::Err> {
        lazy_static::lazy_static! {
            static ref RE: Regex = Regex::new(r#"\s*(.[0-9]*)\s*(.*)"#).unwrap();
        };
        let caps = RE.captures(s).ok_or(anyhow!("invalid raise: {}", s))?;
        info!("caps: {:?}", caps);
        let level = caps[1].parse()?;
        let suit = match caps[2].to_ascii_uppercase().as_str() {
            "NT" => None,
            x => Some(x.parse()?),
        };
        Ok(Raise { level, suit })
    }
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
pub enum ContractModifier {
    None,
    Doubled,
    Redoubled,
}

impl fmt::Display for ContractModifier {
    fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
        match self {
            ContractModifier::None => Ok(()),
            ContractModifier::Doubled => write!(f, "x"),
            ContractModifier::Redoubled => write!(f, "xx"),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
pub struct Contract {
    declarer: Player,
    highest_bid: Raise,
    modifier: ContractModifier,
}

impl fmt::Display for Contract {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), fmt::Error> {
        write!(
            f,
            "{}{}{}",
            self.highest_bid,
            self.declarer.short_str(),
            self.modifier
        )
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct Bidding {
    pub dealer: Player,
    pub bids: Vec<Bid>,
}

impl Bidding {
    pub fn new(dealer: Player) -> Bidding {
        Bidding {
            dealer,
            bids: vec![],
        }
    }

    fn declarer(&self) -> Player {
        // Bids are: [..., winning bid, pass, pass, pass].
        self.dealer.many_next(self.bids.len() - 4)
    }

    pub fn highest_bid(&self) -> Option<Raise> {
        for bid in self.bids.iter().rev() {
            if let Some(raise) = bid.as_raise() {
                return Some(raise);
            }
        }
        None
    }

    fn passed_out(&self) -> bool {
        let mut passes = 0;
        for b in self.bids.iter().rev().take(3) {
            if b == &Bid::Pass {
                passes += 1
            }
        }
        passes == 3
    }

    fn contract(&self) -> Option<Contract> {
        match self.highest_bid() {
            None => None,
            Some(highest_bid) => Some(Contract {
                declarer: self.declarer(),
                highest_bid,
                modifier: ContractModifier::None,
            }),
        }
    }

    pub fn bid(mut self, bid: Bid) -> Result<BiddingResult, anyhow::Error> {
        // TODO: Need logic for double and redouble here.
        if bid.as_raise().is_some() && bid.as_raise() <= self.highest_bid() {
            bail!(
                "bid too low: {:?} <= {:?}",
                bid.as_raise(),
                self.highest_bid()
            );
        }
        self.bids.push(bid);
        if self.passed_out() {
            Ok(BiddingResult::Contract(self.contract(), self))
        } else {
            Ok(BiddingResult::InProgress(self))
        }
    }
}

#[derive(Debug, Clone)]
pub enum BiddingResult {
    InProgress(Bidding),
    Contract(Option<Contract>, Bidding),
}

impl BiddingResult {
    pub fn new(dealer: Player) -> Self {
        BiddingResult::InProgress(Bidding::new(dealer))
    }

    pub fn bidding(&self) -> &Bidding {
        match self {
            BiddingResult::InProgress(bidding) => bidding,
            BiddingResult::Contract(_, bidding) => bidding,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum GameState {
    Bidding {
        dealer: Player,
        deal: Deal,
    },
    PassedOut {
        dealer: Player,
        deal: Deal,
        bidding: Bidding,
    },
    Play {
        dealer: Player,
        playing_deal: DealInPlay,
        contract: Contract,
        bidding: Bidding,
    },
}

impl GameState {
    pub fn deal(&self) -> &Deal {
        match self {
            Self::Bidding { deal, .. } => deal,
            Self::PassedOut { deal, .. } => deal,
            Self::Play { playing_deal, .. } => &playing_deal.deal(),
        }
    }

    pub fn dealer(&self) -> Player {
        match *self {
            Self::Bidding { dealer, .. } => dealer,
            Self::PassedOut { dealer, .. } => dealer,
            Self::Play { dealer, .. } => dealer,
        }
    }
}

pub fn deal() -> Deal {
    let mut rng = rand::thread_rng();
    let mut deal = crate::card::deal(&mut rng);
    deal.sort(&SUIT_DISPLAY_ORDER, RankOrder::Descending);
    deal
}

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
pub struct TableView {
    pub dealer: Player,
    pub player_position: Player,
    pub hand: Vec<Card>,
}

impl TableView {
    pub fn from_game_state(game_state: &GameState, player_position: Player) -> Self {
        TableView {
            dealer: game_state.dealer(),
            player_position,
            hand: player_position.get_cards(game_state.deal()).clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use log::info;

    fn as_bidding(r: BiddingResult) -> Bidding {
        match r {
            BiddingResult::InProgress(bidding) => bidding,
            _ => panic!("expected BiddingResult::InProgress(): {:?}", r),
        }
    }

    fn as_contract(r: BiddingResult) -> Option<Contract> {
        match r {
            BiddingResult::Contract(contract, _) => contract,
            _ => panic!("expected BiddingResult::Contract(): {:?}", r),
        }
    }

    #[test]
    fn bidding() {
        crate::tests::test_setup();
        let bidding = Bidding::new(Player::South);
        let bidding = as_bidding(bidding.bid(Bid::Pass).unwrap());
        let bidding = as_bidding(bidding.bid(Bid::Raise("1♦".parse().unwrap())).unwrap());
        let bidding = as_bidding(bidding.bid(Bid::Pass).unwrap());
        let bidding = as_bidding(bidding.bid(Bid::Pass).unwrap());
        let contract = as_contract(bidding.bid(Bid::Pass).unwrap());
        assert_eq!(
            Some(Contract {
                declarer: Player::West,
                highest_bid: "1♦".parse().unwrap(),
                modifier: ContractModifier::None
            }),
            contract
        );
    }

    #[test]
    fn bid_conversion() {
        crate::tests::test_setup();
        let bid1d = Raise {
            level: ContractLevel::One,
            suit: Some(Suit::Diamond),
        };
        assert_eq!("1♢", format!("{}", bid1d));
        assert_eq!("1♢", format!("{:?}", bid1d));
        assert_eq!(bid1d, Raise::from_str("1D").unwrap());

        assert_eq!(Bid::Pass, Bid::from_str("pass").unwrap());

        let mut checked_raises = 0;
        for bid in Raise::all_raises() {
            assert_eq!(bid, Raise::from_str(format!("{}", bid).as_str()).unwrap());
            assert_eq!(
                Bid::Raise(bid),
                Bid::from_str(format!("{}", bid).as_str()).unwrap()
            );
            checked_raises += 1;
        }
        assert_eq!(checked_raises, 35);
    }

    #[test]
    fn fmt_contract() {
        assert_eq!(
            format!(
                "{}",
                Contract {
                    declarer: Player::West,
                    highest_bid: "1♥".parse().unwrap(),
                    modifier: ContractModifier::None
                }
            ),
            "1♡W"
        );

        assert_eq!(
            format!(
                "{}",
                Contract {
                    declarer: Player::East,
                    highest_bid: "1♥".parse().unwrap(),
                    modifier: ContractModifier::Doubled
                }
            ),
            "1♡Ex"
        );
    }

    #[test]
    fn bid_ord() {
        let bid = |s| Raise::from_str(s).unwrap();
        assert!(bid("2♦") < bid("3♦"));
        assert!(bid("3♦") < bid("3♥"));
        assert!(bid("1♠") < bid("2♣"));
        assert!(bid("1♠") < bid("1NT"));
        for bid in Raise::all_raises() {
            assert_eq!(bid, bid);
        }
    }

    #[test]
    fn contract_level_conversion() {
        crate::tests::test_setup();
        assert_eq!("2", format!("{}", ContractLevel::Two));
        assert_eq!("3", format!("{:?}", ContractLevel::Three));

        let result = ContractLevel::from_str("8");
        info!("{:?}", result);
        assert!(result.unwrap_err().to_string().contains("invalid"));
        assert_eq!(ContractLevel::Seven, "7".parse().unwrap());
    }

    #[test]
    fn next_player() {
        let next_players = vec![Player::North, Player::East, Player::South, Player::West]
            .iter()
            .map(Player::next)
            .collect::<Vec<_>>();
        assert_eq!(
            next_players,
            vec![Player::East, Player::South, Player::West, Player::North]
        );
    }

    #[test]
    fn many_next_player() {
        assert_eq!(Player::South, Player::South.many_next(4 * 1234567890));
    }

    fn as_turn(p: TurnInPlayResult) -> TurnInPlay {
        if let TurnInPlayResult::InProgress(t) = p {
            t
        } else {
            panic!("expected PlayResult::InProgress(): {:?}", p);
        }
    }

    fn as_trick(p: TurnInPlayResult) -> Trick {
        if let TurnInPlayResult::Trick(t) = p {
            t
        } else {
            panic!("expected PlayResult::Trick(): {:?}", p);
        }
    }

    #[test]
    fn play_turn() {
        let turn = TurnInPlay::new(Player::South);
        assert_eq!(turn.next_player(), Player::South);
        let turn = as_turn(turn.play("♣4".parse().unwrap()));
        assert_eq!(turn.next_player(), Player::West);
        let turn = as_turn(turn.play("♥A".parse().unwrap()));
        assert_eq!(turn.next_player(), Player::North);
        let turn = as_turn(turn.play("♣4".parse().unwrap()));
        assert_eq!(turn.next_player(), Player::East);
        let trick = as_trick(turn.play("♣A".parse().unwrap()));
        assert_eq!(
            trick,
            Trick {
                leader: Player::South,
                cards_played: ["♣4", "♥A", "♣4", "♣A"]
                    .into_iter()
                    .map(|c| c.parse().unwrap())
                    .collect()
            }
        );
    }

    #[test]
    fn lead_suit() {
        let turn = TurnInPlay::new(Player::South);
        assert_eq!(turn.suit(), None);
        let turn = as_turn(turn.play("♣4".parse().unwrap()));
        assert_eq!(turn.suit(), Some("♣".parse().unwrap()));
    }

    fn mkcard(s: &str) -> Card {
        Card::from_str(s).unwrap()
    }

    fn mkcards(s: &str) -> Vec<Card> {
        s.split(" ").map(mkcard).collect()
    }

    fn _example_deal() -> Deal {
        Deal {
            west: mkcards("♠5 ♢10 ♡K ♣4 ♡J ♣5 ♢5 ♠9 ♢3 ♠2 ♣2 ♡4 ♠Q"),
            north: mkcards("♢Q ♡9 ♠7 ♠8 ♠A ♡A ♡5 ♠6 ♢9 ♣3 ♡3 ♣9 ♢J"),
            east: mkcards("♣10 ♡7 ♢A ♣6 ♡8 ♣Q ♠K ♡10 ♣K ♠3 ♡Q ♣J ♢4"),
            south: mkcards("♢K ♡6 ♣8 ♢6 ♢7 ♢8 ♣A ♡2 ♣7 ♠10 ♠4 ♠J ♢2"),
        }
    }

    fn mini_deal() -> Deal {
        Deal {
            west: mkcards("♢A ♡Q"),
            north: mkcards("♢Q ♡9"),
            east: mkcards("♢7 ♡K"),
            south: mkcards("♢9 ♠9"),
        }
    }

    #[test]
    fn table_view() {
        crate::tests::test_setup();
        let game_state = GameState::Bidding { dealer: Player::East, deal: mini_deal() };
        info!("Game state: {game_state:?}");
        for p in Player::iter() {
            info!("Testing view for {p:?}");
            let view = TableView::from_game_state(&game_state, p);
            assert_eq!(view.player_position, p);
            assert_eq!(view.dealer, Player::East);
            assert_eq!(&view.hand, p.get_cards_mut(&mut mini_deal()));
        }
    }

    fn as_playing_hand(result: DealInPlayResult) -> DealInPlay {
        match result {
            DealInPlayResult::InProgress(r) => r,
            DealInPlayResult::PlayFinished(_) => {
                panic!("expected PlayingDealResult::InProgress(): {:?}", result)
            }
        }
    }

    #[test]
    fn play_hand() {
        let deal = DealInPlay::new(Player::West, mini_deal());
        assert_eq!(deal.tricks_played, vec!());
        {
            let err = deal.clone().play(mkcard("♥9")).unwrap_err().to_string();
            assert_eq!(err, "West does not have ♡9");
        }

        let deal = as_playing_hand(deal.play(mkcard("♢A")).unwrap());
        assert_eq!(deal.in_progress.trick.cards_played, vec!(mkcard("♢A")));

        let deal = as_playing_hand(deal.play(mkcard("♢Q")).unwrap());
        let deal = as_playing_hand(deal.play(mkcard("♥K")).unwrap());
        let deal = as_playing_hand(deal.play(mkcard("♢9")).unwrap());
        assert_eq!(deal.in_progress.trick.cards_played, []);
        assert_eq!(
            deal.tricks_played,
            vec!(Trick {
                leader: Player::West,
                cards_played: mkcards("♢A ♢Q ♡K ♢9"),
            })
        );
    }
}