[board] Implement BitBoard::file and fmt::Display for BitBoard

BitBoard::file returns a BitBoard representing the 0-indexed file.
fmt::Display prints a grid of bits in the standard orientation (white on bottom, left to right)
Add asserts to the rank and file constructors to catch out of bounds arguments.
This commit is contained in:
Eryn Wells 2023-12-30 10:26:37 -08:00
parent c280258780
commit e30bcb3105

View file

@ -18,9 +18,15 @@ impl BitBoard {
}
pub fn rank(rank: u8) -> BitBoard {
assert!(rank < 8);
BitBoard(0xFF).shift_north(rank)
}
pub fn file(file: u8) -> BitBoard {
assert!(file < 8);
BitBoard(0x0101010101010101).shift_east(file)
}
pub fn is_empty(&self) -> bool {
self.0 == 0
}
@ -68,6 +74,29 @@ impl fmt::UpperHex for BitBoard {
}
}
impl fmt::Display for BitBoard {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let binary_ranks = format!("{:064b}", self.0)
.chars()
.rev()
.map(|c| String::from(c))
.collect::<Vec<String>>();
let mut ranks_written = 0;
for rank in binary_ranks.chunks(8).rev() {
let joined_rank = rank.join(" ");
write!(f, "{}", joined_rank)?;
ranks_written += 1;
if ranks_written < 8 {
write!(f, "\n")?;
}
}
Ok(())
}
}
impl fmt::Debug for BitBoard {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_tuple("BitBoard")
@ -136,6 +165,13 @@ mod tests {
use super::*;
use crate::Square;
#[test]
fn display_and_debug() {
let bb = BitBoard::file(0) | BitBoard::file(3) | BitBoard::rank(7) | BitBoard::rank(4);
println!("{}", &bb);
println!("{:?}", &bb);
}
#[test]
fn rank() {
assert_eq!(BitBoard::rank(0).0, 0xFF, "Rank 1");