Browse Source

tictactoe: hard AI prevents opponents win in col

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

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

@ -19,15 +19,17 @@ public class AIHard implements TicTacToeAI {
@Override @Override
public void calculateNextMove() { public void calculateNextMove() {
int charsOfOpponent = 0;
int charsOfOpponentInRow = 0;
int charsOfOpponentInCol = 0;
char[][] board = gl.getBoard(); char[][] board = gl.getBoard();
for (int i = 0; i < BOARD_SIZE; i++) { for (int i = 0; i < BOARD_SIZE; i++) {
charsOfOpponent = countCharsInRow(i, PLAYER_CHAR);
if (charsOfOpponent == BOARD_SIZE - 1) {
charsOfOpponentInRow = countCharsInRow(i, PLAYER_CHAR);
charsOfOpponentInCol = countCharsInCol(i, PLAYER_CHAR);
if (charsOfOpponentInRow == BOARD_SIZE - 1 || charsOfOpponentInCol == 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[(charsOfOpponentInRow == BOARD_SIZE - 1) ? i : j][(charsOfOpponentInRow == BOARD_SIZE - 1) ? j : i] == EMPTY_CHAR) {
gl.setField((charsOfOpponentInRow == BOARD_SIZE - 1) ? i : j, (charsOfOpponentInRow == BOARD_SIZE - 1) ? j : i, AI_CHAR);
return; return;
} }
} }

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

@ -77,6 +77,17 @@ class AIHardTest {
verify(gl, times(1)).setField(1, 2, realChar); verify(gl, times(1)).setField(1, 2, realChar);
} }
@Test
void preventOpponentsWinInCol() {
char realChar = 'o';
doReturn(new char[][] { {'o', 'x', '-'}, {'-', 'x', '-'}, {'-', '-', '-'} }).when(gl).getBoard();
TicTacToeAI ai = new AIHard(gl);
ai.calculateNextMove();
verify(gl, times(1)).setField(2, 1, 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