hearts-engine 0.1.1

Hearts bots: heuristic and Monte Carlo strategies over an information-hygienic view
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
//! [`HeuristicBot`]: a deterministic knowledge-based player
//!
//! The knowledge-free greedy core in this module — duck point-bearing
//! tricks, take safe control, dump the most dangerous card when void, smoke
//! out the Q♠ — doubles as the rollout policy of the Monte Carlo bot.  The
//! bot itself layers a knowledge-based moon-defense overlay on top: when a
//! single opponent has swept every point so far, it stops ducking and takes
//! a trick to kill the moon.

use crate::{Strategy, View};
use hearts::{Card, Hand, Holding, Rank, Seat, Suit, Trick};

/// The ranks strictly below `rank`, as a holding mask.
fn below(rank: Rank) -> Holding {
    Holding::from_bits_truncate((1u16 << rank.get()) - 1)
}

/// How badly `card` wants to be passed away, higher first
///
/// The knowledge-free pass policy shared with the Monte Carlo rollouts:
/// an unprotected Q♠ tops the list, bare A♠/K♠ follow (they catch the
/// queen), hearts weigh an extra `heart_weight` times their rank, the 2♣
/// takes a flat `two_of_clubs_bonus` for its forced lead, and cards of a
/// short non-spade suit earn a void bonus scaled by `void_weight`.  Lacking
/// the queen, spades below her lose `queen_insurance`.
pub(crate) fn pass_score(hand: Hand, card: Card, config: HeuristicConfig) -> i32 {
    let mut score = i32::from(card.rank.get());

    let guards = (hand[Suit::Spades] & below(Rank::Q)).len();
    if card.suit == Suit::Spades && guards < usize::from(config.spade_guards) {
        if card == Card::QUEEN_OF_SPADES {
            score += 100;
        } else if card.rank == Rank::A {
            score += 90;
        } else if card.rank == Rank::K {
            score += 80;
        }
    }

    if card.suit == Suit::Hearts {
        score += i32::from(config.heart_weight) * i32::from(card.rank.get());
    }

    // The 2♣ has no play to choose — its holder must lead it at the first
    // trick — so it is the cheapest card in the deck to give away, yet it
    // scores bare rank 2 and is otherwise all but unpassable.
    if card == Card::TWO_OF_CLUBS {
        score += i32::from(config.two_of_clubs_bonus);
    }

    // Lacking the queen, a low spade guards against her arriving in the pass.
    // `greedy_pass` rescores what is left, so passing her insures the spades
    // she leaves behind; the measured policy works that way.
    if card.suit == Suit::Spades
        && card.rank.get() < Rank::Q.get()
        && !hand.contains(Card::QUEEN_OF_SPADES)
    {
        score -= i32::from(config.queen_insurance);
    }

    // A short side suit is a void in the making; spades keep their guards.
    let len = hand[card.suit].len() as i32;
    if card.suit != Suit::Spades && len <= 3 {
        score += i32::from(config.void_weight) * (8 - 2 * len);
    }
    score
}

/// Which card leaves first when two [`pass_score`]s tie
///
/// Ties are common — at the shipped `heart_weight = 0` the score is exactly
/// symmetric under permuting ♣/♦/♥ — and they used to fall to whichever suit
/// a stable sort saw first, which is clubs, a bias worth 0.145 cards a pass
/// that nobody chose.  The rules break the symmetry properly: the first trick
/// is led in clubs and cannot score, so a club is the safest side-suit card
/// to keep, with diamonds dearer and hearts dearest.  ♠A/♠K/♠Q lead for the
/// reason the tier bonuses exist; the spades below her are guards and go last.
const fn danger(card: Card) -> u8 {
    match card.suit {
        Suit::Spades if card.rank.get() >= Rank::Q.get() => 4,
        Suit::Spades => 0,
        // ♣ 1, ♦ 2, ♥ 3 — `Suit` is `repr(u8)` in that order.
        suit => suit as u8 + 1,
    }
}

