8 Commits

Author SHA1 Message Date
Quaternions bc2d1b126e clean history 2026-05-19 10:22:44 -07:00
Quaternions 08e8656ecf test klondike iter 2026-05-19 09:46:11 -07:00
Quaternions 73ffef76b0 delete infinite loop test 2026-05-19 09:45:49 -07:00
Quaternions 0a34deb630 Game implies Clone + Debug for associated types 2026-05-19 08:21:21 -07:00
Quaternions bc05bbdc50 O(1) undo 2026-05-19 08:18:28 -07:00
Quaternions f9012b01c4 format 2026-05-19 08:02:23 -07:00
Quaternions e18e242eae refactor is_winnable 2026-05-19 08:02:00 -07:00
Quaternions 576489c226 Revert "temporarily remove is_winnable because it doesn't work"
This reverts commit 5a52f2ab7a.
2026-05-19 07:10:38 -07:00
8 changed files with 252 additions and 368 deletions
Generated
+2 -2
View File
@@ -11,8 +11,8 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]] [[package]]
name = "arrayvec" name = "arrayvec"
version = "0.7.6" version = "0.7.6"
source = "sparse+https://git.aleshym.co/api/packages/Quaternions/cargo/" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "813440870d646c57c222c1d713dc4e3ddcb2919c3801564d767d85d7bf2afee4" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
+1 -1
View File
@@ -9,7 +9,7 @@ authors = ["Rhys Lloyd <krakow20@gmail.com>"]
keywords = ["card", "cards", "solitaire", "klondike"] keywords = ["card", "cards", "solitaire", "klondike"]
[dependencies] [dependencies]
arrayvec = { version = "0.7.6", registry = "Quaternions", features = ["len_u8"], default-features = false } arrayvec = "0.7.6"
[lints] [lints]
workspace = true workspace = true
+119 -104
View File
@@ -6,16 +6,11 @@ struct ReadmeDoctests;
use core::ops::RangeBounds; use core::ops::RangeBounds;
// TODO: pub struct ValidInstruction<I>(I); // TODO: pub struct ValidInstruction<I>(I);
pub trait Game { pub trait Game: Clone + core::fmt::Debug {
type Score; type Stats: Clone + core::fmt::Debug;
type Stats; type Config: Clone + core::fmt::Debug;
type Config; type Instruction: Clone + core::fmt::Debug;
type Instruction; fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<Self>;
fn score(&self, stats: &Self::Stats, config: &Self::Config) -> Self::Score;
fn possible_instructions(
&self,
config: &Self::Config,
) -> impl Iterator<Item = Self::Instruction> + use<Self>;
fn is_instruction_valid(&self, config: &Self::Config, instruction: Self::Instruction) -> bool; fn is_instruction_valid(&self, config: &Self::Config, instruction: Self::Instruction) -> bool;
fn process_instruction( fn process_instruction(
&mut self, &mut self,
@@ -249,13 +244,10 @@ impl<const DN: usize, const UP: usize> Pile<DN, UP> {
face_up: Stack::new(), face_up: Stack::new(),
} }
} }
/// Returns whether a card was flipped up. pub fn flip_up(&mut self) {
pub fn flip_up(&mut self) -> bool {
if let Some(card) = self.face_down.pop() { if let Some(card) = self.face_down.pop() {
self.face_up.push(card); self.face_up.push(card);
return true;
} }
false
} }
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.face_down.is_empty() && self.face_up.is_empty() self.face_down.is_empty() && self.face_up.is_empty()
@@ -263,31 +255,25 @@ impl<const DN: usize, const UP: usize> Pile<DN, UP> {
pub fn pop(&mut self) -> Option<Card> { pub fn pop(&mut self) -> Option<Card> {
self.face_up.pop() self.face_up.pop()
} }
/// Returns the popped card and whether a card was flipped up. pub fn pop_flip_up(&mut self) -> Option<Card> {
pub fn pop_flip_up(&mut self) -> (Option<Card>, bool) { let card = self.face_up.pop()?;
let card = match self.face_up.pop() { if self.face_up.is_empty() {
Some(card) => card, self.flip_up();
None => return (None, false), }
}; Some(card)
let did_flip_up = if self.face_up.is_empty() {
self.flip_up()
} else {
false
};
(Some(card), did_flip_up)
} }
pub fn take_range<R: RangeBounds<usize>>(&mut self, range: R) -> Stack<UP> { pub fn take_range<R: RangeBounds<usize>>(&mut self, range: R) -> Stack<UP> {
// if self.face_up.get(range).is_none() {
// return None;
// }
self.face_up.take_range(range) self.face_up.take_range(range)
} }
/// Returns the card range and whether a card was flipped up. pub fn take_range_flip_up<R: RangeBounds<usize>>(&mut self, range: R) -> Stack<UP> {
pub fn take_range_flip_up<R: RangeBounds<usize>>(&mut self, range: R) -> (Stack<UP>, bool) {
let cards = self.take_range(range); let cards = self.take_range(range);
let did_flip_up = if self.face_up.is_empty() { if self.face_up.is_empty() {
self.flip_up() self.flip_up();
} else { }
false cards
};
(cards, did_flip_up)
} }
pub fn push(&mut self, card: Card) { pub fn push(&mut self, card: Card) {
self.face_up.push(card); self.face_up.push(card);
@@ -320,71 +306,61 @@ pub enum SessionInstruction<I> {
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct SessionStats<S> { pub struct SessionStats<S> {
inner: S, inner_stats: S,
undos: u32, undos: usize,
} }
impl<S> SessionStats<S> { impl<S> SessionStats<S> {
pub const fn stats(&self) -> &S { pub const fn stats(&self) -> &S {
&self.inner &self.inner_stats
} }
const fn increment_undos(&mut self) { const fn increment_undos(&mut self) {
self.undos += 1; self.undos += 1;
} }
pub const fn undos(&self) -> u32 { pub const fn undos(&self) -> usize {
self.undos self.undos
} }
} }
#[derive(Clone, Debug)]
pub struct SessionConfig<C> {
pub inner: C,
pub undo_penalty: i32,
}
impl<C> SessionConfig<C> {
fn new_default(inner: C) -> Self {
Self {
inner,
undo_penalty: -15,
}
}
}
impl<C: Default> Default for SessionConfig<C> {
fn default() -> Self {
Self::new_default(C::default())
}
}
#[derive(Clone, Debug)]
pub struct Session<G: Game> { pub struct Session<G: Game> {
stats: SessionStats<G::Stats>, stats: SessionStats<G::Stats>,
config: SessionConfig<G::Config>, config: G::Config,
state: SessionState<G>, state: SessionState<G>,
} }
#[derive(Clone, Eq, Hash, PartialEq)] #[derive(Clone, Debug)]
pub struct SessionState<G: Game> { pub struct StateSnapshot<G: Game> {
seed: G,
state: G, state: G,
history: Vec<G::Instruction>, instruction: G::Instruction,
}
impl<G: Game> StateSnapshot<G> {
pub const fn state(&self) -> &G {
&self.state
}
pub const fn instruction(&self) -> &G::Instruction {
&self.instruction
}
}
#[derive(Clone, Debug)]
pub struct SessionState<G: Game> {
state: G,
history: Vec<StateSnapshot<G>>,
} }
impl<G: Game + Clone> SessionState<G> { impl<G: Game + Clone> SessionState<G> {
fn new(state: G) -> Self { fn new(state: G) -> Self {
Self { Self {
seed: state.clone(),
state, state,
history: Vec::new(), history: Vec::new(),
} }
} }
} }
impl<G: Game> SessionState<G> { impl<G: Game> Session<G>
pub const fn state(&self) -> &G {
&self.state
}
}
impl<G: Game<Score = i32>> Session<G>
where where
G: Clone + Eq + core::hash::Hash, G: Clone + Eq + core::hash::Hash,
G::Stats: Clone + Default, G::Stats: Clone + Default,
G::Config: Clone,
G::Instruction: Clone + Eq + core::hash::Hash, G::Instruction: Clone + Eq + core::hash::Hash,
{ {
pub fn new(state: G, config: SessionConfig<G::Config>) -> Self { pub fn new(state: G, config: G::Config) -> Self {
Self { Self {
stats: SessionStats::default(), stats: SessionStats::default(),
config, config,
@@ -400,13 +376,13 @@ where
pub const fn stats(&self) -> &SessionStats<G::Stats> { pub const fn stats(&self) -> &SessionStats<G::Stats> {
&self.stats &self.stats
} }
pub const fn state(&self) -> &SessionState<G> { pub const fn state(&self) -> &G {
&self.state &self.state.state
} }
pub const fn config(&self) -> &SessionConfig<G::Config> { pub const fn config(&self) -> &G::Config {
&self.config &self.config
} }
pub fn history(&self) -> &[G::Instruction] { pub fn history(&self) -> &[StateSnapshot<G>] {
&self.state.history &self.state.history
} }
pub fn undo(&mut self) { pub fn undo(&mut self) {
@@ -414,7 +390,7 @@ where
.process_instruction(&mut self.stats, &self.config, SessionInstruction::Undo) .process_instruction(&mut self.stats, &self.config, SessionInstruction::Undo)
} }
pub fn possible_instructions(&self) -> impl Iterator<Item = G::Instruction> + use<G> { pub fn possible_instructions(&self) -> impl Iterator<Item = G::Instruction> + use<G> {
self.state.state.possible_instructions(&self.config.inner) self.state.state.possible_instructions()
} }
pub fn process_instruction(&mut self, instruction: G::Instruction) { pub fn process_instruction(&mut self, instruction: G::Instruction) {
self.state.process_instruction( self.state.process_instruction(
@@ -426,33 +402,75 @@ where
pub fn is_win(&self) -> bool { pub fn is_win(&self) -> bool {
self.state.is_win() self.state.is_win()
} }
} pub fn is_winnable(&self) -> Option<Vec<StateSnapshot<G>>> {
impl<G: Game<Score = i32>> Game for SessionState<G> let mut state_moves = std::collections::HashMap::new();
where let mut state = self.clone();
G: Clone, while !state.is_win() {
G::Stats: Default, // Continue existing iterator if it exists
G::Instruction: Clone, let it = state_moves
{ .entry(state.state().clone())
type Score = i32; .or_insert_with(|| state.state().possible_instructions());
type Stats = SessionStats<G::Stats>;
type Config = SessionConfig<G::Config>; // Run one possible move
type Instruction = SessionInstruction<G::Instruction>; if let Some(instruction) = it.next() {
fn score(&self, stats: &Self::Stats, config: &Self::Config) -> Self::Score { state.process_instruction(instruction);
self.state.score(&stats.inner, &config.inner) + stats.undos as i32 * config.undo_penalty continue;
} }
fn possible_instructions(
&self, // No more moves. If we can't undo we're done
config: &Self::Config, if state.history().is_empty() {
) -> impl Iterator<Item = Self::Instruction> + use<G> { return None;
} else {
state.undo();
}
}
// history includes cycles
let mut state_index: std::collections::HashMap<_, _> = state
.history()
.iter()
.enumerate()
.map(|(i, snapshot)| (snapshot.state().clone(), i))
.collect();
// find the longest range where the start and end are the same state
while let Some(longest_range) = state
.history()
.iter()
.enumerate()
.filter_map(|(index, snapshot)| {
let &last_index = state_index.get(snapshot.state())?;
let longness = last_index - index;
(longness != 0).then_some(index..last_index)
})
.max_by_key(|range| range.len())
{
state.state.history.drain(longest_range);
for (i, snapshot) in state.history().iter().enumerate() {
state_index.insert(snapshot.state().clone(), i);
}
}
Some(state.state.history)
}
}
impl<G: Game> Game for SessionState<G>
where
G::Stats: Default,
{
type Stats = SessionStats<G::Stats>;
type Config = G::Config;
type Instruction = SessionInstruction<G::Instruction>;
fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<G> {
self.state self.state
.possible_instructions(&config.inner) .possible_instructions()
.map(SessionInstruction::InnerInstruction) .map(SessionInstruction::InnerInstruction)
} }
fn is_instruction_valid(&self, config: &Self::Config, instruction: Self::Instruction) -> bool { fn is_instruction_valid(&self, config: &Self::Config, instruction: Self::Instruction) -> bool {
match instruction { match instruction {
SessionInstruction::Undo => !self.history.is_empty(), SessionInstruction::Undo => !self.history.is_empty(),
SessionInstruction::InnerInstruction(instruction) => { SessionInstruction::InnerInstruction(instruction) => {
self.state.is_instruction_valid(&config.inner, instruction) self.state.is_instruction_valid(config, instruction)
} }
} }
} }
@@ -464,21 +482,18 @@ where
) { ) {
match instruction { match instruction {
SessionInstruction::Undo => { SessionInstruction::Undo => {
// replay the entire history of the game except one move if let Some(snapshot) = self.history.pop() {
self.history.pop(); self.state = snapshot.state;
let mut inner_stats = G::Stats::default();
let mut state = self.seed.clone();
for instruction in &self.history {
state.process_instruction(&mut inner_stats, &config.inner, instruction.clone());
}
self.state = state;
stats.inner = inner_stats;
stats.increment_undos(); stats.increment_undos();
} }
}
SessionInstruction::InnerInstruction(instruction) => { SessionInstruction::InnerInstruction(instruction) => {
self.history.push(instruction.clone()); self.history.push(StateSnapshot {
state: self.state.clone(),
instruction: instruction.clone(),
});
self.state self.state
.process_instruction(&mut stats.inner, &config.inner, instruction); .process_instruction(&mut stats.inner_stats, config, instruction);
} }
} }
} }
+6 -8
View File
@@ -1,5 +1,5 @@
use card_game::Game; use card_game::Game;
use klondike::{Klondike, KlondikeConfig, KlondikeStats, Rng, ScoringConfig}; use klondike::{Klondike, KlondikeConfig, KlondikeStats, Rng};
const MAX_MOVES: usize = 250; const MAX_MOVES: usize = 250;
@@ -9,15 +9,13 @@ fn play_to_win(rng: &mut Rng) -> Option<KlondikeStats> {
let mut stats = KlondikeStats::new(); let mut stats = KlondikeStats::new();
const CONFIG: KlondikeConfig = KlondikeConfig { const CONFIG: KlondikeConfig = KlondikeConfig {
draw_stock: klondike::DrawStockConfig::DrawOne, draw_stock: klondike::DrawStockConfig::DrawOne,
move_from_foundation: klondike::MoveFromFoundationConfig::Allowed,
scoring: ScoringConfig::DEFAULT,
}; };
// play game a bit // play game a bit
while let Some(instruction) = game.get_auto_move(&CONFIG) while let Some(instruction) = game.get_auto_move()
&& !game.is_win() && !game.is_win()
{ {
// quit before 250 moves // quit before 250 moves
if (MAX_MOVES as u32) < stats.moves() + 1 { if MAX_MOVES < stats.moves() + 1 {
return None; return None;
} }
@@ -36,9 +34,9 @@ fn main() {
for _ in 0..GAMES { for _ in 0..GAMES {
if let Some(stats) = play_to_win(&mut rng) { if let Some(stats) = play_to_win(&mut rng) {
wins += 1; wins += 1;
score_tally[(stats.score(&ScoringConfig::DEFAULT) / 5) as usize] += 1; score_tally[stats.score() / 5] += 1;
recycle_tally[stats.recycle_count() as usize] += 1; recycle_tally[stats.recycle_count()] += 1;
moves_tally[stats.moves() as usize] += 1; moves_tally[stats.moves()] += 1;
} }
} }
println!("score_tally={score_tally:?}"); println!("score_tally={score_tally:?}");
+40 -69
View File
@@ -1,11 +1,11 @@
use card_game::{Card, Game, Pile, Rank, Session, Suit}; use card_game::{Card, Game, Pile, Rank, Session, SessionStats, Suit};
use klondike::{ use klondike::{
DstFoundation, DstTableau, Foundation, Klondike, KlondikeConfig, KlondikeInstruction, DstFoundation, DstTableau, Foundation, Klondike, KlondikeConfig, KlondikeInstruction,
KlondikePile, KlondikePileStack, SkipCards, Tableau, TableauStack, KlondikePile, KlondikePileStack, KlondikeStats, SkipCards, Tableau, TableauStack,
}; };
// #[cfg(test)] #[cfg(test)]
// mod test; mod test;
use std::fmt::Display; use std::fmt::Display;
struct Displayed<T>(T); struct Displayed<T>(T);
@@ -13,11 +13,11 @@ struct Displayed<T>(T);
impl Display for Displayed<&Card> { impl Display for Displayed<&Card> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0.rank() { match self.0.rank() {
Rank::Ace => write!(f, " A"), Rank::Ace => write!(f, "A"),
Rank::Jack => write!(f, " J"), Rank::Jack => write!(f, "J"),
Rank::Queen => write!(f, " Q"), Rank::Queen => write!(f, "Q"),
Rank::King => write!(f, " K"), Rank::King => write!(f, "K"),
other => write!(f, "{:>2}", other as u8), other => write!(f, "{}", other as u8),
}?; }?;
match self.0.suit() { match self.0.suit() {
Suit::Spades => write!(f, ""), Suit::Spades => write!(f, ""),
@@ -33,7 +33,7 @@ impl Display for OptionalCard<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
&OptionalCard(Some(card)) => write!(f, "{}", Displayed(card)), &OptionalCard(Some(card)) => write!(f, "{}", Displayed(card)),
OptionalCard(None) => write!(f, " []"), OptionalCard(None) => write!(f, "None"),
} }
} }
} }
@@ -42,17 +42,16 @@ impl Display for Displayed<&Klondike> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Stock // Stock
let stock_count = self.0.state().stock().face_down().len(); let stock_count = self.0.state().stock().face_down().len();
writeln!(f, "Stock: {stock_count}")?;
// Hand // Hand
let hand = self.0.state().stock().face_up().last(); let hand = self.0.state().stock().face_up().last();
writeln!(f, "Hand: {}", OptionalCard(hand))?;
// Foundations // Foundations
writeln!(f, " STOCK F1 F2 F3 F4")?;
write!( write!(
f, f,
" {:>2} {} {} {} {} {}", "Foundations: {} {} {} {}",
stock_count,
OptionalCard(hand),
OptionalCard(self.0.state().foundation1().last()), OptionalCard(self.0.state().foundation1().last()),
OptionalCard(self.0.state().foundation2().last()), OptionalCard(self.0.state().foundation2().last()),
OptionalCard(self.0.state().foundation3().last()), OptionalCard(self.0.state().foundation3().last()),
@@ -60,64 +59,42 @@ impl Display for Displayed<&Klondike> {
)?; )?;
writeln!(f)?; writeln!(f)?;
writeln!(f, " T1 T2 T3 T4 T5 T6 T7")?; fn write_pile<const DN: usize, const UP: usize>(
fn write_pile_card<const DN: usize, const UP: usize>(
f: &mut std::fmt::Formatter<'_>, f: &mut std::fmt::Formatter<'_>,
pile: &Pile<DN, UP>, pile: &Pile<DN, UP>,
row: usize, pile_id: usize,
) -> std::fmt::Result { ) -> std::fmt::Result {
if let Some(_card) = pile.face_down().get(row) { write!(f, "T{} ", pile_id)?;
return write!(f, " ⎾⏋"); // └┘ ⨽⨼ ⫭⫬ for _ in pile.face_down() {
write!(f, "]")?;
} }
let Some(row) = row.checked_sub(pile.face_down().len()) else { for card in pile.face_up() {
return write!(f, " "); write!(f, "{}", Displayed(card))?;
};
if let Some(card) = pile.face_up().get(row) {
return write!(f, "{}", Displayed(card));
} }
write!(f, " ") writeln!(f)?;
} Ok(())
fn write_row(
f: &mut std::fmt::Formatter<'_>,
game: &Klondike,
row: usize,
) -> std::fmt::Result {
write_pile_card(f, game.state().tableau1(), row)?;
write!(f, " ")?;
write_pile_card(f, game.state().tableau2(), row)?;
write!(f, " ")?;
write_pile_card(f, game.state().tableau3(), row)?;
write!(f, " ")?;
write_pile_card(f, game.state().tableau4(), row)?;
write!(f, " ")?;
write_pile_card(f, game.state().tableau5(), row)?;
write!(f, " ")?;
write_pile_card(f, game.state().tableau6(), row)?;
write!(f, " ")?;
write_pile_card(f, game.state().tableau7(), row)?;
writeln!(f)
}
for row in 0..7 + 13 {
write_row(f, self.0, row)?;
} }
write_pile(f, self.0.state().tableau1(), 1)?;
write_pile(f, self.0.state().tableau2(), 2)?;
write_pile(f, self.0.state().tableau3(), 3)?;
write_pile(f, self.0.state().tableau4(), 4)?;
write_pile(f, self.0.state().tableau5(), 5)?;
write_pile(f, self.0.state().tableau6(), 6)?;
write_pile(f, self.0.state().tableau7(), 7)?;
Ok(()) Ok(())
} }
} }
struct DisplayStats<'a>(&'a Session<Klondike>); impl Display for Displayed<&SessionStats<KlondikeStats>> {
impl Display for DisplayStats<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!( write!(
f, f,
"recycles: {} moves: {} undos: {} score:{}", "recycles: {} moves: {} undos: {} score:{}",
self.0.stats().stats().recycle_count(), self.0.stats().recycle_count(),
self.0.stats().stats().moves(), self.0.stats().moves(),
self.0.stats().undos(), self.0.undos(),
self.0.state().score(self.0.stats(), &self.0.config()), self.0.stats().score() as isize - self.0.undos() as isize * 15,
) )
} }
} }
@@ -249,9 +226,9 @@ fn main() -> Result<(), std::io::Error> {
loop { loop {
// display stats // display stats
println!("seed: {seed} "); println!("seed: {seed} ");
println!("{}", DisplayStats(&session)); println!("{}", Displayed(session.stats()));
// display game // display game
println!("{}", Displayed(session.state().state())); println!("{}", Displayed(session.state()));
// parse input // parse input
input.clear(); input.clear();
@@ -275,11 +252,7 @@ fn main() -> Result<(), std::io::Error> {
} }
} }
SessionInstruction::Auto => { SessionInstruction::Auto => {
if let Some(instruction) = session if let Some(instruction) = session.state().get_auto_move() {
.state()
.state()
.get_auto_move(&session.config().inner)
{
session.process_instruction(instruction); session.process_instruction(instruction);
} else { } else {
println!("No valid moves!"); println!("No valid moves!");
@@ -289,11 +262,9 @@ fn main() -> Result<(), std::io::Error> {
session.process_instruction(KlondikeInstruction::RotateStock) session.process_instruction(KlondikeInstruction::RotateStock)
} }
SessionInstruction::Klondike(naive_instruction) => { SessionInstruction::Klondike(naive_instruction) => {
if let Some(instruction) = find_valid_instruction( if let Some(instruction) =
&session.config().inner, find_valid_instruction(session.config(), session.state(), naive_instruction)
session.state().state(), {
naive_instruction,
) {
session.process_instruction(instruction); session.process_instruction(instruction);
} else { } else {
println!("Invalid move!"); println!("Invalid move!");
+9 -27
View File
@@ -1,33 +1,15 @@
use klondike::Klondike;
use card_game::Session; use card_game::Session;
use klondike::Klondike;
#[test] #[test]
fn test_is_winnable() { fn test_is_winnable() {
// is winnable // is winnable
let is_winnable = Session::new_default(Klondike::with_seed(123)).is_winnable(); let is_winnable = Session::new_default(Klondike::with_seed(124)).is_winnable();
println!("is_winnable = {is_winnable:?}"); if let Some(win_moves) = is_winnable {
} // for (i, ins) in win_moves.into_iter().enumerate() {
#[test] // println!("{i} = {:?}", ins.instruction());
fn test_klondike() { // }
// create game session println!("Game is winnable with {} moves", win_moves.len());
let game = Klondike::with_seed(123); } else {
let mut session = Session::new_default(game); println!("Game is not winnable");
// is winnable
let is_winnable = session.is_winnable();
println!("is_winnable = {is_winnable:?}");
// play game
while let Some(instruction) = session.possible_instructions().next() {
session.process_instruction(instruction);
} }
// did win
let is_win = session.is_win();
// print session history
for (i, instruction) in session.history().iter().enumerate() {
println!("move {i} = {instruction:?}");
}
println!("is_win = {is_win}");
} }
+4 -5
View File
@@ -7,19 +7,18 @@ Klondike
```rust ```rust
use card_game::Session; use card_game::Session;
use klondike::{Klondike, KlondikeConfig}; use klondike::Klondike;
// create game session // create game session
let game = Klondike::with_seed(123); let game = Klondike::with_seed(123);
let config = KlondikeConfig::default();
let mut session = Session::new_default(game); let mut session = Session::new_default(game);
// play game a bit // play game a bit
while let Some(instruction) = session.state().get_auto_move(&config) { while let Some(instruction) = session.state().get_auto_move() {
session.process_instruction(instruction); session.process_instruction(instruction);
// quit after 200 moves or win // quit after 1000 moves
if session.is_win() || 200 < session.stats().stats().moves() { if 1000 < session.stats().stats().moves() {
break; break;
} }
} }
+71 -152
View File
@@ -7,110 +7,48 @@ use card_game::{Card, Game, Pile, Rank, Stack};
#[cfg(doctest)] #[cfg(doctest)]
struct ReadmeDoctests; struct ReadmeDoctests;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] #[derive(Clone, Copy, Debug, Default)]
pub enum DrawStockConfig { pub enum DrawStockConfig {
#[default] #[default]
DrawOne = 1, DrawOne = 1,
DrawThree = 3, DrawThree = 3,
} }
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum MoveFromFoundationConfig {
#[default]
Allowed,
Disallowed,
}
#[derive(Clone, Copy, Debug)]
pub struct ScoringConfig {
pub move_to_foundation: i32,
pub flip_up_bonus: i32,
pub move_to_tableau: i32,
pub move_from_foundation: i32,
pub recycle: i32,
}
impl ScoringConfig {
pub const DEFAULT: Self = Self {
move_to_foundation: 10,
flip_up_bonus: 5,
move_to_tableau: 5,
move_from_foundation: -15,
recycle: 0,
};
}
impl Default for ScoringConfig {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct KlondikeConfig { pub struct KlondikeConfig {
pub draw_stock: DrawStockConfig, pub draw_stock: DrawStockConfig,
pub move_from_foundation: MoveFromFoundationConfig,
pub scoring: ScoringConfig,
} }
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct KlondikeStats { pub struct KlondikeStats {
moves: u32, score: usize,
move_to_foundation_count: u32, recycle_count: usize,
flip_up_bonus_count: u32, moves: usize,
move_to_tableau_count: u32,
move_from_foundation_count: u32,
recycle_count: u32,
} }
impl KlondikeStats { impl KlondikeStats {
pub const fn new() -> Self { pub const fn new() -> Self {
KlondikeStats { KlondikeStats {
moves: 0, score: 0,
move_to_foundation_count: 0,
flip_up_bonus_count: 0,
move_to_tableau_count: 0,
move_from_foundation_count: 0,
recycle_count: 0, recycle_count: 0,
moves: 0,
} }
} }
pub const fn score(&self, config: &ScoringConfig) -> i32 { pub const fn score(&self) -> usize {
self.move_to_foundation_count as i32 * config.move_to_foundation self.score
+ self.flip_up_bonus_count as i32 * config.flip_up_bonus
+ self.move_to_tableau_count as i32 * config.move_to_tableau
+ self.move_from_foundation_count as i32 * config.move_from_foundation
+ self.recycle_count as i32 * config.recycle
} }
pub const fn moves(&self) -> u32 { pub const fn recycle_count(&self) -> usize {
self.moves
}
pub const fn move_to_foundation_count(&self) -> u32 {
self.move_to_foundation_count
}
pub const fn flip_up_bonus_count(&self) -> u32 {
self.flip_up_bonus_count
}
pub const fn move_to_tableau_count(&self) -> u32 {
self.move_to_tableau_count
}
pub const fn move_from_foundation_count(&self) -> u32 {
self.move_from_foundation_count
}
pub const fn recycle_count(&self) -> u32 {
self.recycle_count self.recycle_count
} }
/// A card was moved to a foundation. pub const fn moves(&self) -> usize {
const fn increment_move_to_foundation(&mut self) { self.moves
self.move_to_foundation_count += 1;
} }
/// A card on the tableau was flipped up. /// A card was moved to a foundation.
const fn increment_flip_up_bonus(&mut self) { const fn increment_score_foundation(&mut self) {
self.flip_up_bonus_count += 1; self.score += 10;
} }
/// A card was moved from stock to tableau. /// A card was moved from stock to tableau.
const fn increment_move_to_tableau(&mut self) { const fn increment_score_tableau(&mut self) {
self.move_to_tableau_count += 1; self.score += 5;
}
/// A card was moved from foundation to tableau.
const fn increment_move_from_foundation(&mut self) {
self.move_from_foundation_count += 1;
} }
const fn increment_recycle_count(&mut self) { const fn increment_recycle_count(&mut self) {
self.recycle_count += 1; self.recycle_count += 1;
@@ -199,6 +137,7 @@ impl From<Foundation> for KlondikePile {
} }
} }
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SkipCards { pub enum SkipCards {
Skip0, Skip0,
@@ -427,26 +366,15 @@ impl KlondikeState {
pub const fn tableau7(&self) -> &Pile<6, 13> { pub const fn tableau7(&self) -> &Pile<6, 13> {
&self.tableau7 &self.tableau7
} }
pub fn tableau_face_down_cards(&self, tableau: Tableau) -> &[Card] { pub fn is_tableau_face_down_empty(&self, tableau: Tableau) -> bool {
match tableau { match tableau {
Tableau::Tableau1 => self.tableau1.face_down(), Tableau::Tableau1 => self.tableau1.face_down().is_empty(),
Tableau::Tableau2 => self.tableau2.face_down(), Tableau::Tableau2 => self.tableau2.face_down().is_empty(),
Tableau::Tableau3 => self.tableau3.face_down(), Tableau::Tableau3 => self.tableau3.face_down().is_empty(),
Tableau::Tableau4 => self.tableau4.face_down(), Tableau::Tableau4 => self.tableau4.face_down().is_empty(),
Tableau::Tableau5 => self.tableau5.face_down(), Tableau::Tableau5 => self.tableau5.face_down().is_empty(),
Tableau::Tableau6 => self.tableau6.face_down(), Tableau::Tableau6 => self.tableau6.face_down().is_empty(),
Tableau::Tableau7 => self.tableau7.face_down(), Tableau::Tableau7 => self.tableau7.face_down().is_empty(),
}
}
pub fn tableau_face_up_cards(&self, tableau: Tableau) -> &[Card] {
match tableau {
Tableau::Tableau1 => self.tableau1.face_up(),
Tableau::Tableau2 => self.tableau2.face_up(),
Tableau::Tableau3 => self.tableau3.face_up(),
Tableau::Tableau4 => self.tableau4.face_up(),
Tableau::Tableau5 => self.tableau5.face_up(),
Tableau::Tableau6 => self.tableau6.face_up(),
Tableau::Tableau7 => self.tableau7.face_up(),
} }
} }
pub fn stack_bottom_card(&self, src: KlondikePileStack) -> Option<&Card> { pub fn stack_bottom_card(&self, src: KlondikePileStack) -> Option<&Card> {
@@ -454,7 +382,15 @@ impl KlondikeState {
KlondikePileStack::Tableau(TableauStack { KlondikePileStack::Tableau(TableauStack {
tableau, tableau,
skip_cards, skip_cards,
}) => self.tableau_face_up_cards(tableau).get(skip_cards as usize), }) => match tableau {
Tableau::Tableau1 => self.tableau1.face_up().get(skip_cards as usize),
Tableau::Tableau2 => self.tableau2.face_up().get(skip_cards as usize),
Tableau::Tableau3 => self.tableau3.face_up().get(skip_cards as usize),
Tableau::Tableau4 => self.tableau4.face_up().get(skip_cards as usize),
Tableau::Tableau5 => self.tableau5.face_up().get(skip_cards as usize),
Tableau::Tableau6 => self.tableau6.face_up().get(skip_cards as usize),
Tableau::Tableau7 => self.tableau7.face_up().get(skip_cards as usize),
},
KlondikePileStack::Foundation(foundation) => { KlondikePileStack::Foundation(foundation) => {
self.foundations[foundation as usize].last() self.foundations[foundation as usize].last()
} }
@@ -463,12 +399,20 @@ impl KlondikeState {
} }
pub fn top_card<S: Into<KlondikePile>>(&self, src: S) -> Option<&Card> { pub fn top_card<S: Into<KlondikePile>>(&self, src: S) -> Option<&Card> {
match src.into() { match src.into() {
KlondikePile::Tableau(tableau) => self.tableau_face_up_cards(tableau).last(), KlondikePile::Tableau(tableau) => match tableau {
Tableau::Tableau1 => self.tableau1.face_up().last(),
Tableau::Tableau2 => self.tableau2.face_up().last(),
Tableau::Tableau3 => self.tableau3.face_up().last(),
Tableau::Tableau4 => self.tableau4.face_up().last(),
Tableau::Tableau5 => self.tableau5.face_up().last(),
Tableau::Tableau6 => self.tableau6.face_up().last(),
Tableau::Tableau7 => self.tableau7.face_up().last(),
},
KlondikePile::Foundation(foundation) => self.foundations[foundation as usize].last(), KlondikePile::Foundation(foundation) => self.foundations[foundation as usize].last(),
KlondikePile::Stock => self.stock.face_up().last(), KlondikePile::Stock => self.stock.face_up().last(),
} }
} }
fn take_stack(&mut self, src: KlondikePileStack) -> (Stack<13>, bool) { fn take_stack(&mut self, src: KlondikePileStack) -> Stack<13> {
match src { match src {
KlondikePileStack::Tableau(TableauStack { KlondikePileStack::Tableau(TableauStack {
tableau, tableau,
@@ -482,14 +426,13 @@ impl KlondikeState {
Tableau::Tableau6 => self.tableau6.take_range_flip_up(skip_cards as usize..), Tableau::Tableau6 => self.tableau6.take_range_flip_up(skip_cards as usize..),
Tableau::Tableau7 => self.tableau7.take_range_flip_up(skip_cards as usize..), Tableau::Tableau7 => self.tableau7.take_range_flip_up(skip_cards as usize..),
}, },
KlondikePileStack::Foundation(foundation) => ( KlondikePileStack::Foundation(foundation) => {
Stack::from_iter(self.foundations[foundation as usize].pop()), Stack::from_iter(self.foundations[foundation as usize].pop())
false, }
), KlondikePileStack::Stock => Stack::from_iter(self.stock.pop()),
KlondikePileStack::Stock => (Stack::from_iter(self.stock.pop()), false),
} }
} }
fn take_top_card<S: Into<KlondikePile>>(&mut self, src: S) -> (Option<Card>, bool) { fn take_top_card<S: Into<KlondikePile>>(&mut self, src: S) -> Option<Card> {
match src.into() { match src.into() {
KlondikePile::Tableau(tableau) => match tableau { KlondikePile::Tableau(tableau) => match tableau {
Tableau::Tableau1 => self.tableau1.pop_flip_up(), Tableau::Tableau1 => self.tableau1.pop_flip_up(),
@@ -500,10 +443,8 @@ impl KlondikeState {
Tableau::Tableau6 => self.tableau6.pop_flip_up(), Tableau::Tableau6 => self.tableau6.pop_flip_up(),
Tableau::Tableau7 => self.tableau7.pop_flip_up(), Tableau::Tableau7 => self.tableau7.pop_flip_up(),
}, },
KlondikePile::Foundation(foundation) => { KlondikePile::Foundation(foundation) => self.foundations[foundation as usize].pop(),
(self.foundations[foundation as usize].pop(), false) KlondikePile::Stock => self.stock.pop(),
}
KlondikePile::Stock => (self.stock.pop(), false),
} }
} }
fn extend_foundation<I: IntoIterator<Item = Card>>( fn extend_foundation<I: IntoIterator<Item = Card>>(
@@ -524,11 +465,7 @@ impl KlondikeState {
Tableau::Tableau7 => self.tableau7.extend(cards), Tableau::Tableau7 => self.tableau7.extend(cards),
} }
} }
pub fn is_instruction_valid( pub fn is_instruction_valid(&self, instruction: KlondikeInstruction) -> bool {
&self,
config: &KlondikeConfig,
instruction: KlondikeInstruction,
) -> bool {
match instruction { match instruction {
// Stock -> Stock draws a card or resets the stock // Stock -> Stock draws a card or resets the stock
KlondikeInstruction::RotateStock => { KlondikeInstruction::RotateStock => {
@@ -557,11 +494,6 @@ impl KlondikeState {
} }
// other = move to tableau // other = move to tableau
KlondikeInstruction::DstTableau(dst_tableau) => { KlondikeInstruction::DstTableau(dst_tableau) => {
if config.move_from_foundation == MoveFromFoundationConfig::Disallowed
&& let KlondikePileStack::Foundation(_) = dst_tableau.src
{
return false;
}
// get the cards // get the cards
if let Some(src_card) = self.stack_bottom_card(dst_tableau.src) { if let Some(src_card) = self.stack_bottom_card(dst_tableau.src) {
match self.top_card(dst_tableau.tableau) { match self.top_card(dst_tableau.tableau) {
@@ -601,6 +533,10 @@ impl Iterator for KlondikeIter {
instruction instruction
} }
} }
#[test]
fn test_klondike_iter() {
assert_eq!(KlondikeIter::new().count(), 721);
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Klondike { pub struct Klondike {
@@ -656,7 +592,7 @@ impl Klondike {
/// Check if the game should be auto-completed /// Check if the game should be auto-completed
pub fn is_win_trivial(&self) -> bool { pub fn is_win_trivial(&self) -> bool {
// all face down cards empty means win // all face down cards empty means win
self.state.stock.is_empty() self.state.stock.face_down().is_empty()
&& self.state.tableau1.face_down().is_empty() && self.state.tableau1.face_down().is_empty()
&& self.state.tableau2.face_down().is_empty() && self.state.tableau2.face_down().is_empty()
&& self.state.tableau3.face_down().is_empty() && self.state.tableau3.face_down().is_empty()
@@ -678,7 +614,7 @@ impl Klondike {
KlondikePileStack::Tableau(TableauStack { KlondikePileStack::Tableau(TableauStack {
tableau, tableau,
skip_cards: SkipCards::Skip0, skip_cards: SkipCards::Skip0,
}) if !self.state().tableau_face_down_cards(tableau).is_empty() }) if !self.state().is_tableau_face_down_empty(tableau)
|| self || self
.state() .state()
.stack_bottom_card(dst_tableau.src) .stack_bottom_card(dst_tableau.src)
@@ -694,15 +630,15 @@ impl Klondike {
} }
} }
/// A single move that usually makes progress towards a winning game /// A single move that usually makes progress towards a winning game
pub fn get_auto_move(&self, config: &KlondikeConfig) -> Option<KlondikeInstruction> { pub fn get_auto_move(&self) -> Option<KlondikeInstruction> {
self.possible_instructions(config) self.possible_instructions()
.filter(|ins| !ins.is_useless()) .filter(|ins| !ins.is_useless())
.min_by_key(|ins| self.instruction_priority(ins)) .min_by_key(|ins| self.instruction_priority(ins))
} }
/// A list of possible moves with useless moves filtered out and sorted by a simple priority function /// A list of possible moves with useless moves filtered out and sorted by a simple priority function
pub fn get_sorted_moves(&self, config: &KlondikeConfig) -> Vec<KlondikeInstruction> { pub fn get_sorted_moves(&self) -> Vec<KlondikeInstruction> {
let mut useful_moves: Vec<_> = self let mut useful_moves: Vec<_> = self
.possible_instructions(config) .possible_instructions()
.filter(|ins| !ins.is_useless()) .filter(|ins| !ins.is_useless())
.collect(); .collect();
useful_moves.sort_by_key(|ins| self.instruction_priority(ins)); useful_moves.sort_by_key(|ins| self.instruction_priority(ins));
@@ -711,24 +647,15 @@ impl Klondike {
} }
impl Game for Klondike { impl Game for Klondike {
type Score = i32;
type Stats = KlondikeStats; type Stats = KlondikeStats;
type Config = KlondikeConfig; type Config = KlondikeConfig;
type Instruction = KlondikeInstruction; type Instruction = KlondikeInstruction;
fn score(&self, stats: &Self::Stats, config: &Self::Config) -> Self::Score { fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<> {
stats.score(&config.scoring)
}
fn possible_instructions(
&self,
config: &Self::Config,
) -> impl Iterator<Item = Self::Instruction> + use<> {
let state = self.state.clone(); let state = self.state.clone();
let config = config.clone(); KlondikeIter::new().filter(move |&instruction| state.is_instruction_valid(instruction))
KlondikeIter::new()
.filter(move |&instruction| state.is_instruction_valid(&config, instruction))
} }
fn is_instruction_valid(&self, config: &Self::Config, instruction: Self::Instruction) -> bool { fn is_instruction_valid(&self, _config: &Self::Config, instruction: Self::Instruction) -> bool {
self.state.is_instruction_valid(config, instruction) self.state.is_instruction_valid(instruction)
} }
fn process_instruction( fn process_instruction(
&mut self, &mut self,
@@ -751,24 +678,16 @@ impl Game for Klondike {
} }
// Move a card from anywhere to a foundation // Move a card from anywhere to a foundation
KlondikeInstruction::DstFoundation(DstFoundation { src, foundation }) => { KlondikeInstruction::DstFoundation(DstFoundation { src, foundation }) => {
stats.increment_move_to_foundation(); stats.increment_score_foundation();
let (card, did_flip_up) = self.state.take_top_card(src); let card = self.state.take_top_card(src);
if did_flip_up {
stats.increment_flip_up_bonus();
}
self.state.extend_foundation(foundation, card); self.state.extend_foundation(foundation, card);
} }
// Move a stack of cards from anywhere to a tableau // Move a stack of cards from anywhere to a tableau
KlondikeInstruction::DstTableau(DstTableau { src, tableau }) => { KlondikeInstruction::DstTableau(DstTableau { src, tableau }) => {
match src { if src == KlondikePileStack::Stock {
KlondikePileStack::Stock => stats.increment_move_to_tableau(), stats.increment_score_tableau();
KlondikePileStack::Foundation(_) => stats.increment_move_from_foundation(),
_ => {}
}
let (cards, did_flip_up) = self.state.take_stack(src);
if did_flip_up {
stats.increment_flip_up_bonus();
} }
let cards = self.state.take_stack(src);
self.state.extend_tableau(tableau, cards); self.state.extend_tableau(tableau, cards);
} }
} }