split off repr

This commit is contained in:
2025-02-20 16:05:14 -05:00
parent 73faf4c1fb
commit 1fe7658deb
14 changed files with 27 additions and 23 deletions

101
src/repr/bitboard.rs Normal file
View File

@@ -0,0 +1,101 @@
use crate::repr::board::{BOARD_AREA, BOARD_SIZE};
use const_fn::const_fn;
use static_assertions::const_assert;
// quick explanation for the dual-nature of [`BitBoard`]
// There's both a `bitvec` impl (which is variable length)
// and a `native` impl which uses a u64 as the backing type
// the `native` impl is ~15-25% faster (in non-BitBoard specific benchmarks)
// `bitvec` is only really useful if you're using esoteric board sizes
#[cfg(feature = "bitvec")]
use bitvec::prelude::*;
#[cfg(feature = "bitvec")]
type BBBaseType = u64;
#[cfg(feature = "bitvec")]
pub type BitBoardInner = BitArr!(for BOARD_AREA, in BBBaseType, Lsb0);
#[cfg(not(feature = "bitvec"))]
pub type BitBoardInner = u64;
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct BitBoard(BitBoardInner);
// BitBoard should be big enough to fit all points on the board
const_assert!(std::mem::size_of::<BitBoard>() * 8 >= BOARD_AREA);
impl Default for BitBoard {
fn default() -> Self {
Self::new()
}
}
impl BitBoard {
#[cfg(feature = "bitvec")]
pub const fn new() -> Self {
Self(bitarr!(BBBaseType, Lsb0; 0; BOARD_AREA))
}
#[cfg(not(feature = "bitvec"))]
pub const fn new() -> Self {
Self(0)
}
#[cfg(not(feature = "bitvec"))]
pub const fn get(&self, row: usize, col: usize) -> bool {
((self.0 >> Self::get_index(row, col)) & 0b1) != 0b0
}
#[cfg(not(feature = "bitvec"))]
pub const fn set(&mut self, row: usize, col: usize, value: bool) {
let index = Self::get_index(row, col);
// PERF! branchless setting of bit (~+3% perf bump)
self.0 &= !(0b1 << index); // clear bit
self.0 |= (value as BitBoardInner) << index; // set bit (if needed)
}
const fn get_index(row: usize, col: usize) -> usize {
row * BOARD_SIZE + col
}
#[cfg(feature = "bitvec")]
pub fn get(&self, row: usize, col: usize) -> bool {
self.0[Self::get_index(row, col)]
}
#[cfg(feature = "bitvec")]
pub fn set(&mut self, row: usize, col: usize, value: bool) {
self.0.set(Self::get_index(row, col), value);
}
// works on both `bitvec` and native (const on native)
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn count(&self) -> usize {
self.0.count_ones() as usize
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn set_and_get() {
let mut b = BitBoard::new();
for i in 0..BOARD_SIZE {
for j in 0..BOARD_SIZE {
assert!(
!b.get(i, j),
"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));
}
}

562
src/repr/board.rs Normal file
View File

@@ -0,0 +1,562 @@
use crate::repr::{
bitboard::BitBoard,
misc::{diag_raw, split_from},
piece::Piece,
};
use arrayvec::ArrayVec;
use const_fn::const_fn;
use lazy_static::lazy_static;
use std::{cmp::Ordering, collections::HashSet, fmt};
/// Size of each dim of the board
pub const BOARD_SIZE: usize = 8;
/// Area of the board
#[allow(dead_code)]
pub const BOARD_AREA: usize = BOARD_SIZE * BOARD_SIZE;
const BOARD_SIZE_N1: usize = BOARD_SIZE - 1;
/// A chain of positions across the board
type Chain = ArrayVec<(usize, usize), BOARD_SIZE_N1>;
/// A collection of chains (up vert, down vert, left horiz, right horiz, diagonals....)
type ChainCollection = ArrayVec<Chain, 8>;
/// Map of all points on the board against some type T
/// Used to index like so: example[i][j]
/// with each coordinate
struct PosMap<T>(ArrayVec<T, BOARD_AREA>);
impl<T> PosMap<T> {
pub fn get(&self, row: usize, col: usize) -> &T {
let index = row * BOARD_SIZE + col;
debug_assert!(
BOARD_AREA + 1 >= index,
"index out of range, was: {}",
index
);
unsafe { self.0.get_unchecked(index) }
}
}
/// Creates a lookup map for adjacencies and chains from each position on the board
fn gen_adj_lookup() -> PosMap<ChainCollection> {
PosMap(
Board::all_positions()
.map(|(i, j)| {
let (i_chain, j_chain) = (
split_from(0..=BOARD_SIZE - 1, i),
split_from(0..=BOARD_SIZE - 1, j),
);
let chains: ChainCollection = ArrayVec::from_iter(
i_chain
.clone()
.into_iter()
.map(|range| range.map(move |i| (i, j)))
.map(Iterator::collect)
.chain(
j_chain
.clone()
.into_iter()
.map(|range| range.map(move |j| (i, j)))
.map(Iterator::collect),
)
.chain(diag_raw(i_chain, j_chain).map(Iterator::collect)),
);
// make sure all chains are in the proper range so we can ignore bounds checking later
assert!(
chains
.iter()
.flatten()
.flat_map(|(i, j)| [i, j]) // flatten to just numbers
.all(|x| (0..BOARD_SIZE).contains(x)),
"chains go out-of-bounds"
);
// SAFETY! ensure all nodes in all chains are unique across chains, ensures beavior in
// [`Board::propegate_from`]
let mut uniq = HashSet::new();
assert!(
chains.iter().flatten().all(move |x| uniq.insert(x)),
"there are duplicate nodes in chain"
);
chains
})
.collect(),
)
}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Winner {
Player(Piece),
Tie,
None,
}
lazy_static! {
/// Precompute all possible chains for each position on the board
static ref ADJ_LOOKUP: PosMap<ChainCollection> = gen_adj_lookup();
}
/// Repersents a Othello game board at a certain space
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Board {
/// [`BitBoard`] containing all white pieces
white_board: BitBoard,
/// [`BitBoard`] containing all black pieces
black_board: BitBoard,
}
impl fmt::Display for Board {
#[allow(clippy::repeat_once)] // clippy gets mad about when PADDING == 1
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let horiz_sep_line = "-".repeat(BOARD_SIZE * 2 + 1);
// basically calculates the # of digits BOARD_SIZE needs
const PADDING: usize = (BOARD_SIZE - 1).ilog10() as usize + 1;
let space_padding = " ".repeat(PADDING);
// Print numbers at top so the board can be read more easier
write!(f, "{} ", space_padding)?;
for j in (0..BOARD_SIZE).rev() {
write!(f, "{:0PADDING$} ", j)?;
}
writeln!(f)?;
for i in (0..BOARD_SIZE).rev() {
writeln!(f, "{}{}", space_padding, horiz_sep_line)?;
write!(f, "{:0PADDING$}|", i)?;
for j in (0..BOARD_SIZE).rev() {
write!(
f,
"{}|",
self.get(i, j).as_ref().map(Piece::symbol).unwrap_or(' ')
)?;
}
writeln!(f)?;
}
// put a line at the bottom of the board too
writeln!(f, " {}", horiz_sep_line)?;
// Print the current score
write!(
f,
"{}",
[Piece::White, Piece::Black]
.map(|p| format!("{} Score: {}\n", p.text(), self.count(p)))
.concat()
)?;
Ok(())
}
}
impl fmt::Debug for Board {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl Default for Board {
fn default() -> Self {
Self::new()
}
}
impl Board {
/// Create a new empty board
pub const fn new() -> Self {
Self {
white_board: BitBoard::new(),
black_board: BitBoard::new(),
}
}
/// Starting position
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn starting_pos(mut self) -> Self {
self.place_unchecked((BOARD_SIZE / 2) - 1, (BOARD_SIZE / 2) - 1, Piece::White);
self.place_unchecked(BOARD_SIZE / 2, (BOARD_SIZE / 2) - 1, Piece::Black);
self.place_unchecked((BOARD_SIZE / 2) - 1, BOARD_SIZE / 2, Piece::Black);
self.place_unchecked(BOARD_SIZE / 2, BOARD_SIZE / 2, Piece::White);
self
}
/// Provides an iterator of all possible positions on the board
pub fn all_positions() -> impl Iterator<Item = (usize, usize)> {
(0..BOARD_SIZE).flat_map(|i| (0..BOARD_SIZE).map(move |j| (i, j)))
}
/// Returns an iterator of all possible moves a `color` can make
pub fn possible_moves(&self, color: Piece) -> impl Iterator<Item = (usize, usize)> + use<'_> {
Self::all_positions().filter(move |&(i, j)| self.would_prop(i, j, color))
}
pub fn sides() -> impl Iterator<Item = (usize, usize)> {
(0..BOARD_SIZE)
.map(|i| (i, BOARD_SIZE - 1))
.chain((0..BOARD_SIZE).map(|i| (i, 0)))
.chain((0..BOARD_SIZE).map(|j| (BOARD_SIZE - 1, j)))
.chain((0..BOARD_SIZE).map(|j| (0, j)))
}
/// Get a reference to a backing [`BitBoard`]
const fn board(&self, color: Piece) -> &BitBoard {
match color {
Piece::Black => &self.black_board,
Piece::White => &self.white_board,
}
}
/// Get a mutable reference to a backing [`BitBoard`]
const fn board_mut(&mut self, color: Piece) -> &mut BitBoard {
match color {
Piece::Black => &mut self.black_board,
Piece::White => &mut self.white_board,
}
}
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn get_piece(&self, i: usize, j: usize, color: Piece) -> bool {
self.board(color).get(i, j)
}
/// Returns the color of a place on the [`Board`] at a position
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn get(&self, i: usize, j: usize) -> Option<Piece> {
if self.get_piece(i, j, Piece::White) {
Some(Piece::White)
} else if self.get_piece(i, j, Piece::Black) {
Some(Piece::Black)
} else {
None
}
}
/// Place a piece without checking for propegation of validity
#[const_fn(cfg(not(feature = "bitvec")))]
const fn place_unchecked(&mut self, i: usize, j: usize, piece: Piece) {
self.board_mut(piece).set(i, j, true);
self.board_mut(piece.flip()).set(i, j, false);
}
#[const_fn(cfg(not(feature = "bitvec")))]
const fn delete(&mut self, i: usize, j: usize) {
self.board_mut(Piece::White).set(i, j, false);
self.board_mut(Piece::Black).set(i, j, 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: usize, j: usize, piece: Piece) -> Result<Self, &'static str> {
// extract check here to avoid copy
if self.get(i, j).is_some() {
return Err("position is occupied");
}
let mut self_copy = *self;
self_copy.place(i, j, 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: usize, j: usize, piece: Piece) -> bool {
self.get(i, j).is_none() && self.propegate_from_dry(i, j, piece).next().is_some()
}
pub fn place(&mut self, i: usize, j: usize, piece: Piece) -> Result<(), &'static str> {
if self.get(i, j).is_some() {
return Err("position is occupied");
}
self.place_unchecked(i, j, piece);
if self.propegate_from(i, j) == 0 {
self.delete(i, j);
Err("move would not propegate")
} else {
Ok(())
}
}
/// Propegate the board and captures starting from a specific position
fn propegate_from(&mut self, i: usize, j: usize) -> usize {
let Some(starting_color) = self.get(i, j) else {
return 0;
};
// PERF! avoid clones and collections here using raw pointers
let iterator = unsafe {
// 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)
};
let mut count = 0;
for &(i, j) in iterator {
self.place_unchecked(i, j, starting_color);
count += 1;
}
count
}
/// Propegate piece captures originating from (i, j)
/// DO NOT USE THIS ALONE, this should be called as a part of
/// [`Board::place`] or [`Board::place_and_prop_unchecked`]
fn propegate_from_dry(
&self,
i: usize,
j: usize,
starting_color: Piece,
) -> impl Iterator<Item = &(usize, usize)> + use<'_> {
ADJ_LOOKUP
.get(i, j)
.iter()
.flat_map(move |chain| {
for (idx, &(new_i, new_j)) in chain.into_iter().enumerate() {
let piece = self.get(new_i, new_j)?;
if piece == starting_color {
// SAFETY! get_unchecked is fine here because it's an index of itself, it's fine
return Some(unsafe { chain.get_unchecked(..idx) });
}
}
None
})
.flatten()
}
/// Count the number of a type of [`Piece`] on the board
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn count(&self, piece: Piece) -> usize {
self.board(piece).count()
}
/// Get the "net score" of a player
/// Formula: `net_score = Score_player - Score_opponent`
#[const_fn(cfg(not(feature = "bitvec")))]
pub const fn net_score(&self, piece: Piece) -> i16 {
self.count(piece) as i16 - self.count(piece.flip()) as i16
}
/// Returns the winner of the board (if any)
pub fn game_winner(&self) -> Winner {
// Wikipedia: `Players take alternate turns. If one player cannot make a valid move, play passes back to the other player. The game ends when the grid has filled up or if neither player can make a valid move.`
if self.possible_moves(Piece::Black).next().is_some()
|| self.possible_moves(Piece::White).next().is_some()
{
// player can still make a move, there is no winner
return Winner::None;
}
match self.count(Piece::White).cmp(&self.count(Piece::Black)) {
Ordering::Greater => Winner::Player(Piece::White), // White win
Ordering::Less => Winner::Player(Piece::Black), // Black win
Ordering::Equal => Winner::Tie,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[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));
}
#[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);
assert_eq!(board.place(0, 2, Piece::Black), Ok(()));
assert_eq!(board.get(0, 1), 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);
// should fail
assert_ne!(board.place(0, 3, Piece::Black), Ok(()));
assert_eq!(
board.get(0, 1),
None,
"(0, 1) was overridden even though it's an empty space"
);
}
#[test]
fn long_capture_horiz() {
let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black);
for j in 1..=6 {
board.place_unchecked(0, j, Piece::White);
}
assert_eq!(board.place(0, 7, Piece::Black), Ok(()));
for j in 2..=6 {
assert_eq!(
board.get(0, j),
Some(Piece::Black),
"should be black at: ({}, {})",
0,
j
);
}
}
#[test]
fn long_capture_vert() {
let mut board = Board::new();
board.place_unchecked(0, 0, Piece::Black);
for i in 1..=6 {
board.place_unchecked(i, 0, Piece::White);
}
assert_eq!(board.place(7, 0, Piece::Black), Ok(()));
for i in 2..=6 {
assert_eq!(
board.get(i, 0),
Some(Piece::Black),
"should be black at: ({}, {})",
i,
0
);
}
}
// Test corner capture from top-left corner
#[test]
fn corner_capture_top_left() {
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(()));
// Capture white piece at (1,1)
assert_eq!(board.get(1, 1), Some(Piece::Black), "\n{}", board);
}
// Test corner capture from top-right corner
#[test]
fn corner_capture_top_right() {
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(()));
// Capture white piece at (1, 6)
assert_eq!(board.get(1, 6), Some(Piece::Black), "\n{}", board);
}
// Test corner capture from bottom-left corner
#[test]
fn corner_capture_bottom_left() {
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(()));
// Capture white piece at (6, 1)
assert_eq!(board.get(6, 1), Some(Piece::Black), "\n{}", board);
}
// Test corner capture from bottom-right corner
#[test]
fn corner_capture_bottom_right() {
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(()));
// Capture white piece at (6, 6)
assert_eq!(board.get(6, 6), Some(Piece::Black), "\n{}", board);
}
// Test capture from top-left corner (horizontal)
#[test]
fn capture_top_left_horiz() {
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(()));
assert_eq!(board.get(0, 1), Some(Piece::Black), "\n{}", board);
}
// Test capture from top-right corner (horizontal)
#[test]
fn capture_top_right_horiz() {
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(()));
assert_eq!(board.get(0, 6), Some(Piece::Black), "\n{}", board);
}
// Test capture from top-left corner (vertical)
#[test]
fn capture_top_left_vert() {
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(()));
assert_eq!(board.get(1, 0), Some(Piece::Black), "\n{}", board);
}
// Test capture from bottom-left corner (vertical)
#[test]
fn capture_bottom_left_vert() {
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(()));
assert_eq!(board.get(6, 0), Some(Piece::Black), "\n{}", board);
}
}

