Browse Source

tictactoe: added easy AI

tictactoe
Tobias Krause 3 years ago
committed by Lorenz Hohmann
parent
commit
a786eb7496
  1. 28
      src/main/java/de/tims/tictactoe/ai/AIEasy.java
  2. 5
      src/main/java/de/tims/tictactoe/ai/TicTacToeAI.java
  3. 41
      src/test/java/de/tims/tictactoe/ai/AIEasyTest.java

28
src/main/java/de/tims/tictactoe/ai/AIEasy.java

@ -0,0 +1,28 @@
package de.tims.tictactoe.ai;
import de.tims.tictactoe.GameLogic;
import java.util.Random;
public class AIEasy implements TicTacToeAI {
private static final char AI_CHAR = 'o';
private Random rand;
private GameLogic gl;
private int boardSize;
public AIEasy(GameLogic gl) {
this.gl = gl;
boardSize = gl.getBoard().length;
rand = new Random(gl.getBoard().hashCode());
}
@Override
public void calculateNextMove() {
char[][] board = gl.getBoard();
int row = rand.nextInt(boardSize);
int col = rand.nextInt(boardSize);
gl.setField(row, col, AI_CHAR);
}
}

5
src/main/java/de/tims/tictactoe/ai/TicTacToeAI.java

@ -0,0 +1,5 @@
package de.tims.tictactoe.ai;
public interface TicTacToeAI {
void calculateNextMove();
}

41
src/test/java/de/tims/tictactoe/ai/AIEasyTest.java

@ -0,0 +1,41 @@
package de.tims.tictactoe.ai;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import de.tims.tictactoe.GameLogic;
@ExtendWith(MockitoExtension.class)
class AIEasyTest {
static int size = 3;
@Mock
private GameLogic gl;
@Test
void emptyBoardChooseRandomField() {
char realChar = 'o';
doReturn(new char[][] { {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'} }).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));
}
private static class ChooseRandomFieldMatcher implements ArgumentMatcher<Integer> {
@Override
public boolean matches(Integer argument) {
return argument.intValue() >= 0 && argument.intValue() < size;
}
}
}
Loading…
Cancel
Save