How do I model a chessboard when programming a computer to play chess?

后端 未结 14 2285
夕颜
夕颜 2021-01-31 10:13

What data structures would you use to represent a chessboard for a computer chess program?

14条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 10:29

    For a serious chess engine, using bitboards is an efficient way to represent a chess board in memory. Bitboards are faster than any array based representation, specially in 64-bit architectures where a bitboard can fit inside a single CPU register.

    Bitboards

    Basic idea of bitboards is to represent every chess piece type in 64 bits. In C++/C# it will be ulong/UInt64. So you'll maintain 12 UInt64 variables to represent your chess board: two (one black and one white) for each piece type, namely, pawn, rook, knight, bishop, queen and king. Every bit in a UInt64 will correspond to a square on chessboard. Typically, the least significant bit will be a1 square, the next b1, then c1 and so on in a row-major fashion. The bit corresponding to a piece's location on chess board will be set to 1, all others will be set to 0. For example, if you have two white rooks on a2 and h1 then the white rooks bitboard will look like this:

    0000000000000000000000000000000000000000000000000000000110000000
    

    Now for example, if you wanted to move your rook from a2 to g2 in the above example, all you need to do is XOR you bitboard with:

    0000000000000000000000000000000000000000000000000100000100000000
    

    Bitboards have a performance advantage when it comes to move generation. There are other performance advantages too that spring naturally from bitboards representation. For example you could use lockless hash tables which are an immense advantage when parallelising your search algorithm.

    Further Reading

    The ultimate resource for chess engine development is the Chess Programming Wiki. I've recently written this chess engine which implements bitboards in C#. An even better open source chess engine is StockFish which also implements bitboards but in C++.

提交回复
热议问题