95
src/repr/misc.rs Normal file
View File

@@ -0,0 +1,95 @@
use either::Either;
use std::{iter::Rev, ops::RangeInclusive};
pub fn split_from<T>(range: RangeInclusive<T>, x: T) -> [impl Iterator<Item = T> + Clone; 2]
where
T: num::Integer + Copy,
RangeInclusive<T>: Iterator<Item = T> + DoubleEndedIterator,
Rev<RangeInclusive<T>>: Iterator<Item = T>,
{
let in_range = range.contains(&x);
let (start, end) = (*range.start(), *range.end());
// RangeInclusive (1..=0), has 0 elements
let base = Either::Right(T::one()..=T::zero());
[
if in_range && x > start + T::one() {
Either::Left((start..=(x - T::one())).rev())
} else {
base.clone()
},
if in_range && x + T::one() < end {
Either::Right((x + T::one())..=end)
} else {
base
},
]
}
pub fn diag_raw<T>(
i_chains: [impl Iterator<Item = T> + Clone; 2],
j_chains: [impl Iterator<Item = T> + Clone; 2],
) -> [impl Iterator<Item = (T, T)> + Clone; 4]
where
T: num::Integer + Copy,
RangeInclusive<T>: Iterator<Item = T> + DoubleEndedIterator,
Rev<RangeInclusive<T>>: Iterator<Item = T>,
{
[(0, 0), (1, 1), (1, 0), (0, 1)].map(move |(a, b)| i_chains[a].clone().zip(j_chains[b].clone()))
}
#[cfg(test)]
mod test {
use super::*;
fn diag_test_helper<T>(
i: T,
j: T,
range_i: RangeInclusive<T>,
range_j: RangeInclusive<T>,
) -> [impl Iterator<Item = (T, T)> + Clone; 4]
where
T: num::Integer + Copy,
RangeInclusive<T>: Iterator<Item = T> + DoubleEndedIterator,
Rev<RangeInclusive<T>>: Iterator<Item = T>,
{
diag_raw(split_from(range_i, i), split_from(range_j, j))
}
#[test]
fn split_test() {
assert_eq!(
split_from(0..=6, 2).map(Iterator::collect::<Vec<usize>>),
[vec![1, 0], vec![3, 4, 5, 6]]
);
assert_eq!(
split_from(0..=6, 0).map(Iterator::collect::<Vec<usize>>),
[vec![], vec![1, 2, 3, 4, 5, 6]]
);
assert_eq!(
split_from(0..=6, 6).map(Iterator::collect::<Vec<usize>>),
[vec![5, 4, 3, 2, 1, 0], vec![]]
);
// test out-of-bounds and also generics
assert_eq!(
split_from::<i16>(-1i16..=4i16, 10i16).map(Iterator::collect::<Vec<i16>>),
[const { Vec::new() }; 2]
);
}
#[test]
fn diag_test() {
assert_eq!(
diag_test_helper(2, 3, 0..=7, 0..=7).map(Iterator::collect::<Vec<(usize, usize)>>),
[
vec![(1, 2), (0, 1)],
vec![(3, 4), (4, 5), (5, 6), (6, 7)],
vec![(3, 2), (4, 1), (5, 0)],
vec![(1, 4), (0, 5)]
]
);
}
}

7
src/repr/mod.rs Normal file
View File

@@ -0,0 +1,7 @@
mod bitboard;
mod board;
mod misc;
mod piece;
pub use board::{Board, Winner};
pub use piece::Piece;

36
src/repr/piece.rs Normal file
View File

@@ -0,0 +1,36 @@
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Piece {
Black,
White,
}
impl Piece {
pub const fn flip(&self) -> Self {
match self {
Piece::Black => Piece::White,
Piece::White => Piece::Black,
}
}
pub const fn symbol(&self) -> char {
match self {
Piece::White => '■',
Piece::Black => '□',
}
}
pub const fn text(&self) -> &'static str {
match self {
Piece::Black => "Black",
Piece::White => "White",
}
}
}
impl std::ops::Not for Piece {
type Output = Piece;
fn not(self) -> Self::Output {
self.flip()
}
}