Skip to content

BitBoard

Rudy Alex Kohn edited this page Sep 3, 2022 · 4 revisions

wip

This chess library uses Bitboard structure for best performance and usability.

Layout

The layout of the Bitboard structure is as follows

A B C D E F G H
56 57 58 59 60 61 62 63
48 49 50 51 52 53 54 55
40 41 42 43 44 45 46 47
32 33 34 35 36 37 38 39
24 25 26 27 28 29 30 31
16 17 18 19 20 21 22 23
08 09 10 11 12 13 14 15
00 01 02 03 04 05 06 07

Implicit ctors

Can do implicit convert from these types

  • ulong
  • int
  • Square

Operators

Most common usage is covered, so there is hardly ever any reason to manipulate anything. Fx. to check if a en-passant move gives check, the following is implemented

var captureSquare = new Square(from.Rank, to.File);
var b = (Board.Pieces() ^ from ^ captureSquare) | to;
var ksq = GetKingSquare(them);

var attacks = (GetAttacks(ksq, PieceTypes.Rook, in b)
              & Board.Pieces(us, PieceTypes.Rook, PieceTypes.Queen))
              | (GetAttacks(ksq, PieceTypes.Bishop, in b) & Board.Pieces(us, PieceTypes.Bishop, PieceTypes.Queen));

return !attacks.IsEmpty;

Iterate Bitboard

To iterate a bitboard to retrieve the squares within, use one of two ways. Both have their strength and weakness.

IEnumerable

The Bitboard struct implements the IEnumerable<Square> interface, which allows it to be used through LINQ.

This method has the simplicity and the ability to make more complex expression on the fly, but has some overhead.

Example

var bb = SomeMethod();

foreach (var sq in bb)
{
    // .. do something with sq
}

While loop with bit reset

The fastest and more verbose way in the library to iterate a Bitboard, it gives less freedom with expressions, but gets the job done.

var bb = SomeMethod();

while (bb)
{
    var sq = bb.Lsb();
    // do something with sq
    BitBoards.ResetLsb(ref bb);
}

It is also possible to use PopLsb()

var bb = SomeMethod();

while (bb)
{
    var sq = BitBoards.PopLsb(ref bb);
    // do something with sq
}

Constants

The following are available as constants in BitBoards

  • WhiteArea - The half of the board for white pieces
  • BlackArea - The half of the board for black pieces
  • LightSquares - The light squares of the board
  • DarkSquares - The dark squares of the board
  • All Files
  • All Ranks
  • Empty
  • All
  • PawnSquares (all ranks except 1 and 8)
  • All 4 corners
  • Queen/Center/CenterFiles/King sides
  • PromotionRanks - array by player side
  • PromotionRanks
  • All squares
  • First rank
  • 3rd rank - array by player side
  • 7th rank - array by player side
  • 6th+7th rank - array by player side
  • 7th+8th rank - array by player side

Computed on startup

  • PseudoAttacks[pt][sq] - all attacks by all piece types (except pawn)
  • PawnAttackSpan
  • PassedPawnMask
  • ForwardRanks
  • KingRing
  • Betweens
  • Line
  • DistanceRing
Clone this wiki locally