piech 0.1.0

A hidden-information Daifugo engine for human and humanoid players
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
//! A deterministic, hidden-information Daifugo engine for humans and humanoids.
//!
//! `piech` gives every controller the same observation/action interface. A
//! [`PlayerView`] exposes the requesting player's hand, public pile state,
//! opponent hand counts, and legal actions—never opponents' cards.
//!
//! Version 0.1 models singles and same-rank groups, optional joker wildcards,
//! revolution, eight-cut, and spade-three-over-joker. Daifugo has many regional
//! rules; unsupported rules such as straights and suit lock are intentionally
//! not inferred.
//!
//! # Example
//!
//! ```
//! use piech::{Action, Controller, Game, Player, Rules};
//!
//! let players = [
//!     Player::new("us", Controller::Human)?,
//!     Player::new("robot", Controller::Humanoid)?,
//! ];
//! let mut game = Game::deal(players, piech::standard_deck(1)?, Rules::default())?;
//! let current = game.current_player_id().unwrap().to_owned();
//! let action = game.view_for(&current)?.legal_actions()[0].clone();
//! game.apply(&current, action)?;
//! # let _ = Action::Pass;
//! # Ok::<(), piech::Error>(())
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::collections::BTreeSet;
use std::error::Error as StdError;
use std::fmt;

/// A standard French-suited card suit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Suit {
    /// Clubs.
    Clubs,
    /// Diamonds.
    Diamonds,
    /// Hearts.
    Hearts,
    /// Spades.
    Spades,
}

/// Daifugo rank order before revolution: 3 is lowest and 2 is highest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Rank {
    /// Three.
    Three = 0,
    /// Four.
    Four = 1,
    /// Five.
    Five = 2,
    /// Six.
    Six = 3,
    /// Seven.
    Seven = 4,
    /// Eight.
    Eight = 5,
    /// Nine.
    Nine = 6,
    /// Ten.
    Ten = 7,
    /// Jack.
    Jack = 8,
    /// Queen.
    Queen = 9,
    /// King.
    King = 10,
    /// Ace.
    Ace = 11,
    /// Two.
    Two = 12,
}

impl Rank {
    const ALL: [Self; 13] = [
        Self::Three,
        Self::Four,
        Self::Five,
        Self::Six,
        Self::Seven,
        Self::Eight,
        Self::Nine,
        Self::Ten,
        Self::Jack,
        Self::Queen,
        Self::King,
        Self::Ace,
        Self::Two,
    ];

    /// Returns ordinary strength from 0 (three) through 12 (two).
    pub const fn strength(self) -> u8 {
        self as u8
    }
}

/// A unique suited card or numbered joker.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Card {
    /// A suited rank.
    Suited {
        /// Card suit.
        suit: Suit,
        /// Card rank.
        rank: Rank,
    },
    /// A joker identified by a zero-based number.
    Joker(u8),
}

impl Card {
    /// Creates a suited card.
    pub const fn suited(suit: Suit, rank: Rank) -> Self {
        Self::Suited { suit, rank }
    }

    /// Returns the rank for a suited card.
    pub const fn rank(self) -> Option<Rank> {
        match self {
            Self::Suited { rank, .. } => Some(rank),
            Self::Joker(_) => None,
        }
    }

    /// Returns whether this is the three of spades.
    pub const fn is_spade_three(self) -> bool {
        matches!(
            self,
            Self::Suited {
                suit: Suit::Spades,
                rank: Rank::Three
            }
        )
    }
}

/// Builds an ordered 52-card deck followed by `joker_count` unique jokers.
///
/// The returned deck is not shuffled. Callers should shuffle it using their
/// chosen random or reproducible source before [`Game::deal`].
pub fn standard_deck(joker_count: u8) -> Result<Vec<Card>, Error> {
    if joker_count > 2 {
        return Err(Error::TooManyJokers(joker_count));
    }
    let mut deck = Vec::with_capacity(52 + usize::from(joker_count));
    for suit in [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades] {
        for rank in Rank::ALL {
            deck.push(Card::suited(suit, rank));
        }
    }
    for index in 0..joker_count {
        deck.push(Card::Joker(index));
    }
    Ok(deck)
}

