Skip to main content

hearts_engine/
heuristic.rs

1//! [`HeuristicBot`]: a deterministic knowledge-based player
2//!
3//! The knowledge-free greedy core in this module — duck point-bearing
4//! tricks, take safe control, dump the most dangerous card when void, smoke
5//! out the Q♠ — doubles as the rollout policy of the Monte Carlo bot.  The
6//! bot itself layers a knowledge-based moon-defense overlay on top: when a
7//! single opponent has swept every point so far, it stops ducking and takes
8//! a trick to kill the moon.
9
10use crate::{Strategy, View};
11use hearts::{Card, Hand, Holding, Rank, Seat, Suit, Trick};
12
13/// The ranks strictly below `rank`, as a holding mask.
14fn below(rank: Rank) -> Holding {
15    Holding::from_bits_truncate((1u16 << rank.get()) - 1)
16}
17
18/// How badly `card` wants to be passed away, higher first
19///
20/// The knowledge-free pass policy shared with the Monte Carlo rollouts:
21/// an unprotected Q♠ tops the list, bare A♠/K♠ follow (they catch the
22/// queen), hearts weigh an extra `heart_weight` times their rank, the 2♣
23/// takes a flat `two_of_clubs_bonus` for its forced lead, and cards of a
24/// short non-spade suit earn a void bonus scaled by `void_weight`.  Lacking
25/// the queen, spades below her lose `queen_insurance`.
26pub(crate) fn pass_score(hand: Hand, card: Card, config: HeuristicConfig) -> i32 {
27    let mut score = i32::from(card.rank.get());
28
29    let guards = (hand[Suit::Spades] & below(Rank::Q)).len();
30    if card.suit == Suit::Spades && guards < usize::from(config.spade_guards) {
31        if card == Card::QUEEN_OF_SPADES {
32            score += 100;
33        } else if card.rank == Rank::A {
34            score += 90;
35        } else if card.rank == Rank::K {
36            score += 80;
37        }
38    }
39
40    if card.suit == Suit::Hearts {
41        score += i32::from(config.heart_weight) * i32::from(card.rank.get());
42    }
43
44    // The 2♣ has no play to choose — its holder must lead it at the first
45    // trick — so it is the cheapest card in the deck to give away, yet it
46    // scores bare rank 2 and is otherwise all but unpassable.
47    if card == Card::TWO_OF_CLUBS {
48        score += i32::from(config.two_of_clubs_bonus);
49    }
50
51    // Lacking the queen, a low spade guards against her arriving in the pass.
52    // `greedy_pass` rescores what is left, so passing her insures the spades
53    // she leaves behind; the measured policy works that way.
54    if card.suit == Suit::Spades
55        && card.rank.get() < Rank::Q.get()
56        && !hand.contains(Card::QUEEN_OF_SPADES)
57    {
58        score -= i32::from(config.queen_insurance);
59    }
60
61    // A short side suit is a void in the making; spades keep their guards.
62    let len = hand[card.suit].len() as i32;
63    if card.suit != Suit::Spades && len <= 3 {
64        score += i32::from(config.void_weight) * (8 - 2 * len);
65    }
66    score
67}
68
69/// Which card leaves first when two [`pass_score`]s tie
70///
71/// Ties are common — at the shipped `heart_weight = 0` the score is exactly
72/// symmetric under permuting ♣/♦/♥ — and they used to fall to whichever suit
73/// a stable sort saw first, which is clubs, a bias worth 0.145 cards a pass
74/// that nobody chose.  The rules break the symmetry properly: the first trick
75/// is led in clubs and cannot score, so a club is the safest side-suit card
76/// to keep, with diamonds dearer and hearts dearest.  ♠A/♠K/♠Q lead for the
77/// reason the tier bonuses exist; the spades below her are guards and go last.
78const fn danger(card: Card) -> u8 {
79    match card.suit {
80        Suit::Spades if card.rank.get() >= Rank::Q.get() => 4,
81        Suit::Spades => 0,
82        // ♣ 1, ♦ 2, ♥ 3 — `Suit` is `repr(u8)` in that order.
83        suit => suit as u8 + 1,
84    }
85}
86
87/// The total order the pass policy and the Monte Carlo ranking share
88///
89/// Total by construction: [`danger`] separates every suit but the two spade
90/// bands, and ranks inside one suit are distinct.  No tie survives to be
91/// settled by sort stability, so ordering never depends on iteration order.
92pub(crate) fn pass_key(hand: Hand, card: Card, config: HeuristicConfig) -> (i32, u8, u8) {
93    (
94        pass_score(hand, card, config),
95        danger(card),
96        card.rank.get(),
97    )
98}
99
100/// The knowledge-free greedy pass: three rounds of take the card that most
101/// wants to go, then rescore what is left
102///
103/// Rescoring is the point.  [`pass_score`] reads the suit lengths of the hand
104/// it is handed, so removing a card escalates the void bonus along the suit it
105/// came from — a doubleton's two cards are worth +4 then +6 — and a triple
106/// that finishes a void outbids three that merely start three.  A single sort
107/// cannot see that: it scores every card against the untouched thirteen and
108/// happily passes one card out of each of three short suits, emptying nothing.
109pub(crate) fn greedy_pass(mut hand: Hand, config: HeuristicConfig) -> [Card; 3] {
110    [(); 3].map(|()| {
111        // A `Copy` snapshot, so the scan borrows nothing the loop mutates —
112        // and so the score is visibly against the *current* hand.
113        let current = hand;
114        let pick = current
115            .into_iter()
116            .max_by_key(|&card| pass_key(current, card, config))
117            .expect("a passing hand holds thirteen cards");
118        hand.remove(pick);
119        pick
120    })
121}
122
123/// The card currently winning `trick`
124fn winning_card(trick: Trick) -> Option<Card> {
125    trick.winner().and_then(|seat| trick.card_from(seat))
126}
127
128/// The most dangerous card to be rid of when free to discard anything
129///
130/// The Q♠ first, then a bare A♠/K♠ while the queen is at large, then the
131/// highest heart, then the highest card overall.
132fn best_dump(legal: Hand, played: Hand) -> Card {
133    if legal.contains(Card::QUEEN_OF_SPADES) {
134        return Card::QUEEN_OF_SPADES;
135    }
136    if !played.contains(Card::QUEEN_OF_SPADES)
137        && let Some(rank) = [Rank::A, Rank::K]
138            .into_iter()
139            .find(|&rank| legal[Suit::Spades].contains(rank))
140    {
141        return Card {
142            suit: Suit::Spades,
143            rank,
144        };
145    }
146    if let Some(rank) = legal[Suit::Hearts].iter().next_back() {
147        return Card {
148            suit: Suit::Hearts,
149            rank,
150        };
151    }
152    legal
153        .into_iter()
154        .max_by_key(|card| card.rank)
155        .expect("legal plays are never empty on turn")
156}
157
158/// The knowledge-free, point-aware greedy play policy shared with the Monte
159/// Carlo rollouts
160///
161/// `legal` must be the acting seat's non-empty legal set, `trick` the
162/// trick in progress, and `played` every card played so far.
163pub(crate) fn greedy_play(legal: Hand, trick: Trick, played: Hand) -> Card {
164    let Some(led) = trick.suit() else {
165        // Leading.  While the Q♠ is at large and not ours, smoke it out
166        // with low spades — unless we hold the A♠ or K♠: each low spade
167        // led spends a guard, and a bare high spade is exactly where the
168        // queen lands.  Otherwise lead our lowest card.
169        if !played.contains(Card::QUEEN_OF_SPADES)
170            && !legal.contains(Card::QUEEN_OF_SPADES)
171            && (legal[Suit::Spades] - below(Rank::Q)).is_empty()
172        {
173            let low_spades = legal[Suit::Spades] & below(Rank::Q);
174            if let Some(rank) = low_spades.iter().next() {
175                return Card {
176                    suit: Suit::Spades,
177                    rank,
178                };
179            }
180        }
181        // Work the shortest suit first: exhausting it creates a place to
182        // shed penalties, while a global low-card ordering merely broke ties
183        // toward clubs.
184        return legal
185            .into_iter()
186            .min_by_key(|card| (legal[card.suit].len(), card.rank))
187            .expect("legal plays are never empty on turn");
188    };
189
190    let follow = legal[led];
191    if follow.is_empty() {
192        // Void: dump the most dangerous card.
193        return best_dump(legal, played);
194    }
195
196    let winner = winning_card(trick).expect("a led trick has a winning card");
197
198    // A dead queen: the A♠ or K♠ already sits in the trick, so the Q♠
199    // rides for free.
200    if led == Suit::Spades && follow.contains(Rank::Q) && winner.rank > Rank::Q {
201        return Card::QUEEN_OF_SPADES;
202    }
203
204    // Last to a clean trick, take the lead with the cheapest winner.  There
205    // is nobody left to dump a penalty on us, and control is worth more than
206    // ducking a scoreless trick.  Do not turn Q♠ itself into the points.
207    if trick.len() == 3 && trick.plays().all(|(_, card)| card.points() == 0) {
208        let mut winners = follow - below(winner.rank) - Holding::from_rank(winner.rank);
209        if led == Suit::Spades {
210            winners -= Holding::from_rank(Rank::Q);
211        }
212        if let Some(rank) = winners.iter().next() {
213            return Card { suit: led, rank };
214        }
215    }
216
217    // Duck with the highest card under the winner.
218    if let Some(rank) = (follow & below(winner.rank)).iter().next_back() {
219        return Card { suit: led, rank };
220    }
221
222    // Forced above the winner; never hand ourselves the Q♠ if avoidable.
223    let safe = if led == Suit::Spades {
224        let others = follow - Holding::from_rank(Rank::Q);
225        if others.is_empty() { follow } else { others }
226    } else {
227        follow
228    };
229
230    // Last to play takes the trick anyway, so shed the highest; earlier,
231    // play the lowest and hope someone overtakes.
232    let rank = if trick.len() == 3 {
233        safe.iter().next_back().expect("checked non-empty")
234    } else {
235        safe.iter().next().expect("checked non-empty")
236    };
237    Card { suit: led, rank }
238}
239
240/// Tuning knobs for [`HeuristicBot`]
241///
242/// Like [`hearts::Rules`], the struct is non-exhaustive: start from
243/// [`HeuristicConfig::default`] and adjust fields.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245#[non_exhaustive]
246pub struct HeuristicConfig {
247    /// Take a trick to kill a suspected moon once a single opponent has
248    /// swept this many points; `u8::MAX` effectively disables the defense
249    pub moon_defense: u8,
250    /// Weight of the void bonus when scoring passes
251    ///
252    /// Zero passes purely on card danger; the default is 1.
253    pub void_weight: u8,
254    /// Extra pass-score weight per rank for hearts, atop the base rank
255    ///
256    /// Zero, the default, prices hearts like any other card: high hearts
257    /// are duckable on demand, unlike a caught Q♠.
258    pub heart_weight: u8,
259    /// High-spade pass bonuses apply while holding fewer than this many
260    /// spades below the queen; the default is 4
261    pub spade_guards: u8,
262    /// Extra pass score for the 2♣ alone
263    ///
264    /// Its holder must lead it at the first trick, so the card carries no
265    /// choice worth keeping — the cheapest thing in the deck to give away —
266    /// yet it scores bare rank 2 and is otherwise all but unpassable.  Zero,
267    /// the default, leaves it at bare rank.
268    pub two_of_clubs_bonus: u8,
269    /// Pass-score malus for a spade below the queen while the hand lacks
270    /// her; zero disables it
271    ///
272    /// After the exchange such a spade guards against the queen arriving.
273    /// The default, 4, already saturates: larger values change no more
274    /// passes.
275    pub queen_insurance: u8,
276}
277
278impl HeuristicConfig {
279    /// The shipped tuning, in a `const` context
280    ///
281    /// [`Default`] delegates here, as [`hearts::Rules`] does: a `const fn`
282    /// constructor — [`MonteCarloBot::new`](crate::MonteCarloBot::new) —
283    /// cannot call a trait method.
284    #[must_use]
285    pub const fn new() -> Self {
286        Self {
287            moon_defense: 8,
288            void_weight: 1,
289            heart_weight: 0,
290            spade_guards: 4,
291            two_of_clubs_bonus: 6,
292            queen_insurance: 4,
293        }
294    }
295}
296
297impl Default for HeuristicConfig {
298    fn default() -> Self {
299        Self::new()
300    }
301}
302
303/// A deterministic knowledge-based player
304///
305/// Fast enough for tournaments at any scale: every decision is a handful
306/// of bit operations.
307#[derive(Debug, Clone, Copy, Default)]
308pub struct HeuristicBot {
309    config: HeuristicConfig,
310}
311
312impl HeuristicBot {
313    /// A bot with the default configuration
314    #[must_use]
315    pub fn new() -> Self {
316        Self::default()
317    }
318
319    /// A bot with custom tuning
320    #[must_use]
321    pub const fn with_config(config: HeuristicConfig) -> Self {
322        Self { config }
323    }
324}
325
326/// The opponent who has swept every point so far, once the sweep weighs at
327/// least `threshold` — enough to smell like a moon attempt
328fn moon_threat(view: &View<'_>, threshold: u8) -> Option<Seat> {
329    let mut sweeper = None;
330    for seat in Seat::ALL {
331        if view.points_taken(seat) > 0 {
332            if sweeper.is_some() {
333                return None;
334            }
335            sweeper = Some(seat);
336        }
337    }
338    sweeper.filter(|&seat| seat != view.seat() && view.points_taken(seat) >= threshold)
339}
340
341/// The knowledge-based moon-defense play, shared by [`HeuristicBot`] and the
342/// [`MonteCarloBot`](crate::MonteCarloBot)'s live decision.
343///
344/// When a single opponent has swept at least `threshold` points and is
345/// winning the current trick, stop ducking: beat them as cheaply as possible
346/// (but never with our own Q♠ if avoidable), and when we cannot beat them, at
347/// least gift them no penalty card toward the sweep.  `None` when no defense
348/// applies, so the caller falls back to its normal policy.  The Monte Carlo
349/// rollouts model opponents as greedy duckers who never shoot the moon, so
350/// the search is blind to a moon in progress; this reactive overlay covers
351/// the gap.
352pub(crate) fn moon_defense(view: &View<'_>, threshold: u8) -> Option<Card> {
353    let threat = moon_threat(view, threshold)?;
354    let trick = view.current_trick()?;
355    if trick.winner() != Some(threat) {
356        return None;
357    }
358    beat_threat(view.legal_plays(), trick)
359}
360
361/// Take this trick away from the seat currently winning it
362///
363/// The knowledge-free core of [`moon_defense`], shared with the rollout
364/// policy: beat the winner as cheaply as possible but never with our own
365/// Q♠, and when we cannot beat them, gift them no penalty card toward the
366/// sweep.  `None` when the trick has no led suit or every legal play would
367/// feed the sweep, so the caller falls back to its normal policy.
368fn beat_threat(legal: Hand, trick: Trick) -> Option<Card> {
369    let led = trick.suit()?;
370    let winner = winning_card(trick).expect("a led trick has a winning card");
371    let follow = legal[led];
372    if follow.is_empty() {
373        // Void: dump the most dangerous card that carries no points into the
374        // sweeper's trick.
375        let harmless = legal - Hand::PENALTIES;
376        return harmless.into_iter().max_by_key(|card| card.rank);
377    }
378    // Beat them as cheaply as possible — taking a trick with our own Q♠
379    // costs more than the sweep it denies.
380    let mut beat = follow - below(winner.rank) - Holding::from_rank(winner.rank);
381    if led == Suit::Spades {
382        beat -= Holding::from_rank(Rank::Q);
383    }
384    if let Some(rank) = beat.iter().next() {
385        return Some(Card { suit: led, rank });
386    }
387    // Can't beat the sweep: duck plainly — and never ride the dead queen
388    // into the sweeper's trick.
389    let mut duck = follow & below(winner.rank);
390    if led == Suit::Spades {
391        let harmless = duck - Holding::from_rank(Rank::Q);
392        if !harmless.is_empty() {
393            duck = harmless;
394        }
395    }
396    duck.iter().next_back().map(|rank| Card { suit: led, rank })
397}
398
399impl Strategy for HeuristicBot {
400    fn pass_cards(&mut self, view: &View<'_>) -> [Card; 3] {
401        greedy_pass(view.hand(), self.config)
402    }
403
404    fn play_card(&mut self, view: &View<'_>) -> Card {
405        if let Some(card) = moon_defense(view, self.config.moon_defense) {
406            return card;
407        }
408        let legal = view.legal_plays();
409        let trick = view.current_trick().expect("a play decision has a trick");
410        greedy_play(legal, trick, view.played())
411    }
412
413    fn name(&self) -> &str {
414        "greedy"
415    }
416}
417
418/// The knowledge-free moon-seeking policy, the mirror of [`greedy_play`]
419///
420/// A shot has to win every trick left, so: cash our highest card when
421/// leading, top the led suit when that beats the current winner, and shed
422/// our cheapest junk when void — the hearts and the queen are cards we mean
423/// to *win*, not discard.  On a trick we can no longer take, the shot needs
424/// nothing from us and [`greedy_play`] keeps the stopper it would have
425/// wasted.
426#[cfg(any(feature = "rand", test))]
427pub(crate) fn shoot_play(legal: Hand, trick: Trick, played: Hand) -> Card {
428    let highest = |cards: Hand| {
429        cards
430            .into_iter()
431            .max_by_key(|card| card.rank)
432            .expect("the set was checked non-empty")
433    };
434
435    let Some(led) = trick.suit() else {
436        return highest(legal);
437    };
438
439    let follow = legal[led];
440    if follow.is_empty() {
441        // Void, so this trick is lost: shed the cheapest card that is not a
442        // penalty we still want to take ourselves.
443        let junk = legal - Hand::PENALTIES;
444        let shed = if junk.is_empty() { legal } else { junk };
445        return shed
446            .into_iter()
447            .min_by_key(|card| card.rank)
448            .expect("legal plays are never empty on turn");
449    }
450
451    let winner = winning_card(trick).expect("a led trick has a winning card");
452    match (follow - below(winner.rank) - Holding::from_rank(winner.rank))
453        .iter()
454        .next_back()
455    {
456        Some(rank) => Card { suit: led, rank },
457        None => greedy_play(legal, trick, played),
458    }
459}
460
461/// The rollout flavor of the policy, for omniscient Monte Carlo worlds
462///
463/// `shooter`, when set, is the seat whose moon the world is testing: it
464/// plays [`shoot_play`] for as long as the shot is alive, and the other
465/// three stop ducking once the shooter holds the live table's eight
466/// points and is winning the trick — the same trigger [`HeuristicBot`]'s
467/// moon-defense overlay fires on.  Defending from trick 1 prices every
468/// shot against a table no real opponent fields, while greedy duckers
469/// with no trigger at all would make every moon look like a laydown.
470///
471/// `played` must equal `round.played()`; the caller threads it so a
472/// rollout does not refold the whole trick history at every play.
473#[cfg(feature = "rand")]
474pub(crate) fn rollout_play(
475    round: &hearts::Round,
476    seat: Seat,
477    shooter: Option<Seat>,
478    played: Hand,
479) -> Card {
480    let legal = round.legal_plays(seat);
481    let trick = round.current_trick().expect("a playing round has a trick");
482
483    if let Some(shooter) = shooter {
484        // A shot dies the moment anyone else scores; from there the shooter
485        // bails out to the greedy policy, as a real one would.
486        let alive = Seat::ALL
487            .into_iter()
488            .all(|other| other == shooter || round.points_taken(other) == 0);
489        if !alive {
490            return greedy_play(legal, trick, played);
491        }
492        if seat == shooter {
493            return shoot_play(legal, trick, played);
494        }
495        if trick.winner() == Some(shooter)
496            && round.points_taken(shooter) >= HeuristicConfig::default().moon_defense
497            && let Some(card) = beat_threat(legal, trick)
498        {
499            return card;
500        }
501    }
502
503    greedy_play(legal, trick, played)
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509
510    fn card(text: &str) -> Card {
511        text.parse().expect("a valid card")
512    }
513
514    fn hand(text: &str) -> Hand {
515        text.parse().expect("a valid hand")
516    }
517
518    /// The policy this module replaced: one flat sort of the dealt thirteen,
519    /// ties falling to whichever suit `Hand`'s iterator reached first.
520    fn flat_pass(dealt: Hand, config: HeuristicConfig) -> [Card; 3] {
521        let mut cards: Vec<Card> = dealt.into_iter().collect();
522        cards.sort_by_key(|&card| -pass_score(dealt, card, config));
523        [cards[0], cards[1], cards[2]]
524    }
525
526    #[test]
527    fn passing_dumps_the_unprotected_queen() {
528        // Q♠ with one guard, the A♥, and filler.
529        let dealt = hand("234567.89.A.2Q");
530        let picks = greedy_pass(dealt, HeuristicConfig::default());
531        assert!(picks.contains(&card("Q♠")));
532        assert!(picks.contains(&card("A♥")));
533
534        // Well guarded, the queen stays; the hearts and short suits go.
535        let guarded = hand("234.8.9A.234567Q");
536        let picks = greedy_pass(guarded, HeuristicConfig::default());
537        assert!(!picks.contains(&card("Q♠")));
538    }
539
540    #[test]
541    fn passing_completes_a_void_instead_of_scattering() {
542        // ♠J86 ♥A6 ♦K2 ♣976432.  Scored flat against the dealt thirteen the
543        // order is A♥ 18, K♦ 17, J♠ 11, 6♥ 10, so one sort passes A♥ K♦ J♠
544        // and leaves both red doubletons alive — three void bonuses
545        // collected, no void created.  Sequentially the A♥ leaves the 6♥ a
546        // singleton worth 6 + 6 = 12, which beats the J♠: the pass opens a
547        // real heart void and keeps the 2♦ as a clean duck.
548        // Queen insurance would demote the J♠ and blur the contrast.
549        let dealt = hand("234679.2K.6A.68J");
550        let config = HeuristicConfig {
551            queen_insurance: 0,
552            ..HeuristicConfig::default()
553        };
554        assert_eq!(
555            greedy_pass(dealt, config),
556            [card("A♥"), card("K♦"), card("6♥")],
557        );
558
559        assert_eq!(
560            flat_pass(dealt, config),
561            [card("A♥"), card("K♦"), card("J♠")],
562            "the flat form scatters, which is what this replaced",
563        );
564    }
565
566    #[test]
567    fn queen_insurance_keeps_a_low_spade_without_her() {
568        let dealt = hand("2345.2345.234.29");
569        let uninsured = HeuristicConfig {
570            queen_insurance: 0,
571            ..HeuristicConfig::default()
572        };
573        assert!(greedy_pass(dealt, uninsured).contains(&card("9♠")));
574        assert!(!greedy_pass(dealt, HeuristicConfig::default()).contains(&card("9♠")));
575
576        // Holding her, a low spade scores bare rank.
577        let config = HeuristicConfig::default();
578        assert_eq!(pass_score(hand("2345.2345.23.29Q"), card("9♠"), config), 9);
579        assert_eq!(pass_score(dealt, card("9♠"), config), 5);
580    }
581
582    #[test]
583    fn the_pass_tie_break_is_designed_not_inherited() {
584        // The ladder: the queen and the two cards that catch her first, then
585        // hearts, diamonds, clubs, and a spade below the queen dead last
586        // because it is a guard worth keeping.
587        assert!(danger(card("Q♠")) > danger(card("A♥")));
588        assert!(danger(card("A♥")) > danger(card("A♦")));
589        assert!(danger(card("A♦")) > danger(card("A♣")));
590        assert!(danger(card("A♣")) > danger(card("J♠")));
591
592        // And the ladder reaching the policy.  Four nines score exactly 9
593        // apiece — a four-card suit earns no void bonus and `heart_weight`
594        // is zero — so nothing but the tie-break decides.  Stable-sort order
595        // used to send the clubs first; the 9♠ is a guard and never goes.
596        let nines = hand("2349.2349.2349.9");
597        assert_eq!(
598            greedy_pass(nines, HeuristicConfig::default()),
599            [card("9♥"), card("9♦"), card("9♣")],
600        );
601        assert_eq!(
602            flat_pass(nines, HeuristicConfig::default()),
603            [card("9♣"), card("9♦"), card("9♥")],
604            "sort stability used to reach for the clubs first",
605        );
606
607        // With five guards the Q♠/A♠/K♠ tier is disarmed, so a bare K♠ and a
608        // K♣ both score 13 and the danger class is the whole difference: the
609        // spade honor goes, the club stays.
610        assert_eq!(
611            greedy_pass(hand("234K..23K.23456K"), HeuristicConfig::default()),
612            [card("K♥"), card("K♠"), card("K♣")],
613        );
614    }
615
616    #[test]
617    fn the_forced_lead_is_worth_passing() {
618        // Four-card clubs, so the 2♣ takes no void bonus and the knob is the
619        // whole difference; the red three-card fragments are the rivals.
620        let dealt = hand("2345.234.234.234");
621        assert_eq!(
622            greedy_pass(dealt, HeuristicConfig::default()),
623            [card("2♣"), card("5♣"), card("4♣")],
624            "the shipped bonus sends the forced lead, then works the suit",
625        );
626
627        // Priced at bare rank 2 it is the last card in the deck to go, and
628        // the pass falls back to emptying hearts.
629        let unpriced = HeuristicConfig {
630            two_of_clubs_bonus: 0,
631            ..HeuristicConfig::default()
632        };
633        assert_eq!(
634            greedy_pass(dealt, unpriced),
635            [card("4♥"), card("3♥"), card("2♥")],
636        );
637    }
638
639    #[test]
640    fn shooting_takes_every_trick_it_can() {
641        // Leading: cash the highest card in hand.
642        let lead = Trick::new(Seat::North);
643        assert_eq!(shoot_play(hand("2.3.A.4"), lead, Hand::EMPTY), card("A♥"));
644
645        // Following a trick we can win: top the led suit, not duck under it.
646        let mut trick = Trick::new(Seat::North);
647        trick.play(card("9♦")).unwrap();
648        let held = hand(".2378Q..");
649        assert_eq!(shoot_play(held, trick, Hand::EMPTY), card("Q♦"));
650        assert_eq!(
651            greedy_play(held, trick, Hand::EMPTY),
652            card("8♦"),
653            "the greedy policy ducks the same holding"
654        );
655    }
656
657    #[test]
658    fn a_dead_trick_costs_the_shooter_nothing() {
659        // The nine is out of reach in diamonds, so the shot needs nothing
660        // here: fall back to the greedy policy rather than burn a stopper.
661        let mut trick = Trick::new(Seat::North);
662        trick.play(card("9♦")).unwrap();
663        let held = hand(".2378..A");
664        assert_eq!(
665            shoot_play(held, trick, Hand::EMPTY),
666            greedy_play(held, trick, Hand::EMPTY)
667        );
668
669        // Void: shed the cheapest junk and keep the penalties to win later.
670        assert_eq!(shoot_play(hand("29..3A.Q"), trick, Hand::EMPTY), card("2♣"));
671        // Nothing but penalties: the lowest of them goes.
672        assert_eq!(shoot_play(hand("..3A.Q"), trick, Hand::EMPTY), card("3♥"));
673    }
674
675    #[test]
676    fn ducking_under_the_winner() {
677        let mut trick = Trick::new(Seat::North);
678        trick.play(card("9♦")).unwrap();
679        // Duck with the highest diamond under the nine.
680        assert_eq!(
681            greedy_play(hand(".2378Q.."), trick, Hand::EMPTY),
682            card("8♦")
683        );
684    }
685
686    #[test]
687    fn last_hand_takes_only_a_point_free_trick() {
688        let mut clean = Trick::new(Seat::North);
689        for text in ["5♦", "2♦", "3♦"] {
690            clean.play(card(text)).unwrap();
691        }
692        assert_eq!(
693            greedy_play(hand(".47.."), clean, Hand::EMPTY),
694            card("7♦"),
695            "take control when nobody can add points"
696        );
697
698        let mut costly = Trick::new(Seat::North);
699        for text in ["5♣", "2♥", "3♣"] {
700            costly.play(card(text)).unwrap();
701        }
702        assert_eq!(
703            greedy_play(hand("47..."), costly, Hand::EMPTY),
704            card("4♣"),
705            "duck when the trick already carries a point"
706        );
707    }
708
709    #[test]
710    fn leading_works_the_shortest_suit() {
711        let trick = Trick::new(Seat::North);
712        let played = Hand::QUEEN_OF_SPADES;
713        assert_eq!(greedy_play(hand("234.5.67.89"), trick, played), card("5♦"));
714    }
715
716    #[test]
717    fn void_dumps_the_queen_first() {
718        let mut trick = Trick::new(Seat::North);
719        trick.play(card("9♦")).unwrap();
720        assert_eq!(greedy_play(hand("2..A.QA"), trick, Hand::EMPTY), card("Q♠"));
721        // Queen gone: a bare A♠ goes while she is at large.
722        assert_eq!(greedy_play(hand("2..A.A"), trick, Hand::EMPTY), card("A♠"));
723        // Queen already played: the high heart goes instead.
724        assert_eq!(
725            greedy_play(hand("2..A.A"), trick, Hand::QUEEN_OF_SPADES),
726            card("A♥")
727        );
728    }
729
730    #[test]
731    fn dead_queen_rides() {
732        let mut trick = Trick::new(Seat::North);
733        trick.play(card("2♠")).unwrap();
734        trick.play(card("A♠")).unwrap();
735        assert_eq!(greedy_play(hand("...5Q"), trick, Hand::EMPTY), card("Q♠"));
736    }
737
738    #[test]
739    fn forced_above_the_winner() {
740        let mut trick = Trick::new(Seat::North);
741        trick.play(card("5♠")).unwrap();
742        trick.play(card("2♠")).unwrap();
743        trick.play(card("3♠")).unwrap();
744        // Last to play and forced to take: shed the king, never the queen.
745        assert_eq!(greedy_play(hand("...QK"), trick, Hand::EMPTY), card("K♠"));
746
747        let mut early = Trick::new(Seat::North);
748        early.play(card("5♠")).unwrap();
749        // Second to play: the low card rides, hoping someone overtakes.
750        assert_eq!(greedy_play(hand("...9K"), early, Hand::EMPTY), card("9♠"));
751    }
752
753    #[test]
754    fn moon_defense_never_spends_or_gifts_the_queen() {
755        use crate::Table;
756        use hearts::{PassDirection, Round, Rules};
757
758        // South holds nothing but hearts and bleeds on trick 1, arming
759        // East as the sole sweeper for a bot with moon_defense = 1.
760        let hands = [
761            hand("23456789TJQ...QK"), // North: low clubs + Q♠ K♠
762            hand("A.23456789TJQ..J"), // East: A♣, diamonds, J♠
763            hand("..23456789TJQKA."), // South: all hearts
764            hand("K.KA..23456789TA"), // West: the rest
765        ];
766        let round = Round::from_deal(Rules::new(), PassDirection::Hold, hands).unwrap();
767        let mut table = Table::new(round);
768        let config = HeuristicConfig {
769            moon_defense: 1,
770            ..HeuristicConfig::default()
771        };
772        let mut defender = HeuristicBot::with_config(config);
773
774        // Trick 1: E takes A♣ over the forced 2♥ — one point, armed.
775        for (seat, text) in [
776            (Seat::North, "2♣"),
777            (Seat::East, "A♣"),
778            (Seat::South, "2♥"),
779            (Seat::West, "K♣"),
780        ] {
781            struct Fixed(Card);
782            impl Strategy for Fixed {
783                fn pass_cards(&mut self, _: &View<'_>) -> [Card; 3] {
784                    unreachable!()
785                }
786                fn play_card(&mut self, _: &View<'_>) -> Card {
787                    self.0
788                }
789            }
790            assert_eq!(table.turn(), Some(seat));
791            table.step(&mut Fixed(card(text))).unwrap();
792        }
793
794        // Trick 2: the sweeper leads J♠; South and West stay under it.
795        for text in ["J♠", "3♥", "2♠"] {
796            struct Fixed(Card);
797            impl Strategy for Fixed {
798                fn pass_cards(&mut self, _: &View<'_>) -> [Card; 3] {
799                    unreachable!()
800                }
801                fn play_card(&mut self, _: &View<'_>) -> Card {
802                    self.0
803                }
804            }
805            let seat = table.turn().unwrap();
806            table.step(&mut Fixed(card(text))).unwrap();
807            let _ = seat;
808        }
809
810        // North must beat the sweep with the K♠ — never its own Q♠.
811        assert_eq!(table.turn(), Some(Seat::North));
812        assert_eq!(defender.play_card(&table.view(Seat::North)), card("K♠"));
813    }
814
815    #[test]
816    fn smoke_out_the_queen() {
817        let trick = Trick::new(Seat::North);
818        let played = hand("2345...");
819        // Leading without the queen: low spades hunt it.
820        assert_eq!(greedy_play(hand("9.9.9.29"), trick, played), card("2♠"));
821        // Holding the queen: no self-hunt, so work a shortest side suit.
822        assert_eq!(greedy_play(hand("9.9..29Q"), trick, played), card("9♣"));
823        // Holding the queen and higher clubs: lead the lowest card, no hunt.
824        assert_eq!(greedy_play(hand("4.9..9Q"), trick, played), card("4♣"));
825        // Holding a high spade: keep its guards, work a shortest side suit.
826        assert_eq!(greedy_play(hand("9.9.9.29K"), trick, played), card("9♣"));
827        assert_eq!(greedy_play(hand("9.9.9.2A"), trick, played), card("9♣"));
828    }
829}