isThreefoldRepetition method

bool isThreefoldRepetition()

Checks if the game is in a draw state due to threefold repetition.

Implementation

bool isThreefoldRepetition() {
  String stripIrrelevantFENParts(String fen) {
    // FEN format: piece_positions active_color castling_avail en_passant halfmove fullmove
    List<String> parts = fen.split(' ');
    if (parts.length < 4) return fen;

    // Keep only parts 0 to 3: board, turn, castling rights, en passant
    return '${parts[0]} ${parts[1]} ${parts[2]} ${parts[3]}';
  }

  Map<String, int> repetitionCount = {};

  for (String fen in history) {
    // Remove move clocks and turn data to avoid false negatives
    String key = stripIrrelevantFENParts(fen);

    repetitionCount[key] = (repetitionCount[key] ?? 0) + 1;

    if (repetitionCount[key]! >= 3) {
      return true;
    }
  }

  return false;
}