Browse Source

tictactoe: hard AI sets edge in second move

tictactoe
Tobias Krause 3 years ago
committed by Lorenz Hohmann
parent
commit
4456251b07
  1. 2
      src/main/java/de/tims/tictactoe/ai/AIEasy.java
  2. 29
      src/main/java/de/tims/tictactoe/ai/AIHard.java
  3. 11
      src/test/java/de/tims/tictactoe/ai/AIHardTest.java

2
src/main/java/de/tims/tictactoe/ai/AIEasy.java

@ -26,7 +26,7 @@ public class AIEasy implements TicTacToeAI {
do {
row = rand.nextInt(boardSize);
col = rand.nextInt(boardSize);
} while (board[row][col] != '-');
} while (board[row][col] != EMPTY_CHAR);
gl.setField(row, col, AI_CHAR);
}

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

@ -5,11 +5,12 @@ import de.tims.tictactoe.GameLogic;
public class AIHard implements TicTacToeAI {
private static final char AI_CHAR = 'o';
private static final char EMPTY_CHAR = '-';
private static final int BOARD_SIZE = 3;
private GameLogic gl;
public AIHard(GameLogic gl) throws IllegalArgumentException {
if (gl.getBoard().length != 3) {
if (gl.getBoard().length != BOARD_SIZE) {
throw new IllegalArgumentException("Hard AI only supports 3x3 boards!");
}
this.gl = gl;
@ -19,15 +20,39 @@ public class AIHard implements TicTacToeAI {
public void calculateNextMove() {
boolean emptyBoard = true;
char[][] board = gl.getBoard();
for (char[] row : board) {
for (char field : row) {
emptyBoard &= field == EMPTY_CHAR;
}
}
if (emptyBoard || board[1][1] == EMPTY_CHAR) {
gl.setField(1, 1, AI_CHAR);
} else {
gl.setField(0, 0, AI_CHAR);
boolean emptyEdgeFound = false;
int row = 0;
int col = 0;
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;
}
}
if (emptyEdgeFound) {
break;
}
}
gl.setField(row, col, AI_CHAR);
}
}
}

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

@ -48,5 +48,16 @@ class AIHardTest {
verify(gl, times(1)).setField(1, 1, realChar);
}
@Test
void setEdgeFieldInSecondMove() {
char realChar = 'o';
doReturn(new char[][] { {'x', '-', '-'}, {'-', 'o', '-'}, {'-', '-', '-'} }).when(gl).getBoard();
TicTacToeAI ai = new AIHard(gl);
ai.calculateNextMove();
verify(gl, times(1)).setField(0, 2, realChar);
}
}
Loading…
Cancel
Save