create Board and Piece types

This commit is contained in:
Simon Gardling 2025-01-23 16:02:02 -05:00
commit a1e2261d50
Signed by: titaniumtown
GPG Key ID: 9AB28AC10ECE533D
5 changed files with 63 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "othello"
version = "0.1.0"

6
Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "othello"
version = "0.1.0"
edition = "2021"
[dependencies]

5
src/main.rs Normal file
View File

@ -0,0 +1,5 @@
mod repr;
fn main() {
println!("Hello, world!");
}

44
src/repr.rs Normal file
View File

@ -0,0 +1,44 @@
#[derive(Copy, Clone)]
pub enum Piece {
Black,
White,
}
const BOARD_SIZE: usize = 8;
#[derive(Copy, Clone)]
pub struct Board {
board: [[Option<Piece>; BOARD_SIZE]; BOARD_SIZE],
}
impl Board {
pub const fn new() -> Self {
Self {
board: [[None; BOARD_SIZE]; BOARD_SIZE],
}
}
/// 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]
}
/// Place a piece on the [`Board`]
/// Returns an error if there already exists a piece there
pub fn place(&mut self, i: usize, j: usize, piece: Piece) -> Result<(), String> {
if self.get(i, j).is_some() {
return Err(format!("Cannot place on ({},{}), piece exists", i, j));
} else {
*self.get_mut(i, j) = Some(piece);
}
Ok(())
}
}