Minimax Java
Minimax Java
Minimax Java
*;
class Minimax {
private static final int MAX_DEPTH = 5;
Board() {
grid = new char[][]{
{'_', '_', '_'},
{'_', '_', '_'},
{'_', '_', '_'}
};
}
boolean isMovesLeft() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (grid[i][j] == '_')
return true;
return false;
}
int evaluate() {
// Evaluación simple: suponemos que X es el jugador humano y O es la
máquina
// Si X gana, retorna -1, si O gana, retorna 1, si hay empate, retorna
0
for (int row = 0; row < 3; row++) {
if (grid[row][0] == grid[row][1] && grid[row][1] == grid[row][2]) {
if (grid[row][0] == 'X')
return -1;
else if (grid[row][0] == 'O')
return 1;
}
}
for (int col = 0; col < 3; col++) {
if (grid[0][col] == grid[1][col] && grid[1][col] == grid[2][col]) {
if (grid[0][col] == 'X')
return -1;
else if (grid[0][col] == 'O')
return 1;
}
}
if (grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2]) {
if (grid[0][0] == 'X')
return -1;
else if (grid[0][0] == 'O')
return 1;
}
if (grid[0][2] == grid[1][1] && grid[1][1] == grid[2][0]) {
if (grid[0][2] == 'X')
return -1;
else if (grid[0][2] == 'O')
return 1;
}
return 0;
}
if (score == 1)
return score;
if (score == -1)
return score;
if (!isMovesLeft())
return 0;
if (isMax) {
int best = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[i][j] == '_') {
grid[i][j] = 'O';
best = Math.max(best, minimax(depth + 1, !isMax));
grid[i][j] = '_';
}
}
}
return best;
} else {
int best = Integer.MAX_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[i][j] == '_') {
grid[i][j] = 'X';
best = Math.min(best, minimax(depth + 1, !isMax));
grid[i][j] = '_';
}
}
}
return best;
}
}
Move findBestMove() {
int bestVal = Integer.MIN_VALUE;
Move bestMove = new Move(-1, -1);
return bestMove;
}
void printBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}
}
while (board.isMovesLeft()) {
Move bestMove = board.findBestMove();
System.out.println("La máquina juega en: " + bestMove.row + ", " +
bestMove.col);
board.grid[bestMove.row][bestMove.col] = 'O';
board.printBoard();
if (board.evaluate() == 1) {
System.out.println("¡La máquina gana!");
break;
} else if (board.evaluate() == -1) {
System.out.println("¡Has ganado!");
break;
} else if (!board.isMovesLeft()) {
System.out.println("¡Empate!");
break;
}
if (board.evaluate() == 1) {
System.out.println("¡La máquina gana!");
break;
} else if (board.evaluate() == -1) {
System.out.println("¡Has ganado!");
break;
} else if (!board.isMovesLeft()) {
System.out.println("¡Empate!");
break;
}
}
}
}