From 412558578c40ed028a74afbd233056c531dbaf69 Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Wed, 2 Feb 2022 21:03:33 +0100 Subject: [PATCH] tictactoe: hard ai sets always in the nearest edge to opponents field --- .../java/de/tims/tictactoe/ai/AIHard.java | 20 +++++++++++++++++-- .../java/de/tims/tictactoe/ai/AIHardTest.java | 11 ++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/tims/tictactoe/ai/AIHard.java b/src/main/java/de/tims/tictactoe/ai/AIHard.java index c8e1de6..5c29316 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/src/main/java/de/tims/tictactoe/ai/AIHard.java @@ -54,8 +54,24 @@ public class AIHard implements TicTacToeAI { } } - if (board[1][1] == EMPTY_CHAR) { - gl.setField(1, 1, AI_CHAR); + if (board[BOARD_SIZE / 2][BOARD_SIZE / 2] == EMPTY_CHAR) { + gl.setField(BOARD_SIZE / 2, BOARD_SIZE / 2, AI_CHAR); + } else if (board[BOARD_SIZE / 2][BOARD_SIZE / 2] == AI_CHAR && (board[0][0] == AI_CHAR || board[0][BOARD_SIZE - 1] == AI_CHAR || board[BOARD_SIZE - 1][0] == AI_CHAR || board[BOARD_SIZE - 1][BOARD_SIZE - 1] == AI_CHAR)) { + for (int i = BOARD_SIZE - 2; i > 0; i--) { + for (int j = 0; j < BOARD_SIZE; j += BOARD_SIZE - 1) { + for (int k = 1; k < BOARD_SIZE - 1; k++) { + if (countCharsInRow(j, AI_CHAR) == i && countCharsInCol(k, AI_CHAR) == i && countCharsInRow(j, EMPTY_CHAR) == BOARD_SIZE -i && countCharsInCol(k, EMPTY_CHAR) == BOARD_SIZE - i) { + gl.setField(j, k, AI_CHAR); + return; + } + + if (countCharsInRow(k, AI_CHAR) == i && countCharsInCol(j, AI_CHAR) == i && countCharsInRow(k, EMPTY_CHAR) == BOARD_SIZE -i && countCharsInCol(j, EMPTY_CHAR) == BOARD_SIZE - i) { + gl.setField(k, j, AI_CHAR); + return; + } + } + } + } } else { boolean emptyEdgeFound = false; int row = -1; diff --git a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java index 07ac838..8c21419 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java @@ -154,6 +154,17 @@ class AIHardTest { verify(gl, times(1)).setField(0, 2, realChar); } + @Test + void chooseFieldWhichCreatesMostOpportunitiesToWin() { + char realChar = 'o'; + doReturn(new char[][] { {'-', 'x', 'o'}, {'-', 'o', '-'}, {'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) {