From 7c7e134ad9e874f5c625c2867f4233a00dcc7c24 Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Mon, 31 Jan 2022 13:06:34 +0100 Subject: [PATCH] tictactoe: hard AI sets middle field if it hasnt been set yet --- src/main/java/de/tims/tictactoe/ai/AIHard.java | 4 ++-- src/test/java/de/tims/tictactoe/ai/AIHardTest.java | 11 +++++++++++ 2 files changed, 13 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 ae1e7cb..146101a 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/src/main/java/de/tims/tictactoe/ai/AIHard.java @@ -21,10 +21,10 @@ public class AIHard implements TicTacToeAI { char[][] board = gl.getBoard(); for (char[] row : board) { for (char field : row) { - emptyBoard &= field == '-'; + emptyBoard &= field == EMPTY_CHAR; } } - if (emptyBoard) { + if (emptyBoard || board[1][1] == EMPTY_CHAR) { gl.setField(1, 1, AI_CHAR); } else { gl.setField(0, 0, 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 dddb7d2..856c1a7 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java @@ -37,5 +37,16 @@ class AIHardTest { verify(gl, times(1)).setField(0, 0, realChar); } + + @Test + void opponentDidntChooseMiddleFieldSoAIDoes() { + char realChar = 'o'; + doReturn(new char[][] { {'-', '-', 'x'}, {'-', '-', '-'}, {'-', '-', '-'} }).when(gl).getBoard(); + + TicTacToeAI ai = new AIHard(gl); + ai.calculateNextMove(); + + verify(gl, times(1)).setField(1, 1, realChar); + } }