/// Who controls a player seat.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Controller {
    /// A human-facing controller.
    Human,
    /// A humanoid or software-agent controller.
    Humanoid,
}

/// A public player seat definition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Player {
    id: String,
    controller: Controller,
}

impl Player {
    /// Creates a player with a non-empty stable ID.
    pub fn new(id: impl Into<String>, controller: Controller) -> Result<Self, Error> {
        let id = id.into();
        if id.trim().is_empty() {
            return Err(Error::EmptyPlayerId);
        }
        Ok(Self { id, controller })
    }

    /// Returns the player ID.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns the controller kind.
    pub const fn controller(&self) -> Controller {
        self.controller
    }
}

/// Configurable rules supported by this engine version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rules {
    /// A four-card group toggles rank order.
    pub revolution: bool,
    /// A group of eights clears the trick immediately.
    pub eight_cut: bool,
    /// A lone three of spades beats a lone joker.
    pub spade_three_over_joker: bool,
    /// Jokers may substitute in same-rank groups.
    pub joker_wildcards: bool,
}

impl Default for Rules {
    fn default() -> Self {
        Self {
            revolution: true,
            eight_cut: true,
            spade_three_over_joker: true,
            joker_wildcards: true,
        }
    }
}

/// An analyzed single or same-rank group.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Meld {
    cards: Vec<Card>,
    effective_rank: Option<Rank>,
    lone_joker: bool,
}

impl Meld {
    /// Analyzes one through four cards under the supplied rules.
    pub fn analyze(cards: impl IntoIterator<Item = Card>, rules: Rules) -> Result<Self, Error> {
        let mut cards: Vec<_> = cards.into_iter().collect();
        cards.sort_unstable();
        if cards.is_empty() || cards.len() > 4 {
            return Err(Error::InvalidMeldSize(cards.len()));
        }
        if cards.windows(2).any(|pair| pair[0] == pair[1]) {
            return Err(Error::DuplicateCardInAction);
        }
        let jokers = cards
            .iter()
            .filter(|card| matches!(card, Card::Joker(_)))
            .count();
        if cards.len() == 1 && jokers == 1 {
            return Ok(Self {
                cards,
                effective_rank: None,
                lone_joker: true,
            });
        }
        if jokers > 0 && !rules.joker_wildcards {
            return Err(Error::JokerWildcardDisabled);
        }
        let ranks: BTreeSet<_> = cards.iter().filter_map(|card| card.rank()).collect();
        if ranks.len() != 1 {
            return Err(Error::MixedRanks);
        }
        let effective_rank = ranks.iter().next().copied().ok_or(Error::AllJokerGroup)?;
        Ok(Self {
            cards,
            effective_rank: Some(effective_rank),
            lone_joker: false,
        })
    }

    /// Returns cards in stable order.
    pub fn cards(&self) -> &[Card] {
        &self.cards
    }

    /// Returns the number of cards.
    pub fn size(&self) -> usize {
        self.cards.len()
    }

    /// Returns the group rank, or `None` for a lone joker.
    pub const fn effective_rank(&self) -> Option<Rank> {
        self.effective_rank
    }

    /// Returns whether this is exactly one joker.
    pub const fn is_lone_joker(&self) -> bool {
        self.lone_joker
    }

    fn beats(&self, previous: &Self, revolution: bool, rules: Rules) -> bool {
        if self.size() != previous.size() {
            return false;
        }
        if previous.lone_joker {
            return rules.spade_three_over_joker
                && self.cards.len() == 1
                && self.cards[0].is_spade_three();
        }
        if self.lone_joker {
            return true;
        }
        let candidate = self.effective_rank.expect("non-joker meld has rank");
        let top = previous.effective_rank.expect("non-joker meld has rank");
        if revolution {
            candidate.strength() < top.strength()
        } else {
            candidate.strength() > top.strength()
        }
    }
}