/// The total order the pass policy and the Monte Carlo ranking share
///
/// Total by construction: [`danger`] separates every suit but the two spade
/// bands, and ranks inside one suit are distinct.  No tie survives to be
/// settled by sort stability, so ordering never depends on iteration order.
pub(crate) fn pass_key(hand: Hand, card: Card, config: HeuristicConfig) -> (i32, u8, u8) {
    (
        pass_score(hand, card, config),
        danger(card),
        card.rank.get(),
    )
}

/// The knowledge-free greedy pass: three rounds of take the card that most
/// wants to go, then rescore what is left
///
/// Rescoring is the point.  [`pass_score`] reads the suit lengths of the hand
/// it is handed, so removing a card escalates the void bonus along the suit it
/// came from — a doubleton's two cards are worth +4 then +6 — and a triple
/// that finishes a void outbids three that merely start three.  A single sort
/// cannot see that: it scores every card against the untouched thirteen and
/// happily passes one card out of each of three short suits, emptying nothing.
pub(crate) fn greedy_pass(mut hand: Hand, config: HeuristicConfig) -> [Card; 3] {
    [(); 3].map(|()| {
        // A `Copy` snapshot, so the scan borrows nothing the loop mutates —
        // and so the score is visibly against the *current* hand.
        let current = hand;
        let pick = current
            .into_iter()
            .max_by_key(|&card| pass_key(current, card, config))
            .expect("a passing hand holds thirteen cards");
        hand.remove(pick);
        pick
    })
}

/// The card currently winning `trick`
fn winning_card(trick: Trick) -> Option<Card> {
    trick.winner().and_then(|seat| trick.card_from(seat))
}

/// The most dangerous card to be rid of when free to discard anything
///
/// The Q♠ first, then a bare A♠/K♠ while the queen is at large, then the
/// highest heart, then the highest card overall.
fn best_dump(legal: Hand, played: Hand) -> Card {
    if legal.contains(Card::QUEEN_OF_SPADES) {
        return Card::QUEEN_OF_SPADES;
    }
    if !played.contains(Card::QUEEN_OF_SPADES)
        && let Some(rank) = [Rank::A, Rank::K]
            .into_iter()
            .find(|&rank| legal[Suit::Spades].contains(rank))
    {
        return Card {
            suit: Suit::Spades,
            rank,
        };
    }
    if let Some(rank) = legal[Suit::Hearts].iter().next_back() {
        return Card {
            suit: Suit::Hearts,
            rank,
        };
    }
    legal
        .into_iter()
        .max_by_key(|card| card.rank)
        .expect("legal plays are never empty on turn")
}

