Bitboard game help

Hello everybody.
I’m trying to write a bitboard game. How can i print a NxN bitboard?

Thanks for the help

I’d use ::bitvec, and then it is just a matter or siwtching between a linear view and a matrix view (with row * width + col):

use ::std::*;
use ::bit_vec::BitVec;

#[derive(
    Debug,
    Clone,
    PartialEq, Eq,
)]
pub
struct BitBoard {
    bits: BitVec,
    width: usize,
    len: usize,
}

impl BitBoard {
    pub
    fn new (width: usize) -> Self
    {
        let len = width
                    .checked_mul(width)
                    .unwrap_or_else(|| panic!("Width overflow"))
        ;
        Self {
            bits: BitVec::from_elem(len, false),
            width,
            len,
        }
    }
}

impl ops::Index<(usize, usize)> for BitBoard {
    type Output = bool;

    fn index (
        self: &'_ Self,
        (row, col): (usize, usize),
    ) -> &'_ Self::Output
    {
        &self.bits[self.width * row + col]
    }
}
impl BitBoard {
    pub
    fn set (
        self: &'_ mut Self,
        (row, col): (usize, usize),
        b: bool,
    )
    {
        self.bits.set(self.width * row + col, b)
    }
}

impl fmt::Display for BitBoard {
    fn fmt (
        self: &'_ Self,
        stream: &'_ mut fmt::Formatter<'_>,
    ) -> fmt::Result
    {
        use ::itertools::Itertools;
        write!(stream, "{}",
            (0 .. self.width).map(move |row|
                (0 .. self.width).map(move |col|
                    if self[(row, col)] { "x" } else { "-" }
                ).format(" ")
            ).format("\n")
        )
    }
}

so that

fn main ()
{
    use bit_board::*;
    const N: usize = 8;
    let mut bit_board = BitBoard::new(N);
    for row in 0 .. N { for col in 0 .. N {
        bit_board.set((row, col), row % 2 == col % 2);
    }}
    println!("{}", bit_board);
}

displays

x - x - x - x -
- x - x - x - x
x - x - x - x -
- x - x - x - x
x - x - x - x -
- x - x - x - x
x - x - x - x -
- x - x - x - x
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.