Browse Source

tictactoe: hard AI prevents opponents win in row

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

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

@ -5,6 +5,7 @@ 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 char PLAYER_CHAR = 'x';
private static final int BOARD_SIZE = 3;
private GameLogic gl;
@ -18,16 +19,22 @@ public class AIHard implements TicTacToeAI {
@Override
public void calculateNextMove() {
boolean emptyBoard = true;
int charsOfOpponent = 0;
char[][] board = gl.getBoard();
for (char[] row : board) {
for (char field : row) {
emptyBoard &= field == EMPTY_CHAR;
for (int i = 0; i < BOARD_SIZE; i++) {
charsOfOpponent = countCharsInRow(i, PLAYER_CHAR);
if (charsOfOpponent == BOARD_SIZE - 1) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY_CHAR) {
gl.setField(i, j, AI_CHAR);
return;
}
}
}
}
if (emptyBoard || board[1][1] == EMPTY_CHAR) {
if (board[1][1] == EMPTY_CHAR) {
gl.setField(1, 1, AI_CHAR);
} else {
boolean emptyEdgeFound = false;

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

@ -66,6 +66,17 @@ class AIHardTest {
verify(gl, times(1)).setField(0, 2, realChar);
}
@Test
void preventOpponentsWinInRow() {
char realChar = 'o';
doReturn(new char[][] { {'o', '-', '-'}, {'x', '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