Browse Source

tictactoe: AIEasy never sets a field which was already set

tictactoe
Tobias Krause 3 years ago
committed by Lorenz Hohmann
parent
commit
bd561b7024
  1. 12
      src/main/java/de/tims/tictactoe/ai/AIEasy.java
  2. 21
      src/test/java/de/tims/tictactoe/ai/AIEasyTest.java

12
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);
}

21
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<Integer> {
@Override
public boolean matches(Integer argument) {

Loading…
Cancel
Save