Browse Source

tictactoe: hard ai uses chance to win in row

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

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

@ -19,18 +19,29 @@ public class AIHard implements TicTacToeAI {
@Override
public void calculateNextMove() {
int ownCharsInRow = 0;
int charsOfOpponentInRow = 0;
int charsOfOpponentInCol = 0;
int charsOfOpponentInDiag = 0;
char[][] board = gl.getBoard();
for (int i = 0; i < BOARD_SIZE; i++) {
ownCharsInRow = countCharsInRow(i, AI_CHAR);
charsOfOpponentInRow = countCharsInRow(i, PLAYER_CHAR);
charsOfOpponentInCol = countCharsInCol(i, PLAYER_CHAR);
if (i < 2) {
charsOfOpponentInDiag = countCharsInDiag(i, PLAYER_CHAR);
}
if (ownCharsInRow == 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 (charsOfOpponentInRow == BOARD_SIZE - 1 || charsOfOpponentInCol == BOARD_SIZE - 1 || charsOfOpponentInDiag == BOARD_SIZE - 1) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (charsOfOpponentInRow == BOARD_SIZE - 1) {

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

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

Loading…
Cancel
Save