Compare commits
7 commits
a3ccfc828e
...
5eda97f461
| Author | SHA1 | Date | |
|---|---|---|---|
| 5eda97f461 | |||
| c503771e76 | |||
| a841a86d96 | |||
| 8df32175f8 | |||
| 78ac476919 | |||
| a0f6ee99b2 | |||
| daf84f29ab |
28 changed files with 2531 additions and 1379 deletions
3345
Cargo.lock
generated
3345
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +1,5 @@
|
||||||
[package]
|
[package]
|
||||||
name = "bot"
|
name = "trictrac-bot"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
|
@ -13,10 +13,10 @@ path = "src/burnrl/main.rs"
|
||||||
pretty_assertions = "1.4.0"
|
pretty_assertions = "1.4.0"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
store = { path = "../store" }
|
trictrac-store = { path = "../store" }
|
||||||
rand = "0.8"
|
rand = "0.9"
|
||||||
env_logger = "0.10"
|
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" }
|
burn-rl = { git = "https://github.com/yunjhongwu/burn-rl-examples.git", package = "burn-rl" }
|
||||||
log = "0.4.20"
|
log = "0.4.20"
|
||||||
confy = "1.0.0"
|
confy = "1.0.0"
|
||||||
|
|
|
||||||
5
bot/python/test.py
Normal file
5
bot/python/test.py
Normal 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()))
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
use crate::training_common;
|
|
||||||
use burn::{prelude::Backend, tensor::Tensor};
|
use burn::{prelude::Backend, tensor::Tensor};
|
||||||
use burn_rl::base::{Action, Environment, Snapshot, State};
|
use burn_rl::base::{Action, Environment, Snapshot, State};
|
||||||
use rand::{thread_rng, Rng};
|
use rand::{rng, Rng};
|
||||||
use store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
|
use trictrac_store::training_common;
|
||||||
|
use trictrac_store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
|
||||||
|
|
||||||
const ERROR_REWARD: f32 = -1.0012121;
|
const ERROR_REWARD: f32 = -1.0012121;
|
||||||
const REWARD_VALID_MOVE: f32 = 1.0012121;
|
const REWARD_VALID_MOVE: f32 = 1.0012121;
|
||||||
|
|
@ -52,10 +52,10 @@ pub struct TrictracAction {
|
||||||
|
|
||||||
impl Action for TrictracAction {
|
impl Action for TrictracAction {
|
||||||
fn random() -> Self {
|
fn random() -> Self {
|
||||||
use rand::{thread_rng, Rng};
|
use rand::{rng, Rng};
|
||||||
let mut rng = thread_rng();
|
let mut rng = rng();
|
||||||
TrictracAction {
|
TrictracAction {
|
||||||
index: rng.gen_range(0..Self::size() as u32),
|
index: rng.random_range(0..Self::size() as u32),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -288,11 +288,11 @@ impl TrictracEnvironment {
|
||||||
// reward += REWARD_VALID_MOVE;
|
// reward += REWARD_VALID_MOVE;
|
||||||
// Simuler le résultat des dés après un Roll
|
// Simuler le résultat des dés après un Roll
|
||||||
if matches!(action, TrictracAction::Roll) {
|
if matches!(action, TrictracAction::Roll) {
|
||||||
let mut rng = thread_rng();
|
let mut rng = rng();
|
||||||
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
|
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
|
||||||
let dice_event = GameEvent::RollResult {
|
let dice_event = GameEvent::RollResult {
|
||||||
player_id: self.active_player_id,
|
player_id: self.active_player_id,
|
||||||
dice: store::Dice {
|
dice: trictrac_store::Dice {
|
||||||
values: dice_values,
|
values: dice_values,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
@ -340,18 +340,18 @@ impl TrictracEnvironment {
|
||||||
|
|
||||||
// Exécuter l'action selon le turn_stage
|
// Exécuter l'action selon le turn_stage
|
||||||
let mut calculate_points = false;
|
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 {
|
let event = match self.game.turn_stage {
|
||||||
TurnStage::RollDice => GameEvent::Roll {
|
TurnStage::RollDice => GameEvent::Roll {
|
||||||
player_id: self.opponent_id,
|
player_id: self.opponent_id,
|
||||||
},
|
},
|
||||||
TurnStage::RollWaiting => {
|
TurnStage::RollWaiting => {
|
||||||
let mut rng = thread_rng();
|
let mut rng = rng();
|
||||||
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
|
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
|
||||||
calculate_points = true;
|
calculate_points = true;
|
||||||
GameEvent::RollResult {
|
GameEvent::RollResult {
|
||||||
player_id: self.opponent_id,
|
player_id: self.opponent_id,
|
||||||
dice: store::Dice {
|
dice: trictrac_store::Dice {
|
||||||
values: dice_values,
|
values: dice_values,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
@ -371,7 +371,7 @@ impl TrictracEnvironment {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
TurnStage::MarkAdvPoints => {
|
TurnStage::MarkAdvPoints => {
|
||||||
let opponent_color = store::Color::Black;
|
let opponent_color = trictrac_store::Color::Black;
|
||||||
let dice_roll_count = self
|
let dice_roll_count = self
|
||||||
.game
|
.game
|
||||||
.players
|
.players
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
use crate::training_common;
|
|
||||||
use burn::{prelude::Backend, tensor::Tensor};
|
use burn::{prelude::Backend, tensor::Tensor};
|
||||||
use burn_rl::base::{Action, Environment, Snapshot, State};
|
use burn_rl::base::{Action, Environment, Snapshot, State};
|
||||||
use rand::{thread_rng, Rng};
|
use rand::{rng, Rng};
|
||||||
use store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
|
use trictrac_store::training_common;
|
||||||
|
use trictrac_store::{GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
|
||||||
|
|
||||||
const ERROR_REWARD: f32 = -1.0012121;
|
const ERROR_REWARD: f32 = -1.0012121;
|
||||||
const REWARD_RATIO: f32 = 0.1;
|
const REWARD_RATIO: f32 = 0.1;
|
||||||
|
|
@ -48,10 +48,10 @@ pub struct TrictracAction {
|
||||||
|
|
||||||
impl Action for TrictracAction {
|
impl Action for TrictracAction {
|
||||||
fn random() -> Self {
|
fn random() -> Self {
|
||||||
use rand::{thread_rng, Rng};
|
use rand::{rng, Rng};
|
||||||
let mut rng = thread_rng();
|
let mut rng = rng();
|
||||||
TrictracAction {
|
TrictracAction {
|
||||||
index: rng.gen_range(0..Self::size() as u32),
|
index: rng.random_range(0..Self::size() as u32),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -237,7 +237,7 @@ impl TrictracEnvironment {
|
||||||
|
|
||||||
// Mapper l'index d'action sur une action valide
|
// Mapper l'index d'action sur une action valide
|
||||||
let action_index = (action.index as usize) % valid_actions.len();
|
let action_index = (action.index as usize) % valid_actions.len();
|
||||||
Some(valid_actions[action_index].clone())
|
Some(valid_actions[action_index])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Exécute une action Trictrac dans le jeu
|
/// Exécute une action Trictrac dans le jeu
|
||||||
|
|
@ -258,11 +258,11 @@ impl TrictracEnvironment {
|
||||||
// reward += REWARD_VALID_MOVE;
|
// reward += REWARD_VALID_MOVE;
|
||||||
// Simuler le résultat des dés après un Roll
|
// Simuler le résultat des dés après un Roll
|
||||||
if matches!(action, TrictracAction::Roll) {
|
if matches!(action, TrictracAction::Roll) {
|
||||||
let mut rng = thread_rng();
|
let mut rng = rng();
|
||||||
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
|
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
|
||||||
let dice_event = GameEvent::RollResult {
|
let dice_event = GameEvent::RollResult {
|
||||||
player_id: self.active_player_id,
|
player_id: self.active_player_id,
|
||||||
dice: store::Dice {
|
dice: trictrac_store::Dice {
|
||||||
values: dice_values,
|
values: dice_values,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
@ -310,18 +310,18 @@ impl TrictracEnvironment {
|
||||||
|
|
||||||
// Exécuter l'action selon le turn_stage
|
// Exécuter l'action selon le turn_stage
|
||||||
let mut calculate_points = false;
|
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 {
|
let event = match self.game.turn_stage {
|
||||||
TurnStage::RollDice => GameEvent::Roll {
|
TurnStage::RollDice => GameEvent::Roll {
|
||||||
player_id: self.opponent_id,
|
player_id: self.opponent_id,
|
||||||
},
|
},
|
||||||
TurnStage::RollWaiting => {
|
TurnStage::RollWaiting => {
|
||||||
let mut rng = thread_rng();
|
let mut rng = rng();
|
||||||
let dice_values = (rng.gen_range(1..=6), rng.gen_range(1..=6));
|
let dice_values = (rng.random_range(1..=6), rng.random_range(1..=6));
|
||||||
calculate_points = true;
|
calculate_points = true;
|
||||||
GameEvent::RollResult {
|
GameEvent::RollResult {
|
||||||
player_id: self.opponent_id,
|
player_id: self.opponent_id,
|
||||||
dice: store::Dice {
|
dice: trictrac_store::Dice {
|
||||||
values: dice_values,
|
values: dice_values,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
use bot::burnrl::algos::{dqn, dqn_valid, ppo, ppo_valid, sac, sac_valid};
|
use trictrac_bot::burnrl::algos::{dqn, dqn_valid, ppo, ppo_valid, sac, sac_valid};
|
||||||
use bot::burnrl::environment::TrictracEnvironment;
|
use trictrac_bot::burnrl::environment::TrictracEnvironment;
|
||||||
use bot::burnrl::environment_valid::TrictracEnvironment as TrictracEnvironmentValid;
|
use trictrac_bot::burnrl::environment_valid::TrictracEnvironment as TrictracEnvironmentValid;
|
||||||
use bot::burnrl::utils::{demo_model, Config};
|
use trictrac_bot::burnrl::utils::{demo_model, Config};
|
||||||
use burn::backend::{Autodiff, NdArray};
|
use burn::backend::{Autodiff, NdArray};
|
||||||
use burn_rl::base::ElemType;
|
use burn_rl::base::ElemType;
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,16 @@
|
||||||
pub mod burnrl;
|
pub mod burnrl;
|
||||||
pub mod strategy;
|
pub mod strategy;
|
||||||
pub mod training_common;
|
|
||||||
pub mod trictrac_board;
|
pub mod trictrac_board;
|
||||||
|
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use store::{CheckerMove, Color, GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage};
|
|
||||||
pub use strategy::default::DefaultStrategy;
|
pub use strategy::default::DefaultStrategy;
|
||||||
pub use strategy::dqnburn::DqnBurnStrategy;
|
pub use strategy::dqnburn::DqnBurnStrategy;
|
||||||
pub use strategy::erroneous_moves::ErroneousStrategy;
|
pub use strategy::erroneous_moves::ErroneousStrategy;
|
||||||
pub use strategy::random::RandomStrategy;
|
pub use strategy::random::RandomStrategy;
|
||||||
pub use strategy::stable_baselines3::StableBaselines3Strategy;
|
pub use strategy::stable_baselines3::StableBaselines3Strategy;
|
||||||
|
use trictrac_store::{
|
||||||
|
CheckerMove, Color, GameEvent, GameState, PlayerId, PointsRules, Stage, TurnStage,
|
||||||
|
};
|
||||||
|
|
||||||
pub trait BotStrategy: std::fmt::Debug {
|
pub trait BotStrategy: std::fmt::Debug {
|
||||||
fn get_game(&self) -> &GameState;
|
fn get_game(&self) -> &GameState;
|
||||||
|
|
@ -144,7 +145,7 @@ impl Bot {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use store::{Dice, Stage};
|
use trictrac_store::{Dice, Stage};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_new() {
|
fn test_new() {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
|
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
|
||||||
use store::MoveRules;
|
use trictrac_store::MoveRules;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct DefaultStrategy {
|
pub struct DefaultStrategy {
|
||||||
|
|
|
||||||
|
|
@ -4,11 +4,13 @@ use burn_rl::base::{ElemType, Model, State};
|
||||||
|
|
||||||
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
|
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
|
||||||
use log::info;
|
use log::info;
|
||||||
use store::MoveRules;
|
use trictrac_store::MoveRules;
|
||||||
|
|
||||||
use crate::burnrl::algos::dqn;
|
use crate::burnrl::algos::dqn;
|
||||||
use crate::burnrl::environment;
|
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>>;
|
type DqnBurnNetwork = dqn::Net<NdArray<ElemType>>;
|
||||||
|
|
||||||
|
|
@ -152,7 +154,7 @@ impl BotStrategy for DqnBurnStrategy {
|
||||||
to1 = if fto1 < 0 { 0 } else { fto1 as usize };
|
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 mut tmp_board = self.game.board.clone();
|
||||||
let move_res = tmp_board.move_checker(&self.color, checker_move1);
|
let move_res = tmp_board.move_checker(&self.color, checker_move1);
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
|
use crate::{BotStrategy, CheckerMove, Color, GameState, PlayerId};
|
||||||
use store::MoveRules;
|
use rand::{prelude::IndexedRandom, rng};
|
||||||
|
use trictrac_store::MoveRules;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct RandomStrategy {
|
pub struct RandomStrategy {
|
||||||
|
|
@ -51,8 +52,7 @@ impl BotStrategy for RandomStrategy {
|
||||||
let rules = MoveRules::new(&self.color, &self.game.board, self.game.dice);
|
let rules = MoveRules::new(&self.color, &self.game.board, self.game.dice);
|
||||||
let possible_moves = rules.get_possible_moves_sequences(true, vec![]);
|
let possible_moves = rules.get_possible_moves_sequences(true, vec![]);
|
||||||
|
|
||||||
use rand::{seq::SliceRandom, thread_rng};
|
let mut rng = rng();
|
||||||
let mut rng = thread_rng();
|
|
||||||
let choosen_move = possible_moves
|
let choosen_move = possible_moves
|
||||||
.choose(&mut rng)
|
.choose(&mut rng)
|
||||||
.cloned()
|
.cloned()
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ use std::io::Read;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use store::MoveRules;
|
use trictrac_store::MoveRules;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct StableBaselines3Strategy {
|
pub struct StableBaselines3Strategy {
|
||||||
|
|
@ -79,12 +79,12 @@ impl StableBaselines3Strategy {
|
||||||
|
|
||||||
// Convertir l'étape du tour en entier
|
// Convertir l'étape du tour en entier
|
||||||
let turn_stage = match self.game.turn_stage {
|
let turn_stage = match self.game.turn_stage {
|
||||||
store::TurnStage::RollDice => 0,
|
trictrac_store::TurnStage::RollDice => 0,
|
||||||
store::TurnStage::RollWaiting => 1,
|
trictrac_store::TurnStage::RollWaiting => 1,
|
||||||
store::TurnStage::MarkPoints => 2,
|
trictrac_store::TurnStage::MarkPoints => 2,
|
||||||
store::TurnStage::HoldOrGoChoice => 3,
|
trictrac_store::TurnStage::HoldOrGoChoice => 3,
|
||||||
store::TurnStage::Move => 4,
|
trictrac_store::TurnStage::Move => 4,
|
||||||
store::TurnStage::MarkAdvPoints => 5,
|
trictrac_store::TurnStage::MarkAdvPoints => 5,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Récupérer les points et trous des joueurs
|
// Récupérer les points et trous des joueurs
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
// https://docs.rs/board-game/ implementation
|
// https://docs.rs/board-game/ implementation
|
||||||
use crate::training_common::{get_valid_actions, TrictracAction};
|
|
||||||
use board_game::board::{
|
use board_game::board::{
|
||||||
Board as BoardGameBoard, BoardDone, BoardMoves, Outcome, PlayError, Player as BoardGamePlayer,
|
Board as BoardGameBoard, BoardDone, BoardMoves, Outcome, PlayError, Player as BoardGamePlayer,
|
||||||
};
|
};
|
||||||
|
|
@ -8,7 +7,8 @@ use internal_iterator::InternalIterator;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::ops::ControlFlow;
|
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)]
|
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
|
||||||
pub struct TrictracBoard(crate::GameState);
|
pub struct TrictracBoard(crate::GameState);
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
[package]
|
[package]
|
||||||
name = "client_cli"
|
name = "trictrac-client_cli"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
|
@ -11,8 +11,8 @@ bincode = "1.3.3"
|
||||||
pico-args = "0.5.0"
|
pico-args = "0.5.0"
|
||||||
pretty_assertions = "1.4.0"
|
pretty_assertions = "1.4.0"
|
||||||
renet = "0.0.13"
|
renet = "0.0.13"
|
||||||
store = { path = "../store" }
|
trictrac-store = { path = "../store" }
|
||||||
bot = { path = "../bot" }
|
trictrac-bot = { path = "../bot" }
|
||||||
itertools = "0.13.0"
|
itertools = "0.13.0"
|
||||||
env_logger = "0.11.6"
|
env_logger = "0.11.6"
|
||||||
log = "0.4.20"
|
log = "0.4.20"
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
use bot::{
|
use trictrac_bot::{
|
||||||
BotStrategy, DefaultStrategy, DqnBurnStrategy, ErroneousStrategy, RandomStrategy,
|
BotStrategy, DefaultStrategy, DqnBurnStrategy, ErroneousStrategy, RandomStrategy,
|
||||||
StableBaselines3Strategy,
|
StableBaselines3Strategy,
|
||||||
};
|
};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
|
|
||||||
use crate::game_runner::GameRunner;
|
use crate::game_runner::GameRunner;
|
||||||
use store::{CheckerMove, GameEvent, GameState, Stage, TurnStage};
|
use trictrac_store::{CheckerMove, GameEvent, GameState, Stage, TurnStage};
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct AppArgs {
|
pub struct AppArgs {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
use bot::{Bot, BotStrategy};
|
use trictrac_bot::{Bot, BotStrategy};
|
||||||
use log::{debug, error};
|
use log::{debug, error};
|
||||||
use store::{CheckerMove, DiceRoller, GameEvent, GameState, PlayerId, TurnStage};
|
use trictrac_store::{CheckerMove, DiceRoller, GameEvent, GameState, PlayerId, TurnStage};
|
||||||
|
|
||||||
// Application Game
|
// Application Game
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
|
|
@ -117,8 +117,8 @@ impl GameRunner {
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(winner) = self.state.determine_winner() {
|
if let Some(winner) = self.state.determine_winner() {
|
||||||
next_event = Some(store::GameEvent::EndGame {
|
next_event = Some(trictrac_store::GameEvent::EndGame {
|
||||||
reason: store::EndGameReason::PlayerWon { winner },
|
reason: trictrac_store::EndGameReason::PlayerWon { winner },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
42
devenv.lock
42
devenv.lock
|
|
@ -3,10 +3,10 @@
|
||||||
"devenv": {
|
"devenv": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"dir": "src/modules",
|
"dir": "src/modules",
|
||||||
"lastModified": 1753667201,
|
"lastModified": 1770390537,
|
||||||
"owner": "cachix",
|
"owner": "cachix",
|
||||||
"repo": "devenv",
|
"repo": "devenv",
|
||||||
"rev": "4d584d7686a50387f975879788043e55af9f0ad4",
|
"rev": "d6f45cc00829254a9a6f8807c8fbfaf3efa7e629",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|
@ -19,14 +19,14 @@
|
||||||
"flake-compat": {
|
"flake-compat": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1747046372,
|
"lastModified": 1767039857,
|
||||||
"owner": "edolstra",
|
"owner": "NixOS",
|
||||||
"repo": "flake-compat",
|
"repo": "flake-compat",
|
||||||
"rev": "9100a0f413b0c601e0533d1d94ffd501ce2e7885",
|
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
"owner": "edolstra",
|
"owner": "NixOS",
|
||||||
"repo": "flake-compat",
|
"repo": "flake-compat",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
|
|
@ -40,10 +40,10 @@
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1750779888,
|
"lastModified": 1769939035,
|
||||||
"owner": "cachix",
|
"owner": "cachix",
|
||||||
"repo": "git-hooks.nix",
|
"repo": "git-hooks.nix",
|
||||||
"rev": "16ec914f6fb6f599ce988427d9d94efddf25fe6d",
|
"rev": "a8ca480175326551d6c4121498316261cbb5b260",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|
@ -60,10 +60,10 @@
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1709087332,
|
"lastModified": 1762808025,
|
||||||
"owner": "hercules-ci",
|
"owner": "hercules-ci",
|
||||||
"repo": "gitignore.nix",
|
"repo": "gitignore.nix",
|
||||||
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
|
"rev": "cb5e3fdca1de58ccbc3ef53de65bd372b48f567c",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|
@ -74,24 +74,40 @@
|
||||||
},
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1753432016,
|
"lastModified": 1770136044,
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "6027c30c8e9810896b92429f0092f624f7b1aace",
|
"rev": "e576e3c9cf9bad747afcddd9e34f51d18c855b4e",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"ref": "nixpkgs-unstable",
|
"ref": "nixos-25.11",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"type": "github"
|
"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": {
|
"root": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"devenv": "devenv",
|
"devenv": "devenv",
|
||||||
"git-hooks": "git-hooks",
|
"git-hooks": "git-hooks",
|
||||||
"nixpkgs": "nixpkgs",
|
"nixpkgs": "nixpkgs",
|
||||||
|
"nixpkgs-cmake3": "nixpkgs-cmake3",
|
||||||
"pre-commit-hooks": [
|
"pre-commit-hooks": [
|
||||||
"git-hooks"
|
"git-hooks"
|
||||||
]
|
]
|
||||||
|
|
|
||||||
34
devenv.nix
34
devenv.nix
|
|
@ -1,13 +1,16 @@
|
||||||
{ pkgs, ... }:
|
{ inputs, pkgs, ... }:
|
||||||
|
|
||||||
|
let
|
||||||
|
pkgs-cmake3 = import inputs.nixpkgs-cmake3 { system = pkgs.stdenv.system; };
|
||||||
|
in
|
||||||
{
|
{
|
||||||
|
|
||||||
packages = [
|
packages = [
|
||||||
|
|
||||||
# pour burn-rs
|
# pour burn-rs
|
||||||
pkgs.SDL2_gfx
|
pkgs.SDL2_gfx
|
||||||
# (compilation sdl2-sys)
|
# (compilation sdl2-sys)
|
||||||
pkgs.cmake
|
pkgs-cmake3.cmake
|
||||||
|
pkgs.libxcb
|
||||||
pkgs.libffi
|
pkgs.libffi
|
||||||
pkgs.wayland-scanner
|
pkgs.wayland-scanner
|
||||||
|
|
||||||
|
|
@ -15,6 +18,12 @@
|
||||||
pkgs.samply # code profiler
|
pkgs.samply # code profiler
|
||||||
pkgs.feedgnuplot # to visualize bots training results
|
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
|
# for bevy
|
||||||
pkgs.alsa-lib
|
pkgs.alsa-lib
|
||||||
pkgs.udev
|
pkgs.udev
|
||||||
|
|
@ -47,6 +56,25 @@
|
||||||
# https://devenv.sh/languages/
|
# https://devenv.sh/languages/
|
||||||
languages.rust.enable = true;
|
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/
|
# https://devenv.sh/scripts/
|
||||||
# scripts.hello.exec = "echo hello from $GREET";
|
# scripts.hello.exec = "echo hello from $GREET";
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
inputs:
|
inputs:
|
||||||
nixpkgs:
|
nixpkgs:
|
||||||
url: github:NixOS/nixpkgs/nixpkgs-unstable
|
url: github:NixOS/nixpkgs/nixos-25.11
|
||||||
|
nixpkgs-cmake3:
|
||||||
|
url: github:NixOS/nixpkgs/f4b140d5b253f5e2a1ff4e5506edbf8267724bde
|
||||||
|
|
|
||||||
|
|
@ -53,6 +53,10 @@ Client
|
||||||
|
|
||||||
### Epic : Bot
|
### Epic : Bot
|
||||||
|
|
||||||
|
- PGX
|
||||||
|
- https://joe-antognini.github.io/ml/jax-tic-tac-toe
|
||||||
|
- https://www.sotets.uk/pgx/api_usage/
|
||||||
|
|
||||||
- OpenAi gym
|
- OpenAi gym
|
||||||
- doc gymnasium <https://gymnasium.farama.org/introduction/basic_usage/>
|
- doc gymnasium <https://gymnasium.farama.org/introduction/basic_usage/>
|
||||||
- Rust implementation for OpenAi gym <https://github.com/MathisWellmann/gym-rs>
|
- Rust implementation for OpenAi gym <https://github.com/MathisWellmann/gym-rs>
|
||||||
|
|
|
||||||
31
doc/python.md
Normal file
31
doc/python.md
Normal 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
|
||||||
1
justfile
1
justfile
|
|
@ -20,6 +20,7 @@ profile:
|
||||||
cargo build --profile profiling
|
cargo build --profile profiling
|
||||||
samply record ./target/profiling/client_cli --bot dummy,dummy
|
samply record ./target/profiling/client_cli --bot dummy,dummy
|
||||||
pythonlib:
|
pythonlib:
|
||||||
|
rm -rf target/wheels
|
||||||
maturin build -m store/Cargo.toml --release
|
maturin build -m store/Cargo.toml --release
|
||||||
pip install --no-deps --force-reinstall --prefix .devenv/state/venv target/wheels/*.whl
|
pip install --no-deps --force-reinstall --prefix .devenv/state/venv target/wheels/*.whl
|
||||||
trainbot algo:
|
trainbot algo:
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,23 @@
|
||||||
[package]
|
[package]
|
||||||
name = "store"
|
name = "trictrac-store"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "store"
|
name = "trictrac_store"
|
||||||
|
# "cdylib" is necessary to produce a shared library for Python to import from.
|
||||||
# Only "rlib" is needed for other Rust crates to use this library
|
# Only "rlib" is needed for other Rust crates to use this library
|
||||||
crate-type = ["rlib"]
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
base64 = "0.21.7"
|
base64 = "0.21.7"
|
||||||
# provides macros for creating log messages to be used by a logger (for example env_logger)
|
# provides macros for creating log messages to be used by a logger (for example env_logger)
|
||||||
log = "0.4.20"
|
log = "0.4.20"
|
||||||
merge = "0.1.0"
|
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"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
transpose = "0.2.2"
|
transpose = "0.2.2"
|
||||||
|
|
|
||||||
8
store/pyproject.toml
Normal file
8
store/pyproject.toml
Normal 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"
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
use rand::distributions::{Distribution, Uniform};
|
use rand::distr::{Distribution, Uniform};
|
||||||
use rand::{rngs::StdRng, SeedableRng};
|
use rand::{rngs::StdRng, SeedableRng};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
@ -17,7 +17,7 @@ impl DiceRoller {
|
||||||
pub fn new(opt_seed: Option<u64>) -> Self {
|
pub fn new(opt_seed: Option<u64>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
rng: match opt_seed {
|
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),
|
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
|
/// 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.
|
/// dice. We use the operating system's random number generator.
|
||||||
pub fn roll(&mut self) -> Dice {
|
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));
|
let v = (between.sample(&mut self.rng), between.sample(&mut self.rng));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,3 +16,8 @@ pub use board::CheckerMove;
|
||||||
|
|
||||||
mod dice;
|
mod dice;
|
||||||
pub use dice::{Dice, DiceRoller};
|
pub use dice::{Dice, DiceRoller};
|
||||||
|
|
||||||
|
pub mod training_common;
|
||||||
|
|
||||||
|
// python interface "trictrac_engine" (for AI training..)
|
||||||
|
mod pyengine;
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,11 @@
|
||||||
|
use pyo3::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
// This just makes it easier to dissern between a player id and any ol' u64
|
// This just makes it easier to dissern between a player id and any ol' u64
|
||||||
pub type PlayerId = u64;
|
pub type PlayerId = u64;
|
||||||
|
|
||||||
|
#[pyclass(eq, eq_int)]
|
||||||
#[derive(Copy, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Copy, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub enum Color {
|
pub enum Color {
|
||||||
White,
|
White,
|
||||||
|
|
|
||||||
218
store/src/pyengine.rs
Normal file
218
store/src/pyengine.rs
Normal file
|
|
@ -0,0 +1,218 @@
|
||||||
|
//! # Expose trictrac game state and rules in a python module
|
||||||
|
use pyo3::prelude::*;
|
||||||
|
use pyo3::types::PyDict;
|
||||||
|
|
||||||
|
use crate::board::CheckerMove;
|
||||||
|
use crate::dice::{Dice, DiceRoller};
|
||||||
|
use crate::game::{GameEvent, GameState, Stage, TurnStage};
|
||||||
|
use crate::game_rules_moves::MoveRules;
|
||||||
|
use crate::game_rules_points::PointsRules;
|
||||||
|
use crate::player::{Color, PlayerId};
|
||||||
|
use crate::training_common::{get_valid_action_indices, TrictracAction};
|
||||||
|
|
||||||
|
#[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("player2");
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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_id: u64) -> Vec<usize> {
|
||||||
|
if player_id == self.current_player_idx() {
|
||||||
|
get_valid_action_indices(&self.game_state)
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn action_to_string(&self, player_idx: u64, action_idx: usize) -> String {
|
||||||
|
TrictracAction::from_action_index(action_idx)
|
||||||
|
.map(|a| a.to_string())
|
||||||
|
.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::RollDice {
|
||||||
|
return Err(pyo3::exceptions::PyRuntimeError::new_err(
|
||||||
|
"Not in RollDice stage",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.game_state.consume(&GameEvent::Roll { player_id });
|
||||||
|
let dice = Dice { values: dices };
|
||||||
|
self.game_state
|
||||||
|
.consume(&GameEvent::RollResult { player_id, dice });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_action(&mut self, action_idx: usize) {
|
||||||
|
if let Some(event) =
|
||||||
|
TrictracAction::from_action_index(action_idx).and_then(|a| a.to_event(&self.game_state))
|
||||||
|
{
|
||||||
|
if self.game_state.validate(&event) {
|
||||||
|
self.game_state.consume(&event);
|
||||||
|
// return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Err(pyo3::exceptions::PyRuntimeError::new_err(
|
||||||
|
// "Could not apply action",
|
||||||
|
// ))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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("player2");
|
||||||
|
|
||||||
|
// 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_store(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||||
|
m.add_class::<TricTrac>()?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -3,11 +3,11 @@
|
||||||
use std::cmp::{max, min};
|
use std::cmp::{max, min};
|
||||||
use std::fmt::{Debug, Display, Formatter};
|
use std::fmt::{Debug, Display, Formatter};
|
||||||
|
|
||||||
|
use crate::{CheckerMove, GameEvent, GameState};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use store::{CheckerMove, GameEvent, GameState};
|
|
||||||
|
|
||||||
// 1 (Roll) + 1 (Go) + mouvements possibles
|
// 1 (Roll) + 1 (Go) + 512 (mouvements possibles)
|
||||||
// Pour les mouvements : 2*16*16 = 514 (choix du dé + choix de la dame 0-15 pour chaque from)
|
// avec 512 = 2 (choix du dé) * 16 * 16 (choix de la dame 0-15 pour chaque from)
|
||||||
pub const ACTION_SPACE_SIZE: usize = 514;
|
pub const ACTION_SPACE_SIZE: usize = 514;
|
||||||
|
|
||||||
/// Types d'actions possibles dans le jeu
|
/// Types d'actions possibles dans le jeu
|
||||||
|
|
@ -15,7 +15,8 @@ pub const ACTION_SPACE_SIZE: usize = 514;
|
||||||
pub enum TrictracAction {
|
pub enum TrictracAction {
|
||||||
/// Lancer les dés
|
/// Lancer les dés
|
||||||
Roll,
|
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,
|
Go,
|
||||||
/// Effectuer un mouvement de pions
|
/// Effectuer un mouvement de pions
|
||||||
Move {
|
Move {
|
||||||
|
|
@ -93,13 +94,13 @@ impl TrictracAction {
|
||||||
(state.dice.values.1, state.dice.values.0)
|
(state.dice.values.1, state.dice.values.0)
|
||||||
};
|
};
|
||||||
|
|
||||||
let color = &store::Color::White;
|
let color = &crate::Color::White;
|
||||||
let from1 = state
|
let from1 = state
|
||||||
.board
|
.board
|
||||||
.get_checker_field(color, *checker1 as u8)
|
.get_checker_field(color, *checker1 as u8)
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
let mut to1 = from1 + dice1 as usize;
|
let mut to1 = from1 + dice1 as usize;
|
||||||
let checker_move1 = store::CheckerMove::new(from1, to1).unwrap_or_default();
|
let checker_move1 = CheckerMove::new(from1, to1).unwrap_or_default();
|
||||||
|
|
||||||
let mut tmp_board = state.board.clone();
|
let mut tmp_board = state.board.clone();
|
||||||
let move_result = tmp_board.move_checker(color, checker_move1);
|
let move_result = tmp_board.move_checker(color, checker_move1);
|
||||||
|
|
@ -119,8 +120,8 @@ impl TrictracAction {
|
||||||
to2 -= 1;
|
to2 -= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
let checker_move1 = store::CheckerMove::new(from1, to1).unwrap_or_default();
|
let checker_move1 = CheckerMove::new(from1, to1).unwrap_or_default();
|
||||||
let checker_move2 = store::CheckerMove::new(from2, to2).unwrap_or_default();
|
let checker_move2 = CheckerMove::new(from2, to2).unwrap_or_default();
|
||||||
|
|
||||||
Some(GameEvent::Move {
|
Some(GameEvent::Move {
|
||||||
player_id: state.active_player_id,
|
player_id: state.active_player_id,
|
||||||
|
|
@ -166,33 +167,11 @@ impl TrictracAction {
|
||||||
pub fn action_space_size() -> usize {
|
pub fn action_space_size() -> usize {
|
||||||
ACTION_SPACE_SIZE
|
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
|
/// Obtient les actions valides pour l'état de jeu actuel
|
||||||
pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
|
pub fn get_valid_actions(game_state: &GameState) -> Vec<TrictracAction> {
|
||||||
use store::TurnStage;
|
use crate::TurnStage;
|
||||||
|
|
||||||
let mut valid_actions = Vec::new();
|
let mut valid_actions = Vec::new();
|
||||||
|
|
||||||
|
|
@ -215,11 +194,11 @@ pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
|
||||||
valid_actions.push(TrictracAction::Go);
|
valid_actions.push(TrictracAction::Go);
|
||||||
|
|
||||||
// Ajoute aussi les mouvements possibles
|
// 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![]);
|
let possible_moves = rules.get_possible_moves_sequences(true, vec![]);
|
||||||
|
|
||||||
// Modififier checker_moves_to_trictrac_action si on doit gérer Black
|
// Modififier checker_moves_to_trictrac_action si on doit gérer Black
|
||||||
assert_eq!(color, store::Color::White);
|
assert_eq!(color, crate::Color::White);
|
||||||
for (move1, move2) in possible_moves {
|
for (move1, move2) in possible_moves {
|
||||||
valid_actions.push(checker_moves_to_trictrac_action(
|
valid_actions.push(checker_moves_to_trictrac_action(
|
||||||
&move1, &move2, &color, game_state,
|
&move1, &move2, &color, game_state,
|
||||||
|
|
@ -227,7 +206,7 @@ pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
TurnStage::Move => {
|
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![]);
|
let mut possible_moves = rules.get_possible_moves_sequences(true, vec![]);
|
||||||
if possible_moves.is_empty() {
|
if possible_moves.is_empty() {
|
||||||
// Empty move
|
// Empty move
|
||||||
|
|
@ -235,7 +214,7 @@ pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modififier checker_moves_to_trictrac_action si on doit gérer Black
|
// Modififier checker_moves_to_trictrac_action si on doit gérer Black
|
||||||
assert_eq!(color, store::Color::White);
|
assert_eq!(color, crate::Color::White);
|
||||||
for (move1, move2) in possible_moves {
|
for (move1, move2) in possible_moves {
|
||||||
valid_actions.push(checker_moves_to_trictrac_action(
|
valid_actions.push(checker_moves_to_trictrac_action(
|
||||||
&move1, &move2, &color, game_state,
|
&move1, &move2, &color, game_state,
|
||||||
|
|
@ -255,8 +234,8 @@ pub fn get_valid_actions(game_state: &crate::GameState) -> Vec<TrictracAction> {
|
||||||
fn checker_moves_to_trictrac_action(
|
fn checker_moves_to_trictrac_action(
|
||||||
move1: &CheckerMove,
|
move1: &CheckerMove,
|
||||||
move2: &CheckerMove,
|
move2: &CheckerMove,
|
||||||
color: &store::Color,
|
color: &crate::Color,
|
||||||
state: &crate::GameState,
|
state: &GameState,
|
||||||
) -> TrictracAction {
|
) -> TrictracAction {
|
||||||
let to1 = move1.get_to();
|
let to1 = move1.get_to();
|
||||||
let to2 = move2.get_to();
|
let to2 = move2.get_to();
|
||||||
|
|
@ -314,7 +293,7 @@ fn checker_moves_to_trictrac_action(
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Retourne les indices des actions valides
|
/// Retourne les indices des actions valides
|
||||||
pub fn get_valid_action_indices(game_state: &crate::GameState) -> Vec<usize> {
|
pub fn get_valid_action_indices(game_state: &GameState) -> Vec<usize> {
|
||||||
get_valid_actions(game_state)
|
get_valid_actions(game_state)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|action| action.to_action_index())
|
.map(|action| action.to_action_index())
|
||||||
|
|
@ -322,11 +301,11 @@ pub fn get_valid_action_indices(game_state: &crate::GameState) -> Vec<usize> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sélectionne une action valide aléatoire
|
/// Sélectionne une action valide aléatoire
|
||||||
pub fn sample_valid_action(game_state: &crate::GameState) -> Option<TrictracAction> {
|
pub fn sample_valid_action(game_state: &GameState) -> Option<TrictracAction> {
|
||||||
use rand::{seq::SliceRandom, thread_rng};
|
use rand::{prelude::IndexedRandom, rng};
|
||||||
|
|
||||||
let valid_actions = get_valid_actions(game_state);
|
let valid_actions = get_valid_actions(game_state);
|
||||||
let mut rng = thread_rng();
|
let mut rng = rng();
|
||||||
valid_actions.choose(&mut rng).cloned()
|
valid_actions.choose(&mut rng).cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue