Browse Source

tictactoe: hard ai sets always in the nearest edge to opponents field

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

20
src/main/java/de/tims/tictactoe/ai/AIHard.java

@ -54,8 +54,24 @@ public class AIHard implements TicTacToeAI {
}
}
if (board[1][1] == EMPTY_CHAR) {
gl.setField(1, 1, AI_CHAR);
if (board[BOARD_SIZE / 2][BOARD_SIZE / 2] == EMPTY_CHAR) {
gl.setField(BOARD_SIZE / 2, BOARD_SIZE / 2, AI_CHAR);
} else if (board[BOARD_SIZE / 2][BOARD_SIZE / 2] == AI_CHAR && (board[0][0] == AI_CHAR || board[0][BOARD_SIZE - 1] == AI_CHAR || board[BOARD_SIZE - 1][0] == AI_CHAR || board[BOARD_SIZE - 1][BOARD_SIZE - 1] == AI_CHAR)) {
for (int i = BOARD_SIZE - 2; i > 0; i--) {
for (int j = 0; j < BOARD_SIZE; j += BOARD_SIZE - 1) {
for (int k = 1; k < BOARD_SIZE - 1; k++) {
if (countCharsInRow(j, AI_CHAR) == i && countCharsInCol(k, AI_CHAR) == i && countCharsInRow(j, EMPTY_CHAR) == BOARD_SIZE -i && countCharsInCol(k, EMPTY_CHAR) == BOARD_SIZE - i) {
gl.setField(j, k, AI_CHAR);
return;
}
if (countCharsInRow(k, AI_CHAR) == i && countCharsInCol(j, AI_CHAR) == i && countCharsInRow(k, EMPTY_CHAR) == BOARD_SIZE -i && countCharsInCol(j, EMPTY_CHAR) == BOARD_SIZE - i) {
gl.setField(k, j, AI_CHAR);
return;
}
}
}
}
} else {
boolean emptyEdgeFound = false;
int row = -1;

11
src/test/java/de/tims/tictactoe/ai/AIHardTest.java

@ -154,6 +154,17 @@ class AIHardTest {
verify(gl, times(1)).setField(0, 2, realChar);
}
@Test
void chooseFieldWhichCreatesMostOpportunitiesToWin() {
char realChar = 'o';
doReturn(new char[][] { {'-', 'x', 'o'}, {'-', 'o', '-'}, {'x', '-', '-'} }).when(gl).getBoard();
TicTacToeAI ai = new AIHard(gl);
ai.calculateNextMove();
verify(gl, times(1)).setField(1, 2, realChar);
}
@ParameterizedTest
@MethodSource("testCasesForCountCharsInRow")
void countCharsInRowTest(String testName, char[][] board, int rowNum, char charToCount, int expectedResult) {

Loading…
Cancel
Save