From 360870072ef6155cb75bb1172cdf725fba1af117 Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Wed, 2 Feb 2022 16:01:40 +0100 Subject: [PATCH] tictactoe: hard ai uses chance to win in row --- src/main/java/de/tims/tictactoe/ai/AIHard.java | 11 +++++++++++ src/test/java/de/tims/tictactoe/ai/AIHardTest.java | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/main/java/de/tims/tictactoe/ai/AIHard.java b/src/main/java/de/tims/tictactoe/ai/AIHard.java index 9768677..60bf53c 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/src/main/java/de/tims/tictactoe/ai/AIHard.java @@ -19,18 +19,29 @@ public class AIHard implements TicTacToeAI { @Override public void calculateNextMove() { + int ownCharsInRow = 0; int charsOfOpponentInRow = 0; int charsOfOpponentInCol = 0; int charsOfOpponentInDiag = 0; char[][] board = gl.getBoard(); for (int i = 0; i < BOARD_SIZE; i++) { + ownCharsInRow = countCharsInRow(i, AI_CHAR); charsOfOpponentInRow = countCharsInRow(i, PLAYER_CHAR); charsOfOpponentInCol = countCharsInCol(i, PLAYER_CHAR); if (i < 2) { charsOfOpponentInDiag = countCharsInDiag(i, PLAYER_CHAR); } + if (ownCharsInRow == 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 (charsOfOpponentInRow == BOARD_SIZE - 1 || charsOfOpponentInCol == BOARD_SIZE - 1 || charsOfOpponentInDiag == BOARD_SIZE - 1) { for (int j = 0; j < BOARD_SIZE; j++) { if (charsOfOpponentInRow == BOARD_SIZE - 1) { diff --git a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java index dbadc8b..15ae318 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java @@ -99,6 +99,17 @@ class AIHardTest { verify(gl, times(1)).setField(2, 2, realChar); } + @Test + void when2InRowSetThird() { + char realChar = 'o'; + doReturn(new char[][] { {'o', '-', 'o'}, {'-', 'x', '-'}, {'x', 'x', '-'} }).when(gl).getBoard(); + + TicTacToeAI ai = new AIHard(gl); + ai.calculateNextMove(); + + verify(gl, times(1)).setField(0, 1, realChar); + } + @ParameterizedTest @MethodSource("testCasesForCountCharsInRow") void countCharsInRowTest(String testName, char[][] board, int rowNum, char charToCount, int expectedResult) {