From c6e0d83d70a6fa8b659f35a9cbf9d0bbc72034ae Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Mon, 31 Jan 2022 16:17:51 +0100 Subject: [PATCH] tictactoe: hard AI prevents opponents win in row --- src/main/java/de/tims/tictactoe/ai/AIHard.java | 17 ++++++++++++----- .../java/de/tims/tictactoe/ai/AIHardTest.java | 11 +++++++++++ 2 files changed, 23 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 3e802c2..a821485 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/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; diff --git a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java index 72934b6..e99dbf9 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/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) {