1use crate::{Strategy, View};
11use hearts::{Card, Hand, Holding, Rank, Seat, Suit, Trick};
12
13fn below(rank: Rank) -> Holding {
15 Holding::from_bits_truncate((1u16 << rank.get()) - 1)
16}
17
18pub(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 if card == Card::TWO_OF_CLUBS {
48 score += i32::from(config.two_of_clubs_bonus);
49 }
50
51 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 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
69const 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 suit => suit as u8 + 1,
84 }
85}
86
87pub(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
100pub(crate) fn greedy_pass(mut hand: Hand, config: HeuristicConfig) -> [Card; 3] {
110 [(); 3].map(|()| {
111 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
123fn winning_card(trick: Trick) -> Option<Card> {
125 trick.winner().and_then(|seat| trick.card_from(seat))
126}
127
128fn 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
158pub(crate) fn greedy_play(legal: Hand, trick: Trick, played: Hand) -> Card {
164 let Some(led) = trick.suit() else {
165 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 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 return best_dump(legal, played);
194 }
195
196 let winner = winning_card(trick).expect("a led trick has a winning card");
197
198 if led == Suit::Spades && follow.contains(Rank::Q) && winner.rank > Rank::Q {
201 return Card::QUEEN_OF_SPADES;
202 }
203
204 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 if let Some(rank) = (follow & below(winner.rank)).iter().next_back() {
219 return Card { suit: led, rank };
220 }
221
222 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245#[non_exhaustive]
246pub struct HeuristicConfig {
247 pub moon_defense: u8,
250 pub void_weight: u8,
254 pub heart_weight: u8,
259 pub spade_guards: u8,
262 pub two_of_clubs_bonus: u8,
269 pub queen_insurance: u8,
276}
277
278impl HeuristicConfig {
279 #[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#[derive(Debug, Clone, Copy, Default)]
308pub struct HeuristicBot {
309 config: HeuristicConfig,
310}
311
312impl HeuristicBot {
313 #[must_use]
315 pub fn new() -> Self {
316 Self::default()
317 }
318
319 #[must_use]
321 pub const fn with_config(config: HeuristicConfig) -> Self {
322 Self { config }
323 }
324}
325
326fn 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
341pub(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
361fn 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 let harmless = legal - Hand::PENALTIES;
376 return harmless.into_iter().max_by_key(|card| card.rank);
377 }
378 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 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#[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 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#[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 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 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 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 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 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 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 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 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 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 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 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 let lead = Trick::new(Seat::North);
643 assert_eq!(shoot_play(hand("2.3.A.4"), lead, Hand::EMPTY), card("A♥"));
644
645 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 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 assert_eq!(shoot_play(hand("29..3A.Q"), trick, Hand::EMPTY), card("2♣"));
671 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 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 assert_eq!(greedy_play(hand("2..A.A"), trick, Hand::EMPTY), card("A♠"));
723 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 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 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 let hands = [
761 hand("23456789TJQ...QK"), hand("A.23456789TJQ..J"), hand("..23456789TJQKA."), hand("K.KA..23456789TA"), ];
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 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 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 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 assert_eq!(greedy_play(hand("9.9.9.29"), trick, played), card("2♠"));
821 assert_eq!(greedy_play(hand("9.9..29Q"), trick, played), card("9♣"));
823 assert_eq!(greedy_play(hand("4.9..9Q"), trick, played), card("4♣"));
825 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}