I'm making a chess engine that has to implement a three-fold repetition as my AI vs AI engine repeats the same moves over and over again (Have a look at my post here - My chess AI makes the same repeated moves). I've read the rules of this scenario from the wiki and would like to implement it. I'm not sure if I have understood the rules thoroughly, so what I'm doing here is -
- Checking if the present move made (from the movelog I have) has already occurred before.
- If it did, check for one more occurrence (as we need three in total).
- If the moves pattern for all the three re-occurred moves is same, return true.
Please have a look at my Java code and suggest me the corrections.
boolean isThreeFoldRepetition() {
List<Move> allMoves = Table.get().getMoveLog().getMoves();
int currentMoveIndex = allMoves.size()-1;
int secondFoldMoveIndex = currentMoveIndex - 4;
int firstFoldMoveIndex = secondFoldMoveIndex - 4;
int distance = currentMoveIndex - secondFoldMoveIndex - 1;
while(firstFoldMoveIndex >= 0){
Move thirdFoldMoveMade = allMoves.get(currentMoveIndex);
Move secondFoldMoveMade = allMoves.get(secondFoldMoveIndex);
Move firstFoldMoveMade = allMoves.get(firstFoldMoveIndex);
if(thirdFoldMoveMade.equals(secondFoldMoveMade) &&
secondFoldMoveMade.equals(firstFoldMoveMade) &&
firstFoldMoveIndex - distance >= 0){
int gap;
for(gap = 1; gap <= distance; gap++){
thirdFoldMoveMade = allMoves.get(currentMoveIndex - gap);
secondFoldMoveMade = allMoves.get(secondFoldMoveIndex - gap);
firstFoldMoveMade = allMoves.get(firstFoldMoveIndex - gap);
if(!thirdFoldMoveMade.equals(secondFoldMoveMade) || !secondFoldMoveMade.equals(firstFoldMoveMade))
break;
}
if(gap == distance)
return true;
}
secondFoldMoveIndex -= 2;
firstFoldMoveIndex = secondFoldMoveIndex - distance - 3;
}
return false;
}