Browse Source

tictactoe: hard AI prevents opponents win in diagonal

tictactoe
Tobias Krause 2 years ago
committed by Lorenz Hohmann
parent
commit
b29b7ee9d7
  1. 25
      src/main/java/de/tims/tictactoe/ai/AIHard.java
  2. 11
      src/test/java/de/tims/tictactoe/ai/AIHardTest.java

25
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;
}
}
}
}

11
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")

Loading…
Cancel
Save