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
f44e9e6eb2
  1. 24
      src/main/java/de/tims/tictactoe/ai/AIHard.java
  2. 11
      src/test/java/de/tims/tictactoe/ai/AIHardTest.java

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

@ -58,19 +58,23 @@ public class AIHard implements TicTacToeAI {
gl.setField(1, 1, AI_CHAR);
} else {
boolean emptyEdgeFound = false;
int row = 0;
int col = 0;
int row = -1;
int col = -1;
int prioRow = -1;
int prioCol = -1;
for (int i = 0; i < BOARD_SIZE; i = i + BOARD_SIZE - 1) {
for (int j = 0; j < BOARD_SIZE; j = j + BOARD_SIZE - 1) {
row = i;
col = j;
if (board[i][j] == EMPTY_CHAR) {
row = i;
col = j;
emptyEdgeFound = true;
break;
row = (row == -1) ? i : row;
col = (col == -1) ? j : col;
if (countCharsInRow(i, PLAYER_CHAR) != 0 || countCharsInCol(j, PLAYER_CHAR) != 0) {
prioRow = i;
prioCol = j;
emptyEdgeFound = true;
break;
}
}
}
@ -79,7 +83,7 @@ public class AIHard implements TicTacToeAI {
}
}
gl.setField(row, col, AI_CHAR);
gl.setField((prioRow != -1) ? prioRow : row, (prioCol != -1) ? prioCol : col, AI_CHAR);
}
}

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

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

Loading…
Cancel
Save