Skip to content

Commit

Permalink
Optimize check and checkmate calculation. Do it only when needed
Browse files Browse the repository at this point in the history
  • Loading branch information
Dolfost committed Aug 26, 2024
1 parent 67c3a7b commit 763a93b
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/board/include/tartan/board/board.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -857,7 +857,8 @@ class Board : private BoardT {
* @brief Turn index
*
* Underlying varriable gets inclremented
* on Turn::apply() and decremented on Turn::undo().
* on Turn::apply().
* Acts like a timestamp fo current Board state.
*
* @return last Piece::Turn index
* @sa b_turnIndex
Expand Down
2 changes: 1 addition & 1 deletion src/board/turn.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <iostream>
#include <tartan/board.hpp>
#include <tartan/board/exceptions.hpp>

Expand Down Expand Up @@ -26,7 +27,6 @@ void Turn::apply(int) {

void Turn::undo() {
Board& cb = *t_piece->p_board;
cb.b_turnIndex--;

t_piece->move(t_from);

Expand Down
6 changes: 6 additions & 0 deletions src/chess/include/tartan/chess/chess.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,13 @@ class King : public Piece {
*/
bool castled() const { return k_castled; };
private:
bool calculateCheck() const;
bool calculateCheckmate() const;
bool k_castled = false;
mutable bool k_check = false;
mutable bool k_checkmate = false;
mutable std::size_t k_checkTurnIndex = -1;
mutable std::size_t k_checkmateTurnIndex = -1;
};

}
Expand Down
17 changes: 17 additions & 0 deletions src/chess/pieces/king/king.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ TurnMap King::moveMap(int mode) const {
}

bool King::check() const {
if (k_checkTurnIndex != board()->turnIndex()) {
k_check = calculateCheck();
k_checkTurnIndex = board()->turnIndex();
}
return k_check;
}

bool King::calculateCheck() const {
for (auto& row : p_board->board()) {
for (auto& p : row) {
if (!p or p->color() == p_color)
Expand All @@ -97,7 +105,16 @@ bool King::check() const {
return false;
}


bool King::checkmate() const {
if (k_checkmateTurnIndex != board()->turnIndex()) {
k_checkmate = calculateCheckmate();
k_checkmateTurnIndex = board()->turnIndex();
}
return k_checkmate;
}

bool King::calculateCheckmate() const {
if (!check() or p_board->possibleMoves(this).possible())
return false;

Expand Down

0 comments on commit 763a93b

Please sign in to comment.