/// The knowledge-free, point-aware greedy play policy shared with the Monte
/// Carlo rollouts
///
/// `legal` must be the acting seat's non-empty legal set, `trick` the
/// trick in progress, and `played` every card played so far.
pub(crate) fn greedy_play(legal: Hand, trick: Trick, played: Hand) -> Card {
    let Some(led) = trick.suit() else {
        // Leading.  While the Q♠ is at large and not ours, smoke it out
        // with low spades — unless we hold the A♠ or K♠: each low spade
        // led spends a guard, and a bare high spade is exactly where the
        // queen lands.  Otherwise lead our lowest card.
        if !played.contains(Card::QUEEN_OF_SPADES)
            && !legal.contains(Card::QUEEN_OF_SPADES)
            && (legal[Suit::Spades] - below(Rank::Q)).is_empty()
        {
            let low_spades = legal[Suit::Spades] & below(Rank::Q);
            if let Some(rank) = low_spades.iter().next() {
                return Card {
                    suit: Suit::Spades,
                    rank,
                };
            }
        }
        // Work the shortest suit first: exhausting it creates a place to
        // shed penalties, while a global low-card ordering merely broke ties
        // toward clubs.
        return legal
            .into_iter()
            .min_by_key(|card| (legal[card.suit].len(), card.rank))
            .expect("legal plays are never empty on turn");
    };

    let follow = legal[led];
    if follow.is_empty() {
        // Void: dump the most dangerous card.
        return best_dump(legal, played);
    }

    let winner = winning_card(trick).expect("a led trick has a winning card");

    // A dead queen: the A♠ or K♠ already sits in the trick, so the Q♠
    // rides for free.
    if led == Suit::Spades && follow.contains(Rank::Q) && winner.rank > Rank::Q {
        return Card::QUEEN_OF_SPADES;
    }

    // Last to a clean trick, take the lead with the cheapest winner.  There
    // is nobody left to dump a penalty on us, and control is worth more than
    // ducking a scoreless trick.  Do not turn Q♠ itself into the points.
    if trick.len() == 3 && trick.plays().all(|(_, card)| card.points() == 0) {
        let mut winners = follow - below(winner.rank) - Holding::from_rank(winner.rank);
        if led == Suit::Spades {
            winners -= Holding::from_rank(Rank::Q);
        }
        if let Some(rank) = winners.iter().next() {
            return Card { suit: led, rank };
        }
    }

    // Duck with the highest card under the winner.
    if let Some(rank) = (follow & below(winner.rank)).iter().next_back() {
        return Card { suit: led, rank };
    }

    // Forced above the winner; never hand ourselves the Q♠ if avoidable.
    let safe = if led == Suit::Spades {
        let others = follow - Holding::from_rank(Rank::Q);
        if others.is_empty() { follow } else { others }
    } else {
        follow
    };

    // Last to play takes the trick anyway, so shed the highest; earlier,
    // play the lowest and hope someone overtakes.
    let rank = if trick.len() == 3 {
        safe.iter().next_back().expect("checked non-empty")
    } else {
        safe.iter().next().expect("checked non-empty")
    };
    Card { suit: led, rank }
}

/// Tuning knobs for [`HeuristicBot`]
///
/// Like [`hearts::Rules`], the struct is non-exhaustive: start from
/// [`HeuristicConfig::default`] and adjust fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct HeuristicConfig {
    /// Take a trick to kill a suspected moon once a single opponent has
    /// swept this many points; `u8::MAX` effectively disables the defense
    pub moon_defense: u8,
    /// Weight of the void bonus when scoring passes
    ///
    /// Zero passes purely on card danger; the default is 1.
    pub void_weight: u8,
    /// Extra pass-score weight per rank for hearts, atop the base rank
    ///
    /// Zero, the default, prices hearts like any other card: high hearts
    /// are duckable on demand, unlike a caught Q♠.
    pub heart_weight: u8,
    /// High-spade pass bonuses apply while holding fewer than this many
    /// spades below the queen; the default is 4
    pub spade_guards: u8,
    /// Extra pass score for the 2♣ alone
    ///
    /// Its holder must lead it at the first trick, so the card carries no
    /// choice worth keeping — the cheapest thing in the deck to give away —
    /// yet it scores bare rank 2 and is otherwise all but unpassable.  Zero,
    /// the default, leaves it at bare rank.
    pub two_of_clubs_bonus: u8,
    /// Pass-score malus for a spade below the queen while the hand lacks
    /// her; zero disables it
    ///
    /// After the exchange such a spade guards against the queen arriving.
    /// The default, 4, already saturates: larger values change no more
    /// passes.
    pub queen_insurance: u8,
}

impl HeuristicConfig {
    /// The shipped tuning, in a `const` context
    ///
    /// [`Default`] delegates here, as [`hearts::Rules`] does: a `const fn`
    /// constructor — [`MonteCarloBot::new`](crate::MonteCarloBot::new) —
    /// cannot call a trait method.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            moon_defense: 8,
            void_weight: 1,
            heart_weight: 0,
            spade_guards: 4,
            two_of_clubs_bonus: 6,
            queen_insurance: 4,
        }
    }
}

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

/// A deterministic knowledge-based player
///
/// Fast enough for tournaments at any scale: every decision is a handful
/// of bit operations.
#[derive(Debug, Clone, Copy, Default)]
pub struct HeuristicBot {
    config: HeuristicConfig,
}

