new ai update that passes all unit tests and does see wins

This commit is contained in:
michiel
2025-09-18 14:11:29 +02:00
parent 5511192c2b
commit a6e97c5070
2 changed files with 7 additions and 2 deletions

View File

@@ -17,6 +17,7 @@ public class MinMaxTicTacToe {
int bestVal = -100; // set bestval to something impossible int bestVal = -100; // set bestval to something impossible
int bestMove = 10; // set bestmove to something impossible int bestMove = 10; // set bestmove to something impossible
int winningmove = -5;
boolean empty = true; boolean empty = true;
for (char cell : game.grid) { for (char cell : game.grid) {
@@ -32,6 +33,8 @@ public class MinMaxTicTacToe {
// simulate all possible moves on the field // simulate all possible moves on the field
for (int i = 0; i < game.grid.length; i++) { for (int i = 0; i < game.grid.length; i++) {
if (game.validateMove(i)) { // check if the move is legal here if (game.validateMove(i)) { // check if the move is legal here
TicTacToe copyGame = game.copyBoard(); // make a copy of the game TicTacToe copyGame = game.copyBoard(); // make a copy of the game
GameBase.State result = copyGame.play(i); // play a move on the copy board GameBase.State result = copyGame.play(i); // play a move on the copy board
@@ -47,7 +50,7 @@ public class MinMaxTicTacToe {
TicTacToe opponentCopy = copyGame.copyBoard(); TicTacToe opponentCopy = copyGame.copyBoard();
GameBase.State opponentResult = opponentCopy.play(index); GameBase.State opponentResult = opponentCopy.play(index);
if (opponentResult == GameBase.State.WIN) { if (opponentResult == GameBase.State.WIN) {
return index; winningmove = index;
} }
} }
} }
@@ -59,6 +62,9 @@ public class MinMaxTicTacToe {
} }
} }
} }
if (winningmove > -5) {
return winningmove;
}
return bestMove; // return the best move when we've done everything return bestMove; // return the best move when we've done everything
} }

View File

@@ -52,7 +52,6 @@ public class MinMaxTicTacToeTest {
'X', GameBase.EMPTY, GameBase.EMPTY, 'X', GameBase.EMPTY, GameBase.EMPTY,
GameBase.EMPTY, GameBase.EMPTY, GameBase.EMPTY GameBase.EMPTY, GameBase.EMPTY, GameBase.EMPTY
}; };
game.movesLeft = 4;
int bestMove = ai.findBestMove(game); int bestMove = ai.findBestMove(game);