Merge branch 'release/v0.2.0'

This commit is contained in:
Henri Bourcereau 2026-03-06 15:13:22 +01:00
commit a859d77be4
39 changed files with 5501 additions and 2592 deletions

3466
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,5 @@
[package]
name = "bot"
name = "trictrac-bot"
version = "0.1.0"
edition = "2021"
@ -13,10 +13,10 @@ path = "src/burnrl/main.rs"
pretty_assertions = "1.4.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
store = { path = "../store" }
rand = "0.8"
trictrac-store = { path = "../store" }
rand = "0.9"
env_logger = "0.10"
burn = { version = "0.18", features = ["ndarray", "autodiff"] }
burn = { version = "0.20", features = ["ndarray", "autodiff"] }
burn-rl = { git = "https://github.com/yunjhongwu/burn-rl-examples.git", package = "burn-rl" }
log = "0.4.20"
confy = "1.0.0"

5
bot/python/test.py Normal file
View file

@ -0,0 +1,5 @@
import trictrac_store
game = trictrac_store.TricTrac()
print(game.current_player_idx())
print(game.get_legal_actions(game.current_player_idx()))

View file

@ -1,10 +1,10 @@
use std::io::Write;
use crate::training_common;
use burn::{prelude::Backend, tensor::Tensor};
use burn_rl::base::{Action, Environment, Snapshot, State};
use rand::{thread_rng, Rng};
use store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
use rand::{rng, Rng};
use trictrac_store::training_common;
use trictrac_store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
const ERROR_REWARD: f32 = -1.0012121;
const REWARD_VALID_MOVE: f32 = 1.0012121;
@ -52,10 +52,10 @@ pub struct TrictracAction {
impl Action for TrictracAction {
fn random() -> Self {
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
use rand::{rng, Rng};
let mut rng = rng();
TrictracAction {
index: rng.gen_range(0..Self::size() as u32),
index: rng.random_range(0..Self::size() as u32),
}
}
@ -114,7 +114,7 @@ impl Environment for TrictracEnvironment {
let player2_id = 2;
// Commencer la partie
game.consume(&GameEvent::BeginGame { goes_first: 1 });
let _ = game.consume(&GameEvent::BeginGame { goes_first: 1 });
let current_state = TrictracState::from_game_state(&game);
TrictracEnvironment {
@ -145,7 +145,7 @@ impl Environment for TrictracEnvironment {
self.game.init_player("Opponent");
// Commencer la partie
self.game.consume(&GameEvent::BeginGame { goes_first: 1 });
let _ = self.game.consume(&GameEvent::BeginGame { goes_first: 1 });
self.current_state = TrictracState::from_game_state(&self.game);
self.episode_reward = 0.0;
@ -259,15 +259,13 @@ impl TrictracEnvironment {
use training_common::get_valid_actions;
// Obtenir les actions valides dans le contexte actuel
let valid_actions = get_valid_actions(game_state);
if valid_actions.is_empty() {
return None;
if let Ok(valid_actions) = get_valid_actions(game_state) {
// Mapper l'index d'action sur une action valide
let action_index = (action.index as usize) % valid_actions.len();
Some(valid_actions[action_index].clone())
} else {
None
}
// Mapper l'index d'action sur une action valide
let action_index = (action.index as usize) % valid_actions.len();
Some(valid_actions[action_index].clone())
}
/// Exécute une action Trictrac dans le jeu
@ -284,20 +282,20 @@ impl TrictracEnvironment {
// Appliquer l'événement si valide
if let Some(event) = action.to_event(&self.game) {
if self.game.validate(&event) {
self.game.consume(&event);
let _ = self.game.consume(&event);
// reward += REWARD_VALID_MOVE;
// Simuler le résultat des dés après un Roll
if matches!(action, TrictracAction::Roll) {
let mut rng = thread_rng();
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
let mut rng = rng();
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
let dice_event = GameEvent::RollResult {
player_id: self.active_player_id,
dice: store::Dice {
dice: trictrac_store::Dice {
values: dice_values,
},
};
if self.game.validate(&dice_event) {
self.game.consume(&dice_event);
let _ = self.game.consume(&dice_event);
let (points, adv_points) = self.game.dice_points;
reward += REWARD_RATIO * (points as f32 - adv_points as f32);
if points > 0 {
@ -340,18 +338,18 @@ impl TrictracEnvironment {
// Exécuter l'action selon le turn_stage
let mut calculate_points = false;
let opponent_color = store::Color::Black;
let opponent_color = trictrac_store::Color::Black;
let event = match self.game.turn_stage {
TurnStage::RollDice => GameEvent::Roll {
player_id: self.opponent_id,
},
TurnStage::RollWaiting => {
let mut rng = thread_rng();
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
let mut rng = rng();
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
calculate_points = true;
GameEvent::RollResult {
player_id: self.opponent_id,
dice: store::Dice {
dice: trictrac_store::Dice {
values: dice_values,
},
}
@ -371,7 +369,7 @@ impl TrictracEnvironment {
}
}
TurnStage::MarkAdvPoints => {
let opponent_color = store::Color::Black;
let opponent_color = trictrac_store::Color::Black;
let dice_roll_count = self
.game
.players
@ -399,7 +397,7 @@ impl TrictracEnvironment {
};
if self.game.validate(&event) {
self.game.consume(&event);
let _ = self.game.consume(&event);
if calculate_points {
let dice_roll_count = self
.game

View file

@ -1,8 +1,8 @@
use crate::training_common;
use burn::{prelude::Backend, tensor::Tensor};
use burn_rl::base::{Action, Environment, Snapshot, State};
use rand::{thread_rng, Rng};
use store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
use rand::{rng, Rng};
use trictrac_store::training_common;
use trictrac_store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
const ERROR_REWARD: f32 = -1.0012121;
const REWARD_RATIO: f32 = 0.1;
@ -48,10 +48,10 @@ pub struct TrictracAction {
impl Action for TrictracAction {
fn random() -> Self {
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
use rand::{rng, Rng};
let mut rng = rng();
TrictracAction {
index: rng.gen_range(0..Self::size() as u32),
index: rng.random_range(0..Self::size() as u32),
}
}
@ -109,7 +109,7 @@ impl Environment for TrictracEnvironment {
let player2_id = 2;
// Commencer la partie
game.consume(&GameEvent::BeginGame { goes_first: 1 });
let _ = game.consume(&GameEvent::BeginGame { goes_first: 1 });
let current_state = TrictracState::from_game_state(&game);
TrictracEnvironment {
@ -136,7 +136,7 @@ impl Environment for TrictracEnvironment {
self.game.init_player("Opponent");
// Commencer la partie
self.game.consume(&GameEvent::BeginGame { goes_first: 1 });
let _ = self.game.consume(&GameEvent::BeginGame { goes_first: 1 });
self.current_state = TrictracState::from_game_state(&self.game);
self.episode_reward = 0.0;
@ -229,15 +229,13 @@ impl TrictracEnvironment {
use training_common::get_valid_actions;
// Obtenir les actions valides dans le contexte actuel
let valid_actions = get_valid_actions(&self.game);
if valid_actions.is_empty() {
return None;
if let Ok(valid_actions) = get_valid_actions(&self.game) {
// Mapper l'index d'action sur une action valide
let action_index = (action.index as usize) % valid_actions.len();
Some(valid_actions[action_index])
} else {
None
}
// Mapper l'index d'action sur une action valide
let action_index = (action.index as usize) % valid_actions.len();
Some(valid_actions[action_index].clone())
}
/// Exécute une action Trictrac dans le jeu
@ -254,20 +252,20 @@ impl TrictracEnvironment {
// Appliquer l'événement si valide
if let Some(event) = action.to_event(&self.game) {
if self.game.validate(&event) {
self.game.consume(&event);
let _ = self.game.consume(&event);
// reward += REWARD_VALID_MOVE;
// Simuler le résultat des dés après un Roll
if matches!(action, TrictracAction::Roll) {
let mut rng = thread_rng();
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
let mut rng = rng();
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
let dice_event = GameEvent::RollResult {
player_id: self.active_player_id,
dice: store::Dice {
dice: trictrac_store::Dice {
values: dice_values,
},
};
if self.game.validate(&dice_event) {
self.game.consume(&dice_event);
let _ = self.game.consume(&dice_event);
let (points, adv_points) = self.game.dice_points;
reward += REWARD_RATIO * (points as f32 - adv_points as f32);
if points > 0 {
@ -310,18 +308,18 @@ impl TrictracEnvironment {
// Exécuter l'action selon le turn_stage
let mut calculate_points = false;
let opponent_color = store::Color::Black;
let opponent_color = trictrac_store::Color::Black;
let event = match self.game.turn_stage {
TurnStage::RollDice => GameEvent::Roll {
player_id: self.opponent_id,
},
TurnStage::RollWaiting => {
let mut rng = thread_rng();
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
let mut rng = rng();
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
calculate_points = true;
GameEvent::RollResult {
player_id: self.opponent_id,
dice: store::Dice {
dice: trictrac_store::Dice {
values: dice_values,
},
}
@ -369,7 +367,7 @@ impl TrictracEnvironment {
};
if self.game.validate(&event) {
self.game.consume(&event);
let _ = self.game.consume(&event);
if calculate_points {
let dice_roll_count = self
.game

View file

@ -1,7 +1,7 @@
use bot::burnrl::algos::{dqn, dqn_valid, ppo, ppo_valid, sac, sac_valid};
use bot::burnrl::environment::TrictracEnvironment;
use bot::burnrl::environment_valid::TrictracEnvironment as TrictracEnvironmentValid;
use bot::burnrl::utils::{demo_model, Config};
use trictrac_bot::burnrl::algos::{dqn, dqn_valid, ppo, ppo_valid, sac, sac_valid};
use trictrac_bot::burnrl::environment::TrictracEnvironment;
use trictrac_bot::burnrl::environment_valid::TrictracEnvironment as TrictracEnvironmentValid;
use trictrac_bot::burnrl::utils::{demo_model, Config};
use burn::backend::{Autodiff, NdArray};
use burn_rl::base::ElemType;
use std::env;

View file

@ -1,15 +1,16 @@
pub mod burnrl;
pub mod strategy;
pub mod training_common;
pub mod trictrac_board;
use log::debug;
use store::{CheckerMove, Color, GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
pub use strategy::default::DefaultStrategy;
pub use strategy::dqnburn::DqnBurnStrategy;
pub use strategy::erroneous_moves::ErroneousStrategy;
pub use strategy::random::RandomStrategy;
pub use strategy::stable_baselines3::StableBaselines3Strategy;
use trictrac_store::{
CheckerMove, Color, GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage,
};
pub trait BotStrategy: std::fmt::Debug {
fn get_game(&self) -> &GameState;
@ -70,14 +71,14 @@ impl Bot {
debug!(">>>> {:?} BOT handle", self.color);
let game = self.strategy.get_mut_game();
let internal_event = if self.color == Color::Black {
&event.get_mirror()
&event.get_mirror(false)
} else {
event
};
let init_player_points = game.who_plays().map(|p| (p.points, p.holes));
let turn_stage = game.turn_stage;
game.consume(internal_event);
let _ = game.consume(internal_event);
if game.stage == Stage::Ended {
debug!("<<<< end {:?} BOT handle", self.color);
return None;
@ -125,7 +126,7 @@ impl Bot {
return if self.color == Color::Black {
debug!(" bot (internal) evt : {internal_event:?} ; points : {player_points:?}");
debug!("<<<< end {:?} BOT handle", self.color);
internal_event.map(|evt| evt.get_mirror())
internal_event.map(|evt| evt.get_mirror(false))
} else {
debug!("<<<< end {:?} BOT handle", self.color);
internal_event
@ -144,7 +145,7 @@ impl Bot {
#[cfg(test)]
mod tests {
use super::*;
use store::{Dice, Stage};
use trictrac_store::{Dice, Stage};
#[test]
fn test_new() {

View file

@ -1,5 +1,5 @@
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
use store::MoveRules;
use trictrac_store::MoveRules;
#[derive(Debug)]
pub struct DefaultStrategy {

View file

@ -4,11 +4,13 @@ use burn_rl::base::{ElemType, Model, State};
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
use log::info;
use store::MoveRules;
use trictrac_store::MoveRules;
use crate::burnrl::algos::dqn;
use crate::burnrl::environment;
use crate::training_common::{get_valid_action_indices, sample_valid_action, TrictracAction};
use trictrac_store::training_common::{
get_valid_action_indices, sample_valid_action, TrictracAction,
};
type DqnBurnNetwork = dqn::Net<NdArray<ElemType>>;
@ -48,30 +50,32 @@ impl DqnBurnStrategy {
fn get_dqn_action(&self) -> Option<TrictracAction> {
if let Some(ref model) = self.model {
let state = environment::TrictracState::from_game_state(&self.game);
let valid_actions_indices = get_valid_action_indices(&self.game);
if valid_actions_indices.is_empty() {
return None; // No valid actions, end of episode
}
// Obtenir les Q-values pour toutes les actions
let q_values = model.infer(state.to_tensor().unsqueeze());
// Set non valid actions q-values to lowest
let mut masked_q_values = q_values.clone();
let q_values_vec: Vec<f32> = q_values.into_data().into_vec().unwrap();
for (index, q_value) in q_values_vec.iter().enumerate() {
if !valid_actions_indices.contains(&index) {
masked_q_values = masked_q_values.clone().mask_fill(
masked_q_values.clone().equal_elem(*q_value),
f32::NEG_INFINITY,
);
if let Ok(valid_actions_indices) = get_valid_action_indices(&self.game) {
if valid_actions_indices.is_empty() {
return None; // No valid actions, end of episode
}
// Obtenir les Q-values pour toutes les actions
let q_values = model.infer(state.to_tensor().unsqueeze());
// Set non valid actions q-values to lowest
let mut masked_q_values = q_values.clone();
let q_values_vec: Vec<f32> = q_values.into_data().into_vec().unwrap();
for (index, q_value) in q_values_vec.iter().enumerate() {
if !valid_actions_indices.contains(&index) {
masked_q_values = masked_q_values.clone().mask_fill(
masked_q_values.clone().equal_elem(*q_value),
f32::NEG_INFINITY,
);
}
}
// Get best action (highest q-value)
let action_index = masked_q_values.argmax(1).into_scalar().to_u32();
return environment::TrictracEnvironment::convert_action(
environment::TrictracAction::from(action_index),
);
}
// Get best action (highest q-value)
let action_index = masked_q_values.argmax(1).into_scalar().to_u32();
environment::TrictracEnvironment::convert_action(environment::TrictracAction::from(
action_index,
))
return None;
} else {
// Fallback : action aléatoire valide
sample_valid_action(&self.game)
@ -152,7 +156,7 @@ impl BotStrategy for DqnBurnStrategy {
to1 = if fto1 < 0 { 0 } else { fto1 as usize };
}
let checker_move1 = store::CheckerMove::new(from1, to1).unwrap_or_default();
let checker_move1 = trictrac_store::CheckerMove::new(from1, to1).unwrap_or_default();
let mut tmp_board = self.game.board.clone();
let move_res = tmp_board.move_checker(&self.color, checker_move1);

View file

@ -1,5 +1,6 @@
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
use store::MoveRules;
use rand::{prelude::IndexedRandom, rng};
use trictrac_store::MoveRules;
#[derive(Debug)]
pub struct RandomStrategy {
@ -51,8 +52,7 @@ impl BotStrategy for RandomStrategy {
let rules = MoveRules::new(&self.color, &self.game.board, self.game.dice);
let possible_moves = rules.get_possible_moves_sequences(true, vec![]);
use rand::{seq::SliceRandom, thread_rng};
let mut rng = thread_rng();
let mut rng = rng();
let choosen_move = possible_moves
.choose(&mut rng)
.cloned()

View file

@ -5,7 +5,7 @@ use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use store::MoveRules;
use trictrac_store::MoveRules;
#[derive(Debug)]
pub struct StableBaselines3Strategy {
@ -79,12 +79,12 @@ impl StableBaselines3Strategy {
// Convertir l'étape du tour en entier
let turn_stage = match self.game.turn_stage {
store::TurnStage::RollDice => 0,
store::TurnStage::RollWaiting => 1,
store::TurnStage::MarkPoints => 2,
store::TurnStage::HoldOrGoChoice => 3,
store::TurnStage::Move => 4,
store::TurnStage::MarkAdvPoints => 5,
trictrac_store::TurnStage::RollDice => 0,
trictrac_store::TurnStage::RollWaiting => 1,
trictrac_store::TurnStage::MarkPoints => 2,
trictrac_store::TurnStage::HoldOrGoChoice => 3,
trictrac_store::TurnStage::Move => 4,
trictrac_store::TurnStage::MarkAdvPoints => 5,
};
// Récupérer les points et trous des joueurs

View file

@ -1,5 +1,4 @@
// https://docs.rs/board-game/ implementation
use crate::training_common::{get_valid_actions, TrictracAction};
use board_game::board::{
Board as BoardGameBoard, BoardDone, BoardMoves, Outcome, PlayError, Player as BoardGamePlayer,
};
@ -8,7 +7,8 @@ use internal_iterator::InternalIterator;
use std::fmt;
use std::hash::Hash;
use std::ops::ControlFlow;
use store::Color;
use trictrac_store::training_common::{get_valid_actions, TrictracAction};
use trictrac_store::Color;
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct TrictracBoard(crate::GameState);
@ -55,8 +55,12 @@ impl BoardGameBoard for TrictracBoard {
fn play(&mut self, mv: Self::Move) -> Result<(), PlayError> {
self.check_can_play(mv)?;
self.0.consume(&mv.to_event(&self.0).unwrap());
Ok(())
if let Some(evt) = mv.to_event(&self.0) {
let _ = self.0.consume(&evt);
Ok(())
} else {
Err(PlayError::UnavailableMove)
}
}
fn outcome(&self) -> Option<Outcome> {
@ -159,6 +163,9 @@ impl InternalIterator for TrictracAvailableMovesIterator<'_> {
where
F: FnMut(Self::Item) -> ControlFlow<R>,
{
get_valid_actions(&self.board.0).into_iter().try_for_each(f)
match get_valid_actions(&self.board.0) {
Ok(actions) => actions.into_iter().try_for_each(f),
Err(_) => ControlFlow::Continue(()),
}
}
}

View file

@ -1,5 +1,5 @@
[package]
name = "client_cli"
name = "trictrac-client_cli"
version = "0.1.0"
edition = "2021"
@ -11,8 +11,8 @@ bincode = "1.3.3"
pico-args = "0.5.0"
pretty_assertions = "1.4.0"
renet = "0.0.13"
store = { path = "../store" }
bot = { path = "../bot" }
trictrac-store = { path = "../store" }
trictrac-bot = { path = "../bot" }
itertools = "0.13.0"
env_logger = "0.11.6"
log = "0.4.20"

View file

@ -1,11 +1,11 @@
use bot::{
use trictrac_bot::{
BotStrategy, DefaultStrategy, DqnBurnStrategy, ErroneousStrategy, RandomStrategy,
StableBaselines3Strategy,
};
use itertools::Itertools;
use crate::game_runner::GameRunner;
use store::{CheckerMove, GameEvent, GameState, Stage, TurnStage};
use trictrac_store::{CheckerMove, GameEvent, GameState, Stage, TurnStage};
#[derive(Debug, Default)]
pub struct AppArgs {

View file

@ -1,6 +1,6 @@
use bot::{Bot, BotStrategy};
use log::{debug, error};
use store::{CheckerMove, DiceRoller, GameEvent, GameState, PlayerId, TurnStage};
use trictrac_bot::{Bot, BotStrategy};
use trictrac_store::{CheckerMove, DiceRoller, GameEvent, GameState, PlayerId, TurnStage};
// Application Game
#[derive(Debug, Default)]
@ -67,7 +67,7 @@ impl GameRunner {
"--------------- new valid event {event:?} (stage {:?}) -----------",
self.state.turn_stage
);
self.state.consume(event);
let _ = self.state.consume(event).inspect_err(|e| error!("{}", e));
debug!(
" --> stage {:?} ; active player points {:?}",
self.state.turn_stage,
@ -117,8 +117,8 @@ impl GameRunner {
}
if let Some(winner) = self.state.determine_winner() {
next_event = Some(store::GameEvent::EndGame {
reason: store::EndGameReason::PlayerWon { winner },
next_event = Some(trictrac_store::GameEvent::EndGame {
reason: trictrac_store::EndGameReason::PlayerWon { winner },
});
}

View file

@ -3,10 +3,10 @@
"devenv": {
"locked": {
"dir": "src/modules",
"lastModified": 1753667201,
"lastModified": 1770390537,
"owner": "cachix",
"repo": "devenv",
"rev": "4d584d7686a50387f975879788043e55af9f0ad4",
"rev": "d6f45cc00829254a9a6f8807c8fbfaf3efa7e629",
"type": "github"
},
"original": {
@ -19,14 +19,14 @@
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1747046372,
"owner": "edolstra",
"lastModified": 1767039857,
"owner": "NixOS",
"repo": "flake-compat",
"rev": "9100a0f413b0c601e0533d1d94ffd501ce2e7885",
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
"type": "github"
},
"original": {
"owner": "edolstra",
"owner": "NixOS",
"repo": "flake-compat",
"type": "github"
}
@ -40,10 +40,10 @@
]
},
"locked": {
"lastModified": 1750779888,
"lastModified": 1769939035,
"owner": "cachix",
"repo": "git-hooks.nix",
"rev": "16ec914f6fb6f599ce988427d9d94efddf25fe6d",
"rev": "a8ca480175326551d6c4121498316261cbb5b260",
"type": "github"
},
"original": {
@ -60,10 +60,10 @@
]
},
"locked": {
"lastModified": 1709087332,
"lastModified": 1762808025,
"owner": "hercules-ci",
"repo": "gitignore.nix",
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
"rev": "cb5e3fdca1de58ccbc3ef53de65bd372b48f567c",
"type": "github"
},
"original": {
@ -74,24 +74,40 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1753432016,
"lastModified": 1770136044,
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "6027c30c8e9810896b92429f0092f624f7b1aace",
"rev": "e576e3c9cf9bad747afcddd9e34f51d18c855b4e",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"ref": "nixos-25.11",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-cmake3": {
"locked": {
"lastModified": 1758213207,
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "f4b140d5b253f5e2a1ff4e5506edbf8267724bde",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "f4b140d5b253f5e2a1ff4e5506edbf8267724bde",
"type": "github"
}
},
"root": {
"inputs": {
"devenv": "devenv",
"git-hooks": "git-hooks",
"nixpkgs": "nixpkgs",
"nixpkgs-cmake3": "nixpkgs-cmake3",
"pre-commit-hooks": [
"git-hooks"
]

View file

@ -1,13 +1,16 @@
{ pkgs, ... }:
{ inputs, pkgs, ... }:
let
pkgs-cmake3 = import inputs.nixpkgs-cmake3 { system = pkgs.stdenv.system; };
in
{
packages = [
# pour burn-rs
pkgs.SDL2_gfx
# (compilation sdl2-sys)
pkgs.cmake
pkgs-cmake3.cmake
pkgs.libxcb
pkgs.libffi
pkgs.wayland-scanner
@ -15,6 +18,12 @@
pkgs.samply # code profiler
pkgs.feedgnuplot # to visualize bots training results
# --- AI training with python ---
# generate python classes from rust code
pkgs.maturin
# required by python numpy
pkgs.libz
# for bevy
pkgs.alsa-lib
pkgs.udev
@ -47,6 +56,25 @@
# https://devenv.sh/languages/
languages.rust.enable = true;
# AI training with python
enterShell = ''
PYTHONPATH=$PYTHONPATH:$PWD/.devenv/state/venv/lib/python3/site-packages
'';
languages.python = {
enable = true;
uv.enable = true;
venv.enable = true;
venv.requirements = "
pip
gymnasium
numpy
stable-baselines3
shimmy
";
};
# https://devenv.sh/scripts/
# scripts.hello.exec = "echo hello from $GREET";

View file

@ -1,3 +1,5 @@
inputs:
nixpkgs:
url: github:NixOS/nixpkgs/nixpkgs-unstable
url: github:NixOS/nixpkgs/nixos-25.11
nixpkgs-cmake3:
url: github:NixOS/nixpkgs/f4b140d5b253f5e2a1ff4e5506edbf8267724bde

View file

@ -1,775 +0,0 @@
# Description
Je développe un jeu de TricTrac (<https://fr.wikipedia.org/wiki/Trictrac>) dans le langage rust.
Pour le moment je me concentre sur l'application en ligne de commande simple, donc ne t'occupe pas des dossiers 'client_bevy', 'client_tui', et 'server' qui ne seront utilisés que pour de prochaines évolutions.
Les règles du jeu et l'état d'une partie sont implémentées dans 'store', l'application ligne de commande est implémentée dans 'client_cli', elle permet déjà de jouer contre un bot, ou de faire jouer deux bots l'un contre l'autre.
Les stratégies de bots sont implémentées dans le dossier 'bot'.
Plus précisément, l'état du jeu est défini par le struct GameState dans store/src/game.rs, la méthode to_string_id() permet de coder cet état de manière compacte dans une chaîne de caractères, mais il n'y a pas l'historique des coups joués. Il y a aussi fmt::Display d'implémenté pour une representation textuelle plus lisible.
'client_cli/src/game_runner.rs' contient la logique permettant de faire jouer deux bots l'un contre l'autre.
'bot/src/default.rs' contient le code d'une stratégie de bot basique : il détermine la liste des mouvements valides (avec la méthode get_possible_moves_sequences de store::MoveRules) et joue simplement le premier de la liste.
J'aimerais maintenant ajouter une stratégie de bot plus forte en entrainant un agent/bot avec OpenAI Gym.
Pour bénéficier des bibliothèques disponibles en python, comme 'Stable-Baselines3', j'ai utilisé PyO3 pour appeler mon code rust depuis python. Le code rust exposé se trouve dans 'store/src/engine.rs', il ne contient pour le moment que du code d'exemple pour m'assurer que la passerelle entre python et rust fonctionne, mais tout est à implémenter : l'état du jeu, les mouvements disponibles, etc.
La classe python 'store/python/trictracEnv.py' est elle aussi presque vide, elle ne contient pour le moment qu'un squelette avec des fonctions à implémenter.
Peux-tu m'aider à modifier engine.rs et trictracenv.py pour permettre d'entrainer un agent (bot) ?
J'aimerais utiliser ce que j'ai déjà implémenté en rust : l'état d'une partie et les règles, et la fonction renvoyant la liste des coups disponibles pour un joueur à partir d'un état du jeu (get_possible_moves_sequences), mais je ne sais pas trop comment m'y prendre.
## Réponse de Claude
Je vois que je n'ai pas l'autorisation d'utiliser l'outil Edit. Je vais vous montrer les modifications nécessaires pour les deux fichiers principaux.
Voici le contenu à utiliser pour `store/src/engine.rs` :
```rust
//! # Expose trictrac game state and rules in a python module
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
use crate::board::CheckerMove;
use crate::dice::Dice;
use crate::game::{GameEvent, GameState, Stage, TurnStage};
use crate::game_rules_moves::MoveRules;
use crate::game_rules_points::{PointsRules, PossibleJans};
use crate::player::{Color, Player, PlayerId};
use std::collections::HashMap;
#[pyclass]
struct TricTrac {
game_state: GameState,
dice_roll_sequence: Vec<(u8, u8)>,
current_dice_index: usize,
}
#[pymethods]
impl TricTrac {
#[new]
fn new() -> Self {
let mut game_state = GameState::new(false); // schools_enabled = false
// Initialiser 2 joueurs
game_state.init_player("player1");
game_state.init_player("bot");
// Commencer la partie avec le joueur 1
game_state.consume(&GameEvent::BeginGame { goes_first: 1 });
TricTrac {
game_state,
dice_roll_sequence: Vec::new(),
current_dice_index: 0,
}
}
/// Obtenir l'état du jeu sous forme de chaîne de caractères compacte
fn get_state_id(&self) -> String {
self.game_state.to_string_id()
}
/// Obtenir l'état du jeu sous forme de dictionnaire pour faciliter l'entrainement
fn get_state_dict(&self) -> PyResult<Py<PyDict>> {
let gil = Python::acquire_gil();
let py = gil.python();
let state_dict = PyDict::new(py);
// Informations essentielles sur l'état du jeu
state_dict.set_item("active_player", self.game_state.active_player_id)?;
state_dict.set_item("stage", format!("{:?}", self.game_state.stage))?;
state_dict.set_item("turn_stage", format!("{:?}", self.game_state.turn_stage))?;
// Dés
let (dice1, dice2) = self.game_state.dice.values;
state_dict.set_item("dice", (dice1, dice2))?;
// Points des joueurs
if let Some(white_player) = self.game_state.get_white_player() {
state_dict.set_item("white_points", white_player.points)?;
state_dict.set_item("white_holes", white_player.holes)?;
}
if let Some(black_player) = self.game_state.get_black_player() {
state_dict.set_item("black_points", black_player.points)?;
state_dict.set_item("black_holes", black_player.holes)?;
}
// Positions des pièces
let white_positions = self.get_checker_positions(Color::White);
let black_positions = self.get_checker_positions(Color::Black);
state_dict.set_item("white_positions", white_positions)?;
state_dict.set_item("black_positions", black_positions)?;
// État compact pour la comparaison d'états
state_dict.set_item("state_id", self.game_state.to_string_id())?;
Ok(state_dict.into())
}
/// Renvoie les positions des pièces pour un joueur spécifique
fn get_checker_positions(&self, color: Color) -> Vec<(usize, i8)> {
self.game_state.board.get_color_fields(color)
}
/// Obtenir la liste des mouvements légaux sous forme de paires (from, to)
fn get_available_moves(&self) -> Vec<((usize, usize), (usize, usize))> {
// L'agent joue toujours le joueur actif
let color = self.game_state.player_color_by_id(&self.game_state.active_player_id).unwrap_or(Color::White);
// Si ce n'est pas le moment de déplacer les pièces, retourner une liste vide
if self.game_state.turn_stage != TurnStage::Move && self.game_state.turn_stage != TurnStage::HoldOrGoChoice {
return vec![];
}
let rules = MoveRules::new(&color, &self.game_state.board, self.game_state.dice);
let possible_moves = rules.get_possible_moves_sequences(true, vec![]);
// Convertir les mouvements CheckerMove en tuples (from, to) pour Python
possible_moves.into_iter()
.map(|(move1, move2)| (
(move1.get_from(), move1.get_to()),
(move2.get_from(), move2.get_to())
)).collect()
}
/// Jouer un coup ((from1, to1), (from2, to2))
fn play_move(&mut self, moves: ((usize, usize), (usize, usize))) -> bool {
let ((from1, to1), (from2, to2)) = moves;
// Vérifier que c'est au tour du joueur de jouer
if self.game_state.turn_stage != TurnStage::Move && self.game_state.turn_stage != TurnStage::HoldOrGoChoice {
return false;
}
let move1 = CheckerMove::new(from1, to1).unwrap_or_default();
let move2 = CheckerMove::new(from2, to2).unwrap_or_default();
let event = GameEvent::Move {
player_id: self.game_state.active_player_id,
moves: (move1, move2),
};
// Vérifier si le mouvement est valide
if !self.game_state.validate(&event) {
return false;
}
// Exécuter le mouvement
self.game_state.consume(&event);
// Si l'autre joueur doit lancer les dés maintenant, simuler ce lancement
if self.game_state.turn_stage == TurnStage::RollDice {
self.roll_dice();
}
true
}
/// Lancer les dés (soit aléatoirement, soit en utilisant une séquence prédéfinie)
fn roll_dice(&mut self) -> (u8, u8) {
// Vérifier que c'est au bon moment pour lancer les dés
if self.game_state.turn_stage != TurnStage::RollDice && self.game_state.turn_stage != TurnStage::RollWaiting {
return self.game_state.dice.values;
}
// Simuler un lancer de dés
let dice_values = if !self.dice_roll_sequence.is_empty() && self.current_dice_index < self.dice_roll_sequence.len() {
// Utiliser la séquence prédéfinie
let dice = self.dice_roll_sequence[self.current_dice_index];
self.current_dice_index += 1;
dice
} else {
// Générer aléatoirement
(
(1 + (rand::random::<u8>() % 6)),
(1 + (rand::random::<u8>() % 6))
)
};
// Envoyer les événements appropriés
let roll_event = GameEvent::Roll {
player_id: self.game_state.active_player_id,
};
if self.game_state.validate(&roll_event) {
self.game_state.consume(&roll_event);
}
let roll_result_event = GameEvent::RollResult {
player_id: self.game_state.active_player_id,
dice: Dice { values: dice_values },
};
if self.game_state.validate(&roll_result_event) {
self.game_state.consume(&roll_result_event);
}
dice_values
}
/// Marquer des points
fn mark_points(&mut self, points: u8) -> bool {
// Vérifier que c'est au bon moment pour marquer des points
if self.game_state.turn_stage != TurnStage::MarkPoints && self.game_state.turn_stage != TurnStage::MarkAdvPoints {
return false;
}
let event = GameEvent::Mark {
player_id: self.game_state.active_player_id,
points,
};
// Vérifier si l'événement est valide
if !self.game_state.validate(&event) {
return false;
}
// Exécuter l'événement
self.game_state.consume(&event);
// Si l'autre joueur doit lancer les dés maintenant, simuler ce lancement
if self.game_state.turn_stage == TurnStage::RollDice {
self.roll_dice();
}
true
}
/// Choisir de "continuer" (Go) après avoir gagné un trou
fn choose_go(&mut self) -> bool {
// Vérifier que c'est au bon moment pour choisir de continuer
if self.game_state.turn_stage != TurnStage::HoldOrGoChoice {
return false;
}
let event = GameEvent::Go {
player_id: self.game_state.active_player_id,
};
// Vérifier si l'événement est valide
if !self.game_state.validate(&event) {
return false;
}
// Exécuter l'événement
self.game_state.consume(&event);
// Simuler le lancer de dés pour le prochain tour
self.roll_dice();
true
}
/// Calcule les points maximaux que le joueur actif peut obtenir avec les dés actuels
fn calculate_points(&self) -> u8 {
let active_player = self.game_state.players.get(&self.game_state.active_player_id);
if let Some(player) = active_player {
let dice_roll_count = player.dice_roll_count;
let color = player.color;
let points_rules = PointsRules::new(&color, &self.game_state.board, self.game_state.dice);
let (points, _) = points_rules.get_points(dice_roll_count);
points
} else {
0
}
}
/// Réinitialise la partie
fn reset(&mut self) {
self.game_state = GameState::new(false);
// Initialiser 2 joueurs
self.game_state.init_player("player1");
self.game_state.init_player("bot");
// Commencer la partie avec le joueur 1
self.game_state.consume(&GameEvent::BeginGame { goes_first: 1 });
// Réinitialiser l'index de la séquence de dés
self.current_dice_index = 0;
}
/// Vérifie si la partie est terminée
fn is_done(&self) -> bool {
self.game_state.stage == Stage::Ended || self.game_state.determine_winner().is_some()
}
/// Obtenir le gagnant de la partie
fn get_winner(&self) -> Option<PlayerId> {
self.game_state.determine_winner()
}
/// Obtenir le score du joueur actif (nombre de trous)
fn get_score(&self, player_id: PlayerId) -> i32 {
if let Some(player) = self.game_state.players.get(&player_id) {
player.holes as i32
} else {
-1
}
}
/// Obtenir l'ID du joueur actif
fn get_active_player_id(&self) -> PlayerId {
self.game_state.active_player_id
}
/// Définir une séquence de dés à utiliser (pour la reproductibilité)
fn set_dice_sequence(&mut self, sequence: Vec<(u8, u8)>) {
self.dice_roll_sequence = sequence;
self.current_dice_index = 0;
}
/// Afficher l'état du jeu (pour le débogage)
fn __str__(&self) -> String {
format!("{}", self.game_state)
}
}
/// A Python module implemented in Rust. The name of this function must match
/// the `lib.name` setting in the `Cargo.toml`, else Python will not be able to
/// import the module.
#[pymodule]
fn trictrac(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<TricTrac>()?;
Ok(())
}
```
Et pour `store/python/trictracEnv.py` :
```python
import gym
import numpy as np
from gym import spaces
import trictrac # module Rust exposé via PyO3
from typing import Dict, List, Tuple, Optional, Any, Union
class TricTracEnv(gym.Env):
"""Environnement OpenAI Gym pour le jeu de Trictrac"""
metadata = {"render.modes": ["human"]}
def __init__(self, opponent_strategy="random"):
super(TricTracEnv, self).__init__()
# Instancier le jeu
self.game = trictrac.TricTrac()
# Stratégie de l'adversaire
self.opponent_strategy = opponent_strategy
# Constantes
self.MAX_FIELD = 24 # Nombre de cases sur le plateau
self.MAX_CHECKERS = 15 # Nombre maximum de pièces par joueur
# Définition de l'espace d'observation
# Format:
# - Position des pièces blanches (24)
# - Position des pièces noires (24)
# - Joueur actif (1: blanc, 2: noir) (1)
# - Valeurs des dés (2)
# - Points de chaque joueur (2)
# - Trous de chaque joueur (2)
# - Phase du jeu (1)
self.observation_space = spaces.Dict({
'board': spaces.Box(low=-self.MAX_CHECKERS, high=self.MAX_CHECKERS, shape=(self.MAX_FIELD,), dtype=np.int8),
'active_player': spaces.Discrete(3), # 0: pas de joueur, 1: blanc, 2: noir
'dice': spaces.MultiDiscrete([7, 7]), # Valeurs des dés (1-6)
'white_points': spaces.Discrete(13), # Points du joueur blanc (0-12)
'white_holes': spaces.Discrete(13), # Trous du joueur blanc (0-12)
'black_points': spaces.Discrete(13), # Points du joueur noir (0-12)
'black_holes': spaces.Discrete(13), # Trous du joueur noir (0-12)
'turn_stage': spaces.Discrete(6), # Étape du tour
})
# Définition de l'espace d'action
# Format:
# - Action type: 0=move, 1=mark, 2=go
# - Move: (from1, to1, from2, to2) ou zeros
self.action_space = spaces.Dict({
'action_type': spaces.Discrete(3),
'move': spaces.MultiDiscrete([self.MAX_FIELD + 1, self.MAX_FIELD + 1,
self.MAX_FIELD + 1, self.MAX_FIELD + 1])
})
# État courant
self.state = self._get_observation()
# Historique des états pour éviter les situations sans issue
self.state_history = []
# Pour le débogage et l'entraînement
self.steps_taken = 0
self.max_steps = 1000 # Limite pour éviter les parties infinies
def reset(self):
"""Réinitialise l'environnement et renvoie l'état initial"""
self.game.reset()
self.state = self._get_observation()
self.state_history = []
self.steps_taken = 0
return self.state
def step(self, action):
"""
Exécute une action et retourne (state, reward, done, info)
Action format:
{
'action_type': 0/1/2, # 0=move, 1=mark, 2=go
'move': [from1, to1, from2, to2] # Utilisé seulement si action_type=0
}
"""
action_type = action['action_type']
reward = 0
done = False
info = {}
# Vérifie que l'action est valide pour le joueur humain (id=1)
player_id = self.game.get_active_player_id()
is_agent_turn = player_id == 1 # L'agent joue toujours le joueur 1
if is_agent_turn:
# Exécute l'action selon son type
if action_type == 0: # Move
from1, to1, from2, to2 = action['move']
move_made = self.game.play_move(((from1, to1), (from2, to2)))
if not move_made:
# Pénaliser les mouvements invalides
reward -= 2.0
info['invalid_move'] = True
else:
# Petit bonus pour un mouvement valide
reward += 0.1
elif action_type == 1: # Mark
points = self.game.calculate_points()
marked = self.game.mark_points(points)
if not marked:
# Pénaliser les actions invalides
reward -= 2.0
info['invalid_mark'] = True
else:
# Bonus pour avoir marqué des points
reward += 0.1 * points
elif action_type == 2: # Go
go_made = self.game.choose_go()
if not go_made:
# Pénaliser les actions invalides
reward -= 2.0
info['invalid_go'] = True
else:
# Petit bonus pour l'action valide
reward += 0.1
else:
# Tour de l'adversaire
self._play_opponent_turn()
# Vérifier si la partie est terminée
if self.game.is_done():
done = True
winner = self.game.get_winner()
if winner == 1:
# Bonus si l'agent gagne
reward += 10.0
info['winner'] = 'agent'
else:
# Pénalité si l'adversaire gagne
reward -= 5.0
info['winner'] = 'opponent'
# Récompense basée sur la progression des trous
agent_holes = self.game.get_score(1)
opponent_holes = self.game.get_score(2)
reward += 0.5 * (agent_holes - opponent_holes)
# Mettre à jour l'état
new_state = self._get_observation()
# Vérifier les états répétés
if self._is_state_repeating(new_state):
reward -= 0.2 # Pénalité légère pour éviter les boucles
info['repeating_state'] = True
# Ajouter l'état à l'historique
self.state_history.append(self._get_state_id())
# Limiter la durée des parties
self.steps_taken += 1
if self.steps_taken >= self.max_steps:
done = True
info['timeout'] = True
# Comparer les scores en cas de timeout
if agent_holes > opponent_holes:
reward += 5.0
info['winner'] = 'agent'
elif opponent_holes > agent_holes:
reward -= 2.0
info['winner'] = 'opponent'
self.state = new_state
return self.state, reward, done, info
def _play_opponent_turn(self):
"""Simule le tour de l'adversaire avec la stratégie choisie"""
player_id = self.game.get_active_player_id()
# Boucle tant qu'il est au tour de l'adversaire
while player_id == 2 and not self.game.is_done():
# Action selon l'étape du tour
state_dict = self._get_state_dict()
turn_stage = state_dict.get('turn_stage')
if turn_stage == 'RollDice' or turn_stage == 'RollWaiting':
self.game.roll_dice()
elif turn_stage == 'MarkPoints' or turn_stage == 'MarkAdvPoints':
points = self.game.calculate_points()
self.game.mark_points(points)
elif turn_stage == 'HoldOrGoChoice':
# Stratégie simple: toujours continuer (Go)
self.game.choose_go()
elif turn_stage == 'Move':
available_moves = self.game.get_available_moves()
if available_moves:
if self.opponent_strategy == "random":
# Choisir un mouvement au hasard
move = available_moves[np.random.randint(0, len(available_moves))]
else:
# Par défaut, prendre le premier mouvement valide
move = available_moves[0]
self.game.play_move(move)
# Mise à jour de l'ID du joueur actif
player_id = self.game.get_active_player_id()
def _get_observation(self):
"""Convertit l'état du jeu en un format utilisable par l'apprentissage par renforcement"""
state_dict = self._get_state_dict()
# Créer un tableau représentant le plateau
board = np.zeros(self.MAX_FIELD, dtype=np.int8)
# Remplir les positions des pièces blanches (valeurs positives)
white_positions = state_dict.get('white_positions', [])
for pos, count in white_positions:
if 1 <= pos <= self.MAX_FIELD:
board[pos-1] = count
# Remplir les positions des pièces noires (valeurs négatives)
black_positions = state_dict.get('black_positions', [])
for pos, count in black_positions:
if 1 <= pos <= self.MAX_FIELD:
board[pos-1] = -count
# Créer l'observation complète
observation = {
'board': board,
'active_player': state_dict.get('active_player', 0),
'dice': np.array([
state_dict.get('dice', (1, 1))[0],
state_dict.get('dice', (1, 1))[1]
]),
'white_points': state_dict.get('white_points', 0),
'white_holes': state_dict.get('white_holes', 0),
'black_points': state_dict.get('black_points', 0),
'black_holes': state_dict.get('black_holes', 0),
'turn_stage': self._turn_stage_to_int(state_dict.get('turn_stage', 'RollDice')),
}
return observation
def _get_state_dict(self) -> Dict:
"""Récupère l'état du jeu sous forme de dictionnaire depuis le module Rust"""
return self.game.get_state_dict()
def _get_state_id(self) -> str:
"""Récupère l'identifiant unique de l'état actuel"""
return self.game.get_state_id()
def _is_state_repeating(self, new_state) -> bool:
"""Vérifie si l'état se répète trop souvent"""
state_id = self.game.get_state_id()
# Compter les occurrences de l'état dans l'historique récent
count = sum(1 for s in self.state_history[-10:] if s == state_id)
return count >= 3 # Considéré comme répétitif si l'état apparaît 3 fois ou plus
def _turn_stage_to_int(self, turn_stage: str) -> int:
"""Convertit l'étape du tour en entier pour l'observation"""
stages = {
'RollDice': 0,
'RollWaiting': 1,
'MarkPoints': 2,
'HoldOrGoChoice': 3,
'Move': 4,
'MarkAdvPoints': 5
}
return stages.get(turn_stage, 0)
def render(self, mode="human"):
"""Affiche l'état actuel du jeu"""
if mode == "human":
print(str(self.game))
print(f"État actuel: {self._get_state_id()}")
# Afficher les actions possibles
if self.game.get_active_player_id() == 1:
turn_stage = self._get_state_dict().get('turn_stage')
print(f"Étape: {turn_stage}")
if turn_stage == 'Move' or turn_stage == 'HoldOrGoChoice':
print("Mouvements possibles:")
moves = self.game.get_available_moves()
for i, move in enumerate(moves):
print(f" {i}: {move}")
if turn_stage == 'HoldOrGoChoice':
print("Option: Go (continuer)")
def get_action_mask(self):
"""Retourne un masque des actions valides dans l'état actuel"""
state_dict = self._get_state_dict()
turn_stage = state_dict.get('turn_stage')
# Masque par défaut (toutes les actions sont invalides)
mask = {
'action_type': np.zeros(3, dtype=bool),
'move': np.zeros((self.MAX_FIELD + 1, self.MAX_FIELD + 1,
self.MAX_FIELD + 1, self.MAX_FIELD + 1), dtype=bool)
}
if self.game.get_active_player_id() != 1:
return mask # Pas au tour de l'agent
# Activer les types d'actions valides selon l'étape du tour
if turn_stage == 'Move' or turn_stage == 'HoldOrGoChoice':
mask['action_type'][0] = True # Activer l'action de mouvement
# Activer les mouvements valides
valid_moves = self.game.get_available_moves()
for ((from1, to1), (from2, to2)) in valid_moves:
mask['move'][from1, to1, from2, to2] = True
if turn_stage == 'MarkPoints' or turn_stage == 'MarkAdvPoints':
mask['action_type'][1] = True # Activer l'action de marquer des points
if turn_stage == 'HoldOrGoChoice':
mask['action_type'][2] = True # Activer l'action de continuer (Go)
return mask
def sample_valid_action(self):
"""Échantillonne une action valide selon le masque d'actions"""
mask = self.get_action_mask()
# Trouver les types d'actions valides
valid_action_types = np.where(mask['action_type'])[0]
if len(valid_action_types) == 0:
# Aucune action valide (pas le tour de l'agent)
return {
'action_type': 0,
'move': np.zeros(4, dtype=np.int32)
}
# Choisir un type d'action
action_type = np.random.choice(valid_action_types)
action = {
'action_type': action_type,
'move': np.zeros(4, dtype=np.int32)
}
# Si c'est un mouvement, sélectionner un mouvement valide
if action_type == 0:
valid_moves = np.where(mask['move'])
if len(valid_moves[0]) > 0:
# Sélectionner un mouvement valide aléatoirement
idx = np.random.randint(0, len(valid_moves[0]))
from1 = valid_moves[0][idx]
to1 = valid_moves[1][idx]
from2 = valid_moves[2][idx]
to2 = valid_moves[3][idx]
action['move'] = np.array([from1, to1, from2, to2], dtype=np.int32)
return action
def close(self):
"""Nettoie les ressources à la fermeture de l'environnement"""
pass
# Exemple d'utilisation avec Stable-Baselines3
def example_usage():
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import DummyVecEnv
# Fonction d'enveloppement pour créer l'environnement
def make_env():
return TricTracEnv()
# Créer un environnement vectorisé (peut être parallélisé)
env = DummyVecEnv([make_env])
# Créer le modèle
model = PPO("MultiInputPolicy", env, verbose=1)
# Entraîner le modèle
model.learn(total_timesteps=10000)
# Sauvegarder le modèle
model.save("trictrac_ppo")
print("Entraînement terminé et modèle sauvegardé")
if __name__ == "__main__":
# Tester l'environnement
env = TricTracEnv()
obs = env.reset()
print("Environnement initialisé")
env.render()
# Jouer quelques coups aléatoires
for _ in range(10):
action = env.sample_valid_action()
obs, reward, done, info = env.step(action)
print(f"\nAction: {action}")
print(f"Reward: {reward}")
print(f"Info: {info}")
env.render()
if done:
print("Game over!")
break
env.close()
```
Ces implémentations vous permettront de créer un environnement Gym pour votre jeu Trictrac qui:
1. Expose l'état du jeu dans un format approprié pour l'apprentissage par renforcement
2. Gère le déroulement des parties et le tour de l'adversaire
3. Définit un système de récompenses pour l'entraînement de l'agent
4. Fournit des masques d'actions pour garantir que seules les actions valides sont sélectionnées
5. Inclut des exemples pour l'intégration avec Stable-Baselines3
Ce code nécessitera probablement quelques ajustements en fonction de la façon dont votre code Rust est organisé, mais il devrait vous donner une base solide pour commencer.
Pour utiliser cette implémentation :
1. Mettez à jour `engine.rs` pour exposer l'API nécessaire à Python
2. Compilez la bibliothèque Rust avec maturin : `maturin build -m store/Cargo.toml --release`
3. Implémentez `trictracEnv.py` avec l'environnement Gym
4. Créez un script d'entraînement qui utilise Stable-Baselines3 ou une autre bibliothèque d'apprentissage par renforcement
Voulez-vous que j'explique plus en détail certaines parties de l'implémentation ou que je vous aide à résoudre des problèmes spécifiques ?

View file

@ -1,268 +0,0 @@
# Description
Je développe un jeu de TricTrac (<https://fr.wikipedia.org/wiki/Trictrac>) dans le langage rust.
Pour le moment ne t'occupe pas des dossiers 'client_bevy', 'client_tui', et 'server' qui ne seront utilisés que pour de prochaines évolutions.
Les règles du jeu et l'état d'une partie sont implémentées dans 'store', l'application ligne de commande est implémentée dans 'client_cli', elle permet de jouer contre un bot, ou de faire jouer deux bots l'un contre l'autre.
Les stratégies de bots sont implémentées dans le dossier 'bot'.
L'état du jeu est défini par le struct GameState dans store/src/game.rs, la méthode to_string_id() permet de coder cet état de manière compacte dans une chaîne de caractères, mais il n'y a pas l'historique des coups joués. Il y a aussi fmt::Display d'implémenté pour une representation textuelle plus lisible.
'client_cli/src/game_runner.rs' contient la logique permettant de faire jouer deux bots l'un contre l'autre.
'bot/src/default.rs' contient le code d'une stratégie de bot basique : il détermine la liste des mouvements valides (avec la méthode get_possible_moves_sequences de store::MoveRules) et joue simplement le premier de la liste.
Dans une précédente session tu m'avais aidé à ajouter une stratégie de bot plus forte en entrainant un agent/bot avec OpenAI Gym en utilisant PyO3 et Stable-Baselines3. Tu m'avais fourni le code pour `store/src/engine.rs` et `store/python/trictracEnv.py`.
Ça fonctionne, mais je voudrais maintenant passer à une solution entièrement rust.
Je pensais utiliser burn et l'algorithme DQN implémenté dans s3-burn ( <https://github.com/will-maclean/sb3-burn> ). Peux-tu m'aider à faire ça ?
----- fin d'implémentation :
Parfait ! Le jeu fonctionne maintenant avec la stratégie DQN ! Le bot DQN a même gagné la partie contre le bot
dummy.
Résumé
J'ai réussi à migrer l'implémentation d'une solution Python/PyO3/Stable-Baselines3 vers une solution entièrement
Rust avec DQN. Voici ce qui a été accompli :
✅ Ce qui fonctionne maintenant :
1. Suppression complète de PyO3 du module store pour éviter les conflits
2. Implémentation DQN native en Rust avec :
- Réseau de neurones simplifié (3 couches, ReLU)
- Initialisation Xavier/Glorot des poids
- Buffer de replay pour l'expérience
- Stratégie epsilon-greedy
- Sauvegarde/chargement de modèles en JSON
3. Intégration complète dans le CLI avec la commande :
- --bot dqn : DQN avec configuration par défaut
- --bot dqn:/path/to/model : DQN avec modèle personnalisé
4. Compilation réussie sans dépendances Burn problématiques
🔄 Points à améliorer plus tard :
1. Entraînement complet : Actuellement la méthode train() simule l'entraînement. Il faudrait implémenter la
backpropagation complète.
2. Espace d'actions plus sophistiqué : L'espace d'actions est simplifié (3 actions). On pourrait l'étendre pour
couvrir tous les mouvements possibles.
3. Système de récompenses : Le système de récompenses est basique et pourrait être enrichi.
4. Migration vers Burn : Quand les problèmes de compatibilité seront résolus, on pourra migrer vers Burn pour de
meilleures performances.
La base DQN est maintenant fonctionnelle et entièrement en Rust ! 🎉
---
Ton implémentation démarre avec un bot non entraîné et il s'entraîne lorsqu'il , le modèle n'est pas entraîné de manière séparée ? On démarre avec un modèle non entraîné et il s'entraîne en même temps que le bot joue ?
Je voudrais que le fichier dqn.rs actuel ne contienne que le code nécessaire pour de charger un modèle entraîné et jouer contre les adversaires (c'est à dire l'implémentation de BotStrategy). Et donc que tu extraies le code qui permet d'entraîner le modèle dans un autre fichier, et que tu ajoutes une commande pour lancer l'entraînement.
---
● Parfait ! Testons maintenant un entraînement court :
● Bash(cd /home/henri/travaux/programmes/trictrac && cargo run --bin=train_dqn -- --episodes 10 --save-every 5)…
 Error: Command timed out after 2m 0.0s warning: unused import: `DqnConfig`
--> bot/src/strategy/dqn.rs:5:25
|
5 | use super::dqn_common::{DqnConfig, SimpleNeuralNetwork, game_state_to_vector};
| ^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: unused import: `store::MoveRules`
--> bot/src/strategy/erroneous_moves.rs:2:5
… +175 lines (ctrl+r to see all)
● Il y a un problème dans la logique d'entraînement - il semble y avoir une boucle infinie avec des erreurs "rules not followed". Il faut corriger la logique du TrictracEnv. Le problème est probablement que l'environnement ne gère pas
correctement les étapes du jeu.
● Update Todos
⎿  ☒ Analyser le code existant avec PyO3/Stable-Baselines3
☒ Examiner l'environnement Gym Python actuel
☒ Créer un environnement DQN natif en Rust
☒ Implémenter la stratégie bot DQN en Rust
☒ Ajouter les dépendances Burn et sb3-burn
☒ Restructurer le code DQN
☒ Créer un module d'entraînement séparé
☒ Ajouter une commande d'entraînement
● Parfait ! J'ai réussi à restructurer complètement le code DQN selon tes demandes :
✅ Restructuration terminée avec succès
📁 Structure du code :
1. dqn.rs - Contient uniquement la stratégie DqnStrategy pour charger et utiliser un modèle pré-entraîné
2. dqn_common.rs - Code partagé (réseau de neurones, configuration, utilitaires)
3. dqn_trainer.rs - Logique d'entraînement complète avec environnement et agent
4. train_dqn - Binaire dédié pour lancer l'entraînement
🚀 Commandes disponibles :
Pour jouer avec un modèle DQN :
cargo run --bin=client_cli -- --bot dqn,dummy # Sans modèle (fallback)
cargo run --bin=client_cli -- --bot dqn:/path/to/model.json,dummy # Avec modèle
Pour entraîner un modèle DQN :
cargo run --bin=train_dqn # Entraînement par défaut (1000 épisodes)
cargo run --bin=train_dqn -- --help # Voir les options
cargo run --bin=train_dqn -- --episodes 5000 --save-every 500
⚠️ Note sur l'environnement d'entraînement :
L'entraînement a révélé un problème dans la logique de l'environnement (boucle infinie avec "rules not followed"). C'est normal pour une première implémentation - l'environnement d'entraînement nécessite des ajustements pour bien
gérer les règles du jeu Trictrac.
Le code est maintenant parfaitement séparé entre :
- Utilisation (stratégie simple qui charge un modèle)
- Entraînement (environnement complet avec logique d'apprentissage)
---
● ✅ Espace d'actions étendu implémenté avec succès !
J'ai complètement étendu l'espace d'actions du DQN pour couvrir tous les choix possibles dans le jeu Trictrac :
🎯 Nouvel espace d'actions :
TrictracAction enum comprend :
- Roll - Lancer les dés (index 0)
- Mark { points } - Marquer des points (indices 1-13 pour 0-12 points)
- Go - Continuer après avoir gagné un trou (index 14)
- Move { move1, move2 } - Mouvement de pions (indices 15+)
- Encode (from, to) pour les deux pions
- Espace total : 331,791 actions possibles
🧠 Améliorations intelligentes :
1. Masquage d'actions valides - Le DQN ne considère que les actions légales dans l'état actuel
2. Encodage compact - Mouvements encodés en un seul entier pour efficacité
3. Décodage automatique - Conversion transparente entre indices et actions
4. Stratégie adaptative - La stratégie DQN utilise maintenant le bon type d'action selon le contexte
🔧 Fonctionnalités ajoutées :
- get_valid_actions() - Obtient les actions valides pour l'état actuel
- TrictracAction::to_action_index() / from_action_index() - Conversion bidirectionnelle
- sample_valid_action() - Sélection aléatoire d'une action valide
- Réseau de neurones élargi (512 neurones cachés) pour gérer l'espace étendu
📊 Utilisation dans le jeu :
Le bot DQN peut maintenant :
- Choisir le nombre exact de points à marquer (pas seulement le maximum)
- Sélectionner des mouvements spécifiques parmi toutes les combinaisons possibles
- Décider intelligemment entre "Go" et les mouvements alternatifs
L'espace d'actions est maintenant parfaitement aligné avec la complexité réelle du jeu Trictrac ! 🎲
---
Pour réduire la taille de l'espace des actions, est-ce qu'on peut tenir compte de l'état du jeu pour le choix des actions ?
Ça voudrait dire que pour le choix du mouvement par exemple, comme on connait la valeur des dés on a juste à choisir quel dé on joue en premier (2 choix), puis la position de départ du premier pion (25 choix), et la position de départ du deuxième pion (25 choix), la position de départ étant déduite de la valeur des dés.
....
● Parfait ! J'ai implémenté l'espace d'actions compactes basé sur le contexte du jeu. Voici les amélirations majeures apportées :
✅ Réduction drastique de l'espace d'actions :
- Avant : 331,791 actions possibles à chaque étape
- Maintenant : 1-200 actions selon le contexte du jeu
✅ Actions contextuelles :
- Roll : Seulement quand c'est possible (1 action)
- Mark : Seulement les points valides 0-12 (≤13 actions)
- Go : Toujours 1 action
- MoveChoice : 2 ordres de dés × ~10 positions de départ × ~10 positions = ~200 actions au lieu de 331,791
✅ Architecture modulaire :
- CompactAction : actions simplifiées basées sur le contexte
- to_trictrac_action() : conversion automatique vers les actions complètes
- get_valid_compact_actions() : génération contextuelle des actions valides
- context_action_space_size() : taille dynamique de l'espace d'actions
L'approche utilise exactement votre suggestion : pour les mouvements, au lieu d'encoder toutes les combinaisons possibles, on choisit :
1. L'ordre des dés (2 choix max si dés différents)
2. Les positions de départ (seulement celles avec des pions)
3. Les destinations sont automatiquement calculées selon les règles
Cela réduit l'espace d'actions de 99.94% tout en gardant toute la richesse du jeu !
---
● Parfait ! J'ai créé le fichier train_burn_rl.rs qui utilise votre environnement Burn-RL corrigé.
Pour lancer l'entraînement avec Burn-RL :
cargo run --bin=train_burn_rl
Ou avec des options personnalisées :
cargo run --bin=train_burn_rl -- --episodes 2000 --save-every 200 --max-steps 1000
Caractéristiques de cet entraîneur :
✅ Utilise l'environnement Burn-RL que vous avez corrigé
✅ Actions contextuelles via get_valid_actions()
✅ Politique epsilon-greedy simple pour commencer
✅ Statistiques détaillées avec moyennes mobiles
✅ Configuration flexible via arguments CLI
✅ Logging progressif pour suivre l'entraînement
Options disponibles :
- --episodes : nombre d'épisodes (défaut: 1000)
- --save-every : fréquence d'affichage des stats (défaut: 100)
- --max-steps : nombre max de steps par épisode (défaut: 500)
- --help : aide complète
Cet entraîneur sert de base pour tester l'environnement Burn-RL. Une fois que tout fonctionne bien, on pourra y intégrer un vrai agent DQN avec réseaux de neurones !
---
Session où je n'ai cessé de recevoir ce message :
⎿ API Error (429 {"type":"error","error":{"type":"rate_limit_error","message":"This request would exceed the rate limit for your organization (813e6b21-ec6f-44c3-a7f0-408244105e5c) of 20,000 input tokens per minute. For details, refer to: <https://docs.anthropic.com/en/api/rate-limits>. You can see the response headers for current usage. Please reduce the prompt length or the maximum tokens requested, or try again later. You may also contact sales at <https://www.anthropic.com/contact-sales> to discuss your options for a rate limit increase."}}) · Retrying in 391 seconds… (attempt 1/10)
✶ Coaching… (403s · ↑ 382 tokens · esc to interrupt)
Pour à la fin de la session avoir ce résumé :
Total cost: $0.95
Total duration (API): 1h 24m 22.8s
Total duration (wall): 1h 43m 3.5s
Total code changes: 746 lines added, 0 lines removed
Token usage by model:
claude-3-5-haiku: 18.8k input, 443 output, 0 cache read, 0 cache write
claude-sonnet: 10 input, 666 output, 0 cache read, 245.6k cache write
Mais pourtant 2 millions indiqués dans la page usage : <https://console.anthropic.com/usage>, et 7.88 dollars de consommés sur <https://console.anthropic.com/cost>.
I just had a claude code session in which I kept having this error, even if the agent didn't seem to read a lot of files : API Error (429 {"type":"error","error":{"type":"rate_limit_error","message":"This request would exceed the rate limit for your organization (813e6b21-ec6f-44c3-a7f0-408244105e5c) of 20,000 input tokens per minute.
at the end of the session the token usage and cost indicated was this :
Total cost: $0.95
Total duration (API): 1h 24m 22.8s
Total duration (wall): 1h 43m 3.5s
Total code changes: 746 lines added, 0 lines removed
Token usage by model:
claude-3-5-haiku: 18.8k input, 443 output, 0 cache read, 0 cache write
claude-sonnet: 10 input, 666 output, 0 cache read, 245.6k cache write
but the usage on the /usage page was 2,073,698 token in, and the cost on the /cost page was $7.90.
When looking at the costs csv file, it seems that it is the "input cache write 5m" that consumed nearly all the tokens ( $7,71 ). Is it a bug ?

View file

@ -53,6 +53,10 @@ Client
### Epic : Bot
- PGX
- https://joe-antognini.github.io/ml/jax-tic-tac-toe
- https://www.sotets.uk/pgx/api_usage/
- OpenAi gym
- doc gymnasium <https://gymnasium.farama.org/introduction/basic_usage/>
- Rust implementation for OpenAi gym <https://github.com/MathisWellmann/gym-rs>

992
doc/plan_cxxbindings.md Normal file
View file

@ -0,0 +1,992 @@
# Plan: C++ OpenSpiel Game via cxx.rs
> Implementation plan for a native C++ OpenSpiel game for Trictrac, powered by the existing Rust engine through [cxx.rs](https://cxx.rs/) bindings.
>
> Base on reading: `store/src/pyengine.rs`, `store/src/training_common.rs`, `store/src/game.rs`, `store/src/board.rs`, `store/src/player.rs`, `store/src/game_rules_points.rs`, `forks/open_spiel/open_spiel/games/backgammon/backgammon.h`, `forks/open_spiel/open_spiel/games/backgammon/backgammon.cc`, `forks/open_spiel/open_spiel/spiel.h`, `forks/open_spiel/open_spiel/games/CMakeLists.txt`.
---
## 1. Overview
The Python binding (`pyengine.rs` + `trictrac.py`) wraps the Rust engine via PyO3. The goal here is an analogous C++ binding:
- **`store/src/cxxengine.rs`** — defines a `#[cxx::bridge]` exposing an opaque `TricTracEngine` Rust type with the same logical API as `pyengine.rs`.
- **`forks/open_spiel/open_spiel/games/trictrac/trictrac.h`** — C++ header for a `TrictracGame : public Game` and `TrictracState : public State`.
- **`forks/open_spiel/open_spiel/games/trictrac/trictrac.cc`** — C++ implementation that holds a `rust::Box<ffi::TricTracEngine>` and delegates all logic to Rust.
- Build wired together via **corrosion** (CMake-native Rust integration) and `cxx-build`.
The resulting C++ game registers itself as `"trictrac"` via `REGISTER_SPIEL_GAME` and is consumable by any OpenSpiel algorithm (AlphaZero, MCTS, etc.) that works with C++ games.
---
## 2. Files to Create / Modify
```
trictrac/
store/
Cargo.toml ← MODIFY: add cxx, cxx-build, staticlib crate-type
build.rs ← CREATE: cxx-build bridge registration
src/
lib.rs ← MODIFY: add cxxengine module
cxxengine.rs ← CREATE: #[cxx::bridge] definition + impl
forks/open_spiel/
CMakeLists.txt ← MODIFY: add Corrosion FetchContent
open_spiel/
games/
CMakeLists.txt ← MODIFY: add trictrac/ sources + test
trictrac/ ← CREATE directory
trictrac.h ← CREATE
trictrac.cc ← CREATE
trictrac_test.cc ← CREATE
justfile ← MODIFY: add buildtrictrac target
trictrac/
justfile ← MODIFY: add cxxlib target
```
---
## 3. Step 1 — Rust: `store/Cargo.toml`
Add `cxx` as a runtime dependency and `cxx-build` as a build dependency. Add `staticlib` to `crate-type` so CMake can link against the Rust code as a static library.
```toml
[package]
name = "trictrac-store"
version = "0.1.0"
edition = "2021"
[lib]
name = "trictrac_store"
# cdylib → Python .so (used by maturin / pyengine)
# rlib → used by other Rust crates in the workspace
# staticlib → used by C++ consumers (cxxengine)
crate-type = ["cdylib", "rlib", "staticlib"]
[dependencies]
base64 = "0.21.7"
cxx = "1.0"
log = "0.4.20"
merge = "0.1.0"
pyo3 = { version = "0.23", features = ["extension-module", "abi3-py38"] }
rand = "0.9"
serde = { version = "1.0", features = ["derive"] }
transpose = "0.2.2"
[build-dependencies]
cxx-build = "1.0"
```
> **Note on `staticlib` + `cdylib` coexistence.** Cargo will build all three types when asked. The static library is used by the C++ OpenSpiel build; the cdylib is used by maturin for the Python wheel. They do not interfere. The `rlib` is used internally by other workspace members (`bot`, `client_cli`).
---
## 4. Step 2 — Rust: `store/build.rs`
The `build.rs` script drives `cxx-build`, which compiles the C++ side of the bridge (the generated shim) and tells Cargo where to find the generated header.
```rust
fn main() {
cxx_build::bridge("src/cxxengine.rs")
.std("c++17")
.compile("trictrac-cxx");
// Re-run if the bridge source changes
println!("cargo:rerun-if-changed=src/cxxengine.rs");
}
```
`cxx-build` will:
- Parse `src/cxxengine.rs` for the `#[cxx::bridge]` block.
- Generate `$OUT_DIR/cxxbridge/include/trictrac_store/src/cxxengine.rs.h` — the C++ header.
- Generate `$OUT_DIR/cxxbridge/sources/trictrac_store/src/cxxengine.rs.cc` — the C++ shim source.
- Compile the shim into `libtrictrac-cxx.a` (alongside the Rust `libtrictrac_store.a`).
---
## 5. Step 3 — Rust: `store/src/cxxengine.rs`
This is the heart of the C++ integration. It mirrors `pyengine.rs` in structure but uses `#[cxx::bridge]` instead of PyO3.
### Design decisions vs. `pyengine.rs`
| pyengine | cxxengine | Reason |
| ------------------------- | ---------------------------- | -------------------------------------------- |
| `PyResult<()>` for errors | `Result<()>` | cxx.rs translates `Err` to a C++ exception |
| `(u8, u8)` tuple for dice | `DicePair` shared struct | cxx cannot cross tuples |
| `Vec<usize>` for actions | `Vec<u64>` | cxx does not support `usize` |
| `[i32; 2]` for scores | `PlayerScores` shared struct | cxx cannot cross fixed arrays |
| Clone via PyO3 pickling | `clone_engine()` method | OpenSpiel's `State::Clone()` needs deep copy |
### File content
```rust
//! # C++ bindings for the TricTrac game engine via cxx.rs
//!
//! Exposes an opaque `TricTracEngine` type and associated functions
//! to C++. The C++ side (trictrac.cc) uses `rust::Box<ffi::TricTracEngine>`.
//!
//! The Rust engine always works from the perspective of White (player 1).
//! For Black (player 2), the board is mirrored before computing actions
//! and events are mirrored back before applying — exactly as in pyengine.rs.
use crate::dice::Dice;
use crate::game::{GameEvent, GameState, Stage, TurnStage};
use crate::training_common::{get_valid_action_indices, TrictracAction};
// ── cxx bridge declaration ────────────────────────────────────────────────────
#[cxx::bridge(namespace = "trictrac_engine")]
pub mod ffi {
// ── Shared types (visible to both Rust and C++) ───────────────────────────
/// Two dice values passed from C++ to Rust for a dice-roll event.
struct DicePair {
die1: u8,
die2: u8,
}
/// Both players' scores: holes * 12 + points.
struct PlayerScores {
score_p1: i32,
score_p2: i32,
}
// ── Opaque Rust type exposed to C++ ───────────────────────────────────────
extern "Rust" {
/// Opaque handle to a TricTrac game state.
/// C++ accesses this only through `rust::Box<TricTracEngine>`.
type TricTracEngine;
/// Create a new engine, initialise two players, begin with player 1.
fn new_trictrac_engine() -> Box<TricTracEngine>;
/// Return a deep copy of the engine (needed for State::Clone()).
fn clone_engine(self: &TricTracEngine) -> Box<TricTracEngine>;
// ── Queries ───────────────────────────────────────────────────────────
/// True when the game is in TurnStage::RollWaiting (OpenSpiel chance node).
fn needs_roll(self: &TricTracEngine) -> bool;
/// True when Stage::Ended.
fn is_game_ended(self: &TricTracEngine) -> bool;
/// Active player index: 0 (player 1 / White) or 1 (player 2 / Black).
fn current_player_idx(self: &TricTracEngine) -> u64;
/// Legal action indices for `player_idx`. Returns empty vec if it is
/// not that player's turn. Indices are in [0, 513].
fn get_legal_actions(self: &TricTracEngine, player_idx: u64) -> Vec<u64>;
/// Human-readable action description, e.g. "0:Move { dice_order: true … }".
fn action_to_string(self: &TricTracEngine, player_idx: u64, action_idx: u64) -> String;
/// Both players' scores: holes * 12 + points.
fn get_players_scores(self: &TricTracEngine) -> PlayerScores;
/// 36-element state observation vector (i8). Mirrored for player 1.
fn get_tensor(self: &TricTracEngine, player_idx: u64) -> Vec<i8>;
/// Human-readable state description for `player_idx`.
fn get_observation_string(self: &TricTracEngine, player_idx: u64) -> String;
/// Full debug representation of the current state.
fn to_debug_string(self: &TricTracEngine) -> String;
// ── Mutations ─────────────────────────────────────────────────────────
/// Apply a dice roll result. Returns Err if not in RollWaiting stage.
fn apply_dice_roll(self: &mut TricTracEngine, dice: DicePair) -> Result<()>;
/// Apply a player action (move, go, roll). Returns Err if invalid.
fn apply_action(self: &mut TricTracEngine, action_idx: u64) -> Result<()>;
}
}
// ── Opaque type implementation ────────────────────────────────────────────────
pub struct TricTracEngine {
game_state: GameState,
}
pub fn new_trictrac_engine() -> Box<TricTracEngine> {
let mut game_state = GameState::new(false); // schools_enabled = false
game_state.init_player("player1");
game_state.init_player("player2");
game_state.consume(&GameEvent::BeginGame { goes_first: 1 });
Box::new(TricTracEngine { game_state })
}
impl TricTracEngine {
fn clone_engine(&self) -> Box<TricTracEngine> {
Box::new(TricTracEngine {
game_state: self.game_state.clone(),
})
}
fn needs_roll(&self) -> bool {
self.game_state.turn_stage == TurnStage::RollWaiting
}
fn is_game_ended(&self) -> bool {
self.game_state.stage == Stage::Ended
}
/// Returns 0 for player 1 (White) and 1 for player 2 (Black).
fn current_player_idx(&self) -> u64 {
self.game_state.active_player_id - 1
}
fn get_legal_actions(&self, player_idx: u64) -> Vec<u64> {
if player_idx == self.current_player_idx() {
if player_idx == 0 {
get_valid_action_indices(&self.game_state)
.into_iter()
.map(|i| i as u64)
.collect()
} else {
let mirror = self.game_state.mirror();
get_valid_action_indices(&mirror)
.into_iter()
.map(|i| i as u64)
.collect()
}
} else {
vec![]
}
}
fn action_to_string(&self, player_idx: u64, action_idx: u64) -> String {
TrictracAction::from_action_index(action_idx as usize)
.map(|a| format!("{}:{}", player_idx, a))
.unwrap_or_else(|| "unknown action".into())
}
fn get_players_scores(&self) -> ffi::PlayerScores {
ffi::PlayerScores {
score_p1: self.score_for(1),
score_p2: self.score_for(2),
}
}
fn score_for(&self, player_id: u64) -> i32 {
if let Some(player) = self.game_state.players.get(&player_id) {
player.holes as i32 * 12 + player.points as i32
} else {
-1
}
}
fn get_tensor(&self, player_idx: u64) -> Vec<i8> {
if player_idx == 0 {
self.game_state.to_vec()
} else {
self.game_state.mirror().to_vec()
}
}
fn get_observation_string(&self, player_idx: u64) -> String {
if player_idx == 0 {
format!("{}", self.game_state)
} else {
format!("{}", self.game_state.mirror())
}
}
fn to_debug_string(&self) -> String {
format!("{}", self.game_state)
}
fn apply_dice_roll(&mut self, dice: ffi::DicePair) -> Result<(), String> {
let player_id = self.game_state.active_player_id;
if self.game_state.turn_stage != TurnStage::RollWaiting {
return Err("Not in RollWaiting stage".into());
}
let dice = Dice {
values: (dice.die1, dice.die2),
};
self.game_state
.consume(&GameEvent::RollResult { player_id, dice });
Ok(())
}
fn apply_action(&mut self, action_idx: u64) -> Result<(), String> {
let action_idx = action_idx as usize;
let needs_mirror = self.game_state.active_player_id == 2;
let event = TrictracAction::from_action_index(action_idx)
.and_then(|a| {
let game_state = if needs_mirror {
&self.game_state.mirror()
} else {
&self.game_state
};
a.to_event(game_state)
.map(|e| if needs_mirror { e.get_mirror(false) } else { e })
});
match event {
Some(evt) if self.game_state.validate(&evt) => {
self.game_state.consume(&evt);
Ok(())
}
Some(_) => Err("Action is invalid".into()),
None => Err("Could not build event from action index".into()),
}
}
}
```
> **Note on `Result<(), String>`**: cxx.rs requires the error type to implement `std::error::Error`. `String` does not implement it directly. Two options:
>
> - Use `anyhow::Error` (add `anyhow` dependency).
> - Define a thin newtype `struct EngineError(String)` that implements `std::error::Error`.
>
> The recommended approach is `anyhow`:
>
> ```toml
> [dependencies]
> anyhow = "1.0"
> ```
>
> Then `fn apply_action(...) -> Result<(), anyhow::Error>` — cxx.rs will convert this to a C++ exception of type `rust::Error` carrying the message.
---
## 6. Step 4 — Rust: `store/src/lib.rs`
Add the new module:
```rust
// existing modules …
mod pyengine;
// NEW: C++ bindings via cxx.rs
pub mod cxxengine;
```
---
## 7. Step 5 — C++: `trictrac/trictrac.h`
Modelled closely after `backgammon/backgammon.h`. The state holds a `rust::Box<ffi::TricTracEngine>` and delegates everything to it.
```cpp
// open_spiel/games/trictrac/trictrac.h
#ifndef OPEN_SPIEL_GAMES_TRICTRAC_H_
#define OPEN_SPIEL_GAMES_TRICTRAC_H_
#include <memory>
#include <string>
#include <vector>
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_utils.h"
// Generated by cxx-build from store/src/cxxengine.rs.
// The include path is set by CMake (see CMakeLists.txt).
#include "trictrac_store/src/cxxengine.rs.h"
namespace open_spiel {
namespace trictrac {
inline constexpr int kNumPlayers = 2;
inline constexpr int kNumChanceOutcomes = 36; // 6 × 6 dice outcomes
inline constexpr int kNumDistinctActions = 514; // matches ACTION_SPACE_SIZE in Rust
inline constexpr int kStateEncodingSize = 36; // matches to_vec() length in Rust
inline constexpr int kDefaultMaxTurns = 1000;
class TrictracGame;
// ---------------------------------------------------------------------------
// TrictracState
// ---------------------------------------------------------------------------
class TrictracState : public State {
public:
explicit TrictracState(std::shared_ptr<const Game> game);
TrictracState(const TrictracState& other);
Player CurrentPlayer() const override;
std::vector<Action> LegalActions() const override;
std::string ActionToString(Player player, Action move_id) const override;
std::vector<std::pair<Action, double>> ChanceOutcomes() const override;
std::string ToString() const override;
bool IsTerminal() const override;
std::vector<double> Returns() const override;
std::string ObservationString(Player player) const override;
void ObservationTensor(Player player, absl::Span<float> values) const override;
std::unique_ptr<State> Clone() const override;
protected:
void DoApplyAction(Action move_id) override;
private:
// Decode a chance action index [0,35] to (die1, die2).
// Matches Python: [(i,j) for i in range(1,7) for j in range(1,7)][action]
static trictrac_engine::DicePair DecodeChanceAction(Action action);
// The Rust engine handle. Deep-copied via clone_engine() when cloning state.
rust::Box<trictrac_engine::TricTracEngine> engine_;
};
// ---------------------------------------------------------------------------
// TrictracGame
// ---------------------------------------------------------------------------
class TrictracGame : public Game {
public:
explicit TrictracGame(const GameParameters& params);
int NumDistinctActions() const override { return kNumDistinctActions; }
std::unique_ptr<State> NewInitialState() const override;
int MaxChanceOutcomes() const override { return kNumChanceOutcomes; }
int NumPlayers() const override { return kNumPlayers; }
double MinUtility() const override { return 0.0; }
double MaxUtility() const override { return 200.0; }
int MaxGameLength() const override { return 3 * max_turns_; }
int MaxChanceNodesInHistory() const override { return MaxGameLength(); }
std::vector<int> ObservationTensorShape() const override {
return {kStateEncodingSize};
}
private:
int max_turns_;
};
} // namespace trictrac
} // namespace open_spiel
#endif // OPEN_SPIEL_GAMES_TRICTRAC_H_
```
---
## 8. Step 6 — C++: `trictrac/trictrac.cc`
```cpp
// open_spiel/games/trictrac/trictrac.cc
#include "open_spiel/games/trictrac/trictrac.h"
#include <memory>
#include <string>
#include <vector>
#include "open_spiel/abseil-cpp/absl/types/span.h"
#include "open_spiel/game_parameters.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_globals.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace trictrac {
namespace {
// ── Game registration ────────────────────────────────────────────────────────
const GameType kGameType{
/*short_name=*/"trictrac",
/*long_name=*/"Trictrac",
GameType::Dynamics::kSequential,
GameType::ChanceMode::kExplicitStochastic,
GameType::Information::kPerfectInformation,
GameType::Utility::kGeneralSum,
GameType::RewardModel::kRewards,
/*min_num_players=*/kNumPlayers,
/*max_num_players=*/kNumPlayers,
/*provides_information_state_string=*/false,
/*provides_information_state_tensor=*/false,
/*provides_observation_string=*/true,
/*provides_observation_tensor=*/true,
/*parameter_specification=*/{
{"max_turns", GameParameter(kDefaultMaxTurns)},
}};
static std::shared_ptr<const Game> Factory(const GameParameters& params) {
return std::make_shared<const TrictracGame>(params);
}
REGISTER_SPIEL_GAME(kGameType, Factory);
} // namespace
// ── TrictracGame ─────────────────────────────────────────────────────────────
TrictracGame::TrictracGame(const GameParameters& params)
: Game(kGameType, params),
max_turns_(ParameterValue<int>("max_turns", kDefaultMaxTurns)) {}
std::unique_ptr<State> TrictracGame::NewInitialState() const {
return std::make_unique<TrictracState>(shared_from_this());
}
// ── TrictracState ─────────────────────────────────────────────────────────────
TrictracState::TrictracState(std::shared_ptr<const Game> game)
: State(game),
engine_(trictrac_engine::new_trictrac_engine()) {}
// Copy constructor: deep-copy the Rust engine via clone_engine().
TrictracState::TrictracState(const TrictracState& other)
: State(other),
engine_(other.engine_->clone_engine()) {}
std::unique_ptr<State> TrictracState::Clone() const {
return std::make_unique<TrictracState>(*this);
}
// ── Current player ────────────────────────────────────────────────────────────
Player TrictracState::CurrentPlayer() const {
if (engine_->is_game_ended()) return kTerminalPlayerId;
if (engine_->needs_roll()) return kChancePlayerId;
return static_cast<Player>(engine_->current_player_idx());
}
// ── Legal actions ─────────────────────────────────────────────────────────────
std::vector<Action> TrictracState::LegalActions() const {
if (IsChanceNode()) {
// All 36 dice outcomes are equally likely; return indices 035.
std::vector<Action> actions(kNumChanceOutcomes);
for (int i = 0; i < kNumChanceOutcomes; ++i) actions[i] = i;
return actions;
}
Player player = CurrentPlayer();
rust::Vec<uint64_t> rust_actions =
engine_->get_legal_actions(static_cast<uint64_t>(player));
std::vector<Action> actions;
actions.reserve(rust_actions.size());
for (uint64_t a : rust_actions) actions.push_back(static_cast<Action>(a));
return actions;
}
// ── Chance outcomes ───────────────────────────────────────────────────────────
std::vector<std::pair<Action, double>> TrictracState::ChanceOutcomes() const {
SPIEL_CHECK_TRUE(IsChanceNode());
const double p = 1.0 / kNumChanceOutcomes;
std::vector<std::pair<Action, double>> outcomes;
outcomes.reserve(kNumChanceOutcomes);
for (int i = 0; i < kNumChanceOutcomes; ++i) outcomes.emplace_back(i, p);
return outcomes;
}
// ── Apply action ──────────────────────────────────────────────────────────────
/*static*/
trictrac_engine::DicePair TrictracState::DecodeChanceAction(Action action) {
// Matches: [(i,j) for i in range(1,7) for j in range(1,7)][action]
return trictrac_engine::DicePair{
/*die1=*/static_cast<uint8_t>(action / 6 + 1),
/*die2=*/static_cast<uint8_t>(action % 6 + 1),
};
}
void TrictracState::DoApplyAction(Action action) {
if (IsChanceNode()) {
engine_->apply_dice_roll(DecodeChanceAction(action));
} else {
engine_->apply_action(static_cast<uint64_t>(action));
}
}
// ── Terminal & returns ────────────────────────────────────────────────────────
bool TrictracState::IsTerminal() const {
return engine_->is_game_ended();
}
std::vector<double> TrictracState::Returns() const {
trictrac_engine::PlayerScores scores = engine_->get_players_scores();
return {static_cast<double>(scores.score_p1),
static_cast<double>(scores.score_p2)};
}
// ── Observation ───────────────────────────────────────────────────────────────
std::string TrictracState::ObservationString(Player player) const {
return std::string(engine_->get_observation_string(
static_cast<uint64_t>(player)));
}
void TrictracState::ObservationTensor(Player player,
absl::Span<float> values) const {
SPIEL_CHECK_EQ(values.size(), kStateEncodingSize);
rust::Vec<int8_t> tensor =
engine_->get_tensor(static_cast<uint64_t>(player));
SPIEL_CHECK_EQ(tensor.size(), static_cast<size_t>(kStateEncodingSize));
for (int i = 0; i < kStateEncodingSize; ++i) {
values[i] = static_cast<float>(tensor[i]);
}
}
// ── Strings ───────────────────────────────────────────────────────────────────
std::string TrictracState::ToString() const {
return std::string(engine_->to_debug_string());
}
std::string TrictracState::ActionToString(Player player, Action action) const {
if (IsChanceNode()) {
trictrac_engine::DicePair d = DecodeChanceAction(action);
return "(" + std::to_string(d.die1) + ", " + std::to_string(d.die2) + ")";
}
return std::string(engine_->action_to_string(
static_cast<uint64_t>(player), static_cast<uint64_t>(action)));
}
} // namespace trictrac
} // namespace open_spiel
```
---
## 9. Step 7 — C++: `trictrac/trictrac_test.cc`
```cpp
// open_spiel/games/trictrac/trictrac_test.cc
#include "open_spiel/games/trictrac/trictrac.h"
#include <iostream>
#include <memory>
#include "open_spiel/spiel.h"
#include "open_spiel/tests/basic_tests.h"
#include "open_spiel/utils/init.h"
namespace open_spiel {
namespace trictrac {
namespace {
void BasicTrictracTests() {
testing::LoadGameTest("trictrac");
testing::RandomSimTest(*LoadGame("trictrac"), /*num_sims=*/5);
}
} // namespace
} // namespace trictrac
} // namespace open_spiel
int main(int argc, char** argv) {
open_spiel::Init(&argc, &argv);
open_spiel::trictrac::BasicTrictracTests();
std::cout << "trictrac tests passed" << std::endl;
return 0;
}
```
---
## 10. Step 8 — Build System: `forks/open_spiel/CMakeLists.txt`
The top-level `CMakeLists.txt` must be extended to bring in **Corrosion**, the standard CMake module for Rust. Add this block before the main `open_spiel` target is defined:
```cmake
# ── Corrosion: CMake integration for Rust ────────────────────────────────────
include(FetchContent)
FetchContent_Declare(
Corrosion
GIT_REPOSITORY https://github.com/corrosion-rs/corrosion.git
GIT_TAG v0.5.1 # pin to a stable release
)
FetchContent_MakeAvailable(Corrosion)
# Import the trictrac-store Rust crate.
# This creates a CMake target named 'trictrac-store'.
corrosion_import_crate(
MANIFEST_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../trictrac/store/Cargo.toml
CRATES trictrac-store
)
# Generate the cxx bridge from cxxengine.rs.
# corrosion_add_cxxbridge:
# - runs cxx-build as part of the Rust build
# - creates a CMake target 'trictrac_cxx_bridge' that:
# * compiles the generated C++ shim
# * exposes INTERFACE include dirs for the generated .rs.h header
corrosion_add_cxxbridge(trictrac_cxx_bridge
CRATE trictrac-store
FILES src/cxxengine.rs
)
```
> **Where to insert**: After the `cmake_minimum_required` / `project()` lines and before `add_subdirectory(open_spiel)` (or wherever games are pulled in). Check the actual file structure before editing.
---
## 11. Step 9 — Build System: `open_spiel/games/CMakeLists.txt`
Two changes: add the new source files to `GAME_SOURCES`, and add a test target.
### 11.1 Add to `GAME_SOURCES`
Find the alphabetically correct position (after `tic_tac_toe`, before `trade_comm`) and add:
```cmake
set(GAME_SOURCES
# ... existing games ...
trictrac/trictrac.cc
trictrac/trictrac.h
# ... remaining games ...
)
```
### 11.2 Link cxx bridge into OpenSpiel objects
The `trictrac` sources need the Rust library and cxx bridge linked in. Since the existing build compiles all `GAME_SOURCES` into `${OPEN_SPIEL_OBJECTS}` as a single object library, you need to ensure the Rust library and cxx bridge are linked when that object library is consumed.
The cleanest approach is to add the link dependencies to the main `open_spiel` library target. Find where `open_spiel` is defined (likely in `open_spiel/CMakeLists.txt`) and add:
```cmake
target_link_libraries(open_spiel
PUBLIC
trictrac_cxx_bridge # C++ shim generated by cxx-build
trictrac-store # Rust static library
)
```
If modifying the central `open_spiel` target is too disruptive, create an explicit object library for the trictrac game:
```cmake
add_library(trictrac_game OBJECT
trictrac/trictrac.cc
trictrac/trictrac.h
)
target_include_directories(trictrac_game
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/..
)
target_link_libraries(trictrac_game
PUBLIC
trictrac_cxx_bridge
trictrac-store
open_spiel_core # or whatever the core target is called
)
```
Then reference `$<TARGET_OBJECTS:trictrac_game>` in relevant executables.
### 11.3 Add the test
```cmake
add_executable(trictrac_test
trictrac/trictrac_test.cc
${OPEN_SPIEL_OBJECTS}
$<TARGET_OBJECTS:tests>
)
target_link_libraries(trictrac_test
PRIVATE
trictrac_cxx_bridge
trictrac-store
)
add_test(trictrac_test trictrac_test)
```
---
## 12. Step 10 — Justfile updates
### `trictrac/justfile` — add `cxxlib` target
Builds the Rust crate as a static library (for use by the C++ build) and confirms the generated header exists:
```just
cxxlib:
cargo build --release -p trictrac-store
@echo "Static lib: $(ls target/release/libtrictrac_store.a)"
@echo "CXX header: $(find target -name 'cxxengine.rs.h' | head -1)"
```
### `forks/open_spiel/justfile` — add `buildtrictrac` and `testtrictrac`
```just
buildtrictrac:
# Rebuild the Rust static lib first, then CMake
cd ../../trictrac && cargo build --release -p trictrac-store
mkdir -p build && cd build && \
CXX=$(which clang++) cmake -DCMAKE_BUILD_TYPE=Release ../open_spiel && \
make -j$(nproc) trictrac_test
testtrictrac: buildtrictrac
./build/trictrac_test
playtrictrac_cpp:
./build/examples/example --game=trictrac
```
---
## 13. Key Design Decisions
### 13.1 Opaque type with `clone_engine()`
OpenSpiel's `State::Clone()` must return a fully independent copy of the game state (used extensively by search algorithms). Since `TricTracEngine` is an opaque Rust type, C++ cannot copy it directly. The bridge exposes `clone_engine() -> Box<TricTracEngine>` which calls `.clone()` on the inner `GameState` (which derives `Clone`).
### 13.2 Action encoding: same 514-element space
The C++ game uses the same 514-action encoding as the Python version and the Rust training code. This means:
- The same `TrictracAction::to_action_index` / `from_action_index` mapping applies.
- Action 0 = Roll (used as the bridge between Move and the next chance node).
- Actions 2513 = Move variants (checker ordinal pair + dice order).
- A trained C++ model and Python model share the same action space.
### 13.3 Chance outcome ordering
The dice outcome ordering is identical to the Python version:
```
action → (die1, die2)
0 → (1,1) 6 → (2,1) ... 35 → (6,6)
```
(`die1 = action/6 + 1`, `die2 = action%6 + 1`)
This matches `_roll_from_chance_idx` in `trictrac.py` exactly, ensuring the two implementations are interchangeable in training pipelines.
### 13.4 `GameType::Utility::kGeneralSum` + `kRewards`
Consistent with the Python version. Trictrac is not zero-sum (both players can score positive holes). Intermediate hole rewards are returned by `Returns()` at every state, not just the terminal.
### 13.5 Mirror pattern preserved
`get_legal_actions` and `apply_action` in `TricTracEngine` mirror the board for player 2 exactly as `pyengine.rs` does. C++ never needs to know about the mirroring — it simply passes `player_idx` and the Rust engine handles the rest.
### 13.6 `rust::Box` vs `rust::UniquePtr`
`rust::Box<T>` (where `T` is an `extern "Rust"` type) is the correct choice for ownership of a Rust type from C++. It owns the heap allocation and drops it when the C++ destructor runs. `rust::UniquePtr<T>` is for C++ types held in Rust.
### 13.7 Separate struct from `pyengine.rs`
`TricTracEngine` in `cxxengine.rs` is a separate struct from `TricTrac` in `pyengine.rs`. They both wrap `GameState` but are independent. This avoids:
- PyO3 and cxx attributes conflicting on the same type.
- Changes to one binding breaking the other.
- Feature-flag complexity.
---
## 14. Known Challenges
### 14.1 Corrosion path resolution
`corrosion_import_crate(MANIFEST_PATH ...)` takes a path relative to the CMake source directory. Since the Rust crate lives outside the `forks/open_spiel/` directory, the path will be something like `${CMAKE_CURRENT_SOURCE_DIR}/../../trictrac/store/Cargo.toml`. Verify this resolves correctly on all developer machines (absolute paths are safer but less portable).
### 14.2 `staticlib` + `cdylib` in one crate
Rust allows `["cdylib", "rlib", "staticlib"]` in one crate, but there are subtle interactions:
- The `cdylib` build (for maturin) does not need `staticlib`, and building both doubles the compile time.
- Consider gating `staticlib` behind a Cargo feature: `crate-type` is not directly feature-gatable, but you can work around this with a separate `Cargo.toml` or a workspace profile.
- Alternatively, accept the extra compile time during development.
### 14.3 Linker symbols from Rust std
When linking a Rust `staticlib`, the C++ linker must pull in Rust's runtime and standard library symbols. Corrosion handles this automatically by reading the output of `rustc --print native-static-libs` and adding them to the link command. If not using Corrosion, these must be added manually (typically `-ldl -lm -lpthread -lc`).
### 14.4 `anyhow` for error types
cxx.rs requires the `Err` type in `Result<T, E>` to implement `std::error::Error + Send + Sync`. `String` does not satisfy this. Use `anyhow::Error` or define a thin newtype wrapper:
```rust
use std::fmt;
#[derive(Debug)]
struct EngineError(String);
impl fmt::Display for EngineError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}
impl std::error::Error for EngineError {}
```
On the C++ side, errors become `rust::Error` exceptions. Wrap `DoApplyAction` in a try-catch during development to surface Rust errors as `SpielFatalError`.
### 14.5 `UndoAction` not implemented
OpenSpiel algorithms that use tree search (e.g., MCTS) may call `UndoAction`. The Rust engine's `GameState` stores a full `history` vec of `GameEvent`s but does not implement undo — the history is append-only. To support undo, `Clone()` is the only reliable strategy (clone before applying, discard clone if undo needed). OpenSpiel's default `UndoAction` raises `SpielFatalError`, which is acceptable for RL training but blocks game-tree search. If search support is needed, the simplest approach is to store a stack of cloned states inside `TrictracState` and pop on undo.
### 14.6 Generated header path in `#include`
The `#include "trictrac_store/src/cxxengine.rs.h"` path used in `trictrac.h` must match the actual path that `cxx-build` (via corrosion) places the generated header. With `corrosion_add_cxxbridge`, this is typically handled by the `trictrac_cxx_bridge` target's `INTERFACE_INCLUDE_DIRECTORIES`, which CMake propagates automatically to any target that links against it. Verify by inspecting the generated build directory.
### 14.7 `rust::String` to `std::string` conversion
The bridge methods returning `String` (Rust) appear as `rust::String` in C++. The conversion `std::string(engine_->action_to_string(...))` is valid because `rust::String` is implicitly convertible to `std::string`. Verify this works with your cxx version; if not, use `engine_->action_to_string(...).c_str()` or `static_cast<std::string>(...)`.
---
## 15. Complete File Checklist
```
[ ] trictrac/store/Cargo.toml — add cxx, cxx-build, staticlib
[ ] trictrac/store/build.rs — new file: cxx_build::bridge(...)
[ ] trictrac/store/src/lib.rs — add `pub mod cxxengine;`
[ ] trictrac/store/src/cxxengine.rs — new file: full bridge implementation
[ ] trictrac/justfile — add `cxxlib` target
[ ] forks/open_spiel/CMakeLists.txt — add Corrosion, corrosion_import_crate, corrosion_add_cxxbridge
[ ] forks/open_spiel/open_spiel/games/CMakeLists.txt — add trictrac sources + test
[ ] forks/open_spiel/open_spiel/games/trictrac/trictrac.h — new file
[ ] forks/open_spiel/open_spiel/games/trictrac/trictrac.cc — new file
[ ] forks/open_spiel/open_spiel/games/trictrac/trictrac_test.cc — new file
[ ] forks/open_spiel/justfile — add buildtrictrac / testtrictrac
```
---
## 16. Implementation Order
Implement in this sequence to get early feedback at each step:
1. **Rust bridge first** (`Cargo.toml``build.rs``cxxengine.rs`). Run `cargo build -p trictrac-store` and confirm the static library and generated header are produced.
2. **Verify generated header** by locating `$OUT_DIR/cxxbridge/include/trictrac_store/src/cxxengine.rs.h` and inspecting it. Confirm C++ signatures match expectations.
3. **CMake Corrosion integration** in `forks/open_spiel/CMakeLists.txt`. Confirm `cmake ..` succeeds and the `trictrac_cxx_bridge` and `trictrac-store` targets exist.
4. **Write `trictrac.h` and `trictrac.cc`**. Compile with `make trictrac_test` (or equivalent). Fix linker errors from Rust std symbols if Corrosion doesn't handle them.
5. **Run `trictrac_test`**. Use `testing::RandomSimTest` to exercise the full game loop, catch panics from `get_valid_actions` (the `TurnStage::RollWaiting` panic path), and verify game termination.
6. **Smoke-test with the example runner**: `./build/examples/example --game=trictrac`.
---
# Implementation complete
All files are in place and trictrac_test passes (168 84 final scores, all assertions pass).
What was done
Rust side (from previous session, already complete):
- trictrac/store/Cargo.toml — added staticlib, cxx, anyhow, cxx-build
- trictrac/store/build.rs — drives cxx-build
- trictrac/store/src/cxxengine.rs — full cxx bridge + TricTracEngine impl
- trictrac/store/src/lib.rs — added pub mod cxxengine;
C++ side (this session):
- forks/open_spiel/open_spiel/games/trictrac/trictrac.h — game header
- forks/open_spiel/open_spiel/games/trictrac/trictrac.cc — game implementation
- forks/open_spiel/open_spiel/games/trictrac/trictrac_test.cc — basic test
Build system:
- forks/open_spiel/open_spiel/CMakeLists.txt — Corrosion + corrosion_import_crate + corrosion_add_cxxbridge
- forks/open_spiel/open_spiel/games/CMakeLists.txt — trictrac_game OBJECT target + trictrac_test executable
Justfiles:
- trictrac/justfile — added cxxlib target
- forks/open_spiel/justfile — added buildtrictrac and testtrictrac
Fixes discovered during build
| Issue | Fix |
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Corrosion creates trictrac_store (underscore), not trictrac-store | Used trictrac_store in CRATE arg and target_link_libraries |
| FILES src/cxxengine.rs doubled src/src/ | Changed to FILES cxxengine.rs (relative to crate's src/) |
| Include path changed: not trictrac-store/src/cxxengine.rs.h but trictrac_cxx_bridge/cxxengine.h | Updated #include in trictrac.h |
| rust::Error not in inline cxx types | Added #include "rust/cxx.h" to trictrac.cc |
| Init() signature differs in this fork | Changed to Init(argv[0], &argc, &argv, true) |
| libtrictrac_store.a contains PyO3 code → missing Python symbols | Added Python3::Python to target_link_libraries |
| LegalActions() not sorted (OpenSpiel requires ascending) | Added std::sort |
| Duplicate actions for doubles | Added std::unique after sort |
| Returns() returned non-zero at intermediate states, violating invariant with default Rewards() | Returns() now returns {0, 0} at non-terminal states |

31
doc/python.md Normal file
View file

@ -0,0 +1,31 @@
# Python bindings
## Génération bindings
```sh
# Generate trictrac python lib as a wheel
maturin build -m store/Cargo.toml --release
# Install wheel in local python env
pip install --no-deps --force-reinstall --prefix .devenv/state/venv target/wheels/*.whl
```
## Usage
Pour vérifier l'accès à la lib : lancer le shell interactif `python`
```python
Python 3.13.11 (main, Dec 5 2025, 16:06:33) [GCC 15.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import trictrac_store
>>> game = trictrac_store.TricTrac()
>>> game.get_active_player_id()
1
```
### Appels depuis python
`python bot/python/test.py`
## Interfaces
## Entraînement

536
doc/python_research.md Normal file
View file

@ -0,0 +1,536 @@
# Trictrac — Research Notes: Engine & OpenSpiel Integration
> Generated from a deep read of `trictrac/store/src/` and `forks/open_spiel/open_spiel/python/games/trictrac.py`.
---
## 1. Architecture Overview
The project connects two codebases through a compiled Python extension:
```
┌─────────────────────────────────────┐
│ trictrac/store/ (Rust crate) │
│ - full game rules engine │
│ - pyengine.rs → PyO3 bindings │
│ compiled by maturin → .whl │
└──────────────┬──────────────────────┘
│ import trictrac_store
┌──────────────▼──────────────────────┐
│ forks/open_spiel/.../trictrac.py │
│ - TrictracGame (pyspiel.Game) │
│ - TrictracState (pyspiel.State) │
│ registered as "python_trictrac" │
└─────────────────────────────────────┘
```
Build pipeline:
- `just pythonlib` (in `trictrac/`) → `maturin build -m store/Cargo.toml --release``.whl` into `target/wheels/`
- `just installtrictrac` (in `forks/open_spiel/`) → `pip install --force-reinstall` the wheel into the devenv venv
The Rust crate is named `trictrac-store` (package) but produces a lib named `trictrac_store` (the Python module name, set in `Cargo.toml` `[lib] name`).
---
## 2. Rust Engine: Module Map
| Module | Responsibility |
|---|---|
| `board.rs` | Board representation, checker manipulation, quarter analysis |
| `dice.rs` | `Dice` struct, `DiceRoller`, bit encoding |
| `player.rs` | `Player` struct (score, bredouille), `Color`, `PlayerId`, `CurrentPlayer` |
| `game.rs` | `GameState` state machine, `GameEvent` enum, `Stage`/`TurnStage` |
| `game_rules_moves.rs` | `MoveRules`: move validation and generation |
| `game_rules_points.rs` | `PointsRules`: jan detection and scoring |
| `training_common.rs` | `TrictracAction` enum, action-space encoding (size 514) |
| `pyengine.rs` | PyO3 Python module exposing `TricTrac` class |
| `lib.rs` | Crate root, re-exports |
---
## 3. Board Representation
```rust
pub struct Board {
positions: [i8; 24],
}
```
- 24 fields indexed 023 internally, 124 externally.
- Positive values = White checkers on that field; negative = Black.
- Initial state: `[15, 0, ..., 0, -15]` — all 15 white pieces on field 1, all 15 black pieces on field 24.
- Field 0 is a sentinel for "exited the board" (never stored in the array).
**Mirroring** is the central symmetry operation used throughout:
```rust
pub fn mirror(&self) -> Self {
let mut positions = self.positions.map(|c| 0 - c);
positions.reverse();
Board { positions }
}
```
This negates all values (swapping who owns each checker) and reverses the array (swapping directions). The entire engine always reasons from White's perspective; Black's moves are handled by mirroring the board first.
**Quarter structure**: fields 16, 712, 1318, 1924. This maps to the four tables of Trictrac:
- 16: White's "petit jan" (own table)
- 712: White's "grand jan"
- 1318: Black's "grand jan" (= White's opponent territory)
- 1924: Black's "petit jan" / White's "jan de retour"
The "coin de repos" (rest corner) is field 12 for White, field 13 for Black.
---
## 4. Dice
```rust
pub struct Dice {
pub values: (u8, u8),
}
```
Dice are always a pair (never quadrupled for doubles, unlike Backgammon). The `DiceRoller` uses `StdRng` seeded from OS entropy (or an optional fixed seed for tests). Bit encoding: `"{d1:0>3b}{d2:0>3b}"` — 3 bits each, 6 bits total.
---
## 5. Player State
```rust
pub struct Player {
pub name: String,
pub color: Color, // White or Black
pub points: u8, // 011 (points within current hole)
pub holes: u8, // holes won (game ends at >12)
pub can_bredouille: bool,
pub can_big_bredouille: bool,
pub dice_roll_count: u8, // rolls since last new_pick_up()
}
```
`PlayerId` is a `u64` alias. Player 1 = White, Player 2 = Black (set at init time; this is fixed for the session in pyengine).
---
## 6. Game State Machine
### Stages
```rust
pub enum Stage { PreGame, InGame, Ended }
pub enum TurnStage {
RollDice, // 1 — player must request a roll
RollWaiting, // 0 — waiting for dice result from outside
MarkPoints, // 2 — points are being marked (schools mode only)
HoldOrGoChoice, // 3 — player won a hole; choose to Go or Hold
Move, // 4 — player must move checkers
MarkAdvPoints, // 5 — mark opponent's points after the move (schools mode)
}
```
### Turn lifecycle (schools disabled — the default in pyengine)
```
RollWaiting
│ RollResult → auto-mark points
├─[no hole]──→ Move
│ │ Move → mark opponent's points → switch player
│ └───────────────────────────────→ RollDice (next player)
└─[hole won]─→ HoldOrGoChoice
├─ Go ──→ new_pick_up() → RollDice (same player)
└─ Move ──→ mark opponent's points → switch player → RollDice
```
In schools mode (`schools_enabled = true`), the player explicitly marks their own points (`Mark` event) and then the opponent's points after moving (`MarkAdvPoints` stage).
### Key events
```rust
pub enum GameEvent {
BeginGame { goes_first: PlayerId },
EndGame { reason: EndGameReason },
PlayerJoined { player_id, name },
PlayerDisconnected { player_id },
Roll { player_id }, // triggers RollWaiting
RollResult { player_id, dice }, // provides dice values
Mark { player_id, points }, // explicit point marking (schools mode)
Go { player_id }, // choose to restart position after hole
Move { player_id, moves: (CheckerMove, CheckerMove) },
PlayError,
}
```
### Initialization in pyengine
```rust
fn new() -> Self {
let mut game_state = GameState::new(false); // schools_enabled = false
game_state.init_player("player1");
game_state.init_player("player2");
game_state.consume(&GameEvent::BeginGame { goes_first: 1 });
TricTrac { game_state }
}
```
Player 1 (White) always goes first. `active_player_id` uses 1-based indexing; pyengine converts to 0-based for the Python side with `active_player_id - 1`.
---
## 7. Scoring System (Jans)
Points are awarded after each dice roll based on "jans" (scoring events) detected by `PointsRules`. All computation assumes White's perspective (board is mirrored for Black before calling).
### Jan types
| Jan | Points (normal / doublet) | Direction |
|---|---|---|
| `TrueHitSmallJan` | 4 / 6 | → active player |
| `TrueHitBigJan` | 2 / 4 | → active player |
| `TrueHitOpponentCorner` | 4 / 6 | → active player |
| `FilledQuarter` | 4 / 6 | → active player |
| `FirstPlayerToExit` | 4 / 6 | → active player |
| `SixTables` | 4 / 6 | → active player |
| `TwoTables` | 4 / 6 | → active player |
| `Mezeas` | 4 / 6 | → active player |
| `FalseHitSmallJan` | 4 / 6 | → opponent |
| `FalseHitBigJan` | 2 / 4 | → opponent |
| `ContreTwoTables` | 4 / 6 | → opponent |
| `ContreMezeas` | 4 / 6 | → opponent |
| `HelplessMan` | 2 / 4 | → opponent |
A single roll can trigger multiple jans, each scored independently. The jan detection process:
1. Try both dice orderings
2. Detect "tout d'une" (combined dice move as a virtual single die)
3. Prefer true hits over false hits for the same move
4. Check quarter-filling opportunities
5. Check rare jans (SixTables at roll 3, TwoTables, Mezeas) given specific board positions and talon counts
### Hole scoring
```rust
fn mark_points(&mut self, player_id: PlayerId, points: u8) -> bool {
let sum_points = p.points + points;
let jeux = sum_points / 12; // number of completed holes
let holes = match (jeux, p.can_bredouille) {
(0, _) => 0,
(_, false) => 2 * jeux - 1, // no bredouille bonus
(_, true) => 2 * jeux, // bredouille doubles the holes
};
p.points = sum_points % 12;
p.holes += holes;
...
}
```
- 12 points = 1 "jeu", which yields 1 or 2 holes depending on bredouille status.
- Scoring any points clears the opponent's `can_bredouille`.
- Completing a hole resets `can_bredouille` for the scorer.
- Game ends when `holes > 12`.
- Score reported to OpenSpiel: `holes * 12 + points`.
### Points from both rolls
After a roll, the active player's points (`dice_points.0`) are auto-marked immediately. After the Move, the opponent's points (`dice_points.1`) are marked (they were computed at roll-time from the pre-move board).
---
## 8. Move Rules
`MoveRules` always works from White's perspective. Key constraints enforced by `moves_allowed()`:
1. **Opponent's corner forbidden**: Cannot land on field 13 (opponent's rest corner for White).
2. **Corner needs two checkers**: The rest corner (field 12) must be taken or vacated with exactly 2 checkers simultaneously.
3. **Corner by effect vs. by power**: If the corner can be taken directly ("par effet"), you cannot take it "par puissance" (using combined dice).
4. **Exit preconditions**: All checkers must be in fields 1924 before any exit is allowed.
5. **Exit by effect priority**: If a normal exit is possible, exceedant moves (using overflow) are forbidden.
6. **Farthest checker first**: When exiting with exceedant, must exit the checker at the highest field.
7. **Must play all dice**: If both dice can be played, playing only one is invalid.
8. **Must play strongest die**: If only one die can be played, it must be the higher value die.
9. **Must fill quarter**: If a quarter can be completed, the move must complete it.
10. **Cannot block opponent's fillable quarter**: Cannot move into a quarter the opponent can still fill.
The board state after each die application is simulated to check two-step sequences.
---
## 9. Action Space (training_common.rs)
Total size: **514 actions**.
| Index | Action | Description |
|---|---|---|
| 0 | `Roll` | Request dice roll (not used in OpenSpiel mode) |
| 1 | `Go` | After winning hole: reset board and continue |
| 2257 | `Move { dice_order: true, checker1, checker2 }` | Move with die[0] first |
| 258513 | `Move { dice_order: false, checker1, checker2 }` | Move with die[1] first |
Move encoding: `index = 2 + (0 if dice_order else 256) + checker1 * 16 + checker2`
`checker1` and `checker2` are **ordinal positions** (1-based) of specific checkers counted left-to-right across all White-occupied fields, not field indices. Checker 0 = "no move" (empty move). Range: 015 (16 values each).
### Mirror pattern in get_legal_actions / apply_action
For player 2 (Black):
```rust
// get_legal_actions: mirror game state before computing
let mirror = self.game_state.mirror();
get_valid_action_indices(&mirror)
// apply_action: convert action → event on mirrored state, then mirror the event back
a.to_event(&self.game_state.mirror())
.map(|e| e.get_mirror(false))
```
This ensures Black's actions are computed as if Black were White on a mirrored board, then translated back to real-board coordinates.
---
## 10. Python Bindings (pyengine.rs)
The `TricTrac` PyO3 class exposes:
| Method | Signature | Description |
|---|---|---|
| `new()` | `→ TricTrac` | Create game, init 2 players, begin with player 1 |
| `needs_roll()` | `→ bool` | True when in `RollWaiting` stage |
| `is_game_ended()` | `→ bool` | True when `Stage::Ended` |
| `current_player_idx()` | `→ u64` | 0 or 1 (active_player_id 1) |
| `get_legal_actions(player_idx)` | `→ Vec<usize>` | Action indices for player; empty if not their turn |
| `action_to_string(player_idx, action_idx)` | `→ String` | Human-readable action description |
| `apply_dice_roll(dices: (u8, u8))` | `→ PyResult<()>` | Inject dice result; errors if not in RollWaiting |
| `apply_action(action_idx)` | `→ PyResult<()>` | Apply a game action; validates before applying |
| `get_score(player_id)` | `→ i32` | `holes * 12 + points` for player (1-indexed!) |
| `get_players_scores()` | `→ [i32; 2]` | `[score_p1, score_p2]` |
| `get_tensor(player_idx)` | `→ Vec<i8>` | 36-element state vector (mirrored for player 1) |
| `get_observation_string(player_idx)` | `→ String` | Human-readable state (mirrored for player 1) |
| `__str__()` | `→ String` | Debug representation of game state |
Note: `get_score(player_id)` takes a 1-based player ID (1 or 2), unlike `current_player_idx()` which returns 0-based.
---
## 11. State Tensor Encoding (36 bytes)
```
[0..23] Board positions (i8): +N white / N black checkers per field
[24] Active player: 0=White, 1=Black
[25] TurnStage: 0=RollWaiting, 1=RollDice, 2=MarkPoints, 3=HoldOrGoChoice,
4=Move, 5=MarkAdvPoints
[26] Dice value 1 (i8)
[27] Dice value 2 (i8)
[28] White: points (011)
[29] White: holes (012)
[30] White: can_bredouille (0 or 1)
[31] White: can_big_bredouille (0 or 1)
[32] Black: points
[33] Black: holes
[34] Black: can_bredouille
[35] Black: can_big_bredouille
```
When called for player 1 (Black), the entire state is mirrored first (`game_state.mirror().to_vec()`).
### State ID (base64 string for hashing)
108 bits packed as 18 base64 characters:
- 77 bits: GNUbg-inspired board position encoding (run-length with separators)
- 1 bit: active player color
- 3 bits: turn stage
- 6 bits: dice (3 bits per die)
- 10 bits: white player (4 pts + 4 holes + 2 flags)
- 10 bits: black player
- Padded to 108 bits, grouped as 18 × 6-bit base64 chunks
---
## 12. OpenSpiel Integration (trictrac.py)
### Game registration
```python
pyspiel.register_game(_GAME_TYPE, TrictracGame)
```
Key parameters:
- `short_name = "python_trictrac"`
- `dynamics = SEQUENTIAL`
- `chance_mode = EXPLICIT_STOCHASTIC`
- `information = PERFECT_INFORMATION`
- `utility = GENERAL_SUM` (both players can score positive; no zero-sum constraint)
- `reward_model = REWARDS` (intermediate rewards, not just terminal)
- `num_distinct_actions = 514`
- `max_chance_outcomes = 36`
- `min_utility = 0.0`, `max_utility = 200.0`
- `max_game_length = 3000` (rough estimate)
### Chance node handling
When `needs_roll()` is true, the state is a chance node. OpenSpiel samples one of 36 outcomes (uniform):
```python
def _roll_from_chance_idx(self, action):
return [(i,j) for i in range(1,7) for j in range(1,7)][action]
def chance_outcomes(self):
p = 1.0 / 36
return [(i, p) for i in range(0, 36)]
```
Action 0 → (1,1), action 1 → (1,2), …, action 35 → (6,6). The chance action is then passed to `apply_dice_roll((d1, d2))` on the Rust side.
### Player action handling
When not a chance node:
```python
def _legal_actions(self, player):
return self._store.get_legal_actions(player)
def _apply_action(self, action):
self._store.apply_action(action)
```
The `Roll` action (index 0) is never returned by `get_legal_actions` in this mode because the Rust side only returns Roll actions from `TurnStage::RollDice`, which is bypassed in the pyengine flow (the RollWaiting→chance node path takes over).
### Returns
```python
def returns(self):
return self._store.get_players_scores()
# → [holes_p1 * 12 + points_p1, holes_p2 * 12 + points_p2]
```
These are cumulative scores available at any point during the game (not just terminal), consistent with `reward_model = REWARDS`.
---
## 13. Known Issues and Inconsistencies
### 13.1 `observation_string` missing return (trictrac.py:156)
```python
def observation_string(self, player):
self._store.get_observation_string(player) # result discarded, returns None
```
Should be `return self._store.get_observation_string(player)`.
### 13.2 `observation_tensor` not populating buffer (trictrac.py:159)
```python
def observation_tensor(self, player, values):
self._store.get_tensor(player) # result discarded, values not filled
```
OpenSpiel's API expects `values` (a mutable buffer, typically a flat numpy array) to be filled in-place. The returned `Vec<i8>` from `get_tensor()` is discarded. Should copy data into `values`.
### 13.3 Debug print statement active (trictrac.py:140)
```python
print("in apply action", self.is_chance_node(), action)
```
This fires on every action application. Should be removed or guarded.
### 13.4 Color swap on new_pick_up disabled
In `game.rs:new_pick_up()`:
```rust
// XXX : switch colors
// désactivé pour le moment car la vérification des mouvements échoue,
// cf. https://code.rhumbs.fr/henri/trictrac/issues/31
// p.color = p.color.opponent_color();
```
In authentic Trictrac, players swap colors between "relevés" (pick-ups after a hole is won with Go). This is commented out, so the same player always plays White and the same always plays Black throughout the entire game.
### 13.5 `can_big_bredouille` tracked but not implemented
The `can_big_bredouille` flag is stored in `Player` and serialized in state encoding, but the scoring logic never reads it. Grande bredouille (a rare extra bonus) is not implemented.
### 13.6 `Roll` action in action space but unused in OpenSpiel mode
`TrictracAction::Roll` (index 0) exists in the 514-action space and in `get_valid_actions()` (for `TurnStage::RollDice`). However, in pyengine, the game starts at `RollWaiting` (dice have been requested but not yet rolled), so `TurnStage::RollDice` is never reached from OpenSpiel's perspective. The chance node mechanism replaces the Roll action entirely. The action space slot 0 is permanently wasted from OpenSpiel's point of view.
### 13.7 `get_valid_actions` panics on `RollWaiting`
```rust
TurnStage::MarkPoints | TurnStage::MarkAdvPoints | TurnStage::RollWaiting => {
panic!("get_valid_actions not implemented for turn stage {:?}", ...)
}
```
If `get_legal_actions` were ever called while `needs_roll()` is true, this would panic. OpenSpiel's turn logic avoids this because chance nodes are handled separately, but it is a latent danger.
### 13.8 PPO training script uses wrong model name
`trictrac_ppo.py` saves to `ppo_backgammon_model.ckpt` — clearly copied from a backgammon example without renaming. Also uses `tensorflow.compat.v1` despite the PyTorch PPO import.
### 13.9 Opponent points marked at pre-move board state
The opponent's `dice_points.1` is computed at roll time (before the active player moves), but applied to the opponent after the move. This means the opponent's scoring is evaluated on the board position that existed before the active player moved — which is per the rules of Trictrac (points are based on where pieces could be hit at the moment of the roll), but it's worth noting this subtlety.
---
## 14. Data Flow: A Complete Turn
```
Python (OpenSpiel) → Rust (trictrac_store)
─────────────────────────────────────────────────────
is_chance_node() ← needs_roll() [TurnStage == RollWaiting]
(true at game start)
chance_outcomes() → [(0,p)..(35,p)]
_apply_action(chance_idx)
_roll_from_chance_idx(idx) → (d1, d2)
apply_dice_roll((d1, d2)) → consume(RollResult{dice})
→ auto-mark active player's points
→ if hole: TurnStage=HoldOrGoChoice
→ else: TurnStage=Move
current_player() → 0 or 1
_legal_actions(player) ← get_legal_actions(player_idx)
→ get_valid_actions on (possibly mirrored) state
→ Vec<usize> of valid action indices
_apply_action(action_idx) → apply_action(action_idx)
→ TrictracAction::from_action_index
→ to_event on (mirrored) state
→ mirror event back if player==2
→ validate → consume
→ mark opponent points
→ switch active player
→ TurnStage=RollDice (→ pyengine starts next turn)
Wait — pyengine starts at RollWaiting, not RollDice!
The next is_chance_node() call will be true again.
```
Note on turn transition: After a `Move` event in `game.rs`, turn stage becomes `RollDice` (not `RollWaiting`). The pyengine `needs_roll()` checks for `RollWaiting`. So after a move, `is_chance_node()` returns false — OpenSpiel will ask for a regular player action. But `get_valid_actions` at `TurnStage::RollDice` returns only `Roll` (index 0), which is **not** the chance path.
This reveals a subtlety: after the Move event, the active player has already been switched, so `current_player()` returns the new active player, and `get_legal_actions` returns `[0]` (Roll). OpenSpiel then applies action 0, which calls `apply_action(0)``TrictracAction::Roll``GameEvent::Roll` → TurnStage becomes `RollWaiting`. Then the next call to `is_chance_node()` returns true, and the chance mechanism kicks in again.
So the full sequence in OpenSpiel terms is:
```
[Chance] dice roll → [Player] move → [Player] Roll action → [Chance] dice roll → ...
```
The `Roll` action IS used — it is the bridge between Move completion and the next chance node.
---
## 15. Summary of Design Choices
| Choice | Rationale |
|---|---|
| All rules engine in Rust | Performance, correctness, can be used in other contexts (CLI, native bots) |
| Mirror pattern for Black | Avoids duplicating all rule logic for both colors |
| Schools disabled by default | Simpler turn structure for RL training; full protocol for human play |
| GENERAL_SUM + REWARDS | Trictrac is not strictly zero-sum; intermediate hole rewards are informative for training |
| Action index for checkers (not fields) | Reduces action space; ordinal checker numbering is compact |
| 514 action slots | 1 Roll + 1 Go + 256 × 2 move combinations (ordered by die priority × 16 × 16 checker pairs) |
| Chance node = dice roll | Standard OpenSpiel pattern for stochastic games |

292
doc/research.md Normal file
View file

@ -0,0 +1,292 @@
# Trictrac — Research Notes
## 1. Rust Engine: Module Map
| Module | Responsibility |
| ---------------------- | ------------------------------------------------------------------------- |
| `board.rs` | Board representation, checker manipulation, quarter analysis |
| `dice.rs` | `Dice` struct, `DiceRoller`, bit encoding |
| `player.rs` | `Player` struct (score, bredouille), `Color`, `PlayerId`, `CurrentPlayer` |
| `game.rs` | `GameState` state machine, `GameEvent` enum, `Stage`/`TurnStage` |
| `game_rules_moves.rs` | `MoveRules`: move validation and generation |
| `game_rules_points.rs` | `PointsRules`: jan detection and scoring |
| `training_common.rs` | `TrictracAction` enum, action-space encoding (size 514) |
| `pyengine.rs` | PyO3 Python module exposing `TricTrac` class |
| `lib.rs` | Crate root, re-exports |
---
## 2. Board Representation
```rust
pub struct Board {
positions: [i8; 24],
}
```
- 24 fields indexed 023 internally, 124 externally.
- Positive values = White checkers on that field; negative = Black.
- Initial state: `[15, 0, ..., 0, -15]` — all 15 white pieces on field 1, all 15 black pieces on field 24.
- Field 0 is a sentinel for "exited the board" (never stored in the array).
**Mirroring** is the central symmetry operation used throughout:
```rust
pub fn mirror(&self) -> Self {
let mut positions = self.positions.map(|c| 0 - c);
positions.reverse();
Board { positions }
}
```
This negates all values (swapping who owns each checker) and reverses the array (swapping directions). The entire engine always reasons from White's perspective; Black's moves are handled by mirroring the board first.
**Quarter structure**: fields 16, 712, 1318, 1924. This maps to the four tables of Trictrac:
- 16: White's "petit jan" (own table)
- 712: White's "grand jan"
- 1318: Black's "grand jan" (= White's opponent territory)
- 1924: Black's "petit jan" / White's "jan de retour"
The "coin de repos" (rest corner) is field 12 for White, field 13 for Black.
---
## 3. Dice
```rust
pub struct Dice {
pub values: (u8, u8),
}
```
Dice are always a pair (never quadrupled for doubles, unlike Backgammon). The `DiceRoller` uses `StdRng` seeded from OS entropy (or an optional fixed seed for tests). Bit encoding: `"{d1:0>3b}{d2:0>3b}"` — 3 bits each, 6 bits total.
---
## 4. Player State
```rust
pub struct Player {
pub name: String,
pub color: Color, // White or Black
pub points: u8, // 011 (points within current hole)
pub holes: u8, // holes won (game ends at >12)
pub can_bredouille: bool,
pub can_big_bredouille: bool,
pub dice_roll_count: u8, // rolls since last new_pick_up()
}
```
`PlayerId` is a `u64` alias. Player 1 = White, Player 2 = Black (set at init time; this is fixed for the session in pyengine).
---
## 5. Game State Machine
### Stages
```rust
pub enum Stage { PreGame, InGame, Ended }
pub enum TurnStage {
RollDice, // 1 — player must request a roll
RollWaiting, // 0 — waiting for dice result from outside
MarkPoints, // 2 — points are being marked (schools mode only)
HoldOrGoChoice, // 3 — player won a hole; choose to Go or Hold
Move, // 4 — player must move checkers
MarkAdvPoints, // 5 — mark opponent's points after the move (schools mode)
}
```
### Turn lifecycle (schools disabled — the default)
```
RollWaiting
│ RollResult → auto-mark points
├─[no hole]──→ Move
│ │ Move → mark opponent's points → switch player
│ └───────────────────────────────→ RollDice (next player)
└─[hole won]─→ HoldOrGoChoice
├─ Go ──→ new_pick_up() → RollDice (same player)
└─ Move ──→ mark opponent's points → switch player → RollDice
```
In schools mode (`schools_enabled = true`), the player explicitly marks their own points (`Mark` event) and then the opponent's points after moving (`MarkAdvPoints` stage).
### Key events
```rust
pub enum GameEvent {
BeginGame { goes_first: PlayerId },
EndGame { reason: EndGameReason },
PlayerJoined { player_id, name },
PlayerDisconnected { player_id },
Roll { player_id }, // triggers RollWaiting
RollResult { player_id, dice }, // provides dice values
Mark { player_id, points }, // explicit point marking (schools mode)
Go { player_id }, // choose to restart position after hole
Move { player_id, moves: (CheckerMove, CheckerMove) },
PlayError,
}
```
### Initialization in pyengine
```rust
fn new() -> Self {
let mut game_state = GameState::new(false); // schools_enabled = false
game_state.init_player("player1");
game_state.init_player("player2");
game_state.consume(&GameEvent::BeginGame { goes_first: 1 });
TricTrac { game_state }
}
```
Player 1 (White) always goes first. `active_player_id` uses 1-based indexing; pyengine converts to 0-based for the Python side with `active_player_id - 1`.
---
## 6. Scoring System (Jans)
Points are awarded after each dice roll based on "jans" (scoring events) detected by `PointsRules`. All computation assumes White's perspective (board is mirrored for Black before calling).
### Jan types
| Jan | Points (normal / doublet) | Direction |
| ----------------------- | ------------------------- | --------------- |
| `TrueHitSmallJan` | 4 / 6 | → active player |
| `TrueHitBigJan` | 2 / 4 | → active player |
| `TrueHitOpponentCorner` | 4 / 6 | → active player |
| `FilledQuarter` | 4 / 6 | → active player |
| `FirstPlayerToExit` | 4 / 6 | → active player |
| `SixTables` | 4 / 6 | → active player |
| `TwoTables` | 4 / 6 | → active player |
| `Mezeas` | 4 / 6 | → active player |
| `FalseHitSmallJan` | 4 / 6 | → opponent |
| `FalseHitBigJan` | 2 / 4 | → opponent |
| `ContreTwoTables` | 4 / 6 | → opponent |
| `ContreMezeas` | 4 / 6 | → opponent |
| `HelplessMan` | 2 / 4 | → opponent |
A single roll can trigger multiple jans, each scored independently. The jan detection process:
1. Try both dice orderings
2. Detect "tout d'une" (combined dice move as a virtual single die)
3. Prefer true hits over false hits for the same move
4. Check quarter-filling opportunities
5. Check rare jans (SixTables at roll 3, TwoTables, Mezeas) given specific board positions and talon counts
### Hole scoring
```rust
fn mark_points(&mut self, player_id: PlayerId, points: u8) -> bool {
let sum_points = p.points + points;
let jeux = sum_points / 12; // number of completed holes
let holes = match (jeux, p.can_bredouille) {
(0, _) => 0,
(_, false) => 2 * jeux - 1, // no bredouille bonus
(_, true) => 2 * jeux, // bredouille doubles the holes
};
p.points = sum_points % 12;
p.holes += holes;
...
}
```
- 12 points = 1 "jeu", which yields 1 or 2 holes depending on bredouille status.
- Scoring any points clears the opponent's `can_bredouille`.
- Completing a hole resets `can_bredouille` for the scorer.
- Game ends when `holes > 12`.
- Score reported to OpenSpiel: `holes * 12 + points`.
### Points from both rolls
After a roll, the active player's points (`dice_points.0`) are auto-marked immediately. After the Move, the opponent's points (`dice_points.1`) are marked (they were computed at roll-time from the pre-move board).
---
## 7. Move Rules
`MoveRules` always works from White's perspective. Key constraints enforced by `moves_allowed()`:
1. **Opponent's corner forbidden**: Cannot land on field 13 (opponent's rest corner for White).
2. **Corner needs two checkers**: The rest corner (field 12) must be taken or vacated with exactly 2 checkers simultaneously.
3. **Corner by effect vs. by power**: If the corner can be taken directly ("par effet"), you cannot take it "par puissance" (using combined dice).
4. **Exit preconditions**: All checkers must be in fields 1924 before any exit is allowed.
5. **Exit by effect priority**: If a normal exit is possible, exceedant moves (using overflow) are forbidden.
6. **Farthest checker first**: When exiting with exceedant, must exit the checker at the highest field.
7. **Must play all dice**: If both dice can be played, playing only one is invalid.
8. **Must play strongest die**: If only one die can be played, it must be the higher value die.
9. **Must fill quarter**: If a quarter can be completed, the move must complete it.
10. **Cannot block opponent's fillable quarter**: Cannot move into a quarter the opponent can still fill.
The board state after each die application is simulated to check two-step sequences.
---
## 8. Action Space (training_common.rs)
Total size: **514 actions**.
| Index | Action | Description |
| ------- | ------------------------------------------------ | ---------------------------------------------- |
| 0 | `Roll` | Request dice roll (not used in OpenSpiel mode) |
| 1 | `Go` | After winning hole: reset board and continue |
| 2257 | `Move { dice_order: true, checker1, checker2 }` | Move with die[0] first |
| 258513 | `Move { dice_order: false, checker1, checker2 }` | Move with die[1] first |
Move encoding: `index = 2 + (0 if dice_order else 256) + checker1 * 16 + checker2`
`checker1` and `checker2` are **ordinal positions** (1-based) of specific checkers counted left-to-right across all White-occupied fields, not field indices. Checker 0 = "no move" (empty move). Range: 015 (16 values each).
### Mirror pattern in get_legal_actions / apply_action
For player 2 (Black):
```rust
// get_legal_actions: mirror game state before computing
let mirror = self.game_state.mirror();
get_valid_action_indices(&mirror)
// apply_action: convert action → event on mirrored state, then mirror the event back
a.to_event(&self.game_state.mirror())
.map(|e| e.get_mirror(false))
```
This ensures Black's actions are computed as if Black were White on a mirrored board, then translated back to real-board coordinates.
---
## 9. Known Issues and Inconsistencies
### 9.1 Color swap on new_pick_up disabled
In `game.rs:new_pick_up()`:
```rust
// XXX : switch colors
// désactivé pour le moment car la vérification des mouvements échoue,
// cf. https://code.rhumbs.fr/henri/trictrac/issues/31
// p.color = p.color.opponent_color();
```
In authentic Trictrac, players swap colors between "relevés" (pick-ups after a hole is won with Go). This is commented out, so the same player always plays White and the same always plays Black throughout the entire game.
### 9.2 `can_big_bredouille` tracked but not implemented
The `can_big_bredouille` flag is stored in `Player` and serialized in state encoding, but the scoring logic never reads it. Grande bredouille (a rare extra bonus) is not implemented.
### 9.3 `get_valid_actions` panics on `RollWaiting`
```rust
TurnStage::MarkPoints | TurnStage::MarkAdvPoints | TurnStage::RollWaiting => {
panic!("get_valid_actions not implemented for turn stage {:?}", ...)
}
```
If `get_legal_actions` were ever called while `needs_roll()` is true, this would panic.
### 9.4 Opponent points marked at pre-move board state
The opponent's `dice_points.1` is computed at roll time (before the active player moves), but applied to the opponent after the move. This means the opponent's scoring is evaluated on the board position that existed before the active player moved — which is per the rules of Trictrac (points are based on where pieces could be hit at the moment of the roll), but it's worth noting this subtlety.

View file

@ -20,8 +20,13 @@ profile:
cargo build --profile profiling
samply record ./target/profiling/client_cli --bot dummy,dummy
pythonlib:
rm -rf target/wheels
maturin build -m store/Cargo.toml --release
pip install --no-deps --force-reinstall --prefix .devenv/state/venv target/wheels/*.whl
cxxlib:
cargo build --release -p trictrac-store
@echo "Static lib: $(ls target/release/libtrictrac_store.a)"
@echo "CXX header: $(find target -name 'cxxengine.rs.h' | head -1)"
trainbot algo:
#python ./store/python/trainModel.py
# cargo run --bin=train_dqn # ok

View file

@ -1,20 +1,29 @@
[package]
name = "store"
name = "trictrac-store"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "store"
# Only "rlib" is needed for other Rust crates to use this library
crate-type = ["rlib"]
name = "trictrac_store"
# "cdylib" → Python .so built by maturin (pyengine)
# "rlib" → used by other workspace crates (bot, client_cli)
# "staticlib" → used by the C++ OpenSpiel game (cxxengine)
crate-type = ["cdylib", "rlib", "staticlib"]
[dependencies]
anyhow = "1.0"
base64 = "0.21.7"
cxx = "1.0"
# provides macros for creating log messages to be used by a logger (for example env_logger)
log = "0.4.20"
merge = "0.1.0"
rand = "0.8.5"
# generate python lib (with maturin) to be used in AI training
pyo3 = { version = "0.23", features = ["extension-module", "abi3-py38"] }
rand = "0.9"
serde = { version = "1.0", features = ["derive"] }
transpose = "0.2.2"
[build-dependencies]
cxx-build = "1.0"

7
store/build.rs Normal file
View file

@ -0,0 +1,7 @@
fn main() {
cxx_build::bridge("src/cxxengine.rs")
.std("c++17")
.compile("trictrac-cxx");
println!("cargo:rerun-if-changed=src/cxxengine.rs");
}

8
store/pyproject.toml Normal file
View file

@ -0,0 +1,8 @@
[build-system]
requires = ["maturin>=1.0,<2.0"]
build-backend = "maturin"
[tool.maturin]
# "extension-module" tells pyo3 we want to build an extension module (skips linking against libpython.so)
features = ["pyo3/extension-module"]
# python-source = "python"

View file

@ -8,7 +8,7 @@ use std::fmt;
pub type Field = usize;
pub type FieldWithCount = (Field, i8);
#[derive(Debug, Copy, Clone, Serialize, PartialEq, Eq, Deserialize)]
#[derive(Debug, Copy, Clone, Serialize, PartialEq, Eq, Deserialize, Hash)]
pub struct CheckerMove {
from: Field,
to: Field,
@ -439,6 +439,7 @@ impl Board {
check_rest_corner_exit: bool,
forbid_exits: bool,
) -> Vec<CheckerMove> {
// println!("------- board.get_possible_moves...");
let mut moves = Vec::new();
let get_dest = |from| {
@ -453,6 +454,7 @@ impl Board {
}
};
// let mut farthest_exit_move = 25;
for (field, count) in self.get_color_fields(color) {
// check rest corner exit
if field == self.get_color_corner(&color) && count == 2 && check_rest_corner_exit {
@ -463,8 +465,11 @@ impl Board {
continue;
}
if !(0..25).contains(&dest) {
// if with_excedants && !forbid_exits && field < farthest_exit_move && 2 < count {
if with_excedants && !forbid_exits {
dest = 0;
// farthest_exit_move = field;
// println!("farthest is now {farthest_exit_move}");
} else {
continue;
}
@ -834,4 +839,27 @@ mod tests {
assert_eq!(4, board.get_field_checker(&Color::White, 2));
assert_eq!(6, board.get_field_checker(&Color::White, 3));
}
#[test]
fn get_possible_moves() {
let mut board = Board::new();
board.set_positions(
&Color::White,
[
-8, -3, -1, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3,
],
);
let moves = vec![
CheckerMove::new(19, 22).unwrap(),
CheckerMove::new(20, 23).unwrap(),
CheckerMove::new(21, 24).unwrap(),
CheckerMove::new(22, 0).unwrap(),
CheckerMove::new(23, 0).unwrap(),
CheckerMove::new(24, 0).unwrap(),
];
assert_eq!(
moves,
board.get_possible_moves(Color::White, 3, true, true, false,)
);
}
}

252
store/src/cxxengine.rs Normal file
View file

@ -0,0 +1,252 @@
//! C++ bindings for the TricTrac game engine via cxx.rs.
//!
//! Exposes an opaque `TricTracEngine` type to C++. The C++ side
//! (open_spiel/games/trictrac/trictrac.cc) holds it via
//! `rust::Box<trictrac_engine::TricTracEngine>`.
//!
//! The Rust engine always reasons from White's (player 1's) perspective.
//! For Black (player 2), the board is mirrored before computing actions
//! and events are mirrored back before being applied — exactly as in
//! pyengine.rs.
use std::panic::{self, AssertUnwindSafe};
use crate::dice::Dice;
use crate::game::{GameEvent, GameState, Stage, TurnStage};
use crate::training_common::{get_valid_action_indices, TrictracAction};
/// Catch any Rust panic and convert it to anyhow::Error so it never
/// crosses the C FFI boundary as undefined behaviour.
fn catch_panics<F, T>(f: F) -> anyhow::Result<T>
where
F: FnOnce() -> anyhow::Result<T> + panic::UnwindSafe,
{
panic::catch_unwind(f).unwrap_or_else(|e| {
let msg = e
.downcast_ref::<String>()
.map(|s| s.as_str())
.or_else(|| e.downcast_ref::<&str>().copied())
.unwrap_or("unknown panic payload");
Err(anyhow::anyhow!("Rust panic in FFI: {}", msg))
})
}
// ── cxx bridge declaration ────────────────────────────────────────────────────
#[cxx::bridge(namespace = "trictrac_engine")]
pub mod ffi {
// ── Shared types (transparent to both Rust and C++) ───────────────────────
/// Two dice values passed from C++ when applying a chance outcome.
struct DicePair {
die1: u8,
die2: u8,
}
/// Both players' cumulative scores: holes * 12 + points.
struct PlayerScores {
score_p1: i32,
score_p2: i32,
}
// ── Opaque Rust type and its free-function constructor ────────────────────
extern "Rust" {
/// Opaque handle to a running TricTrac game.
/// C++ accesses this only through `rust::Box<TricTracEngine>`.
type TricTracEngine;
/// Construct a fresh engine with two players; player 1 (White) goes first.
fn new_trictrac_engine() -> Box<TricTracEngine>;
/// Deep-copy the engine — required by OpenSpiel's State::Clone().
fn clone_engine(self: &TricTracEngine) -> Box<TricTracEngine>;
// ── Queries ───────────────────────────────────────────────────────────
/// True when the game is in TurnStage::RollWaiting (OpenSpiel chance node).
fn needs_roll(self: &TricTracEngine) -> bool;
/// True when Stage::Ended.
fn is_game_ended(self: &TricTracEngine) -> bool;
/// Active player index: 0 = player 1 (White), 1 = player 2 (Black).
fn current_player_idx(self: &TricTracEngine) -> u64;
/// Legal action indices for `player_idx` in [0, 513].
/// Returns an empty vector when it is not that player's turn.
fn get_legal_actions(self: &TricTracEngine, player_idx: u64) -> Result<Vec<u64>>;
/// Human-readable description of an action index.
fn action_to_string(self: &TricTracEngine, player_idx: u64, action_idx: u64) -> String;
/// Both players' scores.
fn get_players_scores(self: &TricTracEngine) -> PlayerScores;
/// 36-element state vector (i8). Mirrored for player_idx == 1.
fn get_tensor(self: &TricTracEngine, player_idx: u64) -> Vec<i8>;
/// Human-readable state description for `player_idx`.
fn get_observation_string(self: &TricTracEngine, player_idx: u64) -> String;
/// Full debug representation of the current state.
fn to_debug_string(self: &TricTracEngine) -> String;
// ── Mutations ─────────────────────────────────────────────────────────
/// Apply a dice-roll result. Returns Err (C++ exception) if not in
/// the RollWaiting stage.
fn apply_dice_roll(self: &mut TricTracEngine, dice: DicePair) -> Result<()>;
/// Apply a player action. Returns Err (C++ exception) if the action
/// is not legal in the current state.
fn apply_action(self: &mut TricTracEngine, action_idx: u64) -> Result<()>;
}
}
// ── Opaque type ───────────────────────────────────────────────────────────────
pub struct TricTracEngine {
game_state: GameState,
}
// ── Free-function constructor (declared in the bridge as a plain function) ────
pub fn new_trictrac_engine() -> Box<TricTracEngine> {
let mut game_state = GameState::new(false); // schools_enabled = false
game_state.init_player("player1");
game_state.init_player("player2");
game_state
.consume(&GameEvent::BeginGame { goes_first: 1 })
.expect("BeginGame failed during engine initialization");
Box::new(TricTracEngine { game_state })
}
// ── Method implementations ────────────────────────────────────────────────────
impl TricTracEngine {
fn clone_engine(&self) -> Box<TricTracEngine> {
Box::new(TricTracEngine {
game_state: self.game_state.clone(),
})
}
fn needs_roll(&self) -> bool {
self.game_state.turn_stage == TurnStage::RollWaiting
}
fn is_game_ended(&self) -> bool {
self.game_state.stage == Stage::Ended
}
fn current_player_idx(&self) -> u64 {
self.game_state.active_player_id - 1
}
fn get_legal_actions(&self, player_idx: u64) -> anyhow::Result<Vec<u64>> {
if player_idx != self.current_player_idx() {
return Ok(vec![]);
}
catch_panics(AssertUnwindSafe(|| {
if player_idx == 0 {
get_valid_action_indices(&self.game_state)
.map(|v| v.into_iter().map(|i| i as u64).collect())
} else {
let mirror = self.game_state.mirror();
get_valid_action_indices(&mirror)
.map(|v| v.into_iter().map(|i| i as u64).collect())
}
}))
}
fn action_to_string(&self, player_idx: u64, action_idx: u64) -> String {
TrictracAction::from_action_index(action_idx as usize)
.map(|a| format!("{}:{}", player_idx, a))
.unwrap_or_else(|| "unknown action".into())
}
fn get_players_scores(&self) -> ffi::PlayerScores {
ffi::PlayerScores {
score_p1: self.score_for(1),
score_p2: self.score_for(2),
}
}
fn score_for(&self, player_id: u64) -> i32 {
self.game_state
.players
.get(&player_id)
.map(|p| p.holes as i32 * 12 + p.points as i32)
.unwrap_or(-1)
}
fn get_tensor(&self, player_idx: u64) -> Vec<i8> {
if player_idx == 0 {
self.game_state.to_vec()
} else {
self.game_state.mirror().to_vec()
}
}
fn get_observation_string(&self, player_idx: u64) -> String {
if player_idx == 0 {
format!("{}", self.game_state)
} else {
format!("{}", self.game_state.mirror())
}
}
fn to_debug_string(&self) -> String {
format!("{}", self.game_state)
}
fn apply_dice_roll(&mut self, dice: ffi::DicePair) -> anyhow::Result<()> {
if self.game_state.turn_stage != TurnStage::RollWaiting {
anyhow::bail!(
"apply_dice_roll: not in RollWaiting stage (currently {:?})",
self.game_state.turn_stage
);
}
let player_id = self.game_state.active_player_id;
let dice = Dice {
values: (dice.die1, dice.die2),
};
catch_panics(AssertUnwindSafe(|| {
self.game_state
.consume(&GameEvent::RollResult { player_id, dice })
.map_err(|e| anyhow::anyhow!(e))
}))
}
fn apply_action(&mut self, action_idx: u64) -> anyhow::Result<()> {
catch_panics(AssertUnwindSafe(|| {
let needs_mirror = self.game_state.active_player_id == 2;
let event = TrictracAction::from_action_index(action_idx as usize).and_then(|a| {
let state = if needs_mirror {
&self.game_state.mirror()
} else {
&self.game_state
};
a.to_event(state)
.map(|e| if needs_mirror { e.get_mirror(false) } else { e })
});
match event {
Some(evt) if self.game_state.validate(&evt) => self
.game_state
.consume(&evt)
.map_err(|e| anyhow::anyhow!(e)),
Some(evt) => anyhow::bail!(
"apply_action: event {:?} is not valid in current state {}",
evt,
self.game_state
),
None => anyhow::bail!(
"apply_action: could not build event from action index {}",
action_idx
),
}
}))
}
}

View file

@ -1,4 +1,4 @@
use rand::distributions::{Distribution, Uniform};
use rand::distr::{Distribution, Uniform};
use rand::{rngs::StdRng, SeedableRng};
use serde::{Deserialize, Serialize};
@ -17,7 +17,7 @@ impl DiceRoller {
pub fn new(opt_seed: Option<u64>) -> Self {
Self {
rng: match opt_seed {
None => StdRng::from_rng(rand::thread_rng()).unwrap(),
None => StdRng::from_rng(&mut rand::rng()),
Some(seed) => SeedableRng::seed_from_u64(seed),
},
}
@ -26,7 +26,7 @@ impl DiceRoller {
/// Roll the dices which generates two random numbers between 1 and 6, replicating a perfect
/// dice. We use the operating system's random number generator.
pub fn roll(&mut self) -> Dice {
let between = Uniform::new_inclusive(1, 6);
let between = Uniform::new_inclusive(1, 6).expect("1 > 6 !?");
let v = (between.sample(&mut self.rng), between.sample(&mut self.rng));

View file

@ -2,8 +2,9 @@
use crate::board::{Board, CheckerMove};
use crate::dice::Dice;
use crate::game_rules_moves::MoveRules;
use crate::game_rules_points::{PointsRules, PossibleJans};
use crate::game_rules_points::{PointsRules, PossibleJans, PossibleJansMethods};
use crate::player::{Color, Player, PlayerId};
// use anyhow::{Context, Result};
use log::{debug, error};
// use itertools::Itertools;
@ -90,7 +91,13 @@ impl fmt::Display for GameState {
self.stage, self.turn_stage
));
s.push_str(&format!("Dice: {:?}\n", self.dice));
// s.push_str(&format!("Who plays: {}\n", self.who_plays().map(|player| &player.name ).unwrap_or("")));
let empty_string = String::from("");
s.push_str(&format!(
"Who plays: {}\n",
self.who_plays()
.map(|player| &player.name)
.unwrap_or_else(|| &empty_string)
));
s.push_str(&format!("Board: {:?}\n", self.board));
// s.push_str(&format!("History: {:?}\n", self.history));
write!(f, "{s}")
@ -133,11 +140,47 @@ impl GameState {
let mut game = Self::default();
if let Some(p1) = game.init_player(p1_name) {
game.init_player(p2_name);
game.consume(&GameEvent::BeginGame { goes_first: p1 });
let _ = game
.consume(&GameEvent::BeginGame { goes_first: p1 })
.inspect_err(|e| error!("{}", e));
}
game
}
pub fn mirror(&self) -> GameState {
let mirrored_active_player = if self.active_player_id == 1 { 2 } else { 1 };
let mut mirrored_players = HashMap::new();
if let Some(p2) = self.players.get(&2) {
mirrored_players.insert(1, p2.mirror());
}
if let Some(p1) = self.players.get(&1) {
mirrored_players.insert(2, p1.mirror());
}
let mirrored_history = self
.history
.clone()
.iter()
.map(|evt| evt.get_mirror(false))
.collect();
let (move1, move2) = self.dice_moves;
GameState {
stage: self.stage,
turn_stage: self.turn_stage,
board: self.board.mirror(),
active_player_id: mirrored_active_player,
// active_player_id: self.active_player_id,
players: mirrored_players,
history: mirrored_history,
dice: self.dice,
dice_points: self.dice_points,
dice_moves: (move1.mirror(), move2.mirror()),
dice_jans: self.dice_jans.mirror(),
roll_first: self.roll_first,
schools_enabled: self.schools_enabled,
}
}
fn set_schools_enabled(&mut self, schools_enabled: bool) {
self.schools_enabled = schools_enabled;
}
@ -194,20 +237,13 @@ impl GameState {
// points, trous, bredouille, grande bredouille length=4 x2 joueurs = 8
let white_player: Vec<i8> = self
.get_white_player()
.unwrap()
.to_vec()
.iter()
.map(|&x| x as i8)
.collect();
.map(|p| p.to_vec().iter().map(|&x| x as i8).collect())
.unwrap_or(vec![0; 10]);
state.extend(white_player);
let black_player: Vec<i8> = self
.get_black_player()
.unwrap()
.to_vec()
.iter()
.map(|&x| x as i8)
.collect();
// .iter().map(|&x| x as i8) .collect()
.map(|p| p.to_vec().iter().map(|&x| x as i8).collect())
.unwrap_or(vec![0; 10]);
state.extend(black_player);
// ensure state has length state_len
@ -219,7 +255,7 @@ impl GameState {
}
/// Calculate game state id :
pub fn to_string_id(&self) -> String {
pub fn to_string_id_slow(&self) -> String {
// Pieces placement -> 77 bits (24 + 23 + 30 max)
let mut pos_bits = self.board.to_gnupg_pos_id();
@ -254,22 +290,141 @@ impl GameState {
pos_bits.push_str(&dice_bits);
// points 10bits x2 joueurs = 20bits
let white_bits = self.get_white_player().unwrap().to_bits_string();
let black_bits = self.get_black_player().unwrap().to_bits_string();
let white_bits = self
.get_white_player()
.map(|p| p.to_bits_string())
.unwrap_or("0000000000".into());
let black_bits = self
.get_black_player()
.map(|p| p.to_bits_string())
.unwrap_or("0000000000".into());
pos_bits.push_str(&white_bits);
pos_bits.push_str(&black_bits);
pos_bits = format!("{pos_bits:0<108}");
// println!("{}", pos_bits);
// let pos_u8 = pos_bits
// .as_bytes()
// .chunks(6)
// .map(|chunk| str::from_utf8(chunk).unwrap())
// .map(|chunk| u8::from_str_radix(chunk, 2).unwrap())
// .collect::<Vec<u8>>();
let pos_u8 = pos_bits
.as_bytes()
.chunks(6)
.map(|chunk| str::from_utf8(chunk).unwrap())
.map(|chunk| u8::from_str_radix(chunk, 2).unwrap())
.map(|chunk| chunk.iter().fold(0u8, |acc, &b| (acc << 1) | (b - b'0')))
.collect::<Vec<u8>>();
general_purpose::STANDARD.encode(pos_u8)
}
pub fn to_string_id(&self) -> String {
const TOTAL_BITS: usize = 108;
const TOTAL_BYTES: usize = TOTAL_BITS / 6; // 18 bytes
let mut output = Vec::with_capacity(TOTAL_BYTES);
let mut current: u8 = 0;
let mut bit_count: u8 = 0;
// helper to push a single bit
let push_bit = |bit: u8, output: &mut Vec<u8>, current: &mut u8, bit_count: &mut u8| {
*current = (*current << 1) | (bit & 1);
*bit_count += 1;
if *bit_count == 6 {
output.push(*current);
*current = 0;
*bit_count = 0;
}
};
// helper to push a string of '0'/'1'
let push_bits_str =
|bits: &str, output: &mut Vec<u8>, current: &mut u8, bit_count: &mut u8| {
for b in bits.bytes() {
push_bit(b - b'0', output, current, bit_count);
}
};
// --------------------------------------------------
// 1⃣ Board position bits
// --------------------------------------------------
push_bits_str(
&self.board.to_gnupg_pos_id(),
&mut output,
&mut current,
&mut bit_count,
);
// --------------------------------------------------
// 2⃣ Active player (1 bit)
// --------------------------------------------------
let active_bit = self
.who_plays()
.map(|player| (player.color == Color::Black) as u8)
.unwrap_or(0);
push_bit(active_bit, &mut output, &mut current, &mut bit_count);
// --------------------------------------------------
// 3⃣ Turn stage (3 bits)
// --------------------------------------------------
let stage_bits: u8 = match self.turn_stage {
TurnStage::RollWaiting => 0b000,
TurnStage::RollDice => 0b001,
TurnStage::MarkPoints => 0b010,
TurnStage::HoldOrGoChoice => 0b011,
TurnStage::Move => 0b100,
TurnStage::MarkAdvPoints => 0b101,
};
for i in (0..3).rev() {
push_bit(
(stage_bits >> i) & 1,
&mut output,
&mut current,
&mut bit_count,
);
}
// --------------------------------------------------
// 4⃣ Dice (6 bits)
// --------------------------------------------------
push_bits_str(
&self.dice.to_bits_string(),
&mut output,
&mut current,
&mut bit_count,
);
// --------------------------------------------------
// 5⃣ Players points (10 bits each)
// --------------------------------------------------
let white_bits = self
.get_white_player()
.map(|p| p.to_bits_string())
.unwrap_or_else(|| "0000000000".to_string());
let black_bits = self
.get_black_player()
.map(|p| p.to_bits_string())
.unwrap_or_else(|| "0000000000".to_string());
push_bits_str(&white_bits, &mut output, &mut current, &mut bit_count);
push_bits_str(&black_bits, &mut output, &mut current, &mut bit_count);
// --------------------------------------------------
// 6⃣ Pad remaining bits (if needed)
// --------------------------------------------------
while output.len() < TOTAL_BYTES {
push_bit(0, &mut output, &mut current, &mut bit_count);
}
base64::engine::general_purpose::STANDARD.encode(output)
}
pub fn from_string_id(id: &str) -> Result<Self, String> {
let bytes = general_purpose::STANDARD
.decode(id)
@ -287,7 +442,9 @@ impl GameState {
let board_bits = &bits[0..77];
let board = Board::from_gnupg_pos_id(board_bits)?;
let active_player_bit = bits.chars().nth(77).unwrap();
let Some(active_player_bit) = bits.chars().nth(77) else {
return Err("No bit at 77th position".to_string());
};
let active_player_color = if active_player_bit == '1' {
Color::Black
} else {
@ -431,10 +588,12 @@ impl GameState {
Roll { player_id } => {
// Check player exists
if !self.players.contains_key(player_id) {
error!("unknown player_id");
return false;
}
// Check player is currently the one making their move
if self.active_player_id != *player_id {
error!("not active player_id");
return false;
}
// Check the turn stage
@ -531,6 +690,7 @@ impl GameState {
*moves
};
if !rules.moves_follow_rules(&moves) {
// println!(">>> rules not followed ");
error!("rules not followed ");
return false;
}
@ -550,7 +710,7 @@ impl GameState {
pub fn init_player(&mut self, player_name: &str) -> Option<PlayerId> {
if self.players.len() > 2 {
println!("more than two players");
// println!("more than two players");
return None;
}
@ -579,23 +739,14 @@ impl GameState {
.next();
self.active_player_id = other_player_id.unwrap_or(0);
}
/// Consumes an event, modifying the GameState and adding the event to its history
/// NOTE: consume assumes the event to have already been validated and will accept *any* event passed to it
pub fn consume(&mut self, valid_event: &GameEvent) {
pub fn consume(&mut self, valid_event: &GameEvent) -> Result<(), String> {
use GameEvent::*;
match valid_event {
BeginGame { goes_first } => {
self.active_player_id = *goes_first;
// if self.who_plays().is_none() {
// let active_color = match self.dice.coin() {
// false => Color::Black,
// true => Color::White,
// };
// let color_player_id = self.player_id_by_color(active_color);
// if color_player_id.is_some() {
// self.active_player_id = *color_player_id.unwrap();
// }
// }
self.stage = Stage::InGame;
self.turn_stage = TurnStage::RollDice;
}
@ -631,14 +782,16 @@ impl GameState {
self.dice = *dice;
self.inc_roll_count(self.active_player_id);
self.turn_stage = TurnStage::MarkPoints;
(self.dice_jans, self.dice_points) = self.get_rollresult_jans(dice);
(self.dice_jans, self.dice_points) = self.get_rollresult_jans(dice)?;
debug!("points from result : {:?}", self.dice_points);
if !self.schools_enabled {
// Schools are not enabled. We mark points automatically
// the points earned by the opponent will be marked on its turn
let new_hole = self.mark_points(self.active_player_id, self.dice_points.0);
if new_hole {
let holes_count = self.get_active_player().unwrap().holes;
let Some(holes_count) = self.get_active_player().map(|p| p.holes) else {
return Err("No active player".into());
};
debug!("new hole -> {holes_count:?}");
if holes_count > 12 {
self.stage = Stage::Ended;
@ -654,7 +807,10 @@ impl GameState {
if self.schools_enabled {
let new_hole = self.mark_points(*player_id, *points);
if new_hole {
if self.get_active_player().unwrap().holes > 12 {
let Some(holes) = self.get_active_player().map(|p| p.holes) else {
return Err("No active player".into());
};
if holes > 12 {
self.stage = Stage::Ended;
} else {
self.turn_stage = if self.turn_stage == TurnStage::MarkAdvPoints {
@ -674,17 +830,26 @@ impl GameState {
}
Go { player_id: _ } => self.new_pick_up(),
Move { player_id, moves } => {
let player = self.players.get(player_id).unwrap();
self.board.move_checker(&player.color, moves.0).unwrap();
self.board.move_checker(&player.color, moves.1).unwrap();
let Some(player) = self.players.get(player_id) else {
return Err("unknown player {player_id}".into());
};
self.board
.move_checker(&player.color, moves.0)
.map_err(|e| e.to_string())?;
self.board
.move_checker(&player.color, moves.1)
.map_err(|e| e.to_string())?;
self.dice_moves = *moves;
self.active_player_id = *self.players.keys().find(|id| *id != player_id).unwrap();
let Some(active_player_id) = self.players.keys().find(|id| *id != player_id) else {
return Err("Can't find player id {id}".into());
};
self.active_player_id = *active_player_id;
self.turn_stage = if self.schools_enabled {
TurnStage::MarkAdvPoints
} else {
// The player has moved, we can mark its opponent's points (which is now the current player)
let new_hole = self.mark_points(self.active_player_id, self.dice_points.1);
if new_hole && self.get_active_player().unwrap().holes > 12 {
if new_hole && self.get_active_player().map(|p| p.holes).unwrap_or(0) > 12 {
self.stage = Stage::Ended;
}
TurnStage::RollDice
@ -693,6 +858,7 @@ impl GameState {
PlayError => {}
}
self.history.push(valid_event.clone());
Ok(())
}
/// Set a new pick up ('relevé') after a player won a hole and choose to 'go',
@ -715,14 +881,16 @@ impl GameState {
self.board = Board::new();
}
fn get_rollresult_jans(&self, dice: &Dice) -> (PossibleJans, (u8, u8)) {
let player = &self.players.get(&self.active_player_id).unwrap();
fn get_rollresult_jans(&self, dice: &Dice) -> Result<(PossibleJans, (u8, u8)), String> {
let Some(player) = &self.players.get(&self.active_player_id) else {
return Err("No active player".into());
};
debug!(
"get rollresult for {:?} {:?} {:?} (roll count {:?})",
player.color, self.board, dice, player.dice_roll_count
);
let points_rules = PointsRules::new(&player.color, &self.board, *dice);
points_rules.get_result_jans(player.dice_roll_count)
Ok(points_rules.get_result_jans(player.dice_roll_count))
}
/// Determines if someone has won the game
@ -864,10 +1032,12 @@ impl GameEvent {
}
}
pub fn get_mirror(&self) -> Self {
pub fn get_mirror(&self, preserve_player: bool) -> Self {
// let mut mirror = self.clone();
let mirror_player_id = if let Some(player_id) = self.player_id() {
if player_id == 1 {
if preserve_player {
player_id
} else if player_id == 1 {
2
} else {
1
@ -952,7 +1122,7 @@ mod tests {
let mut game_state = init_test_gamestate(TurnStage::MarkPoints);
game_state.schools_enabled = true;
let pid = game_state.active_player_id;
game_state.consume(
let _ = game_state.consume(
&(GameEvent::Mark {
player_id: pid,
points: 13,
@ -964,7 +1134,7 @@ mod tests {
assert_eq!(game_state.turn_stage, TurnStage::HoldOrGoChoice);
// Go
game_state.consume(
let _ = game_state.consume(
&(GameEvent::Go {
player_id: game_state.active_player_id,
}),
@ -978,7 +1148,7 @@ mod tests {
let mut game_state = init_test_gamestate(TurnStage::MarkPoints);
game_state.schools_enabled = true;
let pid = game_state.active_player_id;
game_state.consume(
let _ = game_state.consume(
&(GameEvent::Mark {
player_id: pid,
points: 13,
@ -988,7 +1158,7 @@ mod tests {
CheckerMove::new(1, 3).unwrap(),
CheckerMove::new(1, 3).unwrap(),
);
game_state.consume(
let _ = game_state.consume(
&(GameEvent::Move {
player_id: game_state.active_player_id,
moves,

View file

@ -5,6 +5,7 @@ use crate::game::GameState;
use crate::player::Color;
use log::info;
use std::cmp;
use std::collections::HashSet;
#[derive(std::cmp::PartialEq, Debug)]
pub enum MoveError {
@ -22,7 +23,7 @@ pub enum MoveError {
// sans nombre en excédant est possible
ExitByEffectPossible,
// Sortie avec nombre en excédant d'une dame qui n'est pas la plus éloignée
ExitNotFasthest,
ExitNotFarthest,
// Jeu dans un cadran que l'adversaire peut encore remplir
OpponentCanFillQuarter,
// remplir cadran si possible & conserver cadran rempli si possible ----
@ -81,7 +82,8 @@ impl MoveRules {
let is_allowed = self.moves_allowed(moves);
// let is_allowed = self.moves_allowed(moves, ignored_rules);
if is_allowed.is_err() {
info!("Move not allowed : {:?}", is_allowed.unwrap_err());
println!("Move not allowed : {:?}", is_allowed.unwrap_err());
// info!("Move not allowed : {:?}", is_allowed.unwrap_err());
false
} else {
true
@ -99,6 +101,10 @@ impl MoveRules {
if let Ok((field_count, Some(field_color))) = self.board.get_field_checkers(move0_from)
{
if color != field_color || field_count < 2 {
println!(
"Move not physically possible 1. field_color {:?}, count {}",
field_color, field_count
);
info!("Move not physically possible");
return false;
}
@ -110,6 +116,7 @@ impl MoveRules {
if !self.board.passage_possible(color, &moves.0)
|| !self.board.move_possible(color, &chained_move)
{
println!("Tout d'une : Move not physically possible");
info!("Tout d'une : Move not physically possible");
return false;
}
@ -117,6 +124,11 @@ impl MoveRules {
|| !self.board.move_possible(color, &moves.1)
{
// Move is not physically possible
println!("Move not physically possible 2");
println!(
"board: {}, color: {:?} move: {:?}",
self.board, color, moves
);
info!("Move not physically possible");
return false;
}
@ -259,6 +271,9 @@ impl MoveRules {
) -> Result<(), MoveError> {
let filling_moves_sequences = self.get_quarter_filling_moves_sequences();
if !filling_moves_sequences.contains(moves) && !filling_moves_sequences.is_empty() {
if *moves == (CheckerMove::default(), CheckerMove::default()) {
println!("filling moves sequences: {:?}", filling_moves_sequences);
}
return Err(MoveError::MustFillQuarter);
}
Ok(())
@ -329,43 +344,87 @@ impl MoveRules {
return Err(MoveError::ExitByEffectPossible);
}
// - la dame choisie doit être la plus éloignée de la sortie
let mut checkers = self.board.get_color_fields(Color::White);
checkers.sort_by(|a, b| b.0.cmp(&a.0));
let mut farthest = 24;
let mut next_farthest = 24;
let mut has_two_checkers = false;
if let Some((field, count)) = checkers.first() {
farthest = *field;
if *count > 1 {
next_farthest = *field;
has_two_checkers = true;
} else if let Some((field, _count)) = checkers.get(1) {
next_farthest = *field;
has_two_checkers = true;
}
// The chosen checker must be the farthest from exit
// For chained moves (tout d'une), we need to check the board state AFTER the first move
// let board_to_check = if moves.0.get_to() == moves.1.get_from() {
// // Chained move: apply first move to get the board state
// let mut board_copy = self.board.clone();
// let _ = board_copy.move_checker(&Color::White, moves.0);
// board_copy
// } else {
// self.board.clone()
// };
let mut board_to_check = self.board.clone();
let farthest_on_move1 = Self::get_board_exit_farthest(&board_to_check);
let _ = board_to_check.move_checker(&Color::White, moves.0);
let farthest_on_move2 = Self::get_board_exit_farthest(&board_to_check);
let (is_move1_exedant, is_move2_exedant) = self.move_excedants(moves);
if (is_move1_exedant && moves.0.get_from() != farthest_on_move1)
|| (is_move2_exedant && moves.1.get_from() != farthest_on_move2)
{
return Err(MoveError::ExitNotFarthest);
}
// s'il reste au moins deux dames, on vérifie que les plus éloignées soint choisies
if has_two_checkers {
if moves.0.get_to() == 0 && moves.1.get_to() == 0 {
// Deux coups sortants en excédant
if cmp::max(moves.0.get_from(), moves.1.get_from()) > next_farthest {
return Err(MoveError::ExitNotFasthest);
}
} else {
// Un seul coup sortant en excédant le coup sortant doit concerner la plus éloignée du bord
let exit_move_field = if moves.0.get_to() == 0 {
moves.0.get_from()
} else {
moves.1.get_from()
};
if exit_move_field != farthest {
return Err(MoveError::ExitNotFasthest);
}
Ok(())
}
fn move_excedants(&self, moves: &(CheckerMove, CheckerMove)) -> (bool, bool) {
let move1to = if moves.0.get_to() == 0 {
25
} else {
moves.0.get_to()
};
let dist1 = move1to - moves.0.get_from();
let move2to = if moves.1.get_to() == 0 {
25
} else {
moves.1.get_to()
};
let dist2 = move2to - moves.1.get_from();
let dist_min = cmp::min(dist1, dist2);
let dist_max = cmp::max(dist1, dist2);
let dice_min = cmp::min(self.dice.values.0, self.dice.values.1) as usize;
let dice_max = cmp::max(self.dice.values.0, self.dice.values.1) as usize;
let min_excedant = dist_min != 0 && dist_min < dice_min;
let max_excedant = dist_max != 0 && dist_max < dice_max;
if dist_min == dist1 {
(min_excedant, max_excedant)
} else {
(max_excedant, min_excedant)
}
}
fn get_board_exit_farthest(board: &Board) -> Field {
let mut checkers = board.get_color_fields(Color::White);
checkers.sort_by(|a, b| a.0.cmp(&b.0));
let mut farthest = 25;
// Check if we have a filled quarter that must be preserved
let has_filled_quarter = board.any_quarter_filled(Color::White);
if has_filled_quarter {
// When a quarter is filled, we can only exit from fields with >2 checkers
// Find the farthest field with >2 checkers (removing one won't break the quarter)
let available_checkers: Vec<_> =
checkers.iter().filter(|(_, count)| *count > 2).collect();
if !available_checkers.is_empty() {
// Use the farthest available checker (that won't break the quarter)
farthest = available_checkers[0].0;
}
}
Ok(())
if farthest == 25 {
if let Some((field, _)) = checkers.first() {
farthest = *field;
}
}
farthest
}
pub fn get_possible_moves_sequences(
@ -403,6 +462,11 @@ impl MoveRules {
if empty_removed.count() > 0 {
moves_seqs.retain(|(c1, c2)| *c1 != EMPTY_MOVE && *c2 != EMPTY_MOVE);
}
// deduplicate
let mut set = HashSet::new();
moves_seqs.retain(|x| set.insert(*x));
moves_seqs
}
@ -483,6 +547,7 @@ impl MoveRules {
let mut moves_seqs = Vec::new();
let color = &Color::White;
let forbid_exits = self.has_checkers_outside_last_quarter();
// println!("==== First");
for first_move in
self.board
.get_possible_moves(*color, dice1, with_excedents, false, forbid_exits)
@ -496,23 +561,59 @@ impl MoveRules {
// XXX : the goal here is to replicate moves_allowed() checks without using get_possible_moves_sequences to
// avoid an infinite loop...
let mut has_second_dice_move = false;
// println!(" ==== Second");
for second_move in
board2.get_possible_moves(*color, dice2, with_excedents, true, forbid_exits)
{
if self.check_corner_rules(&(first_move, second_move)).is_ok()
if self
.check_corner_rules(&(first_move, second_move))
// .inspect_err(|e| {
// println!(
// " 2nd (corner rule): {:?} - {:?}, {:?}",
// e, first_move, second_move
// )
// })
.is_ok()
&& self
.check_opponent_can_fill_quarter_rule(&(first_move, second_move))
// .inspect_err(|e| {
// println!(
// " 2nd (op fill quarter): {:?} - {:?}, {:?}",
// e, first_move, second_move
// )
// })
.is_ok()
&& !(self.is_move_by_puissance(&(first_move, second_move))
&& self.can_take_corner_by_effect())
&& (ignored_rules.contains(&TricTracRule::Exit)
|| self.check_exit_rules(&(first_move, second_move)).is_ok())
|| self
.check_exit_rules(&(first_move, second_move))
// .inspect_err(|e| {
// println!(
// " 2nd (exit rule): {:?} - {:?}, {:?}",
// e, first_move, second_move
// )
// })
.is_ok())
&& (ignored_rules.contains(&TricTracRule::MustFillQuarter)
|| self
.check_must_fill_quarter_rule(&(first_move, second_move))
// .inspect_err(|e| {
// println!(
// " 2nd: {:?} - {:?}, {:?} for {:?}",
// e, first_move, second_move, self.board
// )
// })
.is_ok())
{
moves_seqs.push((first_move, second_move));
if second_move.get_to() == 0
&& first_move.get_to() == 0
&& second_move.get_from() < first_move.get_from()
{
moves_seqs.push((second_move, first_move));
} else {
moves_seqs.push((first_move, second_move));
}
has_second_dice_move = true;
}
}
@ -763,7 +864,7 @@ mod tests {
CheckerMove::new(20, 0).unwrap(),
CheckerMove::new(23, 0).unwrap(),
);
assert_eq!(Err(MoveError::ExitNotFasthest), state.moves_allowed(&moves));
assert_eq!(Err(MoveError::ExitNotFarthest), state.moves_allowed(&moves));
let moves = (
CheckerMove::new(20, 0).unwrap(),
CheckerMove::new(21, 0).unwrap(),
@ -784,6 +885,19 @@ mod tests {
);
assert!(state.moves_follows_dices(&moves));
assert!(state.moves_allowed(&moves).is_ok());
state.board.set_positions(
&Color::White,
[
-5, -2, -2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 2, 3, 2, 3,
],
);
state.dice.values = (4, 5);
let moves = (
CheckerMove::new(19, 24).unwrap(),
CheckerMove::new(22, 0).unwrap(),
);
assert!(state.moves_allowed(&moves).is_ok());
}
#[test]
@ -1293,5 +1407,202 @@ mod tests {
vec![moves],
state.get_possible_moves_sequences(true, vec![])
);
state.board.set_positions(
&Color::White,
[
-8, -4, -1, 0, 0, 0, 0, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 2, 2, 2,
],
);
state.dice.values = (1, 4);
let moves = (
CheckerMove::new(21, 22).unwrap(),
CheckerMove::new(22, 0).unwrap(),
);
assert_eq!(
vec![moves],
state.get_possible_moves_sequences(true, vec![])
);
state.dice.values = (5, 3);
state.board.set_positions(
&crate::Color::White,
[
-8, -3, -1, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3,
],
);
let moves = (
CheckerMove::new(23, 0).unwrap(),
CheckerMove::new(24, 0).unwrap(),
);
assert_eq!(
vec![moves],
state.get_possible_moves_sequences(true, vec![])
);
let mut board = Board::new();
board.set_positions(
&crate::Color::White,
[
-3, -3, -2, -2, -2, -2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 3, 8,
],
);
let state = MoveRules::new(&Color::Black, &board, Dice { values: (5, 3) });
let moves = (
// CheckerMove::new(2, 0).unwrap(),
// CheckerMove::new(1, 0).unwrap(),
CheckerMove::new(23, 0).unwrap(),
CheckerMove::new(24, 0).unwrap(),
);
assert_eq!(
vec![moves],
state.get_possible_moves_sequences(true, vec![])
);
let mut board = Board::new();
board.set_positions(
&crate::Color::White,
[
-7, -4, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, 0, 0, 3, 2, 1, 2, 3, 4,
],
);
let state = MoveRules::new(&Color::White, &board, Dice { values: (2, 6) });
let moves = vec![
(
CheckerMove::new(23, 0).unwrap(),
CheckerMove::new(19, 21).unwrap(),
),
(
CheckerMove::new(19, 21).unwrap(),
CheckerMove::new(23, 0).unwrap(),
),
];
assert_eq!(moves, state.get_possible_moves_sequences(true, vec![]));
}
#[test]
fn get_possible_moves_sequences_by_dices() {
let mut state = MoveRules::default();
state.dice.values = (5, 3);
state.board.set_positions(
&crate::Color::White,
[
-8, -3, -1, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3,
],
);
let moves = (
CheckerMove::new(23, 0).unwrap(),
CheckerMove::new(24, 0).unwrap(),
);
assert_eq!(
vec![moves],
state.get_possible_moves_sequences_by_dices(
state.dice.values.0,
state.dice.values.1,
true,
false,
vec![]
)
);
state.dice.values = (4, 5);
state.board.set_positions(
&crate::Color::White,
[
-5, -2, -2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 2, 3, 2, 3,
],
);
let moves = vec![(
CheckerMove::new(19, 23).unwrap(),
CheckerMove::new(22, 0).unwrap(),
)];
assert_eq!(
moves,
state.get_possible_moves_sequences_by_dices(
state.dice.values.0,
state.dice.values.1,
true,
false,
vec![]
)
);
let moves = vec![(
CheckerMove::new(19, 24).unwrap(),
CheckerMove::new(22, 0).unwrap(),
)];
assert_eq!(
moves,
state.get_possible_moves_sequences_by_dices(
state.dice.values.1,
state.dice.values.0,
true,
false,
vec![]
)
);
let mut board = Board::new();
board.set_positions(
&crate::Color::White,
[
-7, -4, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, 0, 0, 3, 2, 1, 2, 3, 4,
],
);
let state = MoveRules::new(&Color::White, &board, Dice { values: (2, 6) });
let moves = (
CheckerMove::new(19, 21).unwrap(),
CheckerMove::new(23, 0).unwrap(),
);
assert_eq!(
vec![moves],
state.get_possible_moves_sequences_by_dices(
state.dice.values.0,
state.dice.values.1,
true,
false,
vec![]
)
);
}
#[test]
fn check_exit_rules() {
let mut state = MoveRules::default();
state.dice.values = (4, 5);
state.board.set_positions(
&crate::Color::White,
[
-5, -2, -2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 2, 3, 2, 3,
],
);
let moves = (
CheckerMove::new(19, 23).unwrap(),
CheckerMove::new(22, 0).unwrap(),
);
assert!(state.check_exit_rules(&moves).is_ok());
let moves = (
CheckerMove::new(19, 24).unwrap(),
CheckerMove::new(22, 0).unwrap(),
);
assert!(state.check_exit_rules(&moves).is_ok());
}
#[test]
fn check_must_fill_quarter_rule() {
let mut state = MoveRules::default();
state.dice.values = (4, 5);
state.board.set_positions(
&crate::Color::White,
[
-5, -2, -2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 2, 3, 2, 3,
],
);
let moves = (
CheckerMove::new(19, 24).unwrap(),
CheckerMove::new(22, 0).unwrap(),
);
assert!(state.check_must_fill_quarter_rule(&moves).is_ok());
}
}

View file

@ -69,10 +69,26 @@ pub type PossibleJans = HashMap<Jan, Vec<(CheckerMove, CheckerMove)>>;
pub trait PossibleJansMethods {
fn push(&mut self, jan: Jan, cmoves: (CheckerMove, CheckerMove));
fn merge(&mut self, other: Self);
fn mirror(&self) -> Self;
// fn get_points(&self) -> u8;
}
impl PossibleJansMethods for PossibleJans {
fn mirror(&self) -> Self {
self.clone()
.into_iter()
.map(|(jan, moves)| {
(
jan,
moves
.into_iter()
.map(|(m1, m2)| (m1.mirror(), m2.mirror()))
.collect(),
)
})
.collect()
}
fn push(&mut self, jan: Jan, cmoves: (CheckerMove, CheckerMove)) {
if let Some(ways) = self.get_mut(&jan) {
if !ways.contains(&cmoves) {

View file

@ -16,3 +16,11 @@ pub use board::CheckerMove;
mod dice;
pub use dice::{Dice, DiceRoller};
pub mod training_common;
// python interface "trictrac_engine" (for AI training..)
mod pyengine;
// C++ interface via cxx.rs (for OpenSpiel C++ integration)
pub mod cxxengine;

View file

@ -1,9 +1,11 @@
use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
use std::fmt;
// This just makes it easier to dissern between a player id and any ol' u64
pub type PlayerId = u64;
#[pyclass(eq, eq_int)]
#[derive(Copy, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Color {
White,
@ -46,6 +48,16 @@ impl Player {
}
}
pub fn mirror(&self) -> Self {
let mut player = self.clone();
player.color = if self.color == Color::White {
Color::Black
} else {
Color::White
};
player
}
pub fn to_bits_string(&self) -> String {
format!(
"{:0>4b}{:0>4b}{:b}{:b}",
@ -59,8 +71,8 @@ impl Player {
}
let points = u8::from_str_radix(&bits[0..4], 2).map_err(|e| e.to_string())?;
let holes = u8::from_str_radix(&bits[4..8], 2).map_err(|e| e.to_string())?;
let can_bredouille = bits.chars().nth(8).unwrap() == '1';
let can_big_bredouille = bits.chars().nth(9).unwrap() == '1';
let can_bredouille = bits.chars().nth(8).ok_or_else(|| "8th bit unreadable")? == '1';
let can_big_bredouille = bits.chars().nth(9).ok_or_else(|| "9th bit unreadable")? == '1';
Ok(Player {
name,

146
store/src/pyengine.rs Normal file
View file

@ -0,0 +1,146 @@
//! # Expose trictrac game state and rules in a python module
use pyo3::prelude::*;
use crate::dice::Dice;
use crate::game::{GameEvent, GameState, Stage, TurnStage};
use crate::player::PlayerId;
use crate::training_common::{get_valid_action_indices, TrictracAction};
#[pyclass]
struct TricTrac {
game_state: GameState,
}
#[pymethods]
impl TricTrac {
#[new]
fn new() -> Self {
let mut game_state = GameState::new(false); // schools_enabled = false
// Initialiser 2 joueurs
game_state.init_player("player1");
game_state.init_player("player2");
// Commencer la partie avec le joueur 1
let _ = game_state.consume(&GameEvent::BeginGame { goes_first: 1 });
TricTrac { game_state }
}
fn needs_roll(&self) -> bool {
self.game_state.turn_stage == TurnStage::RollWaiting
}
fn is_game_ended(&self) -> bool {
self.game_state.stage == Stage::Ended
}
// 0 or 1
fn current_player_idx(&self) -> u64 {
self.game_state.active_player_id - 1
}
fn get_legal_actions(&self, player_idx: u64) -> Vec<usize> {
if player_idx == self.current_player_idx() {
if player_idx == 0 {
get_valid_action_indices(&self.game_state).unwrap()
} else {
let mirror = self.game_state.mirror();
get_valid_action_indices(&mirror).unwrap()
}
} else {
vec![]
}
}
fn action_to_string(&self, player_idx: u64, action_idx: usize) -> String {
TrictracAction::from_action_index(action_idx)
.map(|a| format!("{}:{}", player_idx, a))
.unwrap_or("unknown action".into())
}
fn apply_dice_roll(&mut self, dices: (u8, u8)) -> PyResult<()> {
let player_id = self.game_state.active_player_id;
if self.game_state.turn_stage != TurnStage::RollWaiting {
return Err(pyo3::exceptions::PyRuntimeError::new_err(
"Not in RollWaiting stage",
));
}
let dice = Dice { values: dices };
let _ = self
.game_state
.consume(&GameEvent::RollResult { player_id, dice });
Ok(())
}
fn apply_action(&mut self, action_idx: usize) -> PyResult<()> {
if let Some(event) = TrictracAction::from_action_index(action_idx).and_then(|a| {
let needs_mirror = self.game_state.active_player_id == 2;
let game_state = if needs_mirror {
&self.game_state.mirror()
} else {
&self.game_state
};
a.to_event(game_state)
.map(|e| if needs_mirror { e.get_mirror(false) } else { e })
}) {
if self.game_state.validate(&event) {
let _ = self.game_state.consume(&event);
return Ok(());
} else {
return Err(pyo3::exceptions::PyRuntimeError::new_err(
"Action is invalid",
));
}
}
Err(pyo3::exceptions::PyRuntimeError::new_err(
"Could not apply action",
))
}
/// Get a player total score (holes & points)
fn get_score(&self, player_id: PlayerId) -> i32 {
if let Some(player) = self.game_state.players.get(&player_id) {
player.holes as i32 * 12 + player.points as i32
} else {
-1
}
}
fn get_players_scores(&self) -> [i32; 2] {
[self.get_score(1), self.get_score(2)]
}
fn get_tensor(&self, player_idx: u64) -> Vec<i8> {
if player_idx == 0 {
self.game_state.to_vec()
} else {
self.game_state.mirror().to_vec()
}
}
fn get_observation_string(&self, player_idx: u64) -> String {
if player_idx == 0 {
format!("{}", self.game_state)
} else {
format!("{}", self.game_state.mirror())
}
}
/// Afficher l'état du jeu (pour le débogage)
fn __str__(&self) -> String {
format!("{}", self.game_state)
}
}
/// A Python module implemented in Rust. The name of this function must match
/// the `lib.name` setting in the `Cargo.toml`, else Python will not be able to
/// import the module.
#[pymodule]
fn trictrac_store(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<TricTrac>()?;
Ok(())
}

View file

@ -3,11 +3,12 @@
use std::cmp::{max, min};
use std::fmt::{Debug, Display, Formatter};
use crate::board::Board;
use crate::{CheckerMove, Dice, GameEvent, GameState};
use serde::{Deserialize, Serialize};
use store::{CheckerMove, GameEvent, GameState};
// 1 (Roll) + 1 (Go) + mouvements possibles
// Pour les mouvements : 2*16*16 = 514 (choix du dé + choix de la dame 0-15 pour chaque from)
// 1 (Roll) + 1 (Go) + 512 (mouvements possibles)
// avec 512 = 2 (choix du dé) * 16 * 16 (choix de la dame 0-15 pour chaque from)
pub const ACTION_SPACE_SIZE: usize = 514;
/// Types d'actions possibles dans le jeu
@ -15,7 +16,8 @@ pub const ACTION_SPACE_SIZE: usize = 514;
pub enum TrictracAction {
/// Lancer les dés
Roll,
/// Continuer après avoir gagné un trou
/// Faire un nouveau 'relevé' (repositionnement des dames à l'état de départ) après avoir gagné un trou,
/// au lieu de continuer dans la position courante
Go,
/// Effectuer un mouvement de pions
Move {
@ -59,6 +61,22 @@ impl TrictracAction {
}
}
pub fn mirror(&self) -> TrictracAction {
match self {
TrictracAction::Roll => TrictracAction::Roll,
TrictracAction::Go => TrictracAction::Go,
TrictracAction::Move {
dice_order,
checker1,
checker2,
} => TrictracAction::Move {
dice_order: *dice_order,
checker1: if *checker1 == 0 { 0 } else { 25 - checker1 },
checker2: if *checker2 == 0 { 0 } else { 25 - checker2 },
},
}
}
pub fn to_event(&self, state: &GameState) -> Option<GameEvent> {
match self {
TrictracAction::Roll => {
@ -93,13 +111,17 @@ impl TrictracAction {
(state.dice.values.1, state.dice.values.0)
};
let color = &store::Color::White;
let color = &crate::Color::White;
let from1 = state
.board
.get_checker_field(color, *checker1 as u8)
.unwrap_or(0);
let mut to1 = from1 + dice1 as usize;
let checker_move1 = store::CheckerMove::new(from1, to1).unwrap_or_default();
if 24 < to1 {
// exit board
to1 = 0;
}
let checker_move1 = CheckerMove::new(from1, to1).unwrap_or_default();
let mut tmp_board = state.board.clone();
let move_result = tmp_board.move_checker(color, checker_move1);
@ -111,6 +133,10 @@ impl TrictracAction {
.get_checker_field(color, *checker2 as u8)
.unwrap_or(0);
let mut to2 = from2 + dice2 as usize;
if 24 < to2 {
// exit board
to2 = 0;
}
// Gestion prise de coin par puissance
let opp_rest_field = 13;
@ -119,8 +145,8 @@ impl TrictracAction {
to2 -= 1;
}
let checker_move1 = store::CheckerMove::new(from1, to1).unwrap_or_default();
let checker_move2 = store::CheckerMove::new(from2, to2).unwrap_or_default();
let checker_move1 = CheckerMove::new(from1, to1).unwrap_or_default();
let checker_move2 = CheckerMove::new(from2, to2).unwrap_or_default();
Some(GameEvent::Move {
player_id: state.active_player_id,
@ -166,33 +192,11 @@ impl TrictracAction {
pub fn action_space_size() -> usize {
ACTION_SPACE_SIZE
}
// pub fn to_game_event(&self, player_id: PlayerId, dice: Dice) -> GameEvent {
// match action {
// TrictracAction::Roll => Some(GameEvent::Roll { player_id }),
// TrictracAction::Mark => Some(GameEvent::Mark { player_id, points }),
// TrictracAction::Go => Some(GameEvent::Go { player_id }),
// TrictracAction::Move {
// dice_order,
// from1,
// from2,
// } => {
// // Effectuer un mouvement
// let checker_move1 = store::CheckerMove::new(move1.0, move1.1).unwrap_or_default();
// let checker_move2 = store::CheckerMove::new(move2.0, move2.1).unwrap_or_default();
//
// Some(GameEvent::Move {
// player_id: self.agent_player_id,
// moves: (checker_move1, checker_move2),
// })
// }
// };
// }
}
/// Obtient les actions valides pour l'état de jeu actuel
pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
use store::TurnStage;
pub fn get_valid_actions(game_state: &GameState) -> anyhow::Result<Vec<TrictracAction>> {
use crate::TurnStage;
let mut valid_actions = Vec::new();
@ -206,7 +210,7 @@ pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
}
TurnStage::MarkPoints | TurnStage::MarkAdvPoints | TurnStage::RollWaiting => {
// valid_actions.push(TrictracAction::Mark);
panic!(
anyhow::bail!(
"get_valid_actions not implemented for turn stage {:?}",
game_state.turn_stage
);
@ -215,54 +219,73 @@ pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
valid_actions.push(TrictracAction::Go);
// Ajoute aussi les mouvements possibles
let rules = store::MoveRules::new(&color, &game_state.board, game_state.dice);
let rules = crate::MoveRules::new(&color, &game_state.board, game_state.dice);
let possible_moves = rules.get_possible_moves_sequences(true, vec![]);
// Modififier checker_moves_to_trictrac_action si on doit gérer Black
assert_eq!(color, store::Color::White);
for (move1, move2) in possible_moves {
valid_actions.push(checker_moves_to_trictrac_action(
&move1, &move2, &color, game_state,
));
)?);
}
}
TurnStage::Move => {
let rules = store::MoveRules::new(&color, &game_state.board, game_state.dice);
let rules = crate::MoveRules::new(&color, &game_state.board, game_state.dice);
let mut possible_moves = rules.get_possible_moves_sequences(true, vec![]);
if possible_moves.is_empty() {
// Empty move
possible_moves.push((CheckerMove::default(), CheckerMove::default()));
}
// Modififier checker_moves_to_trictrac_action si on doit gérer Black
assert_eq!(color, store::Color::White);
for (move1, move2) in possible_moves {
valid_actions.push(checker_moves_to_trictrac_action(
&move1, &move2, &color, game_state,
));
)?);
}
}
}
}
if valid_actions.is_empty() {
panic!("empty valid_actions for state {game_state}");
anyhow::bail!("empty valid_actions for state {game_state}");
}
valid_actions
Ok(valid_actions)
}
// Valid only for White player
fn checker_moves_to_trictrac_action(
move1: &CheckerMove,
move2: &CheckerMove,
color: &store::Color,
state: &crate::GameState,
) -> TrictracAction {
color: &crate::Color,
state: &GameState,
) -> anyhow::Result<TrictracAction> {
let dice = &state.dice;
let board = &state.board;
if color == &crate::Color::Black {
// Moves are already 'white', so we don't mirror them
white_checker_moves_to_trictrac_action(
move1,
move2,
// &move1.clone().mirror(),
// &move2.clone().mirror(),
dice,
&board.clone().mirror(),
)
// .map(|a| a.mirror())
} else {
white_checker_moves_to_trictrac_action(move1, move2, dice, board)
}
}
fn white_checker_moves_to_trictrac_action(
move1: &CheckerMove,
move2: &CheckerMove,
dice: &Dice,
board: &Board,
) -> anyhow::Result<TrictracAction> {
let to1 = move1.get_to();
let to2 = move2.get_to();
let from1 = move1.get_from();
let from2 = move2.get_from();
let dice = state.dice;
let mut diff_move1 = if to1 > 0 {
// Mouvement sans sortie
@ -298,36 +321,36 @@ fn checker_moves_to_trictrac_action(
}
let dice_order = diff_move1 == dice.values.0 as usize;
let checker1 = state.board.get_field_checker(color, from1) as usize;
let mut tmp_board = state.board.clone();
let checker1 = board.get_field_checker(&crate::Color::White, from1) as usize;
let mut tmp_board = board.clone();
// should not raise an error for a valid action
let move_res = tmp_board.move_checker(color, *move1);
if move_res.is_err() {
panic!("error while moving checker {move_res:?}");
}
let checker2 = tmp_board.get_field_checker(color, from2) as usize;
TrictracAction::Move {
tmp_board.move_checker(&crate::Color::White, *move1)?;
let checker2 = tmp_board.get_field_checker(&crate::Color::White, from2) as usize;
Ok(TrictracAction::Move {
dice_order,
checker1,
checker2,
}
})
}
/// Retourne les indices des actions valides
pub fn get_valid_action_indices(game_state: &crate::GameState) -> Vec<usize> {
get_valid_actions(game_state)
pub fn get_valid_action_indices(game_state: &GameState) -> anyhow::Result<Vec<usize>> {
let actions = get_valid_actions(game_state)?;
Ok(actions
.into_iter()
.map(|action| action.to_action_index())
.collect()
.collect())
}
/// Sélectionne une action valide aléatoire
pub fn sample_valid_action(game_state: &crate::GameState) -> Option<TrictracAction> {
use rand::{seq::SliceRandom, thread_rng};
pub fn sample_valid_action(game_state: &GameState) -> Option<TrictracAction> {
use rand::{prelude::IndexedRandom, rng};
let valid_actions = get_valid_actions(game_state);
let mut rng = thread_rng();
valid_actions.choose(&mut rng).cloned()
let mut rng = rng();
valid_actions
.map(|va| va.choose(&mut rng).cloned())
.unwrap_or_default()
}
#[cfg(test)]
@ -355,4 +378,83 @@ mod tests {
};
assert_eq!(Some(action), TrictracAction::from_action_index(54));
}
#[test]
fn get_valid_actions() {
let mut state = GameState::new_with_players("white", "black");
state.active_player_id = 2;
state.dice = Dice { values: (5, 3) };
state.turn_stage = crate::TurnStage::Move;
state.board.set_positions(
&crate::Color::White,
[
-3, -3, -2, -2, -2, -2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 3, 8,
],
);
let actions = vec![TrictracAction::Move {
dice_order: true,
checker1: 11,
checker2: 13,
}];
assert_eq!(Some(actions), super::get_valid_actions(&state).ok());
}
#[test]
fn checker_moves_to_trictrac_action() {
let mut state = GameState::new_with_players("white", "black");
state.turn_stage = crate::TurnStage::Move;
state.dice = Dice { values: (5, 3) };
// White player
state.active_player_id = 1;
state.board.set_positions(
&crate::Color::White,
[
-8, -3, -1, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3,
],
);
let ttaction = super::checker_moves_to_trictrac_action(
&CheckerMove::new(23, 0).unwrap(),
&CheckerMove::new(24, 0).unwrap(),
&crate::Color::White,
&state,
);
assert_eq!(
Some(TrictracAction::Move {
dice_order: true,
checker1: 11,
checker2: 13, // because the 11th has left
}),
ttaction.ok()
);
// Black player
state.active_player_id = 2;
state.board.set_positions(
&crate::Color::White,
[
-3, -3, -2, -2, -2, -2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 3, 8,
],
);
let ttaction = super::checker_moves_to_trictrac_action(
// &CheckerMove::new(2, 0).unwrap(),
// &CheckerMove::new(1, 0).unwrap(),
&CheckerMove::new(23, 0).unwrap(),
&CheckerMove::new(24, 0).unwrap(),
&crate::Color::Black,
&state,
);
assert_eq!(
Some(TrictracAction::Move {
dice_order: true,
checker1: 11,
checker2: 13, // because the 11th has left
}),
ttaction.ok()
);
}
}