Implement Stats (#6)

Closes #1

Reviewed-on: #6
Co-authored-by: Rhys Lloyd <krakow20@gmail.com>
Co-committed-by: Rhys Lloyd <krakow20@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
2026-05-17 16:46:09 +00:00
committed by Quaternions
parent 5553a7e1a1
commit 595ff73f90
4 changed files with 228 additions and 55 deletions
+136 -30
View File
@@ -2,10 +2,17 @@ use core::ops::RangeBounds;
// TODO: pub struct ValidInstruction<I>(I); // TODO: pub struct ValidInstruction<I>(I);
pub trait Game { pub trait Game {
type Stats;
type Config;
type Instruction; type Instruction;
fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<Self>; fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<Self>;
fn is_instruction_valid(&self, instruction: Self::Instruction) -> bool; fn is_instruction_valid(&self, config: &Self::Config, instruction: Self::Instruction) -> bool;
fn process_instruction(&mut self, instruction: Self::Instruction); fn process_instruction(
&mut self,
stats: &mut Self::Stats,
config: &Self::Config,
instruction: Self::Instruction,
);
fn is_win(&self) -> bool; fn is_win(&self) -> bool;
} }
@@ -225,28 +232,102 @@ impl<const CAP: usize> Pile<CAP, CAP> {
} }
} }
#[derive(Clone, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Debug)]
pub enum SessionInstruction<I> {
Undo,
InnerInstruction(I),
}
#[derive(Clone, Debug)]
pub struct SessionStats<S> {
inner_stats: S,
undos: usize,
}
impl<S> SessionStats<S> {
const fn new(inner_stats: S) -> Self {
SessionStats {
inner_stats,
undos: 0,
}
}
pub const fn stats(&self) -> &S {
&self.inner_stats
}
const fn increment_undos(&mut self) {
self.undos += 1;
}
pub const fn undos(&self) -> usize {
self.undos
}
}
pub struct Session<G: Game> { pub struct Session<G: Game> {
stats: SessionStats<G::Stats>,
config: G::Config,
state: SessionState<G>,
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct SessionState<G: Game> {
seed: G, seed: G,
state: G, state: G,
history: Vec<G::Instruction>, history: Vec<G::Instruction>,
} }
impl<G: Game + Clone + Eq + core::hash::Hash> Session<G> impl<G: Game + Clone> SessionState<G> {
where fn new(state: G) -> Self {
G::Instruction: Clone + Eq + core::hash::Hash,
{
pub fn new(state: G) -> Self {
Self { Self {
seed: state.clone(), seed: state.clone(),
state, state,
history: Vec::new(), history: Vec::new(),
} }
} }
pub fn state(&self) -> &G { }
&self.state impl<G: Game> Session<G>
where
G: Clone + Eq + core::hash::Hash,
G::Stats: Clone + Default,
G::Instruction: Clone + Eq + core::hash::Hash,
{
pub fn new(state: G, stats: G::Stats, config: G::Config) -> Self {
Self {
stats: SessionStats::new(stats),
config,
state: SessionState::new(state),
}
}
pub fn new_default(state: G) -> Self
where
G::Config: Default,
{
Self::new(state, Default::default(), Default::default())
}
pub const fn stats(&self) -> &SessionStats<G::Stats> {
&self.stats
}
pub const fn state(&self) -> &G {
&self.state.state
}
pub const fn config(&self) -> &G::Config {
&self.config
} }
pub fn history(&self) -> &[G::Instruction] { pub fn history(&self) -> &[G::Instruction] {
&self.history &self.state.history
}
pub fn undo(&mut self) {
self.state
.process_instruction(&mut self.stats, &self.config, SessionInstruction::Undo)
}
pub fn possible_instructions(&self) -> impl Iterator<Item = G::Instruction> + use<G> {
self.state.state.possible_instructions()
}
pub fn process_instruction(&mut self, instruction: G::Instruction) {
self.state.process_instruction(
&mut self.stats,
&self.config,
SessionInstruction::InnerInstruction(instruction),
)
}
pub fn is_win(&self) -> bool {
self.state.is_win()
} }
pub fn is_winnable(&self) -> Option<Vec<G::Instruction>> { pub fn is_winnable(&self) -> Option<Vec<G::Instruction>> {
let mut observed = std::collections::HashSet::new(); let mut observed = std::collections::HashSet::new();
@@ -255,14 +336,15 @@ where
possible_instructions_iter: P, possible_instructions_iter: P,
instruction: I, instruction: I,
} }
let mut state = self.state.clone(); let mut dummy_stats = self.stats.inner_stats.clone();
let mut state = self.state.state.clone();
let mut it = state.possible_instructions(); let mut it = state.possible_instructions();
let mut path = Vec::new(); let mut path = Vec::new();
'outer: while !state.is_win() { 'outer: while !state.is_win() {
observed.insert(state.clone()); observed.insert(state.clone());
for instruction in &mut it { for instruction in &mut it {
let mut next_state = state.clone(); let mut next_state = state.clone();
next_state.process_instruction(instruction.clone()); next_state.process_instruction(&mut dummy_stats, &self.config, instruction.clone());
if !observed.contains(&next_state) { if !observed.contains(&next_state) {
let possible_instructions_iter = let possible_instructions_iter =
core::mem::replace(&mut it, next_state.possible_instructions()); core::mem::replace(&mut it, next_state.possible_instructions());
@@ -283,30 +365,54 @@ where
} }
Some(path.into_iter().map(|state| state.instruction).collect()) Some(path.into_iter().map(|state| state.instruction).collect())
} }
pub fn undo(&mut self) {
// replay the entire history of the game except one move
self.history.pop();
let mut state = self.seed.clone();
for instruction in self.history() {
state.process_instruction(instruction.clone());
}
self.state = state;
}
} }
impl<G: Game> Game for Session<G> impl<G: Game> Game for SessionState<G>
where where
G: Clone,
G::Stats: Default,
G::Instruction: Clone, G::Instruction: Clone,
{ {
type Instruction = G::Instruction; 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> { fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<G> {
self.state.possible_instructions() self.state
.possible_instructions()
.map(SessionInstruction::InnerInstruction)
} }
fn is_instruction_valid(&self, instruction: Self::Instruction) -> bool { fn is_instruction_valid(&self, config: &Self::Config, instruction: Self::Instruction) -> bool {
self.state.is_instruction_valid(instruction) match instruction {
SessionInstruction::Undo => !self.history.is_empty(),
SessionInstruction::InnerInstruction(instruction) => {
self.state.is_instruction_valid(config, instruction)
}
}
} }
fn process_instruction(&mut self, instruction: Self::Instruction) { fn process_instruction(
self.history.push(instruction.clone()); &mut self,
self.state.process_instruction(instruction); stats: &mut Self::Stats,
config: &Self::Config,
instruction: Self::Instruction,
) {
match instruction {
SessionInstruction::Undo => {
// replay the entire history of the game except one move
self.history.pop();
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, instruction.clone());
}
self.state = state;
stats.inner_stats = inner_stats;
stats.increment_undos();
}
SessionInstruction::InnerInstruction(instruction) => {
self.history.push(instruction.clone());
self.state
.process_instruction(&mut stats.inner_stats, config, instruction);
}
}
} }
fn is_win(&self) -> bool { fn is_win(&self) -> bool {
self.state.is_win() self.state.is_win()
+23 -8
View File
@@ -1,7 +1,7 @@
use card_game::{Card, CardValue, Game, Pile, Session, Suit}; use card_game::{Card, CardValue, Game, Pile, Session, SessionStats, Suit};
use klondike::{ use klondike::{
DstFoundation, DstTableau, Foundation, Klondike, KlondikeInstruction, KlondikePile, DstFoundation, DstTableau, Foundation, Klondike, KlondikeConfig, KlondikeInstruction,
KlondikePileStack, SkipCards, Tableau, TableauStack, KlondikePile, KlondikePileStack, KlondikeStats, SkipCards, Tableau, TableauStack,
}; };
use std::fmt::Display; use std::fmt::Display;
@@ -83,6 +83,18 @@ impl Display for Displayed<&Klondike> {
} }
} }
impl Display for Displayed<&SessionStats<KlondikeStats>> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"recycles: {} moves: {} undos: {}",
self.0.stats().recycle_count(),
self.0.stats().moves(),
self.0.undos()
)
}
}
#[derive(Debug)] #[derive(Debug)]
struct Invalid; struct Invalid;
struct Parsed<T>(T); struct Parsed<T>(T);
@@ -144,6 +156,7 @@ impl core::str::FromStr for SessionInstruction {
} }
fn find_valid_instruction( fn find_valid_instruction(
config: &KlondikeConfig,
state: &Klondike, state: &Klondike,
naive_instruction: NaiveInstruction, naive_instruction: NaiveInstruction,
) -> Option<KlondikeInstruction> { ) -> Option<KlondikeInstruction> {
@@ -173,7 +186,7 @@ fn find_valid_instruction(
}); });
let instruction = let instruction =
KlondikeInstruction::DstTableau(DstTableau { tableau, src }); KlondikeInstruction::DstTableau(DstTableau { tableau, src });
if state.is_instruction_valid(instruction) { if state.is_instruction_valid(config, instruction) {
return Some(instruction); return Some(instruction);
} }
} }
@@ -191,7 +204,7 @@ fn find_valid_instruction(
_ => return None, _ => return None,
}; };
state state
.is_instruction_valid(instruction) .is_instruction_valid(config, instruction)
.then_some(instruction) .then_some(instruction)
} }
@@ -241,9 +254,11 @@ fn get_good_move(state: &Klondike) -> Option<KlondikeInstruction> {
} }
fn main() -> Result<(), std::io::Error> { fn main() -> Result<(), std::io::Error> {
let mut session = Session::new(Klondike::new_random_default()); let mut session = Session::new_default(Klondike::new_random());
let mut input = String::new(); let mut input = String::new();
loop { loop {
// display stats
println!("{}", Displayed(session.stats()));
// display game // display game
println!("{}", Displayed(session.state())); println!("{}", Displayed(session.state()));
@@ -257,7 +272,7 @@ fn main() -> Result<(), std::io::Error> {
// run game // run game
match instruction { match instruction {
SessionInstruction::New => session = Session::new(Klondike::new_random_default()), SessionInstruction::New => session = Session::new_default(Klondike::new_random()),
SessionInstruction::Undo => session.undo(), SessionInstruction::Undo => session.undo(),
SessionInstruction::Exit => break Ok(()), SessionInstruction::Exit => break Ok(()),
SessionInstruction::Hint => { SessionInstruction::Hint => {
@@ -277,7 +292,7 @@ fn main() -> Result<(), std::io::Error> {
} }
SessionInstruction::Klondike(naive_instruction) => { SessionInstruction::Klondike(naive_instruction) => {
if let Some(instruction) = if let Some(instruction) =
find_valid_instruction(session.state(), naive_instruction) find_valid_instruction(session.config(), session.state(), naive_instruction)
{ {
session.process_instruction(instruction); session.process_instruction(instruction);
} else { } else {
+65 -13
View File
@@ -10,11 +10,53 @@ mod test;
#[cfg(doctest)] #[cfg(doctest)]
struct ReadmeDoctests; struct ReadmeDoctests;
#[derive(Clone, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Debug, Default)]
pub struct KlondikeConfig {} enum DrawStockConfig {
impl Default for KlondikeConfig { #[default]
fn default() -> Self { DrawOne = 1,
KlondikeConfig {} DrawThree = 3,
}
#[derive(Clone, Debug, Default)]
pub struct KlondikeConfig {
draw_stock: DrawStockConfig,
}
impl KlondikeConfig {
pub const fn draw_one_stock() -> Self {
KlondikeConfig {
draw_stock: DrawStockConfig::DrawOne,
}
}
pub const fn draw_three_stock() -> Self {
KlondikeConfig {
draw_stock: DrawStockConfig::DrawThree,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct KlondikeStats {
recycle_count: usize,
moves: usize,
}
impl KlondikeStats {
pub const fn new() -> Self {
KlondikeStats {
recycle_count: 0,
moves: 0,
}
}
pub const fn recycle_count(&self) -> usize {
self.recycle_count
}
pub const fn moves(&self) -> usize {
self.moves
}
const fn increment_recycle_count(&mut self) {
self.recycle_count += 1;
}
const fn increment_moves(&mut self) {
self.moves += 1;
} }
} }
@@ -486,14 +528,13 @@ impl Iterator for KlondikeIter {
#[derive(Clone, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Klondike { pub struct Klondike {
config: KlondikeConfig,
state: KlondikeState, state: KlondikeState,
} }
impl Klondike { impl Klondike {
pub fn new_random_default() -> Self { pub fn new_random() -> Self {
Self::new(Rng::default(), KlondikeConfig::default()) Self::new(Rng::default())
} }
pub fn new(mut seed: Rng, config: KlondikeConfig) -> Self { pub fn new(mut seed: Rng) -> Self {
// shuffle a new deck // shuffle a new deck
let mut deck = Stack::full_deck(0); let mut deck = Stack::full_deck(0);
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
@@ -529,7 +570,7 @@ impl Klondike {
tableau6, tableau6,
tableau7, tableau7,
}; };
Self { config, state } Self { state }
} }
pub const fn state(&self) -> &KlondikeState { pub const fn state(&self) -> &KlondikeState {
&self.state &self.state
@@ -537,22 +578,33 @@ impl Klondike {
} }
impl Game for Klondike { impl Game for Klondike {
type Stats = KlondikeStats;
type Config = KlondikeConfig;
type Instruction = KlondikeInstruction; type Instruction = KlondikeInstruction;
fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<> { fn possible_instructions(&self) -> impl Iterator<Item = Self::Instruction> + use<> {
let state = self.state.clone(); let state = self.state.clone();
KlondikeIter::new().filter(move |&instruction| state.is_instruction_valid(instruction)) KlondikeIter::new().filter(move |&instruction| state.is_instruction_valid(instruction))
} }
fn is_instruction_valid(&self, instruction: Self::Instruction) -> bool { fn is_instruction_valid(&self, _config: &Self::Config, instruction: Self::Instruction) -> bool {
self.state.is_instruction_valid(instruction) self.state.is_instruction_valid(instruction)
} }
fn process_instruction(&mut self, instruction: Self::Instruction) { fn process_instruction(
&mut self,
stats: &mut Self::Stats,
config: &Self::Config,
instruction: Self::Instruction,
) {
stats.increment_moves();
match instruction { match instruction {
// Reset the stock if it's empty // Reset the stock if it's empty
KlondikeInstruction::RotateStock => { KlondikeInstruction::RotateStock => {
if self.state.stock.face_down().is_empty() { if self.state.stock.face_down().is_empty() {
self.state.stock.flip_it_and_reverse_it(); self.state.stock.flip_it_and_reverse_it();
stats.increment_recycle_count();
} else { } else {
self.state.stock.flip_up(); for _ in 0..config.draw_stock as usize {
self.state.stock.flip_up();
}
} }
} }
// Move a card from anywhere to a foundation // Move a card from anywhere to a foundation
+4 -4
View File
@@ -1,16 +1,16 @@
use crate::Klondike; use crate::Klondike;
use card_game::{Game, Session}; use card_game::Session;
#[test] #[test]
fn test_is_winnable() { fn test_is_winnable() {
// is winnable // is winnable
let is_winnable = Session::new(Klondike::new_random_default()).is_winnable(); let is_winnable = Session::new_default(Klondike::new_random()).is_winnable();
println!("is_winnable = {is_winnable:?}"); println!("is_winnable = {is_winnable:?}");
} }
#[test] #[test]
fn test_klondike() { fn test_klondike() {
// create game session // create game session
let game = Klondike::new_random_default(); let game = Klondike::new_random();
let mut session = Session::new(game); let mut session = Session::new_default(game);
// is winnable // is winnable
let is_winnable = session.is_winnable(); let is_winnable = session.is_winnable();