/// A controller action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    /// Play one valid meld.
    Play(Vec<Card>),
    /// Pass for the remainder of the current trick.
    Pass,
}

/// Public phase of the game.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GamePhase {
    /// At least two players still hold cards.
    Playing,
    /// Every finishing position has been determined.
    Complete,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Seat {
    player: Player,
    hand: Vec<Card>,
    finished: bool,
}

/// Public information about another seat.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpponentView {
    /// Player ID.
    pub id: String,
    /// Human or humanoid controller.
    pub controller: Controller,
    /// Number of cards remaining; card identities are hidden.
    pub hand_count: usize,
    /// Whether the player has finished.
    pub finished: bool,
}

/// Information legally visible to one player controller.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlayerView {
    player_id: String,
    hand: Vec<Card>,
    opponents: Vec<OpponentView>,
    current_player_id: Option<String>,
    top_meld: Option<Meld>,
    revolution: bool,
    legal_actions: Vec<Action>,
    finish_order: Vec<String>,
}

impl PlayerView {
    /// Returns the observing player ID.
    pub fn player_id(&self) -> &str {
        &self.player_id
    }
    /// Returns only the observer's cards.
    pub fn hand(&self) -> &[Card] {
        &self.hand
    }
    /// Returns opponent metadata without hidden cards.
    pub fn opponents(&self) -> &[OpponentView] {
        &self.opponents
    }
    /// Returns whose turn it is, or `None` after completion.
    pub fn current_player_id(&self) -> Option<&str> {
        self.current_player_id.as_deref()
    }
    /// Returns the current top meld.
    pub const fn top_meld(&self) -> Option<&Meld> {
        self.top_meld.as_ref()
    }
    /// Returns whether revolution is active.
    pub const fn revolution(&self) -> bool {
        self.revolution
    }
    /// Returns legal actions only when it is this player's turn.
    pub fn legal_actions(&self) -> &[Action] {
        &self.legal_actions
    }
    /// Returns already determined finishing order.
    pub fn finish_order(&self) -> &[String] {
        &self.finish_order
    }
}

/// A human UI, humanoid controller, or software agent that chooses one action
/// from a hidden-information player view.
pub trait Agent {
    /// Controller-specific failure type.
    type Error;

    /// Chooses an action. Implementations should select from
    /// [`PlayerView::legal_actions`]. The game validates the returned action.
    fn choose_action(&mut self, view: &PlayerView) -> Result<Action, Self::Error>;
}

/// Failure while asking an [`Agent`] to take one turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StepError<E> {
    /// Game lookup, turn, or rule validation failed.
    Game(Error),
    /// The controller failed before returning an action.
    Agent(E),
}

impl<E: fmt::Display> fmt::Display for StepError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Game(error) => write!(f, "game step failed: {error}"),
            Self::Agent(error) => write!(f, "agent failed: {error}"),
        }
    }
}

impl<E> StdError for StepError<E>
where
    E: StdError + 'static,
{
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::Game(error) => Some(error),
            Self::Agent(error) => Some(error),
        }
    }
}

/// Deterministic Daifugo game state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Game {
    seats: Vec<Seat>,
    rules: Rules,
    phase: GamePhase,
    current: Option<usize>,
    pile: Option<Meld>,
    last_player: Option<usize>,
    passed: BTreeSet<usize>,
    revolution: bool,
    finish_order: Vec<usize>,
}

