|
|
@ -5,11 +5,12 @@ import de.tims.tictactoe.GameLogic; |
|
|
|
public class AIHard implements TicTacToeAI { |
|
|
|
private static final char AI_CHAR = 'o'; |
|
|
|
private static final char EMPTY_CHAR = '-'; |
|
|
|
private static final int BOARD_SIZE = 3; |
|
|
|
|
|
|
|
private GameLogic gl; |
|
|
|
|
|
|
|
public AIHard(GameLogic gl) throws IllegalArgumentException { |
|
|
|
if (gl.getBoard().length != 3) { |
|
|
|
if (gl.getBoard().length != BOARD_SIZE) { |
|
|
|
throw new IllegalArgumentException("Hard AI only supports 3x3 boards!"); |
|
|
|
} |
|
|
|
this.gl = gl; |
|
|
@ -19,15 +20,39 @@ public class AIHard implements TicTacToeAI { |
|
|
|
public void calculateNextMove() { |
|
|
|
boolean emptyBoard = true; |
|
|
|
char[][] board = gl.getBoard(); |
|
|
|
|
|
|
|
for (char[] row : board) { |
|
|
|
for (char field : row) { |
|
|
|
emptyBoard &= field == EMPTY_CHAR; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
if (emptyBoard || board[1][1] == EMPTY_CHAR) { |
|
|
|
gl.setField(1, 1, AI_CHAR); |
|
|
|
} else { |
|
|
|
gl.setField(0, 0, AI_CHAR); |
|
|
|
boolean emptyEdgeFound = false; |
|
|
|
int row = 0; |
|
|
|
int col = 0; |
|
|
|
|
|
|
|
for (int i = 0; i < BOARD_SIZE; i = i + BOARD_SIZE - 1) { |
|
|
|
for (int j = 0; j < BOARD_SIZE; j = j + BOARD_SIZE - 1) { |
|
|
|
row = i; |
|
|
|
col = j; |
|
|
|
|
|
|
|
if (board[i][j] == EMPTY_CHAR) { |
|
|
|
row = i; |
|
|
|
col = j; |
|
|
|
emptyEdgeFound = true; |
|
|
|
break; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
if (emptyEdgeFound) { |
|
|
|
break; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
gl.setField(row, col, AI_CHAR); |
|
|
|
} |
|
|
|
} |
|
|
|
} |