abstract away more coordinates

This commit is contained in:
2025-02-27 21:00:04 -05:00
parent 956386fb66
commit 6ae1726010
12 changed files with 251 additions and 204 deletions

View File

@@ -1,4 +1,4 @@
use crate::repr::{Board, Coord, Piece}; use crate::repr::{Board, CoordAxis, CoordPair, Piece};
use rand::prelude::*; use rand::prelude::*;
use std::io; use std::io;
use std::io::prelude::*; use std::io::prelude::*;
@@ -6,7 +6,7 @@ use std::io::prelude::*;
#[allow(dead_code)] #[allow(dead_code)]
pub trait Agent { pub trait Agent {
/// Returns the move of an [`Agent`] /// Returns the move of an [`Agent`]
fn next_move(&mut self, board: &Board) -> Option<(Coord, Coord)>; fn next_move(&mut self, board: &Board) -> Option<CoordPair>;
/// Returns the name of the [`Agent`] /// Returns the name of the [`Agent`]
fn name(&self) -> &'static str; fn name(&self) -> &'static str;
/// Returns the color the [`Agent`] is playing /// Returns the color the [`Agent`] is playing
@@ -27,7 +27,7 @@ impl ManualAgent {
#[allow(dead_code)] #[allow(dead_code)]
impl Agent for ManualAgent { impl Agent for ManualAgent {
fn next_move(&mut self, board: &Board) -> Option<(Coord, Coord)> { fn next_move(&mut self, board: &Board) -> Option<CoordPair> {
let stdin = io::stdin(); let stdin = io::stdin();
let mut input = String::new(); let mut input = String::new();
println!("Your turn! ('Skip' to skip)"); println!("Your turn! ('Skip' to skip)");
@@ -44,15 +44,15 @@ impl Agent for ManualAgent {
.map(str::parse) .map(str::parse)
.map(Result::ok) .map(Result::ok)
.collect::<Option<Vec<_>>>() .collect::<Option<Vec<_>>>()
.and_then(|x| -> Option<[Coord; 2]> { x.try_into().ok() }) .and_then(|x| -> Option<[CoordAxis; 2]> { x.try_into().ok() })
.map(|x| (x[0], x[1])); .map(|x| (x[0], x[1]));
if let Some(got) = got { if let Some(got) = got {
if board.possible_moves(self.color).all(|x| x != got) { if board.possible_moves(self.color).all(|x| x != got.into()) {
println!("Invalid move! Try again."); println!("Invalid move! Try again.");
continue; continue;
} }
return Some(got); return Some(got.into());
} }
} }
} }
@@ -73,7 +73,7 @@ pub struct RandomAgent {
#[allow(dead_code)] #[allow(dead_code)]
impl Agent for RandomAgent { impl Agent for RandomAgent {
fn next_move(&mut self, board: &Board) -> Option<(Coord, Coord)> { fn next_move(&mut self, board: &Board) -> Option<CoordPair> {
board.possible_moves(self.color).choose(&mut rand::rng()) board.possible_moves(self.color).choose(&mut rand::rng())
} }

View File

@@ -1,7 +1,7 @@
use crate::{ use crate::{
agent::Agent, agent::Agent,
logic::{FutureMoveConfig, FutureMoves}, logic::{FutureMoveConfig, FutureMoves},
repr::{Board, Coord, Piece}, repr::{Board, CoordPair, Piece},
}; };
pub struct ComplexAgent { pub struct ComplexAgent {
@@ -17,7 +17,7 @@ impl ComplexAgent {
min_arena_depth_sub: 3, min_arena_depth_sub: 3,
top_k_children: 2, top_k_children: 2,
up_to_minus: 3, up_to_minus: 3,
max_arena_size: 50_000_000, max_arena_size: 10_000_000,
}; };
Self { Self {
color, color,
@@ -27,7 +27,7 @@ impl ComplexAgent {
} }
impl Agent for ComplexAgent { impl Agent for ComplexAgent {
fn next_move(&mut self, board: &Board) -> Option<(Coord, Coord)> { fn next_move(&mut self, board: &Board) -> Option<CoordPair> {
self.future_moves.update_from_board(board); self.future_moves.update_from_board(board);
println!("# of moves stored: {}", self.future_moves.arena_len()); println!("# of moves stored: {}", self.future_moves.arena_len());

View File

@@ -53,11 +53,11 @@ impl Game {
loop { loop {
let player_move = self.players[player_i].next_move(&self.board); let player_move = self.players[player_i].next_move(&self.board);
if let Some((i, j)) = player_move { if let Some(coord) = player_move {
match self.board.place(i, j, player_color) { match self.board.place(coord, player_color) {
// Check if its a valid move // Check if its a valid move
Ok(_) => { Ok(_) => {
println!("Player {} placed at ({}, {})", player_i, i, j); println!("Player {} placed at {}", player_i, coord);
break; break;
} }
@@ -65,8 +65,8 @@ impl Game {
// Now we dont need to restart the game if we mess up // Now we dont need to restart the game if we mess up
Err(err) => { Err(err) => {
panic!( panic!(
"Invalid move by Player {}: {}. Try again. Move: ({}, {})", "Invalid move by Player {}: {}. Try again. Move: {}",
player_i, err, i, j player_i, err, coord
); );
} }
} }

View File

@@ -5,8 +5,8 @@ pub struct BoardValueMap(PosMap<i64>);
impl BoardValueMap { impl BoardValueMap {
pub fn board_value(&self, board: &Board, color: Piece) -> i64 { pub fn board_value(&self, board: &Board, color: Piece) -> i64 {
Board::all_positions() Board::all_positions()
.filter_map(|(i, j)| board.get(i, j).map(|p| (i, j, p))) .filter_map(|coord| board.get(coord).map(|p| (coord, p)))
.map(|(i, j, pos_p)| (*self.0.get(i, j), pos_p)) .map(|(coord, pos_p)| (*self.0.get(coord), pos_p))
.map(|(value, pos_p)| { .map(|(value, pos_p)| {
if pos_p != color { if pos_p != color {
// enemy has position // enemy has position

View File

@@ -1,6 +1,6 @@
use crate::{ use crate::{
logic::r#move::Move, logic::r#move::Move,
repr::{Board, Coord, Piece, Winner}, repr::{Board, CoordPair, Piece, Winner},
}; };
use indicatif::{ProgressIterator, ProgressStyle}; use indicatif::{ProgressIterator, ProgressStyle};
use std::{collections::HashMap, hash::BuildHasherDefault, ops::ControlFlow}; use std::{collections::HashMap, hash::BuildHasherDefault, ops::ControlFlow};
@@ -94,10 +94,10 @@ impl FutureMoves {
} }
}); });
self.prune_bad_children(); // self.prune_bad_children();
self.current_depth += 1; self.current_depth += 1;
if cf.is_break() { if cf.is_break() {
dbg!("extend_layers: early break ({})", self.arena_len()); println!("extend_layers: early break");
return; return;
} }
} }
@@ -130,14 +130,14 @@ impl FutureMoves {
// use [`Board::all_positions`] here instead of [`Board::possible_moves`] // use [`Board::all_positions`] here instead of [`Board::possible_moves`]
// because we use [`Board::what_if`] later and we want to reduce calls to [`Board::propegate_from_dry`] // because we use [`Board::what_if`] later and we want to reduce calls to [`Board::propegate_from_dry`]
let mut new: Vec<Move> = Board::all_positions() let mut new: Vec<Move> = Board::all_positions()
.flat_map(|(i, j)| { .flat_map(|coord| {
parent parent
.board .board
.what_if(i, j, new_color) .what_if(coord, new_color)
.map(move |x| (i, j, x)) .map(move |x| (coord, x))
}) })
.map(|(i, j, new_board)| { .map(|(coord, new_board)| {
Move::new(Some((i, j)), new_board, new_color, self.agent_color) Move::new(Some(coord), new_board, new_color, self.agent_color)
}) })
.collect(); .collect();
@@ -200,32 +200,26 @@ impl FutureMoves {
// reversed so we build up the value of the closest (in time) moves from the future // reversed so we build up the value of the closest (in time) moves from the future
for (depth, nodes) in by_depth_vec.into_iter().rev() { for (depth, nodes) in by_depth_vec.into_iter().rev() {
for idx in nodes { for idx in nodes {
// TODO! impl dynamic sorting based on children's states, maybe it propegates
// upwards using the `parent` field
// let mut parent_copy = self.arena[idx].clone();
// parent_copy.sort_children(self.arena.as_mut_slice());
// self.arena[idx] = parent_copy;
let children_value = self.arena[idx] let children_value = self.arena[idx]
.children .children
.iter() .iter()
.map(|&child| self.arena[child].value.expect("child has no value??")) .map(|&child| self.arena[child].value.expect("child has no value??"))
.sum::<i128>(); // average value of children
.sum::<i128>()
.checked_div(self.arena[idx].children.len() as i128)
.unwrap_or(0);
// we use `depth` and divided `self_value` by it, idk if this is worth it // we use `depth` and divided `self_value` by it, idk if this is worth it
// we should really setup some sort of ELO rating for each commit, playing them against // we should really setup some sort of ELO rating for each commit, playing them against
// each other or something, could be cool to benchmark these more subjective things, not // each other or something, could be cool to benchmark these more subjective things, not
// just performance (cycles/time wise) // just performance (cycles/time wise)
self.arena[idx].value = Some( self.arena[idx].value = Some(self.arena[idx].self_value as i128 + children_value);
(self.arena[idx].self_value as i128 + children_value) / (depth + 1) as i128,
);
} }
} }
} }
/// Return the best move which is a child of `self.current_root` /// Return the best move which is a child of `self.current_root`
pub fn best_move(&self) -> Option<Option<(Coord, Coord)>> { pub fn best_move(&self) -> Option<Option<CoordPair>> {
self.current_root self.current_root
.and_then(|x| { .and_then(|x| {
self.arena[x] self.arena[x]
@@ -256,11 +250,11 @@ impl FutureMoves {
if let Some(curr_board_idx) = curr_board { if let Some(curr_board_idx) = curr_board {
self.set_root_idx_raw(curr_board_idx); self.set_root_idx_raw(curr_board_idx);
return false; false
} else { } else {
dbg!("regenerating arena from board"); println!("regenerating arena from board");
self.set_root_from_board(*board); self.set_root_from_board(*board);
return true; true
} }
} }
@@ -269,6 +263,7 @@ impl FutureMoves {
self.arena.clear(); self.arena.clear();
self.arena self.arena
.push(Move::new(None, board, !self.agent_color, self.agent_color)); .push(Move::new(None, board, !self.agent_color, self.agent_color));
// because we have to regenerate root from a [`Board`] // because we have to regenerate root from a [`Board`]
// we need to reset the current_depth (fixes `skip_move_recovery`) // we need to reset the current_depth (fixes `skip_move_recovery`)
self.current_depth = 0; self.current_depth = 0;
@@ -291,7 +286,7 @@ impl FutureMoves {
self.compute_values(0..self.arena.len()); self.compute_values(0..self.arena.len());
// check arena's consistancy // check arena's consistancy
assert_eq!(self.check_arena().join("\n"), ""); debug_assert_eq!(self.check_arena().join("\n"), "");
} }
pub fn set_parent_child(&mut self, parent: usize, child: usize) { pub fn set_parent_child(&mut self, parent: usize, child: usize) {
@@ -485,7 +480,7 @@ mod tests {
// dummy (2) // dummy (2)
futm.arena.push(Move::new( futm.arena.push(Move::new(
Some((123, 123)), Some((9, 9).into()),
Board::new(), Board::new(),
Piece::White, Piece::White,
Piece::Black, Piece::Black,
@@ -509,7 +504,7 @@ mod tests {
assert_ne!( assert_ne!(
futm.arena[2].coord, futm.arena[2].coord,
Some((123, 123)), Some((9, 9).into()),
"dummy value still exists" "dummy value still exists"
); );
} }
@@ -682,8 +677,8 @@ mod tests {
} }
} }
if let Some((i, j)) = coords { if let Some(coord) = coords {
board.place(i, j, color).unwrap(); board.place(coord.into(), color).unwrap();
} }
} }
} }

View File

@@ -1,11 +1,11 @@
use super::board_value::BoardValueMap; use super::board_value::BoardValueMap;
use crate::repr::{Board, Coord, Piece, Winner}; use crate::repr::{Board, CoordPair, Piece, Winner};
use lazy_static::lazy_static; use lazy_static::lazy_static;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Move { pub struct Move {
/// Coordinates (i, j) of the move (if it exists) /// Coordinates (i, j) of the move (if it exists)
pub coord: Option<(Coord, Coord)>, pub coord: Option<CoordPair>,
/// [`Board`] state after move is made /// [`Board`] state after move is made
pub board: Board, pub board: Board,
@@ -40,12 +40,7 @@ lazy_static! {
} }
impl Move { impl Move {
pub fn new( pub fn new(coord: Option<CoordPair>, board: Board, color: Piece, agent_color: Piece) -> Self {
coord: Option<(Coord, Coord)>,
board: Board,
color: Piece,
agent_color: Piece,
) -> Self {
let mut m = Move { let mut m = Move {
coord, coord,
board, board,

View File

@@ -1,6 +1,6 @@
use super::{ use super::{
board::{Board, Coord}, board::Board,
misc::get_index, coords::{CoordAxis, CoordPair},
}; };
use const_fn::const_fn; use const_fn::const_fn;
use static_assertions::const_assert; use static_assertions::const_assert;
@@ -43,34 +43,34 @@ impl BitBoard {
} }
#[const_fn(cfg(not(feature = "bitvec")))] #[const_fn(cfg(not(feature = "bitvec")))]
pub const fn get(&self, row: Coord, col: Coord) -> bool { pub const fn get(&self, coord: CoordPair) -> bool {
self.get_by_index(get_index(row, col)) self.get_by_index(coord.0)
} }
#[const_fn(cfg(not(feature = "bitvec")))] #[const_fn(cfg(not(feature = "bitvec")))]
pub const fn set(&mut self, row: Coord, col: Coord, value: bool) { pub const fn set(&mut self, coord: CoordPair, value: bool) {
self.set_by_index(get_index(row, col), value); self.set_by_index(coord.0, value);
} }
#[cfg(not(feature = "bitvec"))] #[cfg(not(feature = "bitvec"))]
const fn get_by_index(&self, index: Coord) -> bool { const fn get_by_index(&self, index: CoordAxis) -> bool {
((self.0 >> index) & 0b1) != 0b0 ((self.0 >> index) & 0b1) != 0b0
} }
#[cfg(not(feature = "bitvec"))] #[cfg(not(feature = "bitvec"))]
const fn set_by_index(&mut self, index: Coord, value: bool) { const fn set_by_index(&mut self, index: CoordAxis, value: bool) {
// PERF! branchless setting of bit (~+3% perf bump) // PERF! branchless setting of bit (~+3% perf bump)
self.0 &= !(0b1 << index); // clear bit self.0 &= !(0b1 << index); // clear bit
self.0 |= (value as BitBoardInner) << index; // set bit (if needed) self.0 |= (value as BitBoardInner) << index; // set bit (if needed)
} }
#[cfg(feature = "bitvec")] #[cfg(feature = "bitvec")]
pub fn get_by_index(&self, index: Coord) -> bool { pub fn get_by_index(&self, index: CoordAxis) -> bool {
self.0[index as usize] self.0[index as usize]
} }
#[cfg(feature = "bitvec")] #[cfg(feature = "bitvec")]
pub fn set_by_index(&mut self, index: Coord, value: bool) { pub fn set_by_index(&mut self, index: CoordAxis, value: bool) {
self.0.set(index as usize, value); self.0.set(index as usize, value);
} }
@@ -91,15 +91,15 @@ mod test {
for i in 0..Board::BOARD_SIZE { for i in 0..Board::BOARD_SIZE {
for j in 0..Board::BOARD_SIZE { for j in 0..Board::BOARD_SIZE {
assert!( assert!(
!b.get(i, j), !b.get((i, j).into()),
"A just-initalized BitBoard should be completely empty" "A just-initalized BitBoard should be completely empty"
) )
} }
} }
assert!(!b.get(2, 4)); assert!(!b.get((2, 4).into()));
b.set(2, 4, true); b.set((2, 4).into(), true);
assert!(b.get(2, 4)); assert!(b.get((2, 4).into()));
b.set(2, 4, false); b.set((2, 4).into(), false);
assert!(!b.get(2, 4)); assert!(!b.get((2, 4).into()));
} }
} }

View File

@@ -2,15 +2,12 @@ use super::{
bitboard::BitBoard, bitboard::BitBoard,
chains::{gen_adj_lookup, ChainCollection, PosMap}, chains::{gen_adj_lookup, ChainCollection, PosMap},
piece::Piece, piece::Piece,
CoordAxis, CoordPair,
}; };
use const_fn::const_fn; use const_fn::const_fn;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use std::{cmp::Ordering, fmt}; use std::{cmp::Ordering, fmt};
// PERF! having `Coord` be of type `u8` (instead of usize) increases
// performance by about 1-2% overall
pub type Coord = u8;
#[derive(PartialEq, Eq, Copy, Clone, Debug)] #[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Winner { pub enum Winner {
Player(Piece), Player(Piece),
@@ -58,7 +55,10 @@ impl fmt::Display for Board {
write!( write!(
f, f,
"{}|", "{}|",
self.get(i, j).as_ref().map(Piece::symbol).unwrap_or(' ') self.get((i, j).into())
.as_ref()
.map(Piece::symbol)
.unwrap_or(' ')
)?; )?;
} }
writeln!(f)?; writeln!(f)?;
@@ -86,10 +86,10 @@ impl fmt::Debug for Board {
} }
impl Board { impl Board {
pub const BOARD_SIZE: Coord = 8; pub const BOARD_SIZE: CoordAxis = 8;
/// Area of the board /// Area of the board
pub const BOARD_AREA: Coord = Self::BOARD_SIZE.pow(2); pub const BOARD_AREA: CoordAxis = Self::BOARD_SIZE.pow(2);
/// Create a new empty board /// Create a new empty board
#[allow(clippy::new_without_default)] #[allow(clippy::new_without_default)]
@@ -101,39 +101,39 @@ impl Board {
} }
/// Starting position /// Starting position
#[const_fn(cfg(not(feature = "bitvec")))] pub fn starting_pos(mut self) -> Self {
pub const fn starting_pos(mut self) -> Self {
self.place_unchecked( self.place_unchecked(
(Self::BOARD_SIZE / 2) - 1, ((Self::BOARD_SIZE / 2) - 1, (Self::BOARD_SIZE / 2) - 1).into(),
(Self::BOARD_SIZE / 2) - 1,
Piece::White, Piece::White,
); );
self.place_unchecked( self.place_unchecked(
Self::BOARD_SIZE / 2, (Self::BOARD_SIZE / 2, (Self::BOARD_SIZE / 2) - 1).into(),
(Self::BOARD_SIZE / 2) - 1,
Piece::Black, Piece::Black,
); );
self.place_unchecked( self.place_unchecked(
(Self::BOARD_SIZE / 2) - 1, ((Self::BOARD_SIZE / 2) - 1, Self::BOARD_SIZE / 2).into(),
Self::BOARD_SIZE / 2,
Piece::Black, Piece::Black,
); );
self.place_unchecked(Self::BOARD_SIZE / 2, Self::BOARD_SIZE / 2, Piece::White); self.place_unchecked(
(Self::BOARD_SIZE / 2, Self::BOARD_SIZE / 2).into(),
Piece::White,
);
self self
} }
/// Provides an iterator of all possible positions on the board /// Provides an iterator of all possible positions on the board
pub fn all_positions() -> impl Iterator<Item = (Coord, Coord)> { pub fn all_positions() -> impl Iterator<Item = CoordPair> {
(0..Self::BOARD_SIZE) (0..Self::BOARD_SIZE).flat_map(|i| {
.flat_map(|i| (0..Self::BOARD_SIZE).map(move |j| (i as Coord, j as Coord))) (0..Self::BOARD_SIZE).map(move |j| (i as CoordAxis, j as CoordAxis).into())
})
} }
/// Returns an iterator of all possible moves a `color` can make /// Returns an iterator of all possible moves a `color` can make
pub fn possible_moves(&self, color: Piece) -> impl Iterator<Item = (Coord, Coord)> + use<'_> { pub fn possible_moves(&self, color: Piece) -> impl Iterator<Item = CoordPair> + use<'_> {
Self::all_positions().filter(move |&(i, j)| self.would_prop(i, j, color)) Self::all_positions().filter(move |&coord| self.would_prop(coord, color))
} }
pub fn sides() -> impl Iterator<Item = (Coord, Coord)> { pub fn sides() -> impl Iterator<Item = (CoordAxis, CoordAxis)> {
(0..Self::BOARD_SIZE) (0..Self::BOARD_SIZE)
.map(|i| (i, Self::BOARD_SIZE - 1)) .map(|i| (i, Self::BOARD_SIZE - 1))
.chain((0..Self::BOARD_SIZE).map(|i| (i, 0))) .chain((0..Self::BOARD_SIZE).map(|i| (i, 0)))
@@ -141,7 +141,7 @@ impl Board {
.chain((0..Self::BOARD_SIZE).map(|j| (0, j))) .chain((0..Self::BOARD_SIZE).map(|j| (0, j)))
} }
pub fn corners() -> impl Iterator<Item = (Coord, Coord)> { pub fn corners() -> impl Iterator<Item = (CoordAxis, CoordAxis)> {
[0, Self::BOARD_SIZE - 1] [0, Self::BOARD_SIZE - 1]
.into_iter() .into_iter()
.flat_map(|i| [0, Self::BOARD_SIZE - 1].into_iter().map(move |j| (i, j))) .flat_map(|i| [0, Self::BOARD_SIZE - 1].into_iter().map(move |j| (i, j)))
@@ -164,16 +164,16 @@ impl Board {
} }
#[const_fn(cfg(not(feature = "bitvec")))] #[const_fn(cfg(not(feature = "bitvec")))]
pub const fn get_piece(&self, i: Coord, j: Coord, color: Piece) -> bool { pub const fn get_piece(&self, coord: CoordPair, color: Piece) -> bool {
self.board(color).get(i, j) self.board(color).get(coord)
} }
/// Returns the color of a place on the [`Board`] at a position /// Returns the color of a place on the [`Board`] at a position
#[const_fn(cfg(not(feature = "bitvec")))] #[const_fn(cfg(not(feature = "bitvec")))]
pub const fn get(&self, i: Coord, j: Coord) -> Option<Piece> { pub const fn get(&self, coord: CoordPair) -> Option<Piece> {
if self.get_piece(i, j, Piece::White) { if self.get_piece(coord, Piece::White) {
Some(Piece::White) Some(Piece::White)
} else if self.get_piece(i, j, Piece::Black) { } else if self.get_piece(coord, Piece::Black) {
Some(Piece::Black) Some(Piece::Black)
} else { } else {
None None
@@ -182,42 +182,42 @@ impl Board {
/// Place a piece without checking for propegation of validity /// Place a piece without checking for propegation of validity
#[const_fn(cfg(not(feature = "bitvec")))] #[const_fn(cfg(not(feature = "bitvec")))]
const fn place_unchecked(&mut self, i: Coord, j: Coord, piece: Piece) { const fn place_unchecked(&mut self, coord: CoordPair, piece: Piece) {
self.board_mut(piece).set(i, j, true); self.board_mut(piece).set(coord, true);
self.board_mut(piece.flip()).set(i, j, false); self.board_mut(piece.flip()).set(coord, false);
} }
#[const_fn(cfg(not(feature = "bitvec")))] #[const_fn(cfg(not(feature = "bitvec")))]
const fn delete(&mut self, i: Coord, j: Coord) { const fn delete(&mut self, coord: CoordPair) {
self.board_mut(Piece::White).set(i, j, false); self.board_mut(Piece::White).set(coord, false);
self.board_mut(Piece::Black).set(i, j, false); self.board_mut(Piece::Black).set(coord, false);
} }
/// Return a modified [`Board`] with the piece placed at a position /// Return a modified [`Board`] with the piece placed at a position
/// Returns None if the move was invalid /// Returns None if the move was invalid
pub fn what_if(&self, i: Coord, j: Coord, piece: Piece) -> Result<Self, &'static str> { pub fn what_if(&self, coord: CoordPair, piece: Piece) -> Result<Self, &'static str> {
// extract check here to avoid copy // extract check here to avoid copy
if self.get(i, j).is_some() { if self.get(coord).is_some() {
return Err("position is occupied"); return Err("position is occupied");
} }
let mut self_copy = *self; let mut self_copy = *self;
self_copy.place(i, j, piece).map(|_| self_copy) self_copy.place(coord, piece).map(|_| self_copy)
} }
/// Returns a bool which represents whether or not a move would propegate and be valid /// Returns a bool which represents whether or not a move would propegate and be valid
pub fn would_prop(&self, i: Coord, j: Coord, piece: Piece) -> bool { pub fn would_prop(&self, coord: CoordPair, piece: Piece) -> bool {
self.get(i, j).is_none() && self.propegate_from_dry(i, j, piece).next().is_some() self.get(coord).is_none() && self.propegate_from_dry(coord, piece).next().is_some()
} }
pub fn place(&mut self, i: Coord, j: Coord, piece: Piece) -> Result<(), &'static str> { pub fn place(&mut self, coord: CoordPair, piece: Piece) -> Result<(), &'static str> {
if self.get(i, j).is_some() { if self.get(coord).is_some() {
return Err("position is occupied"); return Err("position is occupied");
} }
self.place_unchecked(i, j, piece); self.place_unchecked(coord, piece);
if self.propegate_from(i, j) == 0 { if self.propegate_from(coord) == 0 {
self.delete(i, j); self.delete(coord);
Err("move would not propegate") Err("move would not propegate")
} else { } else {
Ok(()) Ok(())
@@ -225,8 +225,8 @@ impl Board {
} }
/// Propegate the board and captures starting from a specific position /// Propegate the board and captures starting from a specific position
fn propegate_from(&mut self, i: Coord, j: Coord) -> usize { fn propegate_from(&mut self, coord: CoordPair) -> usize {
let Some(starting_color) = self.get(i, j) else { let Some(starting_color) = self.get(coord) else {
return 0; return 0;
}; };
@@ -235,12 +235,12 @@ impl Board {
// SAFETY! `propegate_from_dry` should not have overlapping chains // SAFETY! `propegate_from_dry` should not have overlapping chains
// if overlapping chains were to exist, `self.place_unchecked` could collide with `self.get` // if overlapping chains were to exist, `self.place_unchecked` could collide with `self.get`
// I now have a check in `ADJ_LOOKUP` on creation // I now have a check in `ADJ_LOOKUP` on creation
(*(self as *const Self)).propegate_from_dry(i, j, starting_color) (*(self as *const Self)).propegate_from_dry(coord, starting_color)
}; };
let mut count = 0; let mut count = 0;
for &(i, j) in iterator { for &coord in iterator {
self.place_unchecked(i, j, starting_color); self.place_unchecked(coord, starting_color);
count += 1; count += 1;
} }
@@ -252,16 +252,15 @@ impl Board {
/// [`Board::place`] or [`Board::place_and_prop_unchecked`] /// [`Board::place`] or [`Board::place_and_prop_unchecked`]
fn propegate_from_dry( fn propegate_from_dry(
&self, &self,
i: Coord, coords: CoordPair,
j: Coord,
starting_color: Piece, starting_color: Piece,
) -> impl Iterator<Item = &(Coord, Coord)> + use<'_> { ) -> impl Iterator<Item = &CoordPair> + use<'_> {
ADJ_LOOKUP ADJ_LOOKUP
.get(i, j) .get(coords)
.iter() .iter()
.flat_map(move |chain| { .flat_map(move |chain| {
for (idx, &(new_i, new_j)) in chain.into_iter().enumerate() { for (idx, &coord) in chain.into_iter().enumerate() {
let piece = self.get(new_i, new_j)?; let piece = self.get(coord)?;
if piece == starting_color { if piece == starting_color {
return chain.get(..idx); return chain.get(..idx);
} }
@@ -310,34 +309,34 @@ mod test {
#[test] #[test]
fn place_and_get() { fn place_and_get() {
let mut board = Board::new(); let mut board = Board::new();
assert_eq!(board.get(0, 0), None); assert_eq!(board.get((0, 0).into()), None);
board.place_unchecked(0, 0, Piece::Black); board.place_unchecked((0, 0).into(), Piece::Black);
assert_eq!(board.get(0, 0), Some(Piece::Black)); assert_eq!(board.get((0, 0).into()), Some(Piece::Black));
} }
#[test] #[test]
fn place_and_capture_simple() { fn place_and_capture_simple() {
let mut board = Board::new(); let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black); board.place_unchecked((0, 0).into(), Piece::Black);
board.place_unchecked(0, 1, Piece::White); board.place_unchecked((0, 1).into(), Piece::White);
assert_eq!(board.place(0, 2, Piece::Black), Ok(())); assert_eq!(board.place((0, 2).into(), Piece::Black), Ok(()));
assert_eq!(board.get(0, 1), Some(Piece::Black)); assert_eq!(board.get((0, 1).into()), Some(Piece::Black));
} }
#[test] #[test]
fn failed_capture() { fn failed_capture() {
let mut board = Board::new(); let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black); board.place_unchecked((0, 0).into(), Piece::Black);
board.place_unchecked(0, 2, Piece::White); board.place_unchecked((0, 2).into(), Piece::White);
// should fail // should fail
assert_ne!(board.place(0, 3, Piece::Black), Ok(())); assert_ne!(board.place((0, 3).into(), Piece::Black), Ok(()));
assert_eq!( assert_eq!(
board.get(0, 1), board.get((0, 1).into()),
None, None,
"(0, 1) was overridden even though it's an empty space" "(0, 1) was overridden even though it's an empty space"
); );
@@ -347,17 +346,17 @@ mod test {
fn long_capture_horiz() { fn long_capture_horiz() {
let mut board = Board::new(); let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black); board.place_unchecked((0, 0).into(), Piece::Black);
for j in 1..=6 { for j in 1..=6 {
board.place_unchecked(0, j, Piece::White); board.place_unchecked((0, j).into(), Piece::White);
} }
assert_eq!(board.place(0, 7, Piece::Black), Ok(())); assert_eq!(board.place((0, 7).into(), Piece::Black), Ok(()));
for j in 2..=6 { for j in 2..=6 {
assert_eq!( assert_eq!(
board.get(0, j), board.get((0, j).into()),
Some(Piece::Black), Some(Piece::Black),
"should be black at: ({}, {})", "should be black at: ({}, {})",
0, 0,
@@ -370,17 +369,17 @@ mod test {
fn long_capture_vert() { fn long_capture_vert() {
let mut board = Board::new(); let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black); board.place_unchecked((0, 0).into(), Piece::Black);
for i in 1..=6 { for i in 1..=6 {
board.place_unchecked(i, 0, Piece::White); board.place_unchecked((i, 0).into(), Piece::White);
} }
assert_eq!(board.place(7, 0, Piece::Black), Ok(())); assert_eq!(board.place((7, 0).into(), Piece::Black), Ok(()));
for i in 2..=6 { for i in 2..=6 {
assert_eq!( assert_eq!(
board.get(i, 0), board.get((i, 0).into()),
Some(Piece::Black), Some(Piece::Black),
"should be black at: ({}, {})", "should be black at: ({}, {})",
i, i,
@@ -395,12 +394,12 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Black pieces at (2, 2) and (0, 0) // Black pieces at (2, 2) and (0, 0)
board.place_unchecked(1, 1, Piece::White); // to be captured board.place_unchecked((1, 1).into(), Piece::White); // to be captured
board.place_unchecked(2, 2, Piece::Black); board.place_unchecked((2, 2).into(), Piece::Black);
assert_eq!(board.place(0, 0, Piece::Black), Ok(())); assert_eq!(board.place((0, 0).into(), Piece::Black), Ok(()));
// Capture white piece at (1,1) // Capture white piece at (1,1)
assert_eq!(board.get(1, 1), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((1, 1).into()), Some(Piece::Black), "\n{}", board);
} }
// Test corner capture from top-right corner // Test corner capture from top-right corner
@@ -409,12 +408,12 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Black pieces at (0, 7) and (2, 5) // Black pieces at (0, 7) and (2, 5)
board.place_unchecked(0, 7, Piece::Black); board.place_unchecked((0, 7).into(), Piece::Black);
board.place_unchecked(1, 6, Piece::White); // to be captured board.place_unchecked((1, 6).into(), Piece::White); // to be captured
assert_eq!(board.place(2, 5, Piece::Black), Ok(())); assert_eq!(board.place((2, 5).into(), Piece::Black), Ok(()));
// Capture white piece at (1, 6) // Capture white piece at (1, 6)
assert_eq!(board.get(1, 6), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((1, 6).into()), Some(Piece::Black), "\n{}", board);
} }
// Test corner capture from bottom-left corner // Test corner capture from bottom-left corner
@@ -423,12 +422,12 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Black pieces at (7, 0) and (5, 2) // Black pieces at (7, 0) and (5, 2)
board.place_unchecked(7, 0, Piece::Black); board.place_unchecked((7, 0).into(), Piece::Black);
board.place_unchecked(6, 1, Piece::White); // to be captured board.place_unchecked((6, 1).into(), Piece::White); // to be captured
assert_eq!(board.place(5, 2, Piece::Black), Ok(())); assert_eq!(board.place((5, 2).into(), Piece::Black), Ok(()));
// Capture white piece at (6, 1) // Capture white piece at (6, 1)
assert_eq!(board.get(6, 1), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((6, 1).into()), Some(Piece::Black), "\n{}", board);
} }
// Test corner capture from bottom-right corner // Test corner capture from bottom-right corner
@@ -437,12 +436,12 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Black pieces at (7, 7) and (5, 5) // Black pieces at (7, 7) and (5, 5)
board.place_unchecked(7, 7, Piece::Black); board.place_unchecked((7, 7).into(), Piece::Black);
board.place_unchecked(6, 6, Piece::White); // to be captured board.place_unchecked((6, 6).into(), Piece::White); // to be captured
assert_eq!(board.place(5, 5, Piece::Black), Ok(())); assert_eq!(board.place((5, 5).into(), Piece::Black), Ok(()));
// Capture white piece at (6, 6) // Capture white piece at (6, 6)
assert_eq!(board.get(6, 6), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((6, 6).into()), Some(Piece::Black), "\n{}", board);
} }
// Test capture from top-left corner (horizontal) // Test capture from top-left corner (horizontal)
@@ -451,11 +450,11 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Create a scenario where a capture should happen horizontally from (0, 0) // Create a scenario where a capture should happen horizontally from (0, 0)
board.place_unchecked(0, 0, Piece::Black); board.place_unchecked((0, 0).into(), Piece::Black);
board.place_unchecked(0, 1, Piece::White); // to be captured board.place_unchecked((0, 1).into(), Piece::White); // to be captured
assert_eq!(board.place(0, 2, Piece::Black), Ok(())); assert_eq!(board.place((0, 2).into(), Piece::Black), Ok(()));
assert_eq!(board.get(0, 1), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((0, 1).into()), Some(Piece::Black), "\n{}", board);
} }
// Test capture from top-right corner (horizontal) // Test capture from top-right corner (horizontal)
@@ -464,11 +463,11 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Create a scenario where a capture should happen horizontally from (0, 7) // Create a scenario where a capture should happen horizontally from (0, 7)
board.place_unchecked(0, 7, Piece::Black); board.place_unchecked((0, 7).into(), Piece::Black);
board.place_unchecked(0, 6, Piece::White); // to be captured board.place_unchecked((0, 6).into(), Piece::White); // to be captured
assert_eq!(board.place(0, 5, Piece::Black), Ok(())); assert_eq!(board.place((0, 5).into(), Piece::Black), Ok(()));
assert_eq!(board.get(0, 6), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((0, 6).into()), Some(Piece::Black), "\n{}", board);
} }
// Test capture from top-left corner (vertical) // Test capture from top-left corner (vertical)
@@ -477,11 +476,11 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Create a scenario where a capture should happen vertically from (0, 0) // Create a scenario where a capture should happen vertically from (0, 0)
board.place_unchecked(0, 0, Piece::Black); board.place_unchecked((0, 0).into(), Piece::Black);
board.place_unchecked(1, 0, Piece::White); // to be captured board.place_unchecked((1, 0).into(), Piece::White); // to be captured
assert_eq!(board.place(2, 0, Piece::Black), Ok(())); assert_eq!(board.place((2, 0).into(), Piece::Black), Ok(()));
assert_eq!(board.get(1, 0), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((1, 0).into()), Some(Piece::Black), "\n{}", board);
} }
// Test capture from bottom-left corner (vertical) // Test capture from bottom-left corner (vertical)
@@ -490,10 +489,10 @@ mod test {
let mut board = Board::new(); let mut board = Board::new();
// Create a scenario where a capture should happen vertically from (7, 0) // Create a scenario where a capture should happen vertically from (7, 0)
board.place_unchecked(7, 0, Piece::Black); board.place_unchecked((7, 0).into(), Piece::Black);
board.place_unchecked(6, 0, Piece::White); // to be captured board.place_unchecked((6, 0).into(), Piece::White); // to be captured
assert_eq!(board.place(5, 0, Piece::Black), Ok(())); assert_eq!(board.place((5, 0).into(), Piece::Black), Ok(()));
assert_eq!(board.get(6, 0), Some(Piece::Black), "\n{}", board); assert_eq!(board.get((6, 0).into()), Some(Piece::Black), "\n{}", board);
} }
} }

View File

@@ -1,13 +1,12 @@
use super::{ use super::{
board::Coord, misc::{diag_raw, split_from},
misc::{diag_raw, get_index, split_from}, Board, CoordPair,
Board,
}; };
use arrayvec::ArrayVec; use arrayvec::ArrayVec;
use std::collections::HashSet; use std::collections::HashSet;
/// A chain of positions across the board /// A chain of positions across the board
type Chain = ArrayVec<(Coord, Coord), { (Board::BOARD_SIZE - 1) as usize }>; type Chain = ArrayVec<CoordPair, { (Board::BOARD_SIZE - 1) as usize }>;
/// A collection of chains (up vert, down vert, left horiz, right horiz, diagonals....) /// A collection of chains (up vert, down vert, left horiz, right horiz, diagonals....)
pub type ChainCollection = ArrayVec<Chain, 8>; pub type ChainCollection = ArrayVec<Chain, 8>;
@@ -25,27 +24,24 @@ impl<T: Default> PosMap<T> {
)) ))
} }
pub fn get(&self, row: Coord, col: Coord) -> &T { pub fn get(&self, coords: CoordPair) -> &T {
let index = get_index(row, col);
debug_assert!( debug_assert!(
Board::BOARD_AREA + 1 >= index, Board::BOARD_AREA + 1 >= coords.0,
"index out of range, was: {}", "index out of range, was: {:?}",
index coords
); );
unsafe { self.0.get_unchecked(index as usize) } unsafe { self.0.get_unchecked(coords.0 as usize) }
} }
pub fn set(&mut self, row: Coord, col: Coord, value: T) { pub fn set(&mut self, coords: CoordPair, value: T) {
let index = get_index(row, col);
debug_assert!( debug_assert!(
Board::BOARD_AREA + 1 >= index, Board::BOARD_AREA + 1 >= coords.0,
"index out of range, was: {}", "index out of range, was: {:?}",
index coords
); );
self.0[index as usize] = value; self.0[coords.0 as usize] = value;
} }
} }
@@ -56,7 +52,7 @@ impl<T: Default + Copy> From<PosMapOrig<T>> for PosMap<T> {
let mut new = Self::new(); let mut new = Self::new();
for i in 0..Board::BOARD_SIZE { for i in 0..Board::BOARD_SIZE {
for j in 0..Board::BOARD_SIZE { for j in 0..Board::BOARD_SIZE {
new.set(i, j, value[i as usize][j as usize]); new.set((i, j).into(), value[i as usize][j as usize]);
} }
} }
new new
@@ -67,7 +63,8 @@ impl<T: Default + Copy> From<PosMapOrig<T>> for PosMap<T> {
pub fn gen_adj_lookup() -> PosMap<ChainCollection> { pub fn gen_adj_lookup() -> PosMap<ChainCollection> {
PosMap( PosMap(
Board::all_positions() Board::all_positions()
.map(|(i, j)| { .map(|coord| {
let (i, j) = coord.into();
let (i_chain, j_chain) = ( let (i_chain, j_chain) = (
split_from(0..=Board::BOARD_SIZE - 1, i), split_from(0..=Board::BOARD_SIZE - 1, i),
split_from(0..=Board::BOARD_SIZE - 1, j), split_from(0..=Board::BOARD_SIZE - 1, j),
@@ -86,7 +83,8 @@ pub fn gen_adj_lookup() -> PosMap<ChainCollection> {
.map(|range| range.map(move |j| (i, j))) .map(|range| range.map(move |j| (i, j)))
.map(Iterator::collect), .map(Iterator::collect),
) )
.chain(diag_raw(i_chain, j_chain).map(Iterator::collect)), .chain(diag_raw(i_chain, j_chain).map(Iterator::collect))
.map(|x: Vec<(u8, u8)>| x.into_iter().map(|x| x.into()).collect()),
); );
// make sure all chains are in the proper range so we can ignore bounds checking later // make sure all chains are in the proper range so we can ignore bounds checking later
@@ -94,8 +92,9 @@ pub fn gen_adj_lookup() -> PosMap<ChainCollection> {
chains chains
.iter() .iter()
.flatten() .flatten()
.map(|&x| x.into())
.flat_map(|(i, j)| [i, j]) // flatten to just numbers .flat_map(|(i, j)| [i, j]) // flatten to just numbers
.all(|x| (0..Board::BOARD_SIZE).contains(x)), .all(|x| (0..Board::BOARD_SIZE).contains(&x)),
"chains go out-of-bounds" "chains go out-of-bounds"
); );

63
src/repr/coords.rs Normal file
View File

@@ -0,0 +1,63 @@
use std::fmt::Display;
use super::Board;
use static_assertions::const_assert;
// PERF! having `Coord` be of type `u8` (instead of usize) increases
// performance by about 1-2% overall
pub type CoordAxis = u8;
pub type CoordPairInner = u8;
const_assert!(CoordPairInner::MAX as usize >= Board::BOARD_AREA as usize);
#[derive(PartialEq, Eq, Copy, Clone, Hash)]
pub struct CoordPair(pub CoordPairInner);
impl Display for CoordPair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (i, j) = (*self).into();
write!(f, "({}, {})", i, j)
}
}
impl std::fmt::Debug for CoordPair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
/// Convert a row and column to an index in the board
pub const fn get_index(row: CoordAxis, col: CoordAxis) -> CoordPair {
CoordPair(row * Board::BOARD_SIZE + col)
}
pub const fn from_index(index: CoordPair) -> (CoordAxis, CoordAxis) {
let row = index.0 % Board::BOARD_SIZE;
let col = (index.0 - row) / Board::BOARD_SIZE;
(col, row)
}
impl From<(CoordAxis, CoordAxis)> for CoordPair {
fn from(value: (CoordAxis, CoordAxis)) -> Self {
get_index(value.0, value.1)
}
}
impl From<CoordPair> for (CoordAxis, CoordAxis) {
fn from(val: CoordPair) -> Self {
from_index(val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn into_outof() {
let a: CoordPair = (1, 3).into();
let back: (CoordAxis, CoordAxis) = a.into();
assert_eq!(back, (1, 3));
}
}

View File

@@ -1,4 +1,3 @@
use super::{board::Coord, Board};
use either::Either; use either::Either;
use std::{iter::Rev, ops::RangeInclusive}; use std::{iter::Rev, ops::RangeInclusive};
@@ -39,11 +38,6 @@ where
[(0, 0), (1, 1), (1, 0), (0, 1)].map(move |(a, b)| i_chains[a].clone().zip(j_chains[b].clone())) [(0, 0), (1, 1), (1, 0), (0, 1)].map(move |(a, b)| i_chains[a].clone().zip(j_chains[b].clone()))
} }
/// Convert a row and column to an index in the board
pub const fn get_index(row: Coord, col: Coord) -> Coord {
row * Board::BOARD_SIZE + col
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
@@ -82,7 +76,7 @@ mod test {
// test out-of-bounds and also generics // test out-of-bounds and also generics
assert_eq!( assert_eq!(
split_from::<i16>(-1i16..=4i16, 10i16).map(Iterator::collect::<Vec<i16>>), split_from::<i16>(-1i16..=4i16, 10i16).map(Iterator::collect::<Vec<i16>>),
[const { Vec::new() }; 2] [const { Vec::<i16>::new() }; 2]
); );
} }

View File

@@ -1,9 +1,11 @@
mod bitboard; mod bitboard;
mod board; mod board;
mod chains; mod chains;
mod coords;
mod misc; mod misc;
mod piece; mod piece;
pub use board::{Board, Coord, Winner}; pub use board::{Board, Winner};
pub use chains::PosMap; pub use chains::PosMap;
pub use coords::{CoordAxis, CoordPair};
pub use piece::Piece; pub use piece::Piece;