impl Game {
    /// Deals the supplied pre-shuffled deck round-robin to two through eight
    /// unique players. The holder of three of clubs starts when present;
    /// otherwise seat zero starts.
    pub fn deal(
        players: impl IntoIterator<Item = Player>,
        deck: impl IntoIterator<Item = Card>,
        rules: Rules,
    ) -> Result<Self, Error> {
        let players: Vec<_> = players.into_iter().collect();
        if !(2..=8).contains(&players.len()) {
            return Err(Error::InvalidPlayerCount(players.len()));
        }
        let mut ids = BTreeSet::new();
        for player in &players {
            if !ids.insert(player.id.clone()) {
                return Err(Error::DuplicatePlayerId(player.id.clone()));
            }
        }
        let deck: Vec<_> = deck.into_iter().collect();
        if deck.is_empty() {
            return Err(Error::EmptyDeck);
        }
        let unique: BTreeSet<_> = deck.iter().copied().collect();
        if unique.len() != deck.len() {
            return Err(Error::DuplicateCardInDeck);
        }
        let mut seats: Vec<_> = players
            .into_iter()
            .map(|player| Seat {
                player,
                hand: Vec::new(),
                finished: false,
            })
            .collect();
        let seat_count = seats.len();
        for (index, card) in deck.into_iter().enumerate() {
            seats[index % seat_count].hand.push(card);
        }
        for seat in &mut seats {
            seat.hand.sort_unstable();
        }
        let club_three = Card::suited(Suit::Clubs, Rank::Three);
        let current = seats
            .iter()
            .position(|seat| seat.hand.contains(&club_three))
            .unwrap_or(0);
        Ok(Self {
            seats,
            rules,
            phase: GamePhase::Playing,
            current: Some(current),
            pile: None,
            last_player: None,
            passed: BTreeSet::new(),
            revolution: false,
            finish_order: Vec::new(),
        })
    }

    /// Returns the game phase.
    pub const fn phase(&self) -> GamePhase {
        self.phase
    }

    /// Returns the current player ID.
    pub fn current_player_id(&self) -> Option<&str> {
        self.current.map(|index| self.seats[index].player.id())
    }

    /// Returns whether revolution is active.
    pub const fn revolution(&self) -> bool {
        self.revolution
    }

    /// Returns current top meld, if a trick is open.
    pub const fn top_meld(&self) -> Option<&Meld> {
        self.pile.as_ref()
    }

    /// Returns finishing player IDs in rank order.
    pub fn finish_order(&self) -> impl Iterator<Item = &str> {
        self.finish_order
            .iter()
            .map(|index| self.seats[*index].player.id())
    }

    /// Builds a hidden-information observation for one seat.
    pub fn view_for(&self, player_id: &str) -> Result<PlayerView, Error> {
        let index = self.player_index(player_id)?;
        let opponents = self
            .seats
            .iter()
            .enumerate()
            .filter(|(other, _)| *other != index)
            .map(|(_, seat)| OpponentView {
                id: seat.player.id.clone(),
                controller: seat.player.controller,
                hand_count: seat.hand.len(),
                finished: seat.finished,
            })
            .collect();
        let legal_actions = if self.current == Some(index) {
            self.legal_actions_for(index)
        } else {
            Vec::new()
        };
        Ok(PlayerView {
            player_id: player_id.to_owned(),
            hand: self.seats[index].hand.clone(),
            opponents,
            current_player_id: self.current_player_id().map(str::to_owned),
            top_meld: self.pile.clone(),
            revolution: self.revolution,
            legal_actions,
            finish_order: self.finish_order().map(str::to_owned).collect(),
        })
    }

    /// Applies one action after checking phase, turn, ownership, and rules.
    pub fn apply(&mut self, player_id: &str, action: Action) -> Result<(), Error> {
        if self.phase != GamePhase::Playing {
            return Err(Error::GameComplete);
        }
        let player = self.player_index(player_id)?;
        if self.current != Some(player) {
            return Err(Error::NotPlayersTurn(player_id.to_owned()));
        }
        match action {
            Action::Pass => self.apply_pass(player),
            Action::Play(cards) => self.apply_play(player, cards),
        }
    }

    /// Builds the current player's private view, asks its controller for an
    /// action, and validates/applies the result as one atomic turn request.
    pub fn step_with<A: Agent>(
        &mut self,
        player_id: &str,
        agent: &mut A,
    ) -> Result<(), StepError<A::Error>> {
        if self.current_player_id() != Some(player_id) {
            return Err(StepError::Game(Error::NotPlayersTurn(player_id.to_owned())));
        }
        let view = self.view_for(player_id).map_err(StepError::Game)?;
        let action = agent.choose_action(&view).map_err(StepError::Agent)?;
        self.apply(player_id, action).map_err(StepError::Game)
    }

    fn apply_play(&mut self, player: usize, cards: Vec<Card>) -> Result<(), Error> {
        let meld = Meld::analyze(cards, self.rules)?;
        for card in meld.cards() {
            if !self.seats[player].hand.contains(card) {
                return Err(Error::CardNotInHand(*card));
            }
        }
        if let Some(previous) = &self.pile
            && !meld.beats(previous, self.revolution, self.rules)
        {
            return Err(Error::MeldDoesNotBeatPile);
        }
        for card in meld.cards() {
            let position = self.seats[player]
                .hand
                .iter()
                .position(|owned| owned == card)
                .expect("ownership checked");
            self.seats[player].hand.remove(position);
        }
        let eight_cut = self.rules.eight_cut && meld.effective_rank == Some(Rank::Eight);
        let revolution = self.rules.revolution && meld.size() == 4;
        self.pile = Some(meld);
        self.last_player = Some(player);
        if revolution {
            self.revolution = !self.revolution;
        }
        if self.seats[player].hand.is_empty() {
            self.finish_player(player);
            if self.complete_if_one_remains() {
                return Ok(());
            }
        }
        if eight_cut {
            self.clear_trick_from(player);
        } else {
            self.advance_or_clear_from(player);
        }
        Ok(())
    }

    fn apply_pass(&mut self, player: usize) -> Result<(), Error> {
        if self.pile.is_none() {
            return Err(Error::CannotPassOnLead);
        }
        self.passed.insert(player);
        self.advance_or_clear_from(player);
        Ok(())
    }

    fn advance_or_clear_from(&mut self, from: usize) {
        if let Some(next) = self.next_contender_after(from) {
            self.current = Some(next);
        } else {
            let leader = self.last_player.expect("open pile has last player");
            self.clear_trick_from(leader);
        }
    }

    fn clear_trick_from(&mut self, leader: usize) {
        self.pile = None;
        self.last_player = None;
        self.passed.clear();
        self.current = if !self.seats[leader].finished {
            Some(leader)
        } else {
            self.next_active_after(leader)
        };
    }

    fn next_contender_after(&self, from: usize) -> Option<usize> {
        let leader = self.last_player?;
        (1..=self.seats.len())
            .map(|offset| (from + offset) % self.seats.len())
            .find(|index| {
                *index != leader && !self.seats[*index].finished && !self.passed.contains(index)
            })
    }

    fn next_active_after(&self, from: usize) -> Option<usize> {
        (1..=self.seats.len())
            .map(|offset| (from + offset) % self.seats.len())
            .find(|index| !self.seats[*index].finished)
    }

    fn finish_player(&mut self, player: usize) {
        if !self.seats[player].finished {
            self.seats[player].finished = true;
            self.passed.remove(&player);
            self.finish_order.push(player);
        }
    }

    fn complete_if_one_remains(&mut self) -> bool {
        let remaining: Vec<_> = self
            .seats
            .iter()
            .enumerate()
            .filter(|(_, seat)| !seat.finished)
            .map(|(index, _)| index)
            .collect();
        if remaining.len() == 1 {
            self.finish_player(remaining[0]);
            self.phase = GamePhase::Complete;
            self.current = None;
            self.pile = None;
            self.last_player = None;
            self.passed.clear();
            true
        } else {
            false
        }
    }

