Thursday, August 12, 2010

[BUG] Silly bug in the board evaluation

At some point in time every chess engine must be able to evaluate a given board position. The easiest way to do that is to just score the material. But then the engine moves around rather silly so you try to evaluate a position a bit better.

One of the things I consider in evaluation is the existence of castling rights. Whenever a side has preserved the right to castle it get a small bonus for it (one for king side and one for queen side). This way the engine gives not easily away the rights to castle by making a king move. It also tries now to take away the castling rights from the opponent.

So far so good, but this alone is not enough as the engine will now not castle because this means losing the rights to castle (after castling the engine can't do it again) and the bonuses associated with the rights. To get around this I rewarded a bigger bonus if the engine has made a castling move outweighing the loss of the castling rights.

Engine can castle king side +10
Engine can castle queen side +10
Engine has castled + 60

So if the engine castles it gets a overall bonus of +40  (60-10-10). This actually seemed to work pretty well. until recently I discovered a problem with that approach.

 rnbq1r2/pppppk1p/5n1b/8/3P4/P7/1PP1PPPP/RNBQKB1R w KQ -

Consider the following position. This is one of the positions that search might encounter as a leaf node.

This position can be reached via various combination of moves (transpositions). If in the sequence of moves black has castled king side the position is evaluated with the +40 bonus for black. If the sequence of moves just involves black moving seperately with the rook and king it gets a penalty of -20 (black has given away both castling rights).

So the very same position gets 2 different scores depending on the move history, which I consider a bug in this case. I will try to fix it by removing the bonus for castling and giving a bonus for the king when located at the castling target positions (a good piece-square value for the king).

Another possibility when 2 positions get different scores is the issue of position repetition. Then we might approach a draw by repetition so the position is worse for the one with an advantage if it repeats itself. But this I actually consider a feature and not a bug.