From f44e9e6eb26979cc30f85b379f9ac5cb328f4fec Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Wed, 2 Feb 2022 20:27:44 +0100 Subject: [PATCH] tictactoe: hard ai sets always in the nearest edge to opponents field --- .../java/de/tims/tictactoe/ai/AIHard.java | 24 +++++++++++-------- .../java/de/tims/tictactoe/ai/AIHardTest.java | 11 +++++++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/main/java/de/tims/tictactoe/ai/AIHard.java b/src/main/java/de/tims/tictactoe/ai/AIHard.java index 5146369..c8e1de6 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/src/main/java/de/tims/tictactoe/ai/AIHard.java @@ -58,19 +58,23 @@ public class AIHard implements TicTacToeAI { gl.setField(1, 1, AI_CHAR); } else { boolean emptyEdgeFound = false; - int row = 0; - int col = 0; + int row = -1; + int col = -1; + int prioRow = -1; + int prioCol = -1; for (int i = 0; i < BOARD_SIZE; i = i + BOARD_SIZE - 1) { for (int j = 0; j < BOARD_SIZE; j = j + BOARD_SIZE - 1) { - row = i; - col = j; - if (board[i][j] == EMPTY_CHAR) { - row = i; - col = j; - emptyEdgeFound = true; - break; + row = (row == -1) ? i : row; + col = (col == -1) ? j : col; + + if (countCharsInRow(i, PLAYER_CHAR) != 0 || countCharsInCol(j, PLAYER_CHAR) != 0) { + prioRow = i; + prioCol = j; + emptyEdgeFound = true; + break; + } } } @@ -79,7 +83,7 @@ public class AIHard implements TicTacToeAI { } } - gl.setField(row, col, AI_CHAR); + gl.setField((prioRow != -1) ? prioRow : row, (prioCol != -1) ? prioCol : col, AI_CHAR); } } diff --git a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java index 53af626..07ac838 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java @@ -143,6 +143,17 @@ class AIHardTest { verify(gl, times(1)).setField(1, 2, realChar); } + @Test + void alwaysSetInTheNearestEdgeToOpponentsX() { + char realChar = 'o'; + doReturn(new char[][] { {'-', '-', '-'}, {'-', 'o', 'x'}, {'-', '-', '-'} }).when(gl).getBoard(); + + TicTacToeAI ai = new AIHard(gl); + ai.calculateNextMove(); + + verify(gl, times(1)).setField(0, 2, realChar); + } + @ParameterizedTest @MethodSource("testCasesForCountCharsInRow") void countCharsInRowTest(String testName, char[][] board, int rowNum, char charToCount, int expectedResult) {