    fn legal_actions_for(&self, player: usize) -> Vec<Action> {
        if self.phase != GamePhase::Playing || self.seats[player].finished {
            return Vec::new();
        }
        let hand = &self.seats[player].hand;
        let mut card_sets = Vec::new();
        for size in 1..=4.min(hand.len()) {
            combinations(hand, size, 0, &mut Vec::new(), &mut card_sets);
        }
        let mut actions: Vec<_> = card_sets
            .into_iter()
            .filter_map(|cards| {
                let meld = Meld::analyze(cards.clone(), self.rules).ok()?;
                let legal = self
                    .pile
                    .as_ref()
                    .is_none_or(|previous| meld.beats(previous, self.revolution, self.rules));
                legal.then_some(Action::Play(cards))
            })
            .collect();
        if self.pile.is_some() {
            actions.push(Action::Pass);
        }
        actions
    }

    fn player_index(&self, player_id: &str) -> Result<usize, Error> {
        self.seats
            .iter()
            .position(|seat| seat.player.id == player_id)
            .ok_or_else(|| Error::UnknownPlayer(player_id.to_owned()))
    }
}

fn combinations(
    hand: &[Card],
    remaining: usize,
    start: usize,
    current: &mut Vec<Card>,
    output: &mut Vec<Vec<Card>>,
) {
    if remaining == 0 {
        output.push(current.clone());
        return;
    }
    if hand.len().saturating_sub(start) < remaining {
        return;
    }
    for index in start..=hand.len() - remaining {
        current.push(hand[index]);
        combinations(hand, remaining - 1, index + 1, current, output);
        current.pop();
    }
}

/// Game setup, action, and rule errors.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// More than two jokers were requested for a standard deck.
    TooManyJokers(u8),
    /// A player ID contained only whitespace.
    EmptyPlayerId,
    /// Player count was outside two through eight.
    InvalidPlayerCount(usize),
    /// Two seats used the same player ID.
    DuplicatePlayerId(String),
    /// The supplied deck was empty.
    EmptyDeck,
    /// The supplied deck contained the same unique card twice.
    DuplicateCardInDeck,
    /// A meld contained zero or more than four cards.
    InvalidMeldSize(usize),
    /// One action listed the same card twice.
    DuplicateCardInAction,
    /// A joker appeared in a group while wildcard use was disabled.
    JokerWildcardDisabled,
    /// A group contained multiple ordinary ranks.
    MixedRanks,
    /// A multi-card group contained only jokers and had no effective rank.
    AllJokerGroup,
    /// A requested player ID does not exist.
    UnknownPlayer(String),
    /// An action came from someone other than the current player.
    NotPlayersTurn(String),
    /// The game was already complete.
    GameComplete,
    /// A played card was not in the player's hand.
    CardNotInHand(Card),
    /// The meld did not match and beat the current pile.
    MeldDoesNotBeatPile,
    /// Passing was attempted while leading an empty trick.
    CannotPassOnLead,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooManyJokers(count) => {
                write!(f, "standard deck supports at most 2 jokers: {count}")
            }
            Self::EmptyPlayerId => f.write_str("player ID cannot be empty"),
            Self::InvalidPlayerCount(count) => write!(f, "player count must be 2..=8: {count}"),
            Self::DuplicatePlayerId(id) => write!(f, "duplicate player ID: {id}"),
            Self::EmptyDeck => f.write_str("deck cannot be empty"),
            Self::DuplicateCardInDeck => f.write_str("deck contains a duplicate card"),
            Self::InvalidMeldSize(size) => write!(f, "meld size must be 1..=4: {size}"),
            Self::DuplicateCardInAction => f.write_str("action contains a duplicate card"),
            Self::JokerWildcardDisabled => f.write_str("joker wildcards are disabled"),
            Self::MixedRanks => f.write_str("group contains multiple ordinary ranks"),
            Self::AllJokerGroup => f.write_str("all-joker groups are unsupported"),
            Self::UnknownPlayer(id) => write!(f, "unknown player: {id}"),
            Self::NotPlayersTurn(id) => write!(f, "it is not player {id}'s turn"),
            Self::GameComplete => f.write_str("game is complete"),
            Self::CardNotInHand(card) => write!(f, "card is not in hand: {card:?}"),
            Self::MeldDoesNotBeatPile => f.write_str("meld does not beat current pile"),
            Self::CannotPassOnLead => f.write_str("cannot pass while leading an empty trick"),
        }
    }
}

impl StdError for Error {}

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

    fn c(suit: Suit, rank: Rank) -> Card {
        Card::suited(suit, rank)
    }

    fn players(count: usize) -> Vec<Player> {
        (0..count)
            .map(|index| {
                Player::new(
                    format!("p{index}"),
                    if index == 1 {
                        Controller::Humanoid
                    } else {
                        Controller::Human
                    },
                )
                .unwrap()
            })
            .collect()
    }

    #[test]
    fn deck_is_unique_and_unshuffled() {
        let deck = standard_deck(2).unwrap();
        assert_eq!(deck.len(), 54);
        assert_eq!(deck[0], c(Suit::Clubs, Rank::Three));
        assert_eq!(deck[53], Card::Joker(1));
        assert_eq!(deck.iter().copied().collect::<BTreeSet<_>>().len(), 54);
    }

    #[test]
    fn view_hides_opponent_cards_but_exposes_counts() {
        let game = Game::deal(players(3), standard_deck(1).unwrap(), Rules::default()).unwrap();
        let view = game.view_for("p0").unwrap();
        assert_eq!(view.hand().len(), 18);
        assert_eq!(view.opponents().len(), 2);
        assert_eq!(
            view.opponents().iter().map(|o| o.hand_count).sum::<usize>(),
            35
        );
        assert_eq!(view.opponents()[0].controller, Controller::Humanoid);
    }

    #[test]
    fn holder_of_club_three_starts() {
        let deck = [c(Suit::Hearts, Rank::Ace), c(Suit::Clubs, Rank::Three)];
        let game = Game::deal(players(2), deck, Rules::default()).unwrap();
        assert_eq!(game.current_player_id(), Some("p1"));
    }

    #[test]
    fn normal_and_revolution_strength_are_opposite() {
        let rules = Rules::default();
        let five = Meld::analyze([c(Suit::Clubs, Rank::Five)], rules).unwrap();
        let six = Meld::analyze([c(Suit::Clubs, Rank::Six)], rules).unwrap();
        assert!(six.beats(&five, false, rules));
        assert!(five.beats(&six, true, rules));
    }

    #[test]
    fn spade_three_beats_only_lone_joker() {
        let rules = Rules::default();
        let joker = Meld::analyze([Card::Joker(0)], rules).unwrap();
        let spade_three = Meld::analyze([c(Suit::Spades, Rank::Three)], rules).unwrap();
        let club_three = Meld::analyze([c(Suit::Clubs, Rank::Three)], rules).unwrap();
        assert!(spade_three.beats(&joker, false, rules));
        assert!(!club_three.beats(&joker, false, rules));
    }

    #[test]
    fn legal_actions_match_group_size_and_include_pass() {
        let deck = [
            c(Suit::Clubs, Rank::Three),
            c(Suit::Clubs, Rank::Four),
            c(Suit::Diamonds, Rank::Three),
            c(Suit::Diamonds, Rank::Five),
            c(Suit::Hearts, Rank::Six),
            c(Suit::Spades, Rank::Seven),
        ];
        let mut game = Game::deal(players(2), deck, Rules::default()).unwrap();
        game.apply("p0", Action::Play(vec![c(Suit::Clubs, Rank::Three)]))
            .unwrap();
        let view = game.view_for("p1").unwrap();
        assert!(view.legal_actions().contains(&Action::Pass));
        assert!(
            view.legal_actions()
                .contains(&Action::Play(vec![c(Suit::Clubs, Rank::Four)]))
        );
    }

    #[test]
    fn passes_clear_trick_and_last_player_leads_again() {
        let deck = [
            c(Suit::Clubs, Rank::Three),
            c(Suit::Clubs, Rank::Four),
            c(Suit::Diamonds, Rank::Five),
            c(Suit::Diamonds, Rank::Six),
            c(Suit::Hearts, Rank::Seven),
            c(Suit::Hearts, Rank::Nine),
        ];
        let mut game = Game::deal(players(3), deck, Rules::default()).unwrap();
        game.apply("p0", Action::Play(vec![c(Suit::Clubs, Rank::Three)]))
            .unwrap();
        game.apply("p1", Action::Pass).unwrap();
        game.apply("p2", Action::Pass).unwrap();
        assert!(game.top_meld().is_none());
        assert_eq!(game.current_player_id(), Some("p0"));
    }

    #[test]
    fn four_card_group_toggles_revolution() {
        let deck = [
            c(Suit::Clubs, Rank::Three),
            c(Suit::Clubs, Rank::Four),
            c(Suit::Diamonds, Rank::Three),
            c(Suit::Diamonds, Rank::Four),
            c(Suit::Hearts, Rank::Three),
            c(Suit::Hearts, Rank::Four),
            c(Suit::Spades, Rank::Three),
            c(Suit::Spades, Rank::Four),
            c(Suit::Clubs, Rank::Five),
            c(Suit::Clubs, Rank::Six),
        ];
        let mut game = Game::deal(players(2), deck, Rules::default()).unwrap();
        game.apply(
            "p0",
            Action::Play(vec![
                c(Suit::Clubs, Rank::Three),
                c(Suit::Diamonds, Rank::Three),
                c(Suit::Hearts, Rank::Three),
                c(Suit::Spades, Rank::Three),
            ]),
        )
        .unwrap();
        assert!(game.revolution());
    }

    #[test]
    fn eight_cut_clears_and_same_player_leads() {
        let deck = [
            c(Suit::Clubs, Rank::Three),
            c(Suit::Clubs, Rank::Four),
            c(Suit::Diamonds, Rank::Eight),
            c(Suit::Diamonds, Rank::Nine),
            c(Suit::Hearts, Rank::Ten),
            c(Suit::Hearts, Rank::Jack),
        ];
        let mut game = Game::deal(players(2), deck, Rules::default()).unwrap();
        game.apply("p0", Action::Play(vec![c(Suit::Clubs, Rank::Three)]))
            .unwrap();
        game.apply("p1", Action::Play(vec![c(Suit::Clubs, Rank::Four)]))
            .unwrap();
        game.apply("p0", Action::Play(vec![c(Suit::Diamonds, Rank::Eight)]))
            .unwrap();
        assert!(game.top_meld().is_none());
        assert_eq!(game.current_player_id(), Some("p0"));
    }

    #[test]
    fn finishing_order_completes_with_last_player() {
        let deck = [c(Suit::Clubs, Rank::Three), c(Suit::Clubs, Rank::Four)];
        let mut game = Game::deal(players(2), deck, Rules::default()).unwrap();
        game.apply("p0", Action::Play(vec![c(Suit::Clubs, Rank::Three)]))
            .unwrap();
        assert_eq!(game.phase(), GamePhase::Complete);
        assert_eq!(game.finish_order().collect::<Vec<_>>(), ["p0", "p1"]);
    }

    #[test]
    fn humanoid_agent_can_take_a_turn_from_private_view() {
        struct FirstLegal;
        impl Agent for FirstLegal {
            type Error = std::convert::Infallible;

            fn choose_action(&mut self, view: &PlayerView) -> Result<Action, Self::Error> {
                Ok(view.legal_actions()[0].clone())
            }
        }

        let deck = [
            c(Suit::Clubs, Rank::Four),
            c(Suit::Clubs, Rank::Three),
            c(Suit::Diamonds, Rank::Five),
            c(Suit::Diamonds, Rank::Six),
        ];
        let mut game = Game::deal(players(2), deck, Rules::default()).unwrap();
        assert_eq!(game.current_player_id(), Some("p1"));
        game.step_with("p1", &mut FirstLegal).unwrap();
        assert_ne!(game.current_player_id(), Some("p1"));
    }
}