I am in the process of adding an opening book to my C++ engine and I hit a problem. Here is what I have:

  • The Perfect2021.bin opening book that I would like to use.
  • The function that creates the polyglot hash for the board. I tested this with many boards, and it is correct.

Now I would like to retrieve and for now only print all the moves my engine can make in a position, according to the book. I tried it with the following method:

move opening_book::getBookMove(const chessboard& board, const game_information& info) {
        uint64 boardKey = polyKeyFromBoard(board, info); //get key for board
        std::cout << "Finding moves for board key: " << std::hex << boardKey << std::dec << std::endl;
        unsigned short moveKey;
        //list moves from the book
        for(polyglot_book_entry* entry = entries; entry < entries + entriesNumber; entry++) {
            //apparently I need to swap bits for these
            if(boardKey == swap_uint64(entry->boardKey)) { //found the board in the book
                moveKey = swap_uint16(entry->move);
                unsigned short fromFile = (moveKey>>6)&7, fromRank = (moveKey>>9)&7,
                               toFile = (moveKey>>0)&7, toRank = (moveKey>>3)&7;
                unsigned int fromSquare = (8 * fromRank) + fromFile,
                             toSquare = (8 * toRank) + toFile;
                std::cout << "Move found: " << createSquareName(fromSquare) << createSquareName(toSquare) << std::endl;
        return move(); //not returning actual move right now

But when I for example make my engine play black and I open the game on white with the move e2e4 then the following is printed upon the engine checking the opening book:

Finding moves for board key: 823c9b50fd114196
Move found: c2c4
Move found: e2e4
Move found: c2c3
Move found: e2e3

The board key is correct. It is one of the test cases on this site. However, as you can see the moves that are found seem to be for white.

Can someone please help me out? Thanks.


I have found the problem: my board representation was different and while my ranks are also from 0-7, but they are counted from the black side, while in the polyglot encoding, they are counted from the white side (which makes sense).

So I had to invert my ranks like so:

unsigned short fromFile = (moveKey>>6)&7,
                          fromRank = 7 - ((moveKey>>9)&7),
                          toFile = (moveKey>>0)&7,
                          toRank = 7 - ((moveKey>>3)&7);

Files remain unchanged. I am now getting reasonable output:

Finding moves for board key: 823c9b50fd114196
Move found: c7c5
Move found: e7e5
Move found: c7c6
Move found: e7e6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.