mod compile;
mod counters;
mod deal;
mod moves;
mod play;
use std::fmt;
use crate::card::{Card, FACES};
use crate::rules::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RulesError(pub String);
impl fmt::Display for RulesError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid rules: {}", self.0)
}
}
impl std::error::Error for RulesError {}
fn err<T>(msg: impl Into<String>) -> Result<T, RulesError> {
Err(RulesError(msg.into()))
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct State {
pub piles: Vec<Vec<Card>>,
pub redeals_used: u32,
pub base_rank: Option<u8>,
pub seed: u64,
pub aux: [i16; 2],
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Action {
Transfer { from: u16, to: u16, count: u16 },
Deal,
Remove { rule: u8, n: u8, piles: [u16; 4] },
Pick { from: u16, to: u16, index: u16 },
RemoveRange { rule: u8, start: u16, len: u16 },
DealSecondary { from: u16, to: u16 },
Extract { from: u16, to: u16 },
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Move {
pub talon: u16,
pub action: Action,
}
impl Move {
pub fn new(action: Action) -> Move {
Move { talon: 0, action }
}
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum Op {
Shift { from: u16, to: u16, count: u16 },
Pick { from: u16, to: u16, index: u16 },
Turn {
from: u16,
to: u16,
count: u16,
up: bool,
},
Flip(u16),
Redeal,
SetBaseRank(u8),
SetLatch { was: bool, now: bool },
Swap { pile: u16, i: u16, j: u16 },
SwapPiles(u16, u16),
SetAux { slot: u8, was: i16, now: i16 },
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledChooseBase {
pub from_group: u16,
pub also_from_group: Option<u16>,
pub refill_from_stock: bool,
pub deal_waste: bool,
pub free_moves: bool,
pub lock_mask: u64,
}
#[derive(Clone, Debug)]
pub(crate) struct CompiledFromPileMap {
pub group: u16,
pub to: Vec<i16>,
pub only_when_stock_non_empty: bool,
pub only_non_empty_dest: bool,
pub except_ranks: Vec<u8>,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledSecondaryStock {
pub to: u16,
pub unlock_when_to_empty: bool,
pub stay_unlocked_below: Option<u16>,
}
#[derive(Clone, Debug)]
pub(crate) struct Group {
pub name: String,
pub kind: PileKind,
pub start: u16,
pub count: u16,
pub accepts_from: u64,
pub empty_accepts_from: u64,
pub refill_from: Vec<u16>,
pub refill_count: u16,
pub symmetric: bool,
pub symmetric_when_no_stock: bool,
pub symmetric_when_no_redeal: bool,
pub sym_classes: Vec<Vec<u16>>,
pub columns: Option<u16>,
pub hidden: bool,
pub reach: Option<Vec<u16>>,
pub reach_both_ways: bool,
pub reach_grid: bool,
pub empty_needs_group_empty: Option<u16>,
pub accept_whole_from_group: bool,
pub run_must_fit_build: bool,
pub move_fits: Vec<[u64; FACES]>,
pub repeat_rank: Option<u16>,
pub dropdown: bool,
pub from_pile_map: Option<CompiledFromPileMap>,
pub clear_tops: Option<(u16, u16)>,
pub first_round_bans: Vec<(u16, u16, u16)>,
pub row_start: Option<u8>,
pub replace_on_drop: Option<u16>,
pub compact: bool,
pub requires_rank_on_prev: bool,
pub match_longest_rank: bool,
pub accept_only_when_empty: bool,
pub accept_when_stock_empty: bool,
pub accept_when_waste_empty: bool,
pub compact_face_up: bool,
pub refill_largest: bool,
pub refill_on_empty: bool,
pub requires_prev_non_empty: bool,
pub max_same_rank: Option<u8>,
pub moves_when_stock_empty: bool,
pub moves_when_any_empty: Option<u16>,
pub moves_when_same_index_empty: Option<u16>,
pub moves_when_slice_empty: Option<u16>,
pub requires_same_index_non_empty: Option<u16>,
pub accept_when_same_index_empty: Option<u16>,
pub move_from_frontier: Option<crate::rules::Frontier>,
pub empty_open_after_bases: Option<u16>,
pub empty_open_when_full: Option<u16>,
pub empty_needs_first_full: bool,
pub flip_only_last: bool,
pub final_from_same_index: Option<u16>,
pub lock_build_dir: bool,
pub no_flip: bool,
pub refill_same_index: bool,
pub refill_nearest: bool,
pub require_valid_base: bool,
pub swap_bases: Option<SwapBases>,
pub swap_on_waste_match: Option<Adjacency>,
pub supermove_complete_run: bool,
pub unrestricted_from: u64,
pub lock_pile_dir: bool,
pub exclude_suit: Option<crate::card::Suit>,
pub freeze_when_built: bool,
pub accept_on_face_down: bool,
pub one_way_split: Option<u16>,
pub move_face_down_top: bool,
pub rank_sequence: Vec<u8>,
pub unique_suits: bool,
pub unique_ranks: bool,
pub cyclic_ranks: bool,
pub same_suit_group: bool,
pub same_rank_group: bool,
pub clear_when_full: Option<u16>,
pub clear_same_rank: bool,
pub run_len: Option<u8>,
pub compact_when_stock_empty: bool,
pub flip_when_dealt_out: bool,
pub spill_when_hollow: bool,
pub auto_foundation_rank: Option<u8>,
pub refill_when_empty: Option<u16>,
pub no_build_single_while_stock: bool,
pub refill_first_face_down: bool,
pub flip_when_same_index_full: Option<u16>,
pub flip_when_same_index_non_empty: Option<u16>,
pub face_down_while_same_index_non_empty: Option<u16>,
pub flip_after_prev_empty: bool,
pub flip_when_all_at_most: Option<u16>,
pub flip_when_any_empty: Option<u16>,
pub accept_any_on_single: bool,
pub empty_requires_same_index_non_empty: Option<u16>,
pub empty_match_suit_of: Option<u16>,
pub from_requires_left_empty: bool,
pub grid_vertical: bool,
pub grid_bottom_open: bool,
pub push_off_to: Vec<u16>,
pub push_off_bypasses_accept: bool,
pub fission_shift: bool,
pub requires_same_index_groups_non_empty: Vec<u16>,
pub from_pile_sets: Option<(u16, Vec<Vec<u16>>)>,
pub flush_at_len: Option<CompiledFlushAtLen>,
pub match_depth_suit: bool,
pub secondary_stock: Option<CompiledSecondaryStock>,
pub moves_when_group_cards_at_least: Option<(u16, u16)>,
pub accept_first_round_only: bool,
pub min_accept_len: Option<u16>,
pub accept_when_piles_full: Option<(u16, Vec<u16>)>,
pub joker_bomb: bool,
pub sum_limit: Option<crate::rules::SumLimit>,
pub refill_divert_ranks: Vec<u8>,
pub refill_group_on_leave: Option<CompiledLeaveRefill>,
pub refill_self_on_leave: bool,
pub staging: Option<CompiledStaging>,
pub pair_flush: Vec<CompiledPairFlush>,
pub tiered_set: Option<CompiledTieredSet>,
pub staged_empty: Option<(u16, u16)>,
pub even_segments: Option<u8>,
pub refill_when_stock_at_most: Option<u16>,
pub simple_movable: bool,
pub simple_accept: bool,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledLeaveRefill {
pub group: u16,
pub reshuffle_from: Option<u16>,
}
#[derive(Clone, Debug)]
pub(crate) struct CompiledStaging {
pub to: u16,
pub court_from: u8,
pub pip_sum: u16,
pub pip_courts: u8,
pub court_set: Vec<u8>,
pub distinct_ranks: bool,
pub max_courts: Option<u8>,
pub cap_pip_sum: bool,
pub exact_at_pips: Option<u8>,
}
impl CompiledStaging {
fn pips(&self, rank: u8) -> Option<u16> {
(rank < self.court_from).then_some(u16::from(rank))
}
pub(crate) fn accepts(&self, pile: &[Card], card: Card) -> bool {
if self.distinct_ranks && pile.iter().any(|c| c.rank() == card.rank()) {
return false;
}
match self.pips(card.rank()) {
None => {
let courts = pile
.iter()
.filter(|c| self.pips(c.rank()).is_none())
.count();
self.max_courts.is_none_or(|m| courts < m as usize)
}
Some(p) => {
let (sum, n) = pile
.iter()
.filter_map(|c| self.pips(c.rank()))
.fold((p, 1usize), |(s, n), q| (s + q, n + 1));
(!self.cap_pip_sum || sum <= self.pip_sum)
&& self
.exact_at_pips
.is_none_or(|k| n != k as usize || sum == self.pip_sum)
}
}
}
pub(crate) fn clears(&self, pile: &[Card]) -> bool {
if pile.is_empty() {
return false;
}
if !self.court_set.is_empty() {
let mut ranks: Vec<u8> = pile.iter().map(|c| c.rank()).collect();
ranks.sort_unstable();
if ranks == self.court_set {
return true;
}
}
let courts = pile
.iter()
.filter(|c| self.pips(c.rank()).is_none())
.count();
let sum: u16 = pile.iter().filter_map(|c| self.pips(c.rank())).sum();
courts == self.pip_courts as usize && sum == self.pip_sum
}
}
pub(crate) const TIERED_SET_LEN: usize = 4;
#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledTieredSet {
pub to: u16,
pub bonus: u16,
pub joker_value: u16,
}
impl CompiledTieredSet {
fn value(&self, c: Card) -> u16 {
if c.is_joker() {
self.joker_value
} else {
u16::from(c.rank())
}
}
pub(crate) fn accepts(&self, pile: &[Card], card: Card) -> bool {
let up: Vec<Card> = pile.iter().copied().filter(|c| c.is_face_up()).collect();
let Some(&base) = up.first() else {
return false;
};
match up.len() {
1 => self.value(card) + self.bonus >= self.value(base),
2 => self.value(card) + self.value(up[1]) >= self.value(base),
3 => card.is_joker() || (!base.is_joker() && card.suit() == base.suit()),
_ => false,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct CompiledPairFlush {
pub bottom_ranks: Vec<u8>,
pub to: u16,
pub suit_pos: [u8; 4],
pub first: Option<u8>,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledFlushAtLen {
pub len: u16,
pub pull_from: Option<u16>,
pub to: u16,
}
#[derive(Clone, Debug)]
pub(crate) struct Redeal {
pub group: u16,
pub times: u32,
pub how: RedealHow,
pub gather: u16,
pub refill: Option<u16>,
}
#[derive(Clone, Debug)]
pub(crate) struct PileRules {
pub build: Build,
pub empty: EmptyRule,
pub moves: MoveUnit,
pub max_cards: u16,
pub min_cards: u16,
pub max_accept: u16,
pub empty_max_accept: u16,
pub non_empty_max_accept: u16,
pub complete_runs: bool,
pub autoplay: bool,
pub competing_foundation: bool,
pub sink: bool,
pub admits: u64,
pub empty_suit: Option<crate::card::Suit>,
pub fits: [u64; FACES],
pub wild: bool,
pub wild_permissive: bool,
pub joker_anywhere: bool,
pub min_accept: u16,
pub after_pile: Option<(u16, i8)>,
pub after_pile_bottom: Option<(u16, u16, i8)>,
}
impl PileRules {
pub(crate) fn same_policy(&self, other: &PileRules) -> bool {
let PileRules {
build,
empty,
moves,
max_cards,
min_cards,
max_accept,
empty_max_accept,
non_empty_max_accept,
complete_runs,
admits,
empty_suit,
wild,
wild_permissive,
joker_anywhere,
min_accept,
after_pile,
after_pile_bottom,
autoplay: _,
competing_foundation: _,
sink: _,
fits: _,
} = self;
*build == other.build
&& *empty == other.empty
&& *moves == other.moves
&& *max_cards == other.max_cards
&& *min_cards == other.min_cards
&& *max_accept == other.max_accept
&& *empty_max_accept == other.empty_max_accept
&& *non_empty_max_accept == other.non_empty_max_accept
&& *complete_runs == other.complete_runs
&& *admits == other.admits
&& *empty_suit == other.empty_suit
&& *wild == other.wild
&& *wild_permissive == other.wild_permissive
&& *joker_anywhere == other.joker_anywhere
&& *min_accept == other.min_accept
&& *after_pile == other.after_pile
&& *after_pile_bottom == other.after_pile_bottom
}
pub(crate) fn same_foundation_policy(&self, other: &PileRules) -> bool {
self.build == other.build
&& self.empty == other.empty
&& self.empty_suit == other.empty_suit
&& self.max_cards == other.max_cards
&& self.admits == other.admits
}
}
impl Group {
pub fn piles(&self) -> std::ops::Range<u16> {
self.start..self.start + self.count
}
pub(crate) fn has_positional_rules(&self) -> bool {
self.reach.is_some()
|| self.swap_on_waste_match.is_some()
|| self.compact
|| self.compact_face_up
|| self.requires_rank_on_prev
|| self.requires_prev_non_empty
|| self.final_from_same_index.is_some()
|| self.moves_when_same_index_empty.is_some()
|| self.moves_when_slice_empty.is_some()
|| self.requires_same_index_non_empty.is_some()
|| self.accept_when_same_index_empty.is_some()
|| self.empty_requires_same_index_non_empty.is_some()
|| self.empty_match_suit_of.is_some()
|| self.move_from_frontier.is_some()
|| self.empty_open_after_bases.is_some()
|| self.empty_open_when_full.is_some()
|| self.empty_needs_first_full
|| self.flip_when_same_index_full.is_some()
|| self.flip_when_same_index_non_empty.is_some()
|| self.spill_when_hollow
|| self.face_down_while_same_index_non_empty.is_some()
|| self.flip_after_prev_empty
|| self.flip_when_any_empty.is_some()
|| self.refill_same_index
|| self.refill_nearest
|| self.one_way_split.is_some()
|| self.from_requires_left_empty
|| self.from_pile_map.is_some()
|| self.fission_shift
|| !self.requires_same_index_groups_non_empty.is_empty()
|| self.from_pile_sets.is_some()
|| self.even_segments.is_some()
}
pub(crate) fn depends_on_stock_empty(&self) -> bool {
self.accept_when_stock_empty
|| self.accept_when_waste_empty
|| self.moves_when_stock_empty
|| self.no_build_single_while_stock
|| self.refill_when_stock_at_most.is_some()
|| self
.from_pile_map
.as_ref()
.is_some_and(|m| m.only_when_stock_non_empty)
}
pub(crate) fn needs_settle(&self) -> bool {
self.compact
|| self.compact_face_up
|| !self.refill_from.is_empty()
|| self.clear_when_full.is_some()
|| self.clear_tops.is_some()
|| self.auto_foundation_rank.is_some()
|| self.flip_when_same_index_full.is_some()
|| self.flip_when_same_index_non_empty.is_some()
|| self.face_down_while_same_index_non_empty.is_some()
|| self.flip_after_prev_empty
|| self.flip_when_all_at_most.is_some()
|| self.flip_when_any_empty.is_some()
|| self.flip_when_dealt_out
|| self.spill_when_hollow
|| self.fission_shift
|| self.flush_at_len.is_some()
|| !self.pair_flush.is_empty()
|| self.staging.is_some()
|| self.tiered_set.is_some()
|| self.staged_empty.is_some()
}
pub(crate) fn hidden_scratch(name: &str, start: u16) -> Group {
Group {
name: name.into(),
kind: PileKind::Reserve,
start,
count: 1,
accepts_from: 0,
empty_accepts_from: 0,
refill_from: Vec::new(),
refill_count: 1,
symmetric: true,
symmetric_when_no_stock: false,
symmetric_when_no_redeal: false,
sym_classes: Vec::new(),
columns: None,
hidden: true,
reach: None,
reach_both_ways: false,
reach_grid: false,
empty_needs_group_empty: None,
accept_whole_from_group: false,
run_must_fit_build: false,
move_fits: Vec::new(),
repeat_rank: None,
dropdown: false,
from_pile_map: None,
clear_tops: None,
first_round_bans: Vec::new(),
row_start: None,
replace_on_drop: None,
compact: false,
requires_rank_on_prev: false,
match_longest_rank: false,
accept_only_when_empty: false,
accept_when_stock_empty: false,
accept_when_waste_empty: false,
compact_face_up: false,
refill_largest: false,
refill_on_empty: false,
requires_prev_non_empty: false,
max_same_rank: None,
moves_when_stock_empty: false,
moves_when_any_empty: None,
moves_when_same_index_empty: None,
moves_when_slice_empty: None,
requires_same_index_non_empty: None,
accept_when_same_index_empty: None,
move_from_frontier: None,
empty_open_after_bases: None,
empty_open_when_full: None,
empty_needs_first_full: false,
flip_only_last: false,
final_from_same_index: None,
lock_build_dir: false,
no_flip: false,
refill_same_index: false,
refill_nearest: false,
require_valid_base: false,
swap_bases: None,
swap_on_waste_match: None,
supermove_complete_run: false,
unrestricted_from: 0,
lock_pile_dir: false,
exclude_suit: None,
freeze_when_built: false,
accept_on_face_down: false,
one_way_split: None,
move_face_down_top: false,
rank_sequence: Vec::new(),
unique_suits: false,
unique_ranks: false,
cyclic_ranks: false,
same_suit_group: false,
same_rank_group: false,
clear_when_full: None,
clear_same_rank: false,
run_len: None,
compact_when_stock_empty: false,
flip_when_dealt_out: false,
spill_when_hollow: false,
auto_foundation_rank: None,
refill_when_empty: None,
no_build_single_while_stock: false,
refill_first_face_down: false,
flip_when_same_index_full: None,
flip_when_same_index_non_empty: None,
face_down_while_same_index_non_empty: None,
flip_after_prev_empty: false,
flip_when_all_at_most: None,
flip_when_any_empty: None,
accept_any_on_single: false,
empty_requires_same_index_non_empty: None,
empty_match_suit_of: None,
from_requires_left_empty: false,
grid_vertical: false,
grid_bottom_open: false,
push_off_to: Vec::new(),
push_off_bypasses_accept: false,
fission_shift: false,
requires_same_index_groups_non_empty: Vec::new(),
from_pile_sets: None,
flush_at_len: None,
match_depth_suit: false,
secondary_stock: None,
moves_when_group_cards_at_least: None,
accept_first_round_only: false,
accept_when_piles_full: None,
joker_bomb: false,
sum_limit: None,
refill_divert_ranks: Vec::new(),
min_accept_len: None,
refill_group_on_leave: None,
refill_self_on_leave: false,
staging: None,
pair_flush: Vec::new(),
tiered_set: None,
staged_empty: None,
even_segments: None,
refill_when_stock_at_most: None,
simple_movable: false,
simple_accept: false,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Stock {
pub pile: u16,
pub target: u16,
pub target_kind: PileKind,
pub count: u16,
pub count_per_round: Vec<u16>,
pub final_to: Option<u16>,
pub targets: Vec<u16>,
pub piles_per_round: Vec<Vec<u16>>,
pub final_piles: Option<Vec<u16>>,
pub redeals: u32,
pub require_no_empty: bool,
pub auto: bool,
pub only_when_empty: bool,
pub first_empty: bool,
pub skip_empty: bool,
pub face_up: bool,
pub deal_per_pile: bool,
pub drop_to_before_deal: Option<u16>,
pub deal_down_then_up: bool,
pub redeal_reverse: bool,
pub redeal_flip_stock: bool,
pub redeal_gather_only: bool,
pub redeal_shuffle: bool,
pub redeal_deal_all_alternating: bool,
pub deal_empty_first: bool,
pub divert_ranks: Vec<u8>,
pub final_split_to: Option<u16>,
pub final_also_to: Option<u16>,
pub require_no_empty_group: Option<u16>,
pub require_group_empty: Option<u16>,
pub auto_for_empty: Option<u16>,
pub skip_built_from: Option<u8>,
pub max_deals: Option<u32>,
pub skip_run_with_rank: Option<u8>,
pub open_next_on_rank: Option<u8>,
pub fill_grid_holes_then_row: bool,
pub fill_grid_holes_repeat: bool,
pub redeal_redistribute_reverse: bool,
pub skip_when_same_index_full: Option<u16>,
pub redeal_from_groups: Vec<u16>,
pub redeal_waste_onto_group: bool,
pub bookend: Option<u16>,
pub only_when_empty_first_round: bool,
pub top_up_group_to: Option<(u16, u16)>,
pub redeal_switch_to_auto_refill: Option<u16>,
pub sweep_to_discard_round1: Option<u16>,
pub sweep_group_on_waste: Option<u16>,
pub sweep_scratch: Option<u16>,
pub deal_after_play_to: Option<u16>,
pub redeal_bottom_count_from: Option<u16>,
pub fill_empty_or_reshuffle: bool,
pub reshuffle_at_counter: Option<i16>,
pub fan_rows: Option<u16>,
pub wrap_mid_deal: bool,
pub bonus_redeals: Option<CompiledBonusRedeals>,
}
#[derive(Clone, Debug)]
pub(crate) struct CompiledBonusRedeals {
pub groups: Vec<u16>,
pub threshold: u16,
pub max_redeals: Option<u32>,
}
impl Stock {
#[inline]
pub fn deal_count(&self, redeals_used: u32) -> u16 {
if self.count_per_round.is_empty() {
self.count
} else {
let i = (redeals_used as usize).min(self.count_per_round.len() - 1);
self.count_per_round[i]
}
}
#[inline]
pub fn round_targets(&self, redeals_used: u32) -> &[u16] {
if self.piles_per_round.is_empty() {
&self.targets
} else {
let i = (redeals_used as usize).min(self.piles_per_round.len() - 1);
&self.piles_per_round[i]
}
}
pub fn sensitive_to_empty_piles(&self) -> bool {
self.require_no_empty
|| self.require_no_empty_group.is_some()
|| self.require_group_empty.is_some()
|| self.auto_for_empty.is_some()
|| self.skip_built_from.is_some()
|| self.max_deals.is_some()
|| self.skip_run_with_rank.is_some()
|| self.skip_empty
|| self.first_empty
|| self.deal_empty_first
|| self.open_next_on_rank.is_some()
|| self.fill_grid_holes_then_row
|| self.fill_grid_holes_repeat
|| self.redeal_redistribute_reverse
|| self.skip_when_same_index_full.is_some()
|| self.top_up_group_to.is_some()
|| self.redeal_switch_to_auto_refill.is_some()
|| self.sweep_to_discard_round1.is_some()
|| self.sweep_group_on_waste.is_some()
|| self.bookend.is_some()
|| self.fill_empty_or_reshuffle
|| self.reshuffle_at_counter.is_some()
|| self.fan_rows.is_some()
|| self.wrap_mid_deal
|| self.bonus_redeals.is_some()
}
}
#[derive(Clone, Debug)]
pub(crate) struct Removal {
pub kind: RemovalKind,
pub from: u64,
pub to: u16,
pub adjacent: Option<(Adjacency, u16)>,
pub exclude_ranks: Vec<u8>,
pub needs_latch: bool,
pub min_len: Option<u8>,
pub max_sum: Option<u8>,
pub face_ten: bool,
}
#[derive(Clone, Debug)]
pub(crate) enum Win {
AllOnFoundations,
Empty(Vec<u16>),
PilesEmpty(u16, Vec<u16>, Vec<u16>),
RingRuns(u16, u16, u16),
Count(u16, u16),
CountAndEmpty(u16, u16, Vec<u16>),
CountAndSpread(u16, u16, u16),
Rows(u16, u16, u8),
AtMostPiles(u16, u16),
Score(u32),
RoundScore(u32),
AllFull(u16),
ColorSplit(u16, u16),
PackOrder(u16),
EachRowScore(u32),
PilesBuilt {
group: u16,
length: Option<u16>,
has_build: bool,
empty: Vec<u16>,
non_empty: bool,
pile: Option<u16>,
bottom: Option<u8>,
},
AllIsolated {
group: u16,
empty: Vec<u16>,
},
TargetCard {
group: u16,
discard: u16,
cards: u16,
exclude_piles: u16,
},
}
#[derive(Clone, Debug)]
pub struct Game {
rules: Rules,
pub(crate) groups: Vec<Group>,
pub(crate) pile_group: Vec<u16>,
pub(crate) pile_rules: Vec<PileRules>,
pub(crate) covered_by: Vec<Vec<u16>>,
pub(crate) has_covers: bool,
pub(crate) stock: Option<Stock>,
pub(crate) stock_pile: Option<u16>,
pub(crate) redeal: Option<Redeal>,
pub(crate) removal: Vec<Removal>,
pub(crate) win: Win,
pub(crate) row_win_fits: Option<[u64; FACES]>,
pub(crate) rank_idx: [u8; 14],
pub(crate) nranks: u8,
pub(crate) copies: u8,
pub(crate) total_cards: u16,
pub(crate) jokers: u8,
pub(crate) in_pack: [bool; FACES],
pub(crate) rank_faces: [u64; 14],
pub(crate) suit_faces: [u64; 4],
pub(crate) dependents: Vec<Vec<u8>>,
pub(crate) any_autoplay: bool,
pub(crate) compress_talon: bool,
pub(crate) simple_talon_filter: bool,
pub(crate) free_draw1_talon: bool,
pub(crate) simple_settle: bool,
pub(crate) movable_piles: Vec<u16>,
pub(crate) pick_piles: Vec<u16>,
pub(crate) targets_for_group: Vec<Vec<u16>>,
pub(crate) has_supermove: bool,
pub(crate) pile_sym_class: Vec<u16>,
pub(crate) num_sym_classes: usize,
pub(crate) force_lower_of_suit: bool,
pub(crate) waste: Option<u16>,
pub(crate) choose_base: Option<CompiledChooseBase>,
pub(crate) latch_group: Option<u16>,
pub(crate) any_secondary_stock: bool,
pub(crate) hooks: Option<std::sync::Arc<dyn crate::hooks::Hooks>>,
pub(crate) score: Option<crate::score::Score>,
pub(crate) aux: Option<counters::CompiledAux>,
pub(crate) aux_initial: [i16; 2],
pub(crate) extract: Option<(u16, Vec<u16>)>,
pub(crate) rounds: Option<Rounds>,
}
#[derive(Clone, Debug)]
pub(crate) struct Rounds {
pub crib: u16,
pub hands: Vec<u16>,
pub starter: u16,
pub discard: u16,
pub crib_down: u16,
pub hand_size: u16,
pub keep: u16,
pub next_hand_after: u16,
pub points: CribbagePoints,
}
impl Game {
pub fn rules(&self) -> &Rules {
&self.rules
}
pub fn score(&self, s: &State) -> Option<u32> {
self.score.as_ref().map(|sc| sc.score(s))
}
pub fn is_scored(&self) -> bool {
self.score.is_some()
}
pub fn target_score(&self) -> Option<u32> {
match self.win {
Win::Score(t) => Some(t),
_ => None,
}
}
pub fn distinct_moves(&self, s: &State) -> Vec<Move> {
let mut moves = self.legal_moves(s);
if let Some(sc) = self.score.as_ref().filter(|sc| sc.symmetric) {
moves.retain(|m| match m.action {
Action::Transfer { to, .. } => !sc.redundant(self, s, to),
_ => true,
});
}
moves
}
pub fn name(&self) -> &str {
&self.rules.name
}
pub fn num_piles(&self) -> usize {
self.pile_group.len()
}
pub fn pile_ref(&self, pile: u16) -> PileRef {
let g = &self.groups[self.pile_group[pile as usize] as usize];
PileRef {
group: g.name.clone(),
index: pile - g.start,
}
}
pub fn pile_index(&self, group: &str, index: u16) -> Option<u16> {
let g = self.groups.iter().find(|g| g.name == group)?;
(index < g.count).then_some(g.start + index)
}
pub fn pile_kind(&self, pile: u16) -> PileKind {
self.group_of(pile).kind
}
#[inline]
pub(crate) fn group_of(&self, pile: u16) -> &Group {
&self.groups[self.pile_group[pile as usize] as usize]
}
pub fn groups(&self) -> impl Iterator<Item = (&str, PileKind, u16)> {
self.groups
.iter()
.map(|g| (g.name.as_str(), g.kind, g.count))
}
pub fn steps(&self, start: &State, moves: &[Move]) -> Vec<Step> {
let mut s = start.clone();
let mut j = Vec::new();
let mut out = Vec::new();
for &mv in moves {
for _ in 0..mv.talon {
out.push(self.deal_step_kind(&s));
self.talon_step(&mut s, &mut j);
}
match mv.action {
Action::Deal => out.push(self.deal_step_kind(&s)),
Action::Transfer { from, to, count } => out.push(Step::Move {
from: self.pile_ref(from),
to: self.pile_ref(to),
count,
}),
Action::Pick { from, to, index } => out.push(Step::Pick {
from: self.pile_ref(from),
to: self.pile_ref(to),
index,
}),
Action::Remove { n, piles, .. } => out.push(Step::Remove {
piles: piles[..n as usize]
.iter()
.map(|&p| self.pile_ref(p))
.collect(),
}),
Action::RemoveRange { start, len, .. } => out.push(Step::Remove {
piles: (start..start + len).map(|p| self.pile_ref(p)).collect(),
}),
Action::DealSecondary { from, to } => out.push(Step::DealSecondary {
from: self.pile_ref(from),
to: self.pile_ref(to),
}),
Action::Extract { from, to } => out.push(Step::Extract {
from: self.pile_ref(from),
to: self.pile_ref(to),
}),
}
self.apply(&mut s, Move::new(mv.action), &mut j);
j.clear();
}
out
}
pub fn step_to_move(&self, s: &State, step: &Step) -> Option<Move> {
let idx = |r: &PileRef| self.pile_index(&r.group, r.index);
let mv = match step {
Step::Deal | Step::Redeal if self.redeal.is_some() => {
if !matches!(step, Step::Redeal) {
return None;
}
Move::new(Action::Deal)
}
Step::Deal | Step::Redeal => {
let empty = self
.stock
.as_ref()
.is_some_and(|st| s.piles[st.pile as usize].is_empty());
if empty != matches!(step, Step::Redeal) {
return None;
}
Move::new(Action::Deal)
}
Step::Move { from, to, count } => Move::new(Action::Transfer {
from: idx(from)?,
to: idx(to)?,
count: *count,
}),
Step::Pick { from, to, index } => Move::new(Action::Pick {
from: idx(from)?,
to: idx(to)?,
index: *index,
}),
Step::DealSecondary { from, to } => Move::new(Action::DealSecondary {
from: idx(from)?,
to: idx(to)?,
}),
Step::Extract { from, to } => Move::new(Action::Extract {
from: idx(from)?,
to: idx(to)?,
}),
Step::Remove { piles } => {
let mut want: Vec<u16> = piles.iter().map(idx).collect::<Option<_>>()?;
want.sort_unstable();
let mut moves = Vec::new();
self.gen_removals(s, None, &mut moves);
return moves.into_iter().find(|m| match m.action {
Action::Remove { n, piles, .. } => piles[..n as usize] == want[..],
Action::RemoveRange { start, len, .. } => {
want.len() == len as usize
&& want.iter().enumerate().all(|(i, &p)| p == start + i as u16)
}
_ => false,
});
}
};
self.is_legal(s, mv).then_some(mv)
}
pub fn legal_steps(&self, s: &State) -> Vec<Step> {
let mut out = Vec::new();
self.gen_actions_unpruned(s, &mut out);
let mut steps: Vec<Step> = out.iter().map(|&m| self.steps(s, &[m]).remove(0)).collect();
if self.can_deal(s) {
steps.push(self.deal_step_kind(s));
}
steps
}
pub fn play_step(&self, s: &mut State, step: &Step) -> Result<(), IllegalStep> {
let mv = self
.step_to_move(s, step)
.ok_or_else(|| IllegalStep(step.clone()))?;
let mut j = Vec::new();
self.apply(s, mv, &mut j);
Ok(())
}
pub fn describe_step(
&self,
s: &State,
step: &Step,
) -> Result<(StepDetails, State), IllegalStep> {
let mv = self
.step_to_move(s, step)
.ok_or_else(|| IllegalStep(step.clone()))?;
let mut cards = Vec::new();
let mut onto = None;
match step {
Step::Move { from, to, count } => {
if let Some(fp) = self.pile_index(&from.group, from.index) {
let pile = &s.piles[fp as usize];
let start = pile.len().saturating_sub(*count as usize);
cards.extend(pile[start..].iter().map(|c| c.to_string()));
}
if let Some(tp) = self.pile_index(&to.group, to.index) {
onto = s.piles[tp as usize].last().map(|c| c.to_string());
}
}
Step::Pick { from, to, index } => {
if let Some(fp) = self.pile_index(&from.group, from.index) {
if let Some(c) = s.piles[fp as usize].get(*index as usize) {
cards.push(c.to_string());
}
}
if let Some(tp) = self.pile_index(&to.group, to.index) {
onto = s.piles[tp as usize].last().map(|c| c.to_string());
}
}
Step::Extract { from, to } => {
if let Some(fp) = self.pile_index(&from.group, from.index) {
let pile = &s.piles[fp as usize];
if pile.len() >= 2 {
cards.push(pile[pile.len() - 2].to_string());
}
}
if let Some(tp) = self.pile_index(&to.group, to.index) {
onto = s.piles[tp as usize].last().map(|c| c.to_string());
}
}
Step::Remove { piles } => {
for r in piles {
if let Some(p) = self.pile_index(&r.group, r.index) {
if let Some(c) = s.piles[p as usize].last() {
cards.push(c.to_string());
}
}
}
}
Step::DealSecondary { from, to } => {
if let Some(fp) = self.pile_index(&from.group, from.index) {
if let Some(c) = s.piles[fp as usize].last() {
cards.push(c.up().to_string());
}
}
if let Some(tp) = self.pile_index(&to.group, to.index) {
onto = s.piles[tp as usize].last().map(|c| c.to_string());
}
}
Step::Deal | Step::Redeal => {}
}
let mut next = s.clone();
let mut j = Vec::new();
self.apply(&mut next, mv, &mut j);
let mut flipped = Vec::new();
for g in self
.groups
.iter()
.filter(|g| !g.hidden && g.kind != PileKind::Stock)
{
for p in g.piles() {
let before = &s.piles[p as usize];
let after = &next.piles[p as usize];
let shared = before.len().min(after.len());
for i in 0..shared {
if !before[i].is_face_up()
&& after[i].is_face_up()
&& before[i].face() == after[i].face()
{
flipped.push(FlippedCard {
pile: self.pile_ref(p),
card: after[i].to_string(),
});
}
}
}
}
let text = format_step_details(step, &cards, onto.as_deref());
Ok((
StepDetails {
step: step.clone(),
cards,
onto,
flipped,
text,
},
next,
))
}
pub fn describe_steps(
&self,
initial: &State,
steps: &[Step],
) -> Result<Vec<StepDetails>, IllegalStep> {
let mut cur = initial.clone();
let mut out = Vec::with_capacity(steps.len());
for step in steps {
let (details, next) = self.describe_step(&cur, step)?;
out.push(details);
cur = next;
}
Ok(out)
}
fn deal_step_kind(&self, s: &State) -> Step {
if self.redeal.is_some() {
return Step::Redeal;
}
let st = self.stock.as_ref().unwrap();
if s.piles[st.pile as usize].is_empty() {
Step::Redeal
} else {
Step::Deal
}
}
pub fn render(&self, s: &State) -> String {
let mut out = String::new();
for g in self.groups.iter().filter(|g| !g.hidden) {
for p in g.piles() {
let cards: Vec<String> =
s.piles[p as usize].iter().map(|c| c.to_string()).collect();
let label = if g.count == 1 {
g.name.clone()
} else {
format!("{} {}", g.name, p - g.start + 1)
};
out.push_str(&format!("{label:>14}: {}\n", cards.join(" ")));
}
}
if s.redeals_used > 0 {
out.push_str(&format!("{:>14}: {}\n", "redeals used", s.redeals_used));
}
out
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IllegalMove(pub Move);
impl fmt::Display for IllegalMove {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "illegal move: {:?}", self.0)
}
}
impl std::error::Error for IllegalMove {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IllegalStep(pub Step);
impl fmt::Display for IllegalStep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "illegal step: {}", self.0)
}
}
impl std::error::Error for IllegalStep {}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PileRef {
pub group: String,
pub index: u16,
}
impl fmt::Display for PileRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.group, self.index + 1)
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Step {
Deal,
Redeal,
Move {
from: PileRef,
to: PileRef,
count: u16,
},
Remove { piles: Vec<PileRef> },
Pick {
from: PileRef,
to: PileRef,
index: u16,
},
DealSecondary { from: PileRef, to: PileRef },
Extract { from: PileRef, to: PileRef },
}
impl fmt::Display for Step {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Step::Deal => write!(f, "deal"),
Step::Redeal => write!(f, "redeal"),
Step::Move { from, to, count: 1 } => write!(f, "{from} -> {to}"),
Step::Move { from, to, count } => write!(f, "{from} -> {to} ({count} cards)"),
Step::Pick { from, to, index } => write!(f, "{from}[{index}] -> {to}"),
Step::Remove { piles } => {
let names: Vec<String> = piles.iter().map(|p| p.to_string()).collect();
write!(f, "remove {}", names.join(" + "))
}
Step::DealSecondary { from, to } => write!(f, "deal {from} -> {to}"),
Step::Extract { from, to } => write!(f, "{from} (second card) -> {to}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct FlippedCard {
pub pile: PileRef,
pub card: String,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct StepDetails {
pub step: Step,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cards: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub onto: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub flipped: Vec<FlippedCard>,
pub text: String,
}
fn format_step_details(step: &Step, cards: &[String], onto: Option<&str>) -> String {
let target = onto.unwrap_or("empty");
match step {
Step::Deal | Step::Redeal => step.to_string(),
Step::Move { from, to, count: 1 } if !cards.is_empty() => {
format!("{} -> {target} ({from} -> {to})", cards[0])
}
Step::Move { from, to, count } if !cards.is_empty() => {
format!("{} ({count} cards) -> {target} ({from} -> {to})", cards[0])
}
Step::Pick { from, to, index } if !cards.is_empty() => {
format!("{} -> {target} ({from}[{index}] -> {to})", cards[0])
}
Step::Extract { from, to } if !cards.is_empty() => {
format!("{} -> {target} ({from} (second card) -> {to})", cards[0])
}
Step::DealSecondary { from, to } if !cards.is_empty() => {
format!("deal {} -> {target} ({from} -> {to})", cards[0])
}
Step::Remove { piles } if !cards.is_empty() => {
let names: Vec<String> = piles.iter().map(|p| p.to_string()).collect();
format!("remove {} ({})", cards.join(" + "), names.join(" + "))
}
_ => step.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presets;
#[test]
fn game_metadata_render_and_steps() {
let mut r = presets::klondike1();
r.stock.as_mut().unwrap().unlimited_redeals = false;
r.stock.as_mut().unwrap().redeals = 2;
let g = Game::new(r).unwrap();
assert_eq!(g.name(), "Klondike");
assert_eq!(g.groups().count(), 4);
assert_eq!(g.pile_kind(0), PileKind::Stock);
let mut s = g.deal(1);
assert!(g.legal_steps(&s).contains(&Step::Deal));
g.play_step(&mut s, &Step::Deal).unwrap();
assert!(g.play_step(&mut s, &Step::Redeal).is_err());
while g.step_to_move(&s, &Step::Deal).is_some() {
g.play_step(&mut s, &Step::Deal).unwrap();
}
assert!(g.legal_steps(&s).contains(&Step::Redeal));
g.play_step(&mut s, &Step::Redeal).unwrap();
let rendered = g.render(&s);
assert!(rendered.contains("redeals used"), "{rendered}");
assert_eq!(Step::Deal.to_string(), "deal");
assert_eq!(Step::Redeal.to_string(), "redeal");
let p0 = PileRef {
group: "tableau".into(),
index: 0,
};
let p1 = PileRef {
group: "tableau".into(),
index: 1,
};
assert_eq!(
Step::Move {
from: p0.clone(),
to: p1.clone(),
count: 1
}
.to_string(),
"tableau 1 -> tableau 2"
);
assert_eq!(
Step::Move {
from: p0.clone(),
to: p1.clone(),
count: 3
}
.to_string(),
"tableau 1 -> tableau 2 (3 cards)"
);
assert_eq!(
Step::Remove {
piles: vec![p0, p1]
}
.to_string(),
"remove tableau 1 + tableau 2"
);
let im = IllegalMove(Move::new(Action::Deal));
assert!(im.to_string().contains("illegal move"));
let is = IllegalStep(Step::Redeal);
assert!(is.to_string().contains("illegal step"));
}
#[test]
fn step_to_move_handles_redeal_and_remove() {
let g_lbl = Game::new(presets::la_belle_lucie()).unwrap();
let s_lbl = g_lbl.deal(1);
assert!(g_lbl.step_to_move(&s_lbl, &Step::Deal).is_none());
assert!(g_lbl.step_to_move(&s_lbl, &Step::Redeal).is_some());
let g_pyr = Game::new(presets::pyramid()).unwrap();
let s_pyr = g_pyr.deal(1);
let remove = g_pyr
.legal_steps(&s_pyr)
.into_iter()
.find(|st| matches!(st, Step::Remove { .. }))
.expect("pyramid seed 1 has a removal");
assert!(g_pyr.step_to_move(&s_pyr, &remove).is_some());
}
#[test]
fn contiguous_sum_range_and_r1_mechanics() {
use crate::card::{Card, Suit};
let mut t = GroupRules::new("tableau", PileKind::Tableau, 10)
.empty(EmptyRule::None)
.moves(MoveUnit::None)
.max_cards(1);
t.compact = false;
let mut r = Rules::new(
"contiguous_range_test",
Pack::new(&[Suit::Spades, Suit::Hearts], &[1, 2, 3, 4, 5, 11, 12, 13]),
vec![
GroupRules::new("foundation", PileKind::Foundation, 1)
.build(BuildBy::None, Dir::Up)
.empty(EmptyRule::None),
t,
GroupRules::new("stock", PileKind::Stock, 1),
],
vec![
DealStep::to("tableau").piles(&[0]).each(1),
DealStep::to("stock").rest().down(),
],
);
let mut rem = RemovalRules::new(
RemovalKind::ContiguousSumMultiple {
divisor: 10,
max_len: 10,
},
&["tableau"],
"foundation",
);
rem.min_len = Some(2);
rem.max_sum = Some(30);
rem.face_ten = true;
r.removal = vec![rem];
r.win = WinRule::Count {
group: "foundation".into(),
cards: 6,
};
let json = serde_json::to_string(&r).unwrap();
let r_back: Rules = serde_json::from_str(&json).unwrap();
assert_eq!(r, r_back);
let legacy_json = r#"{"kind":{"contiguous_sum_multiple":{"divisor":10,"max_len":4}},"from":["tableau"],"to":"foundation"}"#;
let legacy: RemovalRules = serde_json::from_str(legacy_json).unwrap();
assert_eq!(
legacy,
RemovalRules::new(
RemovalKind::ContiguousSumMultiple {
divisor: 10,
max_len: 4,
},
&["tableau"],
"foundation",
)
);
let g = Game::new(r).unwrap();
assert!(!g.groups[1].symmetric);
let mut s = g.deal(0);
for p in &mut s.piles {
p.clear();
}
let tab = g.groups[1].start;
s.piles[tab as usize].push(Card::new(Suit::Spades, 1));
s.piles[tab as usize + 1].push(Card::new(Suit::Spades, 2));
s.piles[tab as usize + 2].push(Card::new(Suit::Spades, 3));
s.piles[tab as usize + 3].push(Card::new(Suit::Spades, 4));
s.piles[tab as usize + 4].push(Card::new(Suit::Hearts, 11));
s.piles[tab as usize + 5].push(Card::new(Suit::Hearts, 12));
s.piles[tab as usize + 6].push(Card::new(Suit::Hearts, 13));
let moves = g.legal_moves(&s);
let range_mv = moves
.iter()
.copied()
.find(|m| matches!(m.action, Action::RemoveRange { len: 6, .. }))
.expect("6-card contiguous removal totaling 30");
assert!(!moves
.iter()
.any(|m| matches!(m.action, Action::RemoveRange { len: 7, .. })));
assert!(!moves
.iter()
.any(|m| matches!(m.action, Action::Remove { n: 1, .. })));
let steps = g.steps(&s, &[range_mv]);
assert_eq!(
steps[0],
Step::Remove {
piles: (0..6)
.map(|index| PileRef {
group: "tableau".into(),
index,
})
.collect()
}
);
assert_eq!(g.step_to_move(&s, &steps[0]), Some(range_mv));
let orig = s.clone();
let mut j = Vec::new();
g.apply(&mut s, range_mv, &mut j);
assert_eq!(s.piles[g.groups[0].start as usize].len(), 6);
assert!(g.is_won(&s));
g.undo_to(&mut s, &mut j, 0);
assert_eq!(s, orig);
let mut r2 = Rules::new(
"r1_gates_test",
Pack::new(&[Suit::Spades, Suit::Hearts], &[1, 2, 3, 4]),
vec![
GroupRules::new("stock", PileKind::Stock, 1),
GroupRules::new("foundation", PileKind::Foundation, 2)
.build(BuildBy::Suit, Dir::Up)
.empty(EmptyRule::Rank(1))
.max_cards(4),
GroupRules::new("tableau", PileKind::Tableau, 4)
.build(BuildBy::Suit, Dir::Down)
.moves(MoveUnit::Top)
.empty(EmptyRule::Any)
.accept_any_on_single()
.empty_requires_same_index_non_empty("foundation")
.empty_match_suit_of("foundation"),
],
vec![DealStep::to("stock").rest().down()],
);
r2.stock = Some(StockRules::to("tableau").open_next_on_rank(4));
let g2 = Game::new(r2).unwrap();
assert!(!g2.compress_talon);
assert!(!g2.any_autoplay);
assert!(!g2.groups[1].symmetric);
assert!(!g2.groups[2].symmetric);
let mut s2 = g2.deal(0);
for p in &mut s2.piles {
p.clear();
}
let sp = g2.stock_pile.unwrap() as usize;
let t0 = g2.groups[2].start as usize;
let f0 = g2.groups[1].start as usize;
s2.piles[sp].push(Card::new(Suit::Spades, 2).down());
s2.piles[sp].push(Card::new(Suit::Hearts, 4).down());
let s2_before = s2.clone();
let mut j2 = Vec::new();
g2.apply(&mut s2, Move::new(Action::Deal), &mut j2);
assert_eq!(s2.piles[t0], vec![Card::new(Suit::Hearts, 4)]);
g2.apply(&mut s2, Move::new(Action::Deal), &mut j2);
assert_eq!(
s2.piles[t0],
vec![Card::new(Suit::Hearts, 4), Card::new(Suit::Spades, 2)]
);
g2.undo_to(&mut s2, &mut j2, 0);
assert_eq!(s2, s2_before);
s2.piles[sp].clear();
s2.piles[f0].push(Card::new(Suit::Spades, 1));
s2.piles[t0].push(Card::new(Suit::Spades, 3));
s2.piles[t0 + 1].push(Card::new(Suit::Hearts, 2));
assert!(g2.is_legal(
&s2,
Move::new(Action::Transfer {
from: t0 as u16,
to: (t0 + 1) as u16,
count: 1,
})
));
assert!(!g2.is_legal(
&s2,
Move::new(Action::Transfer {
from: (t0 + 1) as u16,
to: (t0 + 2) as u16,
count: 1,
})
));
assert!(g2.is_legal(
&s2,
Move::new(Action::Transfer {
from: t0 as u16,
to: (t0 + 2) as u16,
count: 1,
})
));
assert!(!g2.is_legal(
&s2,
Move::new(Action::Transfer {
from: t0 as u16,
to: (t0 + 3) as u16,
count: 1,
})
));
}
#[test]
fn grid_hole_fill_phases_and_can_deal() {
use crate::card::Suit;
let mut r = Rules::new(
"hole_fill_unit",
Pack::new(&[Suit::Spades, Suit::Hearts, Suit::Clubs], &[1, 2, 3, 4]),
vec![
GroupRules::new("stock", PileKind::Stock, 1),
GroupRules::new("tableau", PileKind::Tableau, 9)
.layout(Layout::GridVertical { columns: 3 })
.max_cards(1),
],
vec![DealStep::to("stock").rest().down()],
);
let mut st = StockRules::to("tableau");
st.fill_grid_holes_then_row = true;
r.stock = Some(st);
r.win = WinRule::Empty(vec!["tableau".into(), "stock".into()]);
let g = Game::new(r).unwrap();
let tab = g.groups[1].start as usize;
let stk = g.groups[0].start as usize;
let mut s = g.deal(1);
assert!(g.can_deal(&s));
let mut j = Vec::new();
assert!(g.talon_step(&mut s, &mut j));
assert_eq!(s.piles[tab].len(), 1);
assert_eq!(s.piles[tab + 1].len(), 1);
assert_eq!(s.piles[tab + 2].len(), 1);
assert!(s.piles[tab + 3].is_empty());
assert!(g.talon_step(&mut s, &mut j));
assert_eq!(s.piles[tab + 3].len(), 1);
assert_eq!(s.piles[tab + 4].len(), 1);
assert_eq!(s.piles[tab + 5].len(), 1);
assert!(g.talon_step(&mut s, &mut j));
for i in 0..9 {
assert_eq!(s.piles[tab + i].len(), 1);
}
assert!(!s.piles[stk].is_empty());
assert!(!g.can_deal(&s));
let c0 = s.piles[tab].pop().unwrap().down();
let c3 = s.piles[tab + 3].pop().unwrap().down();
let c1 = s.piles[tab + 1].pop().unwrap().down();
let c7 = s.piles[tab + 7].pop().unwrap().down();
s.piles[stk].extend([c0, c3, c1, c7]);
s.piles[stk].truncate(3);
assert!(g.can_deal(&s));
let mark = j.len();
assert!(g.talon_step(&mut s, &mut j));
assert_eq!(s.piles[tab + 3].len(), 1);
assert_eq!(s.piles[tab + 1].len(), 1);
assert_eq!(s.piles[tab].len(), 1);
assert!(s.piles[tab + 7].is_empty());
g.undo_to(&mut s, &mut j, mark);
assert!(s.piles[tab + 3].is_empty());
assert!(s.piles[tab + 1].is_empty());
assert!(s.piles[tab].is_empty());
}
#[test]
fn fission_shift_bottom_up_and_undo() {
use crate::card::Suit;
let mut tab = GroupRules::new("tableau", PileKind::Tableau, 5)
.build(BuildBy::Any, Dir::Down)
.moves(MoveUnit::Top)
.empty(EmptyRule::None)
.layout(Layout::GridBottomOpen { columns: 1 });
tab.fission_shift = true;
let mut r = Rules::new(
"fission_unit",
Pack::new(&[Suit::Spades], &[1, 2, 3, 4, 5]),
vec![
GroupRules::new("cell", PileKind::Cell, 1)
.empty(EmptyRule::Any)
.moves(MoveUnit::Top)
.max_cards(1),
tab,
],
vec![DealStep::to("tableau").each(1)],
);
r.win = WinRule::AllIsolated {
group: "tableau".into(),
empty: vec!["cell".into()],
};
let g = Game::new(r).unwrap();
let mut s = g.deal(1);
let orig = s.clone();
let cell = g.groups[0].start;
let t = g.groups[1].start;
let expect_r2 = s.piles[(t + 2) as usize][0];
let expect_r3 = s.piles[(t + 3) as usize][0];
let mut j = Vec::new();
g.apply(
&mut s,
Move::new(Action::Transfer {
from: t + 4,
to: cell,
count: 1,
}),
&mut j,
);
assert!(s.piles[(t + 2) as usize].is_empty());
assert_eq!(s.piles[(t + 3) as usize], vec![expect_r2]);
assert_eq!(s.piles[(t + 4) as usize], vec![expect_r3]);
assert!(!g.is_won(&s));
g.undo_to(&mut s, &mut j, 0);
assert_eq!(s, orig);
}
#[test]
fn compact_columns_noop_and_after_neighbor_wrap() {
use crate::card::Suit;
let mut r = Rules::new(
"cc_unit",
Pack::new(&[Suit::Spades], &[1, 3, 5, 7]),
vec![
GroupRules::new("stock", PileKind::Stock, 1),
GroupRules::new("tableau", PileKind::Tableau, 4)
.build_rule(Build::new(BuildBy::Suit, Dir::Up).wrap())
.empty(EmptyRule::AfterNeighbor { first: 0 })
.moves(MoveUnit::Top)
.max_cards(1)
.layout(Layout::Grid { columns: 2 }),
],
vec![DealStep::to("tableau").each(1)],
);
r.redeal = Some(RedealRules::new(
"tableau",
RedealHow::CompactColumns {
refill_from: Some("stock".into()),
},
));
r.win = WinRule::Empty(vec!["tableau".into(), "stock".into()]);
let g = Game::new(r).unwrap();
let mut s = g.deal(1);
assert!(!g.can_deal(&s));
let t = g.groups[1].start as usize;
s.piles[t].clear();
s.piles[t + 1] = vec![Card::new(Suit::Spades, 1).up()];
s.piles[t + 2] = vec![Card::new(Suit::Spades, 3).up()];
s.piles[t + 3] = vec![Card::new(Suit::Spades, 5).up()];
let mask = g.empty_set(t as u16, &s);
assert_eq!(mask, 1u64 << Card::new(Suit::Spades, 7).face());
s.piles[t + 1].clear();
assert_eq!(g.empty_set(t as u16 + 1, &s), 0);
assert!(g.can_deal(&s));
}
#[test]
fn describe_step_and_steps_report_cards_onto_and_flips() {
let fc = Game::new(presets::freecell()).unwrap();
let s = fc.deal(1);
let step = fc
.legal_steps(&s)
.into_iter()
.find(|st| matches!(st, Step::Move { .. }))
.expect("freecell has legal moves");
let (details, next) = fc.describe_step(&s, &step).unwrap();
assert_eq!(details.step, step);
assert_eq!(details.cards.len(), 1);
assert!(details.text.contains(&details.cards[0]));
assert!(details.flipped.is_empty());
let mut s2 = s.clone();
fc.play_step(&mut s2, &step).unwrap();
assert_eq!(next, s2);
let list = fc.describe_steps(&s, &[step]).unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0], details);
let kl = Game::new(presets::klondike1()).unwrap();
let mut found_flip = false;
for seed in 1..=20 {
let ks = kl.deal(seed);
for st in kl.legal_steps(&ks) {
let (d, _) = kl.describe_step(&ks, &st).unwrap();
if !d.flipped.is_empty() {
assert_eq!(d.flipped[0].pile.group, "tableau");
assert!(!d.flipped[0].card.starts_with('~'));
found_flip = true;
break;
}
}
if found_flip {
break;
}
}
assert!(
found_flip,
"expected at least one Klondike move to flip a face-down card"
);
}
}