Skip to content

Commit

Permalink
style: fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
LeoDog896 committed Sep 26, 2024
1 parent 952fa3a commit d055366
Show file tree
Hide file tree
Showing 11 changed files with 138 additions and 70 deletions.
16 changes: 13 additions & 3 deletions crates/game-solver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ fn negamax<T: Game<Player = impl TwoPlayer + 'static> + Eq + Hash>(
// TODO: can we not duplicate this
if let Some(stats) = stats {
if let Ok(player) = castaway::cast!(winning_player, ImpartialPlayer) {
if ImpartialPlayer::from_move_count(stats.original_move_count, game.move_count()) == player {
if ImpartialPlayer::from_move_count(
stats.original_move_count,
game.move_count(),
) == player
{
stats.terminal_ends.winning.fetch_add(1, Ordering::Relaxed);
} else {
stats.terminal_ends.losing.fetch_add(1, Ordering::Relaxed);
Expand Down Expand Up @@ -118,7 +122,11 @@ fn negamax<T: Game<Player = impl TwoPlayer + 'static> + Eq + Hash>(
GameState::Win(winning_player) => {
if let Some(stats) = stats {
if let Ok(player) = castaway::cast!(winning_player, ImpartialPlayer) {
if ImpartialPlayer::from_move_count(stats.original_move_count, game.move_count()) == player {
if ImpartialPlayer::from_move_count(
stats.original_move_count,
game.move_count(),
) == player
{
stats.terminal_ends.winning.fetch_add(1, Ordering::Relaxed);
} else {
stats.terminal_ends.losing.fetch_add(1, Ordering::Relaxed);
Expand Down Expand Up @@ -370,7 +378,9 @@ where
///
/// A vector of tuples of the form `(move, score)`.
#[cfg(feature = "rayon")]
pub fn par_move_scores<T: Game<Player = impl TwoPlayer + Sync + 'static> + Eq + Hash + Sync + Send + 'static>(
pub fn par_move_scores<
T: Game<Player = impl TwoPlayer + Sync + 'static> + Eq + Hash + Sync + Send + 'static,
>(
game: &T,
stats: Option<&Stats<T::Player>>,
cancellation_token: &Option<Arc<AtomicBool>>,
Expand Down
2 changes: 1 addition & 1 deletion crates/game-solver/src/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub trait Player: Sized + Eq {
}

/// Represents a two player player.
///
///
/// This player should always be representable by a byte.
pub trait TwoPlayer: Player + Copy {
/// Gets the other player
Expand Down
3 changes: 1 addition & 2 deletions crates/game-solver/src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,5 @@ pub struct Stats<P: Player> {
pub pruning_cutoffs: AtomicU64,
pub terminal_ends: TerminalEnds,
pub original_player: P,
pub original_move_count: usize
pub original_move_count: usize,
}

12 changes: 6 additions & 6 deletions crates/games/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ pub mod tic_tac_toe;

use crate::{
chomp::ChompArgs, domineering::DomineeringArgs, nim::NimArgs,
order_and_chaos::OrderAndChaosArgs, reversi::ReversiArgs, tic_tac_toe::TicTacToeArgs,
sprouts::SproutsArgs
order_and_chaos::OrderAndChaosArgs, reversi::ReversiArgs, sprouts::SproutsArgs,
tic_tac_toe::TicTacToeArgs,
};
use clap::Subcommand;
use once_cell::sync::Lazy;
Expand All @@ -25,7 +25,7 @@ pub enum Games {
Nim(NimArgs),
Domineering(DomineeringArgs),
Chomp(ChompArgs),
Sprouts(SproutsArgs)
Sprouts(SproutsArgs),
}

pub static DEFAULT_GAMES: Lazy<[Games; 7]> = Lazy::new(|| {
Expand All @@ -36,7 +36,7 @@ pub static DEFAULT_GAMES: Lazy<[Games; 7]> = Lazy::new(|| {
Games::Nim(Default::default()),
Games::Domineering(Default::default()),
Games::Chomp(Default::default()),
Games::Sprouts(Default::default())
Games::Sprouts(Default::default()),
]
});

Expand All @@ -49,7 +49,7 @@ impl Games {
Self::Nim(_) => "Nim".to_string(),
Self::Domineering(_) => "Domineering".to_string(),
Self::Chomp(_) => "Chomp".to_string(),
Self::Sprouts(_) => "Sprouts".to_string()
Self::Sprouts(_) => "Sprouts".to_string(),
}
}

Expand All @@ -61,7 +61,7 @@ impl Games {
Self::Nim(_) => include_str!("./nim/README.md"),
Self::Domineering(_) => include_str!("./domineering/README.md"),
Self::Chomp(_) => include_str!("./chomp/README.md"),
Self::Sprouts(_) => include_str!("./sprouts/README.md")
Self::Sprouts(_) => include_str!("./sprouts/README.md"),
}
}

Expand Down
100 changes: 67 additions & 33 deletions crates/games/src/sprouts/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
#![doc = include_str!("./README.md")]

use std::{fmt::{Debug, Display}, hash::Hash, str::FromStr};
use std::{
fmt::{Debug, Display},
hash::Hash,
str::FromStr,
};

use anyhow::Error;
use clap::Args;
use game_solver::{game::{Game, StateType}, player::ImpartialPlayer};
use game_solver::{
game::{Game, StateType},
player::ImpartialPlayer,
};
use itertools::Itertools;
use petgraph::{matrix_graph::{MatrixGraph, NodeIndex}, visit::{IntoEdgeReferences, IntoNodeIdentifiers}, Undirected};
use petgraph::{
matrix_graph::{MatrixGraph, NodeIndex},
visit::{IntoEdgeReferences, IntoNodeIdentifiers},
Undirected,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

Expand All @@ -18,7 +29,7 @@ pub type SproutsIx = u8;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct SproutsMove {
from: NodeIndex<SproutsIx>,
to: NodeIndex<SproutsIx>
to: NodeIndex<SproutsIx>,
}

impl Display for SproutsMove {
Expand Down Expand Up @@ -49,7 +60,8 @@ impl Hash for Sprouts {
impl PartialEq for Sprouts {
fn eq(&self, other: &Self) -> bool {
self.0.node_count() == other.0.node_count()
&& self.0.edge_references().collect::<Vec<_>>() == other.0.edge_references().collect::<Vec<_>>()
&& self.0.edge_references().collect::<Vec<_>>()
== other.0.edge_references().collect::<Vec<_>>()
}

fn ne(&self, other: &Self) -> bool {
Expand All @@ -62,11 +74,11 @@ impl Eq for Sprouts {}
impl Sprouts {
pub fn new(node_count: SproutsIx) -> Self {
let mut graph = SproutsGraph::default();

for _ in 0..node_count {
graph.add_node(());
}

Self(graph)
}
}
Expand All @@ -78,7 +90,7 @@ pub enum SproutsMoveError {
#[error("chosen index {0} from move {1:?} references a dead sprout.")]
DeadSprout(SproutsIx, SproutsMove),
#[error("a move for {0:?} has already been made")]
SproutsConnected(SproutsMove)
SproutsConnected(SproutsMove),
}

const MAX_SPROUTS: usize = 3;
Expand Down Expand Up @@ -115,15 +127,15 @@ impl Game for Sprouts {
if !self.0.node_identifiers().contains(&m.from) {
return Err(SproutsMoveError::MoveOutOfBounds(
m.from.index().try_into().unwrap(),
m.clone())
);
m.clone(),
));
}

if !self.0.node_identifiers().contains(&m.to) {
return Err(SproutsMoveError::MoveOutOfBounds(
m.to.index().try_into().unwrap(),
m.clone())
);
m.clone(),
));
}
}

Expand All @@ -132,14 +144,14 @@ impl Game for Sprouts {
if self.0.edges(m.from).count() >= MAX_SPROUTS {
return Err(SproutsMoveError::DeadSprout(
m.from.index().try_into().unwrap(),
m.clone()
m.clone(),
));
}

if self.0.edges(m.to).count() >= MAX_SPROUTS {
return Err(SproutsMoveError::DeadSprout(
m.to.index().try_into().unwrap(),
m.clone()
m.clone(),
));
}
}
Expand All @@ -155,7 +167,7 @@ impl Game for Sprouts {

fn possible_moves(&self) -> Self::Iter<'_> {
let mut sprouts_moves = vec![];

for id in self.0.node_identifiers() {
let edge_count = self.0.edges(id).count();

Expand All @@ -166,22 +178,40 @@ impl Game for Sprouts {
sprouts_moves.push(SproutsMove { from: id, to: id });
}
for sub_id in self.0.node_identifiers() {
if id >= sub_id { continue; }
if self.0.edges(sub_id).count() >= MAX_SPROUTS { continue; }
if self.0.has_edge(id, sub_id) { continue; }
sprouts_moves.push(SproutsMove { from: id, to: sub_id })
if id >= sub_id {
continue;
}
if self.0.edges(sub_id).count() >= MAX_SPROUTS {
continue;
}
if self.0.has_edge(id, sub_id) {
continue;
}
sprouts_moves.push(SproutsMove {
from: id,
to: sub_id,
})
}
},
}
2 => {
for sub_id in self.0.node_identifiers() {
if id >= sub_id { continue; }
if self.0.edges(sub_id).count() >= MAX_SPROUTS { continue; }
if self.0.has_edge(id, sub_id) { continue; }
sprouts_moves.push(SproutsMove { from: id, to: sub_id })
if id >= sub_id {
continue;
}
if self.0.edges(sub_id).count() >= MAX_SPROUTS {
continue;
}
if self.0.has_edge(id, sub_id) {
continue;
}
sprouts_moves.push(SproutsMove {
from: id,
to: sub_id,
})
}
},
}
MAX_SPROUTS => (),
_ => panic!("No node should have more than three edges")
_ => panic!("No node should have more than three edges"),
}
}

Expand All @@ -196,7 +226,7 @@ impl Game for Sprouts {
impl Debug for Sprouts {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let references = self.0.edge_references().collect::<Vec<_>>();

writeln!(f, "graph of vertices count {}", references.len())?;

if references.is_empty() {
Expand All @@ -219,7 +249,7 @@ impl Display for Sprouts {
}

/// Analyzes Sprouts.
///
///
#[doc = include_str!("./README.md")]
#[derive(Args, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct SproutsArgs {
Expand All @@ -228,14 +258,14 @@ pub struct SproutsArgs {
starting_sprouts: SproutsIx,
/// Sprouts moves, ordered as i1-j1 i2-j2 ...
#[arg(value_parser = clap::value_parser!(SproutsMove))]
moves: Vec<SproutsMove>
moves: Vec<SproutsMove>,
}

impl Default for SproutsArgs {
fn default() -> Self {
Self {
starting_sprouts: 6,
moves: vec![]
moves: vec![],
}
}
}
Expand All @@ -260,11 +290,15 @@ impl FromStr for SproutsMove {
fn from_str(s: &str) -> Result<Self, Self::Err> {
let components = s.split("-").collect::<Vec<_>>();

assert_eq!(components.len(), 2, "a move shouldn't connect more than two sprouts");
assert_eq!(
components.len(),
2,
"a move shouldn't connect more than two sprouts"
);

Ok(SproutsMove {
from: str::parse::<SproutsIx>(components[0])?.into(),
to: str::parse::<SproutsIx>(components[1])?.into()
to: str::parse::<SproutsIx>(components[1])?.into(),
})
}
}
4 changes: 2 additions & 2 deletions crates/games/src/tic_tac_toe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ impl Square {
fn to_player(self) -> PartizanPlayer {
match self {
Self::X => PartizanPlayer::Left,
Self::O => PartizanPlayer::Right
Self::O => PartizanPlayer::Right,
}
}

fn from_player(player: PartizanPlayer) -> Square {
match player {
PartizanPlayer::Left => Self::X,
PartizanPlayer::Right => Self::O
PartizanPlayer::Right => Self::O,
}
}
}
Expand Down
15 changes: 8 additions & 7 deletions crates/games/src/util/cli/human.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,7 @@ impl<G: Game> App<G> {
impl<G: Game> Widget for &App<G> {
fn render(self, area: Rect, buf: &mut Buffer) {
let title = Title::from(" game-solver ".bold().green());
let instructions = Title::from(Line::from(vec![
" Quit ".into(),
"<Q> ".blue().bold(),
]));
let instructions = Title::from(Line::from(vec![" Quit ".into(), "<Q> ".blue().bold()]));
let block = Block::bordered()
.title(title.alignment(Alignment::Center))
.title(
Expand Down Expand Up @@ -181,14 +178,14 @@ where
{
let mut terminal = ratatui::init();

let stats = Arc::new(Stats {
let stats = Arc::new(Stats {
states_explored: AtomicU64::new(0),
max_depth: AtomicUsize::new(0),
cache_hits: AtomicU64::new(0),
pruning_cutoffs: AtomicU64::new(0),
terminal_ends: TerminalEnds::default(),
original_player: game.player(),
original_move_count: game.move_count()
original_move_count: game.move_count(),
});

let exit = Arc::new(AtomicBool::new(false));
Expand All @@ -203,7 +200,11 @@ where
let internal_game = game.clone();
let internal_stats = stats.clone();
let game_thread = thread::spawn(move || {
let move_scores = par_move_scores(&internal_game, Some(internal_stats.as_ref()), &Some(exit.clone()));
let move_scores = par_move_scores(
&internal_game,
Some(internal_stats.as_ref()),
&Some(exit.clone()),
);

exit_ui.store(true, Ordering::SeqCst);

Expand Down
2 changes: 1 addition & 1 deletion crates/games/src/util/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mod human;
mod robot;
mod report;
mod robot;

use anyhow::{anyhow, Result};
use game_solver::{
Expand Down
2 changes: 1 addition & 1 deletion crates/games/src/util/cli/report/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod scores;
pub mod stats;
pub mod stats;
Loading

0 comments on commit d055366

Please sign in to comment.