impl HeuristicBot {
    /// A bot with the default configuration
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// A bot with custom tuning
    #[must_use]
    pub const fn with_config(config: HeuristicConfig) -> Self {
        Self { config }
    }
}

/// The opponent who has swept every point so far, once the sweep weighs at
/// least `threshold` — enough to smell like a moon attempt
fn moon_threat(view: &View<'_>, threshold: u8) -> Option<Seat> {
    let mut sweeper = None;
    for seat in Seat::ALL {
        if view.points_taken(seat) > 0 {
            if sweeper.is_some() {
                return None;
            }
            sweeper = Some(seat);
        }
    }
    sweeper.filter(|&seat| seat != view.seat() && view.points_taken(seat) >= threshold)
}

/// The knowledge-based moon-defense play, shared by [`HeuristicBot`] and the
/// [`MonteCarloBot`](crate::MonteCarloBot)'s live decision.
///
/// When a single opponent has swept at least `threshold` points and is
/// winning the current trick, stop ducking: beat them as cheaply as possible
/// (but never with our own Q♠ if avoidable), and when we cannot beat them, at
/// least gift them no penalty card toward the sweep.  `None` when no defense
/// applies, so the caller falls back to its normal policy.  The Monte Carlo
/// rollouts model opponents as greedy duckers who never shoot the moon, so
/// the search is blind to a moon in progress; this reactive overlay covers
/// the gap.
pub(crate) fn moon_defense(view: &View<'_>, threshold: u8) -> Option<Card> {
    let threat = moon_threat(view, threshold)?;
    let trick = view.current_trick()?;
    if trick.winner() != Some(threat) {
        return None;
    }
    beat_threat(view.legal_plays(), trick)
}

/// Take this trick away from the seat currently winning it
///
/// The knowledge-free core of [`moon_defense`], shared with the rollout
/// policy: beat the winner as cheaply as possible but never with our own
/// Q♠, and when we cannot beat them, gift them no penalty card toward the
/// sweep.  `None` when the trick has no led suit or every legal play would
/// feed the sweep, so the caller falls back to its normal policy.
fn beat_threat(legal: Hand, trick: Trick) -> Option<Card> {
    let led = trick.suit()?;
    let winner = winning_card(trick).expect("a led trick has a winning card");
    let follow = legal[led];
    if follow.is_empty() {
        // Void: dump the most dangerous card that carries no points into the
        // sweeper's trick.
        let harmless = legal - Hand::PENALTIES;
        return harmless.into_iter().max_by_key(|card| card.rank);
    }
    // Beat them as cheaply as possible — taking a trick with our own Q♠
    // costs more than the sweep it denies.
    let mut beat = follow - below(winner.rank) - Holding::from_rank(winner.rank);
    if led == Suit::Spades {
        beat -= Holding::from_rank(Rank::Q);
    }
    if let Some(rank) = beat.iter().next() {
        return Some(Card { suit: led, rank });
    }
    // Can't beat the sweep: duck plainly — and never ride the dead queen
    // into the sweeper's trick.
    let mut duck = follow & below(winner.rank);
    if led == Suit::Spades {
        let harmless = duck - Holding::from_rank(Rank::Q);
        if !harmless.is_empty() {
            duck = harmless;
        }
    }
    duck.iter().next_back().map(|rank| Card { suit: led, rank })
}

impl Strategy for HeuristicBot {
    fn pass_cards(&mut self, view: &View<'_>) -> [Card; 3] {
        greedy_pass(view.hand(), self.config)
    }

    fn play_card(&mut self, view: &View<'_>) -> Card {
        if let Some(card) = moon_defense(view, self.config.moon_defense) {
            return card;
        }
        let legal = view.legal_plays();
        let trick = view.current_trick().expect("a play decision has a trick");
        greedy_play(legal, trick, view.played())
    }

    fn name(&self) -> &str {
        "greedy"
    }
}

/// The knowledge-free moon-seeking policy, the mirror of [`greedy_play`]
///
/// A shot has to win every trick left, so: cash our highest card when
/// leading, top the led suit when that beats the current winner, and shed
/// our cheapest junk when void — the hearts and the queen are cards we mean
/// to *win*, not discard.  On a trick we can no longer take, the shot needs
/// nothing from us and [`greedy_play`] keeps the stopper it would have
/// wasted.
#[cfg(any(feature = "rand", test))]
pub(crate) fn shoot_play(legal: Hand, trick: Trick, played: Hand) -> Card {
    let highest = |cards: Hand| {
        cards
            .into_iter()
            .max_by_key(|card| card.rank)
            .expect("the set was checked non-empty")
    };

    let Some(led) = trick.suit() else {
        return highest(legal);
    };

    let follow = legal[led];
    if follow.is_empty() {
        // Void, so this trick is lost: shed the cheapest card that is not a
        // penalty we still want to take ourselves.
        let junk = legal - Hand::PENALTIES;
        let shed = if junk.is_empty() { legal } else { junk };
        return shed
            .into_iter()
            .min_by_key(|card| card.rank)
            .expect("legal plays are never empty on turn");
    }

    let winner = winning_card(trick).expect("a led trick has a winning card");
    match (follow - below(winner.rank) - Holding::from_rank(winner.rank))
        .iter()
        .next_back()
    {
        Some(rank) => Card { suit: led, rank },
        None => greedy_play(legal, trick, played),
    }
}

