othello/src/board.rs
2025-02-18 15:08:35 -05:00

518 lines
16 KiB
Rust

use crate::{
bitboard::BitBoard,
misc::{diag_raw, split_from},
piece::Piece,
};
use arrayvec::ArrayVec;
use lazy_static::lazy_static;
use std::{cmp::Ordering, fmt};
/// Size of each dim of the board
pub const BOARD_SIZE: usize = 8;
/// Area of the board
pub const BOARD_AREA: usize = BOARD_SIZE * BOARD_SIZE;
/// A chain of positions across the board
type Chain = ArrayVec<(usize, usize), BOARD_SIZE>;
/// 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
type PosMap<T> = ArrayVec<ArrayVec<T, BOARD_SIZE>, BOARD_SIZE>;
/// Creates a lookup map for adjacencies and chains from each position on the board
fn gen_adj_lookup() -> PosMap<ChainCollection> {
(0..BOARD_SIZE)
.map(|i| {
(0..BOARD_SIZE)
.map(|j| {
let (i_chain, j_chain) = (
split_from(0..=BOARD_SIZE - 1, i),
split_from(0..=BOARD_SIZE - 1, j),
);
let mut chains: ChainCollection = ArrayVec::new_const();
chains.extend(
i_chain
.clone()
.map(|range| range.map(move |i| (i, j)))
.map(Iterator::collect),
);
chains.extend(
j_chain
.clone()
.map(|range| range.map(move |j| (i, j)))
.map(Iterator::collect),
);
// handle diagonals
chains.extend(diag_raw(i_chain, j_chain).map(Iterator::collect));
chains
})
.collect()
})
.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
pub 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
writeln!(
f,
"White Score: {}\nBlack Score: {}",
self.count(Piece::White),
self.count(Piece::Black)
)?;
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
pub 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))
}
/// Get a reference to a backing [`BitBoard`]
pub 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`]
pub fn board_mut(&mut self, color: Piece) -> &mut BitBoard {
match color {
Piece::Black => &mut self.black_board,
Piece::White => &mut self.white_board,
}
}
pub 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
pub 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
fn place_unchecked(&mut self, i: usize, j: usize, piece: Piece) {
self.board_mut(piece).set(i, j, true);
self.board_mut(!piece).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) -> Option<Self> {
if self.get(i, j).is_some() {
return None;
}
let mut self_copy = *self;
self_copy.place_unchecked(i, j, piece);
let how_many_prop = self_copy.propegate_from(i, j);
if how_many_prop == 0 {
return None;
}
Some(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 let Some(what_if_result) = self.what_if(i, j, piece) {
*self = what_if_result;
return Ok(());
}
Err("move would not propegate")
}
/// 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;
};
let pos_s: Vec<(usize, usize)> = self.propegate_from_dry(i, j, starting_color).collect();
let pos_len = pos_s.len();
for (i, j) in pos_s {
self.place_unchecked(i, j, starting_color);
}
pos_len
}
/// 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[i][j]
.iter()
.filter_map(move |chain| {
let mut end_idx = None;
for (idx, &(new_i, new_j)) in chain.into_iter().enumerate() {
let piece = self.get(new_i, new_j)?;
if piece == starting_color {
end_idx = Some(idx);
break;
}
}
end_idx.and_then(|idx| chain.get(..idx))
})
.flatten()
.cloned()
}
/// Count the number of a type of [`Piece`] on the board
pub fn count(&self, piece: Piece) -> usize {
self.board(piece).count()
}
/// Get the "net score" of a player
/// Formula: `net_score = Score_player - Score_opponent`
pub fn net_score(&self, piece: Piece) -> isize {
self.count(piece) as isize - self.count(!piece) as isize
}
/// Returns the winner of the board (if any)
pub fn game_winner(&self, turn: Piece) -> 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(turn).next().is_some() || self.possible_moves(!turn).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);
board.place_unchecked(0, 2, Piece::Black);
board.propegate_from(0, 2);
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);
board.place_unchecked(0, 3, Piece::Black);
board.propegate_from(0, 3);
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);
}
board.place_unchecked(0, 7, Piece::Black);
board.propegate_from(0, 7);
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);
}
board.place_unchecked(7, 0, Piece::Black);
board.propegate_from(7, 0);
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 (0, 0) and (2, 2)
board.place_unchecked(0, 0, Piece::Black);
board.place_unchecked(1, 1, Piece::White); // to be captured
board.place_unchecked(2, 2, Piece::Black);
board.propegate_from(0, 0);
// 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
board.place_unchecked(2, 5, Piece::Black);
board.propegate_from(2, 5);
// 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
board.place_unchecked(5, 2, Piece::Black);
board.propegate_from(5, 2);
// 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
board.place_unchecked(5, 5, Piece::Black);
board.propegate_from(5, 5);
// 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
board.place_unchecked(0, 2, Piece::Black);
board.propegate_from(0, 2);
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
board.place_unchecked(0, 5, Piece::Black);
board.propegate_from(0, 5);
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
board.place_unchecked(2, 0, Piece::Black);
board.propegate_from(2, 0);
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
board.place_unchecked(5, 0, Piece::Black);
board.propegate_from(5, 0);
assert_eq!(board.get(6, 0), Some(Piece::Black), "\n{}", board);
}
}