Browse Source

tictactoe: hard ai uses chance to win in cols

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

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

@ -20,6 +20,7 @@ public class AIHard implements TicTacToeAI {
@Override @Override
public void calculateNextMove() { public void calculateNextMove() {
int ownCharsInRow = 0; int ownCharsInRow = 0;
int ownCharsInCol = 0;
int charsOfOpponentInRow = 0; int charsOfOpponentInRow = 0;
int charsOfOpponentInCol = 0; int charsOfOpponentInCol = 0;
int charsOfOpponentInDiag = 0; int charsOfOpponentInDiag = 0;
@ -27,16 +28,17 @@ public class AIHard implements TicTacToeAI {
for (int i = 0; i < BOARD_SIZE; i++) { for (int i = 0; i < BOARD_SIZE; i++) {
ownCharsInRow = countCharsInRow(i, AI_CHAR); ownCharsInRow = countCharsInRow(i, AI_CHAR);
ownCharsInCol = countCharsInCol(i, AI_CHAR);
charsOfOpponentInRow = countCharsInRow(i, PLAYER_CHAR); charsOfOpponentInRow = countCharsInRow(i, PLAYER_CHAR);
charsOfOpponentInCol = countCharsInCol(i, PLAYER_CHAR); charsOfOpponentInCol = countCharsInCol(i, PLAYER_CHAR);
if (i < 2) { if (i < 2) {
charsOfOpponentInDiag = countCharsInDiag(i, PLAYER_CHAR); charsOfOpponentInDiag = countCharsInDiag(i, PLAYER_CHAR);
} }
if (ownCharsInRow == BOARD_SIZE - 1) {
if (ownCharsInRow == BOARD_SIZE - 1 || ownCharsInCol == BOARD_SIZE - 1) {
for (int j = 0; j < BOARD_SIZE; j++) { for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY_CHAR) {
gl.setField(i, j, AI_CHAR);
if (board[(ownCharsInRow == BOARD_SIZE - 1) ? i : j][(ownCharsInRow == BOARD_SIZE - 1) ? j : i] == EMPTY_CHAR) {
gl.setField((ownCharsInRow == BOARD_SIZE - 1) ? i : j, (ownCharsInRow == BOARD_SIZE - 1) ? j : i, AI_CHAR);
return; return;
} }
} }

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

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

Loading…
Cancel
Save