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 std::io;
use std::io::prelude::*;
@@ -6,7 +6,7 @@ use std::io::prelude::*;
#[allow(dead_code)]
pub trait 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`]
fn name(&self) -> &'static str;
/// Returns the color the [`Agent`] is playing
@@ -27,7 +27,7 @@ impl ManualAgent {
#[allow(dead_code)]
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 mut input = String::new();
println!("Your turn! ('Skip' to skip)");
@@ -44,15 +44,15 @@ impl Agent for ManualAgent {
.map(str::parse)
.map(Result::ok)
.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]));
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.");
continue;
}
return Some(got);
return Some(got.into());
}
}
}
@@ -73,7 +73,7 @@ pub struct RandomAgent {
#[allow(dead_code)]
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())
}

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
use crate::{
logic::r#move::Move,
repr::{Board, Coord, Piece, Winner},
repr::{Board, CoordPair, Piece, Winner},
};
use indicatif::{ProgressIterator, ProgressStyle};
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;
if cf.is_break() {
dbg!("extend_layers: early break ({})", self.arena_len());
println!("extend_layers: early break");
return;
}
}
@@ -130,14 +130,14 @@ impl FutureMoves {
// 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`]
let mut new: Vec<Move> = Board::all_positions()
.flat_map(|(i, j)| {
.flat_map(|coord| {
parent
.board
.what_if(i, j, new_color)
.map(move |x| (i, j, x))
.what_if(coord, new_color)
.map(move |x| (coord, x))
})
.map(|(i, j, new_board)| {
Move::new(Some((i, j)), new_board, new_color, self.agent_color)
.map(|(coord, new_board)| {
Move::new(Some(coord), new_board, new_color, self.agent_color)
})
.collect();
@@ -200,32 +200,26 @@ impl FutureMoves {
// 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 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]
.children
.iter()
.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 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
// just performance (cycles/time wise)
self.arena[idx].value = Some(
(self.arena[idx].self_value as i128 + children_value) / (depth + 1) as i128,
);
self.arena[idx].value = Some(self.arena[idx].self_value as i128 + children_value);
}
}
}
/// 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
.and_then(|x| {
self.arena[x]
@@ -256,11 +250,11 @@ impl FutureMoves {
if let Some(curr_board_idx) = curr_board {
self.set_root_idx_raw(curr_board_idx);
return false;
false
} else {
dbg!("regenerating arena from board");
println!("regenerating arena from board");
self.set_root_from_board(*board);
return true;
true
}
}
@@ -269,6 +263,7 @@ impl FutureMoves {
self.arena.clear();
self.arena
.push(Move::new(None, board, !self.agent_color, self.agent_color));
// because we have to regenerate root from a [`Board`]
// we need to reset the current_depth (fixes `skip_move_recovery`)
self.current_depth = 0;
@@ -291,7 +286,7 @@ impl FutureMoves {
self.compute_values(0..self.arena.len());
// 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) {
@@ -485,7 +480,7 @@ mod tests {
// dummy (2)
futm.arena.push(Move::new(
Some((123, 123)),
Some((9, 9).into()),
Board::new(),
Piece::White,
Piece::Black,
@@ -509,7 +504,7 @@ mod tests {
assert_ne!(
futm.arena[2].coord,
Some((123, 123)),
Some((9, 9).into()),
"dummy value still exists"
);
}
@@ -682,8 +677,8 @@ mod tests {
}
}
if let Some((i, j)) = coords {
board.place(i, j, color).unwrap();
if let Some(coord) = coords {
board.place(coord.into(), color).unwrap();
}
}
}

View File

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

View File

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

View File

@@ -2,15 +2,12 @@ use super::{
bitboard::BitBoard,
chains::{gen_adj_lookup, ChainCollection, PosMap},
piece::Piece,
CoordAxis, CoordPair,
};
use const_fn::const_fn;
use lazy_static::lazy_static;
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)]
pub enum Winner {
Player(Piece),
@@ -58,7 +55,10 @@ impl fmt::Display for Board {
write!(
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)?;
@@ -86,10 +86,10 @@ impl fmt::Debug for Board {
}
impl Board {
pub const BOARD_SIZE: Coord = 8;
pub const BOARD_SIZE: CoordAxis = 8;
/// 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
#[allow(clippy::new_without_default)]
@@ -101,39 +101,39 @@ impl Board {
}
/// Starting position
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn starting_pos(mut self) -> Self {
pub fn starting_pos(mut self) -> Self {
self.place_unchecked(
(Self::BOARD_SIZE / 2) - 1,
(Self::BOARD_SIZE / 2) - 1,
((Self::BOARD_SIZE / 2) - 1, (Self::BOARD_SIZE / 2) - 1).into(),
Piece::White,
);
self.place_unchecked(
Self::BOARD_SIZE / 2,
(Self::BOARD_SIZE / 2) - 1,
(Self::BOARD_SIZE / 2, (Self::BOARD_SIZE / 2) - 1).into(),
Piece::Black,
);
self.place_unchecked(
(Self::BOARD_SIZE / 2) - 1,
Self::BOARD_SIZE / 2,
((Self::BOARD_SIZE / 2) - 1, Self::BOARD_SIZE / 2).into(),
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
}
/// Provides an iterator of all possible positions on the board
pub fn all_positions() -> impl Iterator<Item = (Coord, Coord)> {
(0..Self::BOARD_SIZE)
.flat_map(|i| (0..Self::BOARD_SIZE).map(move |j| (i as Coord, j as Coord)))
pub fn all_positions() -> impl Iterator<Item = CoordPair> {
(0..Self::BOARD_SIZE).flat_map(|i| {
(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
pub fn possible_moves(&self, color: Piece) -> impl Iterator<Item = (Coord, Coord)> + use<'_> {
Self::all_positions().filter(move |&(i, j)| self.would_prop(i, j, color))
pub fn possible_moves(&self, color: Piece) -> impl Iterator<Item = CoordPair> + use<'_> {
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)
.map(|i| (i, Self::BOARD_SIZE - 1))
.chain((0..Self::BOARD_SIZE).map(|i| (i, 0)))
@@ -141,7 +141,7 @@ impl Board {
.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]
.into_iter()
.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")))]
pub const fn get_piece(&self, i: Coord, j: Coord, color: Piece) -> bool {
self.board(color).get(i, j)
pub const fn get_piece(&self, coord: CoordPair, color: Piece) -> bool {
self.board(color).get(coord)
}
/// Returns the color of a place on the [`Board`] at a position
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn get(&self, i: Coord, j: Coord) -> Option<Piece> {
if self.get_piece(i, j, Piece::White) {
pub const fn get(&self, coord: CoordPair) -> Option<Piece> {
if self.get_piece(coord, 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)
} else {
None
@@ -182,42 +182,42 @@ impl Board {
/// Place a piece without checking for propegation of validity
#[const_fn(cfg(not(feature = "bitvec")))]
const fn place_unchecked(&mut self, i: Coord, j: Coord, piece: Piece) {
self.board_mut(piece).set(i, j, true);
self.board_mut(piece.flip()).set(i, j, false);
const fn place_unchecked(&mut self, coord: CoordPair, piece: Piece) {
self.board_mut(piece).set(coord, true);
self.board_mut(piece.flip()).set(coord, false);
}
#[const_fn(cfg(not(feature = "bitvec")))]
const fn delete(&mut self, i: Coord, j: Coord) {
self.board_mut(Piece::White).set(i, j, false);
self.board_mut(Piece::Black).set(i, j, false);
const fn delete(&mut self, coord: CoordPair) {
self.board_mut(Piece::White).set(coord, false);
self.board_mut(Piece::Black).set(coord, false);
}
/// Return a modified [`Board`] with the piece placed at a position
/// 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
if self.get(i, j).is_some() {
if self.get(coord).is_some() {
return Err("position is occupied");
}
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
pub fn would_prop(&self, i: Coord, j: Coord, piece: Piece) -> bool {
self.get(i, j).is_none() && self.propegate_from_dry(i, j, piece).next().is_some()
pub fn would_prop(&self, coord: CoordPair, piece: Piece) -> bool {
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> {
if self.get(i, j).is_some() {
pub fn place(&mut self, coord: CoordPair, piece: Piece) -> Result<(), &'static str> {
if self.get(coord).is_some() {
return Err("position is occupied");
}
self.place_unchecked(i, j, piece);
if self.propegate_from(i, j) == 0 {
self.delete(i, j);
self.place_unchecked(coord, piece);
if self.propegate_from(coord) == 0 {
self.delete(coord);
Err("move would not propegate")
} else {
Ok(())
@@ -225,8 +225,8 @@ impl Board {
}
/// Propegate the board and captures starting from a specific position
fn propegate_from(&mut self, i: Coord, j: Coord) -> usize {
let Some(starting_color) = self.get(i, j) else {
fn propegate_from(&mut self, coord: CoordPair) -> usize {
let Some(starting_color) = self.get(coord) else {
return 0;
};
@@ -235,12 +235,12 @@ impl Board {
// SAFETY! `propegate_from_dry` should not have overlapping chains
// if overlapping chains were to exist, `self.place_unchecked` could collide with `self.get`
// 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;
for &(i, j) in iterator {
self.place_unchecked(i, j, starting_color);
for &coord in iterator {
self.place_unchecked(coord, starting_color);
count += 1;
}
@@ -252,16 +252,15 @@ impl Board {
/// [`Board::place`] or [`Board::place_and_prop_unchecked`]
fn propegate_from_dry(
&self,
i: Coord,
j: Coord,
coords: CoordPair,
starting_color: Piece,
) -> impl Iterator<Item = &(Coord, Coord)> + use<'_> {
) -> impl Iterator<Item = &CoordPair> + use<'_> {
ADJ_LOOKUP
.get(i, j)
.get(coords)
.iter()
.flat_map(move |chain| {
for (idx, &(new_i, new_j)) in chain.into_iter().enumerate() {
let piece = self.get(new_i, new_j)?;
for (idx, &coord) in chain.into_iter().enumerate() {
let piece = self.get(coord)?;
if piece == starting_color {
return chain.get(..idx);
}
@@ -310,34 +309,34 @@ mod test {
#[test]
fn place_and_get() {
let mut board = Board::new();
assert_eq!(board.get(0, 0), None);
board.place_unchecked(0, 0, Piece::Black);
assert_eq!(board.get(0, 0), Some(Piece::Black));
assert_eq!(board.get((0, 0).into()), None);
board.place_unchecked((0, 0).into(), Piece::Black);
assert_eq!(board.get((0, 0).into()), Some(Piece::Black));
}
#[test]
fn place_and_capture_simple() {
let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black);
board.place_unchecked(0, 1, Piece::White);
board.place_unchecked((0, 0).into(), Piece::Black);
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]
fn failed_capture() {
let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black);
board.place_unchecked(0, 2, Piece::White);
board.place_unchecked((0, 0).into(), Piece::Black);
board.place_unchecked((0, 2).into(), Piece::White);
// should fail
assert_ne!(board.place(0, 3, Piece::Black), Ok(()));
assert_ne!(board.place((0, 3).into(), Piece::Black), Ok(()));
assert_eq!(
board.get(0, 1),
board.get((0, 1).into()),
None,
"(0, 1) was overridden even though it's an empty space"
);
@@ -347,17 +346,17 @@ mod test {
fn long_capture_horiz() {
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 {
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 {
assert_eq!(
board.get(0, j),
board.get((0, j).into()),
Some(Piece::Black),
"should be black at: ({}, {})",
0,
@@ -370,17 +369,17 @@ mod test {
fn long_capture_vert() {
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 {
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 {
assert_eq!(
board.get(i, 0),
board.get((i, 0).into()),
Some(Piece::Black),
"should be black at: ({}, {})",
i,
@@ -395,12 +394,12 @@ mod test {
let mut board = Board::new();
// Black pieces at (2, 2) and (0, 0)
board.place_unchecked(1, 1, Piece::White); // to be captured
board.place_unchecked(2, 2, Piece::Black);
assert_eq!(board.place(0, 0, Piece::Black), Ok(()));
board.place_unchecked((1, 1).into(), Piece::White); // to be captured
board.place_unchecked((2, 2).into(), Piece::Black);
assert_eq!(board.place((0, 0).into(), Piece::Black), Ok(()));
// 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
@@ -409,12 +408,12 @@ mod test {
let mut board = Board::new();
// Black pieces at (0, 7) and (2, 5)
board.place_unchecked(0, 7, Piece::Black);
board.place_unchecked(1, 6, Piece::White); // to be captured
assert_eq!(board.place(2, 5, Piece::Black), Ok(()));
board.place_unchecked((0, 7).into(), Piece::Black);
board.place_unchecked((1, 6).into(), Piece::White); // to be captured
assert_eq!(board.place((2, 5).into(), Piece::Black), Ok(()));
// 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
@@ -423,12 +422,12 @@ mod test {
let mut board = Board::new();
// Black pieces at (7, 0) and (5, 2)
board.place_unchecked(7, 0, Piece::Black);
board.place_unchecked(6, 1, Piece::White); // to be captured
assert_eq!(board.place(5, 2, Piece::Black), Ok(()));
board.place_unchecked((7, 0).into(), Piece::Black);
board.place_unchecked((6, 1).into(), Piece::White); // to be captured
assert_eq!(board.place((5, 2).into(), Piece::Black), Ok(()));
// 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
@@ -437,12 +436,12 @@ mod test {
let mut board = Board::new();
// Black pieces at (7, 7) and (5, 5)
board.place_unchecked(7, 7, Piece::Black);
board.place_unchecked(6, 6, Piece::White); // to be captured
assert_eq!(board.place(5, 5, Piece::Black), Ok(()));
board.place_unchecked((7, 7).into(), Piece::Black);
board.place_unchecked((6, 6).into(), Piece::White); // to be captured
assert_eq!(board.place((5, 5).into(), Piece::Black), Ok(()));
// 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)
@@ -451,11 +450,11 @@ mod test {
let mut board = Board::new();
// Create a scenario where a capture should happen horizontally from (0, 0)
board.place_unchecked(0, 0, Piece::Black);
board.place_unchecked(0, 1, Piece::White); // to be captured
assert_eq!(board.place(0, 2, Piece::Black), Ok(()));
board.place_unchecked((0, 0).into(), Piece::Black);
board.place_unchecked((0, 1).into(), Piece::White); // to be captured
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)
@@ -464,11 +463,11 @@ mod test {
let mut board = Board::new();
// Create a scenario where a capture should happen horizontally from (0, 7)
board.place_unchecked(0, 7, Piece::Black);
board.place_unchecked(0, 6, Piece::White); // to be captured
assert_eq!(board.place(0, 5, Piece::Black), Ok(()));
board.place_unchecked((0, 7).into(), Piece::Black);
board.place_unchecked((0, 6).into(), Piece::White); // to be captured
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)
@@ -477,11 +476,11 @@ mod test {
let mut board = Board::new();
// Create a scenario where a capture should happen vertically from (0, 0)
board.place_unchecked(0, 0, Piece::Black);
board.place_unchecked(1, 0, Piece::White); // to be captured
assert_eq!(board.place(2, 0, Piece::Black), Ok(()));
board.place_unchecked((0, 0).into(), Piece::Black);
board.place_unchecked((1, 0).into(), Piece::White); // to be captured
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)
@@ -490,10 +489,10 @@ mod test {
let mut board = Board::new();
// Create a scenario where a capture should happen vertically from (7, 0)
board.place_unchecked(7, 0, Piece::Black);
board.place_unchecked(6, 0, Piece::White); // to be captured
assert_eq!(board.place(5, 0, Piece::Black), Ok(()));
board.place_unchecked((7, 0).into(), Piece::Black);
board.place_unchecked((6, 0).into(), Piece::White); // to be captured
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::{
board::Coord,
misc::{diag_raw, get_index, split_from},
Board,
misc::{diag_raw, split_from},
Board, CoordPair,
};
use arrayvec::ArrayVec;
use std::collections::HashSet;
/// 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....)
pub type ChainCollection = ArrayVec<Chain, 8>;
@@ -25,27 +24,24 @@ impl<T: Default> PosMap<T> {
))
}
pub fn get(&self, row: Coord, col: Coord) -> &T {
let index = get_index(row, col);
pub fn get(&self, coords: CoordPair) -> &T {
debug_assert!(
Board::BOARD_AREA + 1 >= index,
"index out of range, was: {}",
index
Board::BOARD_AREA + 1 >= coords.0,
"index out of range, was: {:?}",
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) {
let index = get_index(row, col);
pub fn set(&mut self, coords: CoordPair, value: T) {
debug_assert!(
Board::BOARD_AREA + 1 >= index,
"index out of range, was: {}",
index
Board::BOARD_AREA + 1 >= coords.0,
"index out of range, was: {:?}",
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();
for i 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
@@ -67,7 +63,8 @@ impl<T: Default + Copy> From<PosMapOrig<T>> for PosMap<T> {
pub fn gen_adj_lookup() -> PosMap<ChainCollection> {
PosMap(
Board::all_positions()
.map(|(i, j)| {
.map(|coord| {
let (i, j) = coord.into();
let (i_chain, j_chain) = (
split_from(0..=Board::BOARD_SIZE - 1, i),
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(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
@@ -94,8 +92,9 @@ pub fn gen_adj_lookup() -> PosMap<ChainCollection> {
chains
.iter()
.flatten()
.map(|&x| x.into())
.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"
);

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 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()))
}
/// 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)]
mod test {
use super::*;
@@ -82,7 +76,7 @@ mod test {
// test out-of-bounds and also generics
assert_eq!(
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 board;
mod chains;
mod coords;
mod misc;
mod piece;
pub use board::{Board, Coord, Winner};
pub use board::{Board, Winner};
pub use chains::PosMap;
pub use coords::{CoordAxis, CoordPair};
pub use piece::Piece;