DEV Community

Cover image for Chess Engine in C #2: Bitboards
Victor Chigbo
Victor Chigbo

Posted on

Chess Engine in C #2: Bitboards

In the last project dev log, I talked about board representations, and specifically, I talked about the mailbox matrix being used in the project. Now, let's discuss about bitboards.

Bitboards are piece-centric representations of the chessboard, showing the state of the pieces on the board. It works by using a 64-bit integer which it's type is defined like this:

typedef unsigned long long U64;
Enter fullscreen mode Exit fullscreen mode

 

Each of the digits(in this case, bit) in the integer represent whether a piece(e.g. a pawn♟) is there or not. In order to print the bitboard on the console, we have to put this function in the bitboards.c file:

void PrintBitBoard(U64 bb) {
    U64 shiftMe = 1ULL;

    int rank = 0;
    int file = 0;
    int sq = 0;
    int sq64 = 0;

    printf("\n");
    for (rank = RANK_8; rank >= RANK_1; --rank){
        for (file = FILE_A; file <= FILE_H; ++file) {
            sq = FR2SQ(file, rank); // 120-based square
            sq64 = SQ64(sq); // 64-based square. SQ64 is Sq120ToSq64[(sq120)]

            if ((shiftMe << sq64) & bb) {
                printf("X");
            } else {
                printf("-");
            }
        }

        printf("\n");
    }
    printf("\n\n");
}
Enter fullscreen mode Exit fullscreen mode

 

When the loops begin to run, they used shiftMe to check if a pawn in the sq64th of the chessboard by shifting the single bit in shiftMe sq64 number of times and if in the bitboard(represented as bb), a pawn, or any chess piece is in the same place, or position as the bit in shiftMe, then X is printed, else - is printed. If a new piece is added to the bitboard, it can be displayed too.

U64 playBitBoard = 0ULL;

printf("Start: \n\n");
PrintBitBoard(playBitBoard);

playBitBoard |= (1ULL << SQ64(D2));
printf("D2 Added: \n\n");
PrintBitBoard(playBitBoard);

playBitBoard |= (1ULL << SQ64(G2));
printf("G2 Added: \n\n");
PrintBitBoard(playBitBoard);
Enter fullscreen mode Exit fullscreen mode

 

A bitboard printed on the console, showing pawns on D2 and G2.

A bitboard printed on the console, showing pawns on D2 and G2

 

If you haven't read the previous article, click here so that you can follow along and if you want to see the code, you can click here to view the Github repo.

Until the next commit....bye 👋

Top comments (0)