implement solver

This commit is contained in:
2026-05-19 07:10:38 -07:00
parent 50cf2f3750
commit 1de633adb3
4 changed files with 77 additions and 55 deletions
+62 -26
View File
@@ -6,11 +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 {
type Score; type Score: Clone + core::fmt::Debug;
type Stats; type Stats: Clone + core::fmt::Debug;
type Config; type Config: Clone + core::fmt::Debug;
type Instruction; type Instruction: Clone + core::fmt::Debug;
fn score(&self, stats: &Self::Stats, config: &Self::Config) -> Self::Score; fn score(&self, stats: &Self::Stats, config: &Self::Config) -> Self::Score;
fn possible_instructions( fn possible_instructions(
&self, &self,
@@ -353,21 +353,33 @@ impl<C: Default> Default for SessionConfig<C> {
} }
} }
#[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: SessionConfig<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(),
} }
@@ -380,9 +392,9 @@ impl<G: Game> SessionState<G> {
} }
impl<G: Game<Score = i32>> Session<G> impl<G: Game<Score = i32>> Session<G>
where where
G: Clone + Eq + core::hash::Hash, G: Eq + core::hash::Hash,
G::Stats: Clone + Default, G::Stats: Default,
G::Instruction: Clone + Eq + core::hash::Hash, G::Instruction: Eq + core::hash::Hash,
{ {
pub fn new(state: G, config: SessionConfig<G::Config>) -> Self { pub fn new(state: G, config: SessionConfig<G::Config>) -> Self {
Self { Self {
@@ -406,7 +418,7 @@ where
pub const fn config(&self) -> &SessionConfig<G::Config> { pub const fn config(&self) -> &SessionConfig<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) {
@@ -426,12 +438,39 @@ 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>>> {
let mut state_moves = std::collections::HashMap::new();
let mut state = self.clone();
while !state.is_win() {
// Continue existing iterator if it exists
let it = state_moves
.entry(state.state().state().clone())
.or_insert_with(|| {
state
.state()
.state()
.possible_instructions(&self.config().inner)
});
// Run one possible move
if let Some(instruction) = it.next() {
state.process_instruction(instruction);
continue;
}
// No more moves. If we can't undo we're done
if state.history().is_empty() {
return None;
} else {
state.undo();
}
}
Some(state.state.history)
}
} }
impl<G: Game<Score = i32>> Game for SessionState<G> impl<G: Game<Score = i32>> Game for SessionState<G>
where where
G: Clone,
G::Stats: Default, G::Stats: Default,
G::Instruction: Clone,
{ {
type Score = i32; type Score = i32;
type Stats = SessionStats<G::Stats>; type Stats = SessionStats<G::Stats>;
@@ -464,19 +503,16 @@ 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(); stats.increment_undos();
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();
} }
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, &config.inner, instruction);
} }
+2 -2
View File
@@ -4,8 +4,8 @@ use klondike::{
KlondikePile, KlondikePileStack, SkipCards, Tableau, TableauStack, KlondikePile, KlondikePileStack, 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);
+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
View File
@@ -601,6 +601,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 {