From bd561b7024740bee322d81841bb8c9de4d6e5b52 Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Mon, 31 Jan 2022 12:07:27 +0100 Subject: [PATCH] tictactoe: AIEasy never sets a field which was already set --- .../java/de/tims/tictactoe/ai/AIEasy.java | 12 ++++++++--- .../java/de/tims/tictactoe/ai/AIEasyTest.java | 21 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/tims/tictactoe/ai/AIEasy.java b/src/main/java/de/tims/tictactoe/ai/AIEasy.java index 308eaf1..d838bbf 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIEasy.java +++ b/src/main/java/de/tims/tictactoe/ai/AIEasy.java @@ -6,6 +6,7 @@ import java.util.Random; public class AIEasy implements TicTacToeAI { private static final char AI_CHAR = 'o'; + private static final char EMPTY_CHAR = '-'; private Random rand; private GameLogic gl; @@ -14,14 +15,19 @@ public class AIEasy implements TicTacToeAI { public AIEasy(GameLogic gl) { this.gl = gl; boardSize = gl.getBoard().length; - rand = new Random(gl.getBoard().hashCode()); + rand = new Random(); } @Override public void calculateNextMove() { char[][] board = gl.getBoard(); - int row = rand.nextInt(boardSize); - int col = rand.nextInt(boardSize); + int row; + int col; + do { + row = rand.nextInt(boardSize); + col = rand.nextInt(boardSize); + } while (board[row][col] != '-'); + gl.setField(row, col, AI_CHAR); } diff --git a/src/test/java/de/tims/tictactoe/ai/AIEasyTest.java b/src/test/java/de/tims/tictactoe/ai/AIEasyTest.java index 5c169ba..181577e 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIEasyTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIEasyTest.java @@ -32,6 +32,27 @@ class AIEasyTest { verify(gl, times(100)).setField(intThat(new ChooseRandomFieldMatcher()), intThat(new ChooseRandomFieldMatcher()), eq(realChar)); } + @Test + void notEmptyBoardChooseRandomFreeField() { + char realChar = 'o'; + doReturn(new char[][] { {'x', '-', 'o'}, {'-', 'o', '-'}, {'-', 'x', 'x'} }).when(gl).getBoard(); + + TicTacToeAI ai = new AIEasy(gl); + + //run method 100 times, because of random generator + for (int i = 0; i < 100; i++) { + ai.calculateNextMove(); + } + + verify(gl, times(100)).setField(intThat(new ChooseRandomFieldMatcher()), intThat(new ChooseRandomFieldMatcher()), eq(realChar)); + //verify that the method is never called with a field which was already set + verify(gl, never()).setField(0, 0, realChar); + verify(gl, never()).setField(0, 2, realChar); + verify(gl, never()).setField(1, 1, realChar); + verify(gl, never()).setField(2, 1, realChar); + verify(gl, never()).setField(2, 2, realChar); + } + private static class ChooseRandomFieldMatcher implements ArgumentMatcher { @Override public boolean matches(Integer argument) {