inThreefoldRepetition property

bool inThreefoldRepetition

Implementation

bool get inThreefoldRepetition {
  /* TODO: while this function is fine for casual use, a better
   * implementation would use a Zobrist key (instead of FEN). the
   * Zobrist key would be maintained in the make_move/undo_move functions,
   * avoiding the costly that we do below.
   */
  List moves = [];
  Map positions = {};
  bool repetition = false;

  while (true) {
    var move = undoMove();
    if (move == null) {
      break;
    }
    moves.add(move);
  }

  while (true) {
    /* remove the last two fields in the FEN string, they're not needed
     * when checking for draw by rep */
    var fen = generateFen().split(' ').sublist(0, 4).join(' ');

    /* has the position occurred three or move times */
    positions[fen] = (positions.containsKey(fen)) ? positions[fen] + 1 : 1;
    if (positions[fen] >= 3) {
      repetition = true;
    }

    if (moves.length == 0) {
      break;
    }
    makeMove(moves.removeLast());
  }

  return repetition;
}