diff --git a/src/main/java/de/tims/tictactoe/ai/AIHard.java b/src/main/java/de/tims/tictactoe/ai/AIHard.java index 99aee69..9768677 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/src/main/java/de/tims/tictactoe/ai/AIHard.java @@ -21,16 +21,33 @@ public class AIHard implements TicTacToeAI { public void calculateNextMove() { int charsOfOpponentInRow = 0; int charsOfOpponentInCol = 0; + int charsOfOpponentInDiag = 0; char[][] board = gl.getBoard(); for (int i = 0; i < BOARD_SIZE; i++) { charsOfOpponentInRow = countCharsInRow(i, PLAYER_CHAR); charsOfOpponentInCol = countCharsInCol(i, PLAYER_CHAR); - if (charsOfOpponentInRow == BOARD_SIZE - 1 || charsOfOpponentInCol == BOARD_SIZE - 1) { + if (i < 2) { + charsOfOpponentInDiag = countCharsInDiag(i, PLAYER_CHAR); + } + + if (charsOfOpponentInRow == BOARD_SIZE - 1 || charsOfOpponentInCol == BOARD_SIZE - 1 || charsOfOpponentInDiag == BOARD_SIZE - 1) { for (int j = 0; j < BOARD_SIZE; j++) { - if (board[(charsOfOpponentInRow == BOARD_SIZE - 1) ? i : j][(charsOfOpponentInRow == BOARD_SIZE - 1) ? j : i] == EMPTY_CHAR) { - gl.setField((charsOfOpponentInRow == BOARD_SIZE - 1) ? i : j, (charsOfOpponentInRow == BOARD_SIZE - 1) ? j : i, AI_CHAR); - return; + if (charsOfOpponentInRow == BOARD_SIZE - 1) { + if (board[i][j] == EMPTY_CHAR) { + gl.setField(i, j, AI_CHAR); + return; + } + } else if (charsOfOpponentInCol == BOARD_SIZE - 1) { + if (board[j][i] == EMPTY_CHAR) { + gl.setField(j, i, AI_CHAR); + return; + } + } else if (charsOfOpponentInDiag == BOARD_SIZE - 1) { + if (board[j][(i == 0) ? j : BOARD_SIZE - 1 - j] == EMPTY_CHAR) { + gl.setField(j, (i == 0) ? j : BOARD_SIZE - 1 - j, AI_CHAR); + return; + } } } } diff --git a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java index ecede92..dbadc8b 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java @@ -87,6 +87,17 @@ class AIHardTest { verify(gl, times(1)).setField(2, 1, realChar); } + + @Test + void preventOpponentsWinInDiag() { + char realChar = 'o'; + doReturn(new char[][] { {'x', '-', 'o'}, {'-', 'x', '-'}, {'-', '-', '-'} }).when(gl).getBoard(); + + TicTacToeAI ai = new AIHard(gl); + ai.calculateNextMove(); + + verify(gl, times(1)).setField(2, 2, realChar); + } @ParameterizedTest @MethodSource("testCasesForCountCharsInRow")