From 7115050d60ed38d90142149e03e72eed9600f54f Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Mon, 31 Jan 2022 16:22:32 +0100 Subject: [PATCH] tictactoe: hard AI prevents opponents win in col --- src/main/java/de/tims/tictactoe/ai/AIHard.java | 12 +++++++----- src/test/java/de/tims/tictactoe/ai/AIHardTest.java | 11 +++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/main/java/de/tims/tictactoe/ai/AIHard.java b/src/main/java/de/tims/tictactoe/ai/AIHard.java index a821485..99aee69 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/src/main/java/de/tims/tictactoe/ai/AIHard.java @@ -19,15 +19,17 @@ public class AIHard implements TicTacToeAI { @Override public void calculateNextMove() { - int charsOfOpponent = 0; + int charsOfOpponentInRow = 0; + int charsOfOpponentInCol = 0; char[][] board = gl.getBoard(); 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++) { - 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; } } diff --git a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java index e99dbf9..ecede92 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java @@ -77,6 +77,17 @@ class AIHardTest { 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 @MethodSource("testCasesForCountCharsInRow") void countCharsInRowTest(String testName, char[][] board, int rowNum, char charToCount, int expectedResult) {