othello/src/board.rs
2025-01-28 16:44:28 -05:00

241 lines
6.8 KiB
Rust

use crate::{misc::split_from, piece::Piece};
use std::fmt;
pub const BOARD_SIZE: usize = 8;
#[derive(Copy, Clone)]
pub struct Board {
board: [[Option<Piece>; BOARD_SIZE]; BOARD_SIZE],
}
impl fmt::Display for Board {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let horiz_sep_line = "-".repeat(BOARD_SIZE * 2 + 1);
for i in 0..BOARD_SIZE {
writeln!(f, "{}", horiz_sep_line)?;
write!(f, "|")?;
for j in 0..BOARD_SIZE {
write!(
f,
"{}|",
self.get(i, j).as_ref().map(Piece::text).unwrap_or(" ")
)?;
}
writeln!(f)?;
}
// put a line at the bottom of the board too
writeln!(f, "{}", horiz_sep_line)?;
Ok(())
}
}
impl Board {
pub const fn new() -> Self {
Self {
board: [[None; BOARD_SIZE]; BOARD_SIZE],
}
}
pub const fn starting_pos(mut self) -> Self {
self.place_unchecked(3, 3, Piece::White);
self.place_unchecked(4, 3, Piece::Black);
self.place_unchecked(3, 4, Piece::Black);
self.place_unchecked(4, 4, Piece::White);
self
}
/// Returns a mutable reference to a place on the [`Board`]
/// at (i, j)
pub const fn get_mut(&mut self, i: usize, j: usize) -> &mut Option<Piece> {
&mut self.board[i][j]
}
/// Returns a reference to a place on the [`Board`]
/// at (i, j)
pub const fn get(&self, i: usize, j: usize) -> &Option<Piece> {
&self.board[i][j]
}
const fn place_unchecked(&mut self, i: usize, j: usize, piece: Piece) {
*self.get_mut(i, j) = Some(piece);
}
pub fn what_if(&self, i: usize, j: usize, piece: Piece) -> Option<(Self, usize)> {
let mut self_copy = *self;
if self_copy.get(i, j).is_some() {
return None;
}
self_copy.place_unchecked(i, j, piece);
let how_many_prop = self_copy.propegate_from(i, j);
Some((self_copy, how_many_prop))
}
pub fn place(&mut self, i: usize, j: usize, piece: Piece) -> Result<(), String> {
let what_if_result = self.what_if(i, j, piece);
if let Some(what_if_result) = what_if_result {
if what_if_result.1 > 0 {
*self = what_if_result.0;
return Ok(());
}
}
Err("move would not propegate".to_string())
}
/// 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(&mut self, i: usize, j: usize) -> usize {
// returns if that place is empty
let Some(starting_color) = *self.get(i, j) else {
return 0;
};
// Create all chains from the piece being propegated from in `i` and `j` coordinates
let mut chains: Vec<Vec<(usize, usize)>> = split_from(0, BOARD_SIZE - 1, i)
.into_iter()
.map(|range| range.into_iter().map(|i| (i, j)).collect())
.collect();
chains.extend(
split_from(0, BOARD_SIZE - 1, j)
.into_iter()
.map(|range| range.into_iter().map(|j| (i, j)).collect()),
);
// TODO! add diagonals to `chains` here
let mut captured: usize = 0;
for chain in chains {
for (chain_length, &(new_i, new_j)) in chain.iter().enumerate() {
let Some(piece) = self.get(new_i, new_j) else {
break;
};
if piece == &starting_color {
if chain_length > 0 {
// fill all opposite colors with this color
let Some(history) = chain.get(..chain_length) else {
break;
};
captured += history.len();
// fill all opposite colors with this color
for &(i_o, j_o) in history {
self.place_unchecked(i_o, j_o, starting_color);
}
}
// either the other pieces were replaced, or this was an invalid chain,
// in both cases, the loop needs to be breaked
break;
}
}
}
captured
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn place_and_get() {
let mut board = Board::new();
assert_eq!(board.get(0, 0), &None);
assert_eq!(
board.place(0, 0, Piece::Black),
Ok(()),
"placing black on (0, 0)"
);
assert_eq!(board.get(0, 0), &Some(Piece::Black));
}
#[test]
fn place_and_capture_simple() {
let mut board = Board::new();
assert_eq!(
board.place(0, 0, Piece::Black),
Ok(()),
"first move of piece black to (0, 0)"
);
assert_eq!(
board.place(0, 1, Piece::White),
Ok(()),
"white move to (0, 1)"
);
assert_eq!(
board.place(0, 2, Piece::Black),
Ok(()),
"black counter, capturing white"
);
assert_eq!(board.get(0, 1), &Some(Piece::Black));
}
#[test]
fn failed_capture() {
let mut board = Board::new();
assert_eq!(board.place(0, 0, Piece::Black), Ok(()));
assert_eq!(board.place(0, 2, Piece::White), Ok(()));
assert_eq!(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();
assert_eq!(board.place(0, 0, Piece::Black), Ok(()));
for j in 1..=6 {
assert_eq!(board.place(0, j, Piece::White), Ok(()));
}
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();
assert_eq!(board.place(0, 0, Piece::Black), Ok(()));
for i in 1..=6 {
assert_eq!(board.place(i, 0, Piece::White), Ok(()));
}
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
);
}
}
}