/// The rollout flavor of the policy, for omniscient Monte Carlo worlds
///
/// `shooter`, when set, is the seat whose moon the world is testing: it
/// plays [`shoot_play`] for as long as the shot is alive, and the other
/// three stop ducking once the shooter holds the live table's eight
/// points and is winning the trick — the same trigger [`HeuristicBot`]'s
/// moon-defense overlay fires on.  Defending from trick 1 prices every
/// shot against a table no real opponent fields, while greedy duckers
/// with no trigger at all would make every moon look like a laydown.
///
/// `played` must equal `round.played()`; the caller threads it so a
/// rollout does not refold the whole trick history at every play.
#[cfg(feature = "rand")]
pub(crate) fn rollout_play(
    round: &hearts::Round,
    seat: Seat,
    shooter: Option<Seat>,
    played: Hand,
) -> Card {
    let legal = round.legal_plays(seat);
    let trick = round.current_trick().expect("a playing round has a trick");

    if let Some(shooter) = shooter {
        // A shot dies the moment anyone else scores; from there the shooter
        // bails out to the greedy policy, as a real one would.
        let alive = Seat::ALL
            .into_iter()
            .all(|other| other == shooter || round.points_taken(other) == 0);
        if !alive {
            return greedy_play(legal, trick, played);
        }
        if seat == shooter {
            return shoot_play(legal, trick, played);
        }
        if trick.winner() == Some(shooter)
            && round.points_taken(shooter) >= HeuristicConfig::default().moon_defense
            && let Some(card) = beat_threat(legal, trick)
        {
            return card;
        }
    }

    greedy_play(legal, trick, played)
}

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

    fn card(text: &str) -> Card {
        text.parse().expect("a valid card")
    }

    fn hand(text: &str) -> Hand {
        text.parse().expect("a valid hand")
    }

    /// The policy this module replaced: one flat sort of the dealt thirteen,
    /// ties falling to whichever suit `Hand`'s iterator reached first.
    fn flat_pass(dealt: Hand, config: HeuristicConfig) -> [Card; 3] {
        let mut cards: Vec<Card> = dealt.into_iter().collect();
        cards.sort_by_key(|&card| -pass_score(dealt, card, config));
        [cards[0], cards[1], cards[2]]
    }

    #[test]
    fn passing_dumps_the_unprotected_queen() {
        // Q♠ with one guard, the A♥, and filler.
        let dealt = hand("234567.89.A.2Q");
        let picks = greedy_pass(dealt, HeuristicConfig::default());
        assert!(picks.contains(&card("Q♠")));
        assert!(picks.contains(&card("A♥")));

        // Well guarded, the queen stays; the hearts and short suits go.
        let guarded = hand("234.8.9A.234567Q");
        let picks = greedy_pass(guarded, HeuristicConfig::default());
        assert!(!picks.contains(&card("Q♠")));
    }

    #[test]
    fn passing_completes_a_void_instead_of_scattering() {
        // ♠J86 ♥A6 ♦K2 ♣976432.  Scored flat against the dealt thirteen the
        // order is A♥ 18, K♦ 17, J♠ 11, 6♥ 10, so one sort passes A♥ K♦ J♠
        // and leaves both red doubletons alive — three void bonuses
        // collected, no void created.  Sequentially the A♥ leaves the 6♥ a
        // singleton worth 6 + 6 = 12, which beats the J♠: the pass opens a
        // real heart void and keeps the 2♦ as a clean duck.
        // Queen insurance would demote the J♠ and blur the contrast.
        let dealt = hand("234679.2K.6A.68J");
        let config = HeuristicConfig {
            queen_insurance: 0,
            ..HeuristicConfig::default()
        };
        assert_eq!(
            greedy_pass(dealt, config),
            [card("A♥"), card("K♦"), card("6♥")],
        );

        assert_eq!(
            flat_pass(dealt, config),
            [card("A♥"), card("K♦"), card("J♠")],
            "the flat form scatters, which is what this replaced",
        );
    }

    #[test]
    fn queen_insurance_keeps_a_low_spade_without_her() {
        let dealt = hand("2345.2345.234.29");
        let uninsured = HeuristicConfig {
            queen_insurance: 0,
            ..HeuristicConfig::default()
        };
        assert!(greedy_pass(dealt, uninsured).contains(&card("9♠")));
        assert!(!greedy_pass(dealt, HeuristicConfig::default()).contains(&card("9♠")));

        // Holding her, a low spade scores bare rank.
        let config = HeuristicConfig::default();
        assert_eq!(pass_score(hand("2345.2345.23.29Q"), card("9♠"), config), 9);
        assert_eq!(pass_score(dealt, card("9♠"), config), 5);
    }

    #[test]
    fn the_pass_tie_break_is_designed_not_inherited() {
        // The ladder: the queen and the two cards that catch her first, then
        // hearts, diamonds, clubs, and a spade below the queen dead last
        // because it is a guard worth keeping.
        assert!(danger(card("Q♠")) > danger(card("A♥")));
        assert!(danger(card("A♥")) > danger(card("A♦")));
        assert!(danger(card("A♦")) > danger(card("A♣")));
        assert!(danger(card("A♣")) > danger(card("J♠")));

        // And the ladder reaching the policy.  Four nines score exactly 9
        // apiece — a four-card suit earns no void bonus and `heart_weight`
        // is zero — so nothing but the tie-break decides.  Stable-sort order
        // used to send the clubs first; the 9♠ is a guard and never goes.
        let nines = hand("2349.2349.2349.9");
        assert_eq!(
            greedy_pass(nines, HeuristicConfig::default()),
            [card("9♥"), card("9♦"), card("9♣")],
        );
        assert_eq!(
            flat_pass(nines, HeuristicConfig::default()),
            [card("9♣"), card("9♦"), card("9♥")],
            "sort stability used to reach for the clubs first",
        );

        // With five guards the Q♠/A♠/K♠ tier is disarmed, so a bare K♠ and a
        // K♣ both score 13 and the danger class is the whole difference: the
        // spade honor goes, the club stays.
        assert_eq!(
            greedy_pass(hand("234K..23K.23456K"), HeuristicConfig::default()),
            [card("K♥"), card("K♠"), card("K♣")],
        );
    }

    #[test]
    fn the_forced_lead_is_worth_passing() {
        // Four-card clubs, so the 2♣ takes no void bonus and the knob is the
        // whole difference; the red three-card fragments are the rivals.
        let dealt = hand("2345.234.234.234");
        assert_eq!(
            greedy_pass(dealt, HeuristicConfig::default()),
            [card("2♣"), card("5♣"), card("4♣")],
            "the shipped bonus sends the forced lead, then works the suit",
        );

        // Priced at bare rank 2 it is the last card in the deck to go, and
        // the pass falls back to emptying hearts.
        let unpriced = HeuristicConfig {
            two_of_clubs_bonus: 0,
            ..HeuristicConfig::default()
        };
        assert_eq!(
            greedy_pass(dealt, unpriced),
            [card("4♥"), card("3♥"), card("2♥")],
        );
    }

    #[test]
    fn shooting_takes_every_trick_it_can() {
        // Leading: cash the highest card in hand.
        let lead = Trick::new(Seat::North);
        assert_eq!(shoot_play(hand("2.3.A.4"), lead, Hand::EMPTY), card("A♥"));

        // Following a trick we can win: top the led suit, not duck under it.
        let mut trick = Trick::new(Seat::North);
        trick.play(card("9♦")).unwrap();
        let held = hand(".2378Q..");
        assert_eq!(shoot_play(held, trick, Hand::EMPTY), card("Q♦"));
        assert_eq!(
            greedy_play(held, trick, Hand::EMPTY),
            card("8♦"),
            "the greedy policy ducks the same holding"
        );
    }

    #[test]
    fn a_dead_trick_costs_the_shooter_nothing() {
        // The nine is out of reach in diamonds, so the shot needs nothing
        // here: fall back to the greedy policy rather than burn a stopper.
        let mut trick = Trick::new(Seat::North);
        trick.play(card("9♦")).unwrap();
        let held = hand(".2378..A");
        assert_eq!(
            shoot_play(held, trick, Hand::EMPTY),
            greedy_play(held, trick, Hand::EMPTY)
        );

        // Void: shed the cheapest junk and keep the penalties to win later.
        assert_eq!(shoot_play(hand("29..3A.Q"), trick, Hand::EMPTY), card("2♣"));
        // Nothing but penalties: the lowest of them goes.
        assert_eq!(shoot_play(hand("..3A.Q"), trick, Hand::EMPTY), card("3♥"));
    }

    #[test]
    fn ducking_under_the_winner() {
        let mut trick = Trick::new(Seat::North);
        trick.play(card("9♦")).unwrap();
        // Duck with the highest diamond under the nine.
        assert_eq!(
            greedy_play(hand(".2378Q.."), trick, Hand::EMPTY),
            card("8♦")
        );
    }

    #[test]
    fn last_hand_takes_only_a_point_free_trick() {
        let mut clean = Trick::new(Seat::North);
        for text in ["5♦", "2♦", "3♦"] {
            clean.play(card(text)).unwrap();
        }
        assert_eq!(
            greedy_play(hand(".47.."), clean, Hand::EMPTY),
            card("7♦"),
            "take control when nobody can add points"
        );

        let mut costly = Trick::new(Seat::North);
        for text in ["5♣", "2♥", "3♣"] {
            costly.play(card(text)).unwrap();
        }
        assert_eq!(
            greedy_play(hand("47..."), costly, Hand::EMPTY),
            card("4♣"),
            "duck when the trick already carries a point"
        );
    }

    #[test]
    fn leading_works_the_shortest_suit() {
        let trick = Trick::new(Seat::North);
        let played = Hand::QUEEN_OF_SPADES;
        assert_eq!(greedy_play(hand("234.5.67.89"), trick, played), card("5♦"));
    }

    #[test]
    fn void_dumps_the_queen_first() {
        let mut trick = Trick::new(Seat::North);
        trick.play(card("9♦")).unwrap();
        assert_eq!(greedy_play(hand("2..A.QA"), trick, Hand::EMPTY), card("Q♠"));
        // Queen gone: a bare A♠ goes while she is at large.
        assert_eq!(greedy_play(hand("2..A.A"), trick, Hand::EMPTY), card("A♠"));
        // Queen already played: the high heart goes instead.
        assert_eq!(
            greedy_play(hand("2..A.A"), trick, Hand::QUEEN_OF_SPADES),
            card("A♥")
        );
    }

    #[test]
    fn dead_queen_rides() {
        let mut trick = Trick::new(Seat::North);
        trick.play(card("2♠")).unwrap();
        trick.play(card("A♠")).unwrap();
        assert_eq!(greedy_play(hand("...5Q"), trick, Hand::EMPTY), card("Q♠"));
    }

    #[test]
    fn forced_above_the_winner() {
        let mut trick = Trick::new(Seat::North);
        trick.play(card("5♠")).unwrap();
        trick.play(card("2♠")).unwrap();
        trick.play(card("3♠")).unwrap();
        // Last to play and forced to take: shed the king, never the queen.
        assert_eq!(greedy_play(hand("...QK"), trick, Hand::EMPTY), card("K♠"));

        let mut early = Trick::new(Seat::North);
        early.play(card("5♠")).unwrap();
        // Second to play: the low card rides, hoping someone overtakes.
        assert_eq!(greedy_play(hand("...9K"), early, Hand::EMPTY), card("9♠"));
    }

    #[test]
    fn moon_defense_never_spends_or_gifts_the_queen() {
        use crate::Table;
        use hearts::{PassDirection, Round, Rules};

        // South holds nothing but hearts and bleeds on trick 1, arming
        // East as the sole sweeper for a bot with moon_defense = 1.
        let hands = [
            hand("23456789TJQ...QK"), // North: low clubs + Q♠ K♠
            hand("A.23456789TJQ..J"), // East: A♣, diamonds, J♠
            hand("..23456789TJQKA."), // South: all hearts
            hand("K.KA..23456789TA"), // West: the rest
        ];
        let round = Round::from_deal(Rules::new(), PassDirection::Hold, hands).unwrap();
        let mut table = Table::new(round);
        let config = HeuristicConfig {
            moon_defense: 1,
            ..HeuristicConfig::default()
        };
        let mut defender = HeuristicBot::with_config(config);

        // Trick 1: E takes A♣ over the forced 2♥ — one point, armed.
        for (seat, text) in [
            (Seat::North, "2♣"),
            (Seat::East, "A♣"),
            (Seat::South, "2♥"),
            (Seat::West, "K♣"),
        ] {
            struct Fixed(Card);
            impl Strategy for Fixed {
                fn pass_cards(&mut self, _: &View<'_>) -> [Card; 3] {
                    unreachable!()
                }
                fn play_card(&mut self, _: &View<'_>) -> Card {
                    self.0
                }
            }
            assert_eq!(table.turn(), Some(seat));
            table.step(&mut Fixed(card(text))).unwrap();
        }

        // Trick 2: the sweeper leads J♠; South and West stay under it.
        for text in ["J♠", "3♥", "2♠"] {
            struct Fixed(Card);
            impl Strategy for Fixed {
                fn pass_cards(&mut self, _: &View<'_>) -> [Card; 3] {
                    unreachable!()
                }
                fn play_card(&mut self, _: &View<'_>) -> Card {
                    self.0
                }
            }
            let seat = table.turn().unwrap();
            table.step(&mut Fixed(card(text))).unwrap();
            let _ = seat;
        }

        // North must beat the sweep with the K♠ — never its own Q♠.
        assert_eq!(table.turn(), Some(Seat::North));
        assert_eq!(defender.play_card(&table.view(Seat::North)), card("K♠"));
    }

    #[test]
    fn smoke_out_the_queen() {
        let trick = Trick::new(Seat::North);
        let played = hand("2345...");
        // Leading without the queen: low spades hunt it.
        assert_eq!(greedy_play(hand("9.9.9.29"), trick, played), card("2♠"));
        // Holding the queen: no self-hunt, so work a shortest side suit.
        assert_eq!(greedy_play(hand("9.9..29Q"), trick, played), card("9♣"));
        // Holding the queen and higher clubs: lead the lowest card, no hunt.
        assert_eq!(greedy_play(hand("4.9..9Q"), trick, played), card("4♣"));
        // Holding a high spade: keep its guards, work a shortest side suit.
        assert_eq!(greedy_play(hand("9.9.9.29K"), trick, played), card("9♣"));
        assert_eq!(greedy_play(hand("9.9.9.2A"), trick, played), card("9♣"));
    }
}