isaksolheim / chess

1 stars 0 forks source link

IsKingInCheck calculation can be improved #37

Closed sondrp closed 4 months ago

sondrp commented 5 months ago

When finding out if a move is legal or not, we have to check if the move puts the king in check. This is done by calculating all the moves of the enemy, and checking if at least one of them captures the king. Here is the relevant code:

    // return true if one of the moves results in a board without a king
    return board.indices
      .filter { square -> board[square] != ' ' } // remove emtpy squares
      .filter { piece -> board[piece].isLowerCase() == whiteKing } // remove friendly pieces
      .flatMap { enemy -> calculateSimpleMoves(board, enemy) } // calculate all moves of the enemy piece
      .any { move -> !move.result.contains(kingToLookFor) } // check if one of the moves captured the king

it works fine, however it requires more computation than necessary. Even worse, the results are not cached, meaning that the whole calculation must be repeated for each potential move! That number could be 20+ for a queen on a sparse board.

Task: be more clever about this

sondrp commented 4 months ago

fixed