0% found this document useful (0 votes)
13 views4 pages

Java Minimax Tic Tac Toe Implementation

The document describes an implementation of a Tic-Tac-Toe game that uses the minimax algorithm for the computer player to select optimal moves. It defines Board and Move classes to represent the game state and a player's move. The minimax method recursively evaluates board positions to determine the best move for the maximizing player.

Uploaded by

davids.boteron
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views4 pages

Java Minimax Tic Tac Toe Implementation

The document describes an implementation of a Tic-Tac-Toe game that uses the minimax algorithm for the computer player to select optimal moves. It defines Board and Move classes to represent the game state and a player's move. The minimax method recursively evaluates board positions to determine the best move for the maximizing player.

Uploaded by

davids.boteron
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import [Link].

*;

class Minimax {
private static final int MAX_DEPTH = 5;

static class Move {


int row, col;

Move(int row, int col) {


[Link] = row;
[Link] = col;
}
}

static class Board {


char[][] grid;

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

int minimax(int depth, boolean isMax) {


int score = evaluate();

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 = [Link](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 = [Link](best, minimax(depth + 1, !isMax));
grid[i][j] = '_';
}
}
}
return best;
}
}

Move findBestMove() {
int bestVal = Integer.MIN_VALUE;
Move bestMove = new Move(-1, -1);

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {
if (grid[i][j] == '_') {
grid[i][j] = 'O';
int moveVal = minimax(0, false);
grid[i][j] = '_';
if (moveVal > bestVal) {
[Link] = i;
[Link] = j;
bestVal = moveVal;
}
}
}
}

return bestMove;
}

void printBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](grid[i][j] + " ");
}
[Link]();
}
}
}

public static void main(String[] args) {


Board board = new Board();
[Link]();

while ([Link]()) {
Move bestMove = [Link]();
[Link]("La máquina juega en: " + [Link] + ", " +
[Link]);
[Link][[Link]][[Link]] = 'O';
[Link]();

if ([Link]() == 1) {
[Link]("¡La máquina gana!");
break;
} else if ([Link]() == -1) {
[Link]("¡Has ganado!");
break;
} else if (![Link]()) {
[Link]("¡Empate!");
break;
}

Scanner scanner = new Scanner([Link]);


[Link]("Tu turno. Ingresa fila (0-2): ");
int row = [Link]();
[Link]("Ingresa columna (0-2): ");
int col = [Link]();
if (row < 0 || row > 2 || col < 0 || col > 2 || [Link][row][col] !=
'_') {
[Link]("Movimiento inválido, intenta de nuevo.");
continue;
}
[Link][row][col] = 'X';
[Link]();

if ([Link]() == 1) {
[Link]("¡La máquina gana!");
break;
} else if ([Link]() == -1) {
[Link]("¡Has ganado!");
break;
} else if (![Link]()) {
[Link]("¡Empate!");
break;
}
}
}
}

Common questions

Powered by AI

The 'evaluate' function is crucial for determining the value of the current game board state in the Minimax algorithm. It checks for any winning states horizontally, vertically, and diagonally. If the player 'X' has won, it returns -1, indicating a losing state for 'O'. Conversely, if 'O' has won, it returns 1, suggesting a favorable outcome for the maximizing player. In any draw situation, or if neither has won, it returns 0. This evaluation guides the algorithm in making recursive decisions to either maximize or minimize the potential outcomes based on which player's turn it is .

The implementation includes several user interaction features, such as a terminal-based input and output system that allows the human player to make moves by entering the desired row and column. The system provides real-time feedback by displaying the board status after each move. Instructions and prompts guide the player through the decision-making process, ensuring a user-friendly interface. Error handling is also integrated to manage incorrect inputs by prompting the user to re-enter their move, hence maintaining an interactive and responsive experience .

When it is the human player's turn ('X'), the algorithm attempts to minimize its future loss potential. It evaluates all possible moves the human can make by simulating each move on the board and recursively calling the 'minimax' function to determine the potential score of resulting positions. The human player ('X') aims to minimize the game score by choosing moves that decrease the chance of winning for the machine ('O'). The function returns the minimum score of the potential moves made by 'X', hence it is known as a minimizing player .

The 'isMovesLeft' function is crucial for controlling the flow of the game as it determines if there are any remaining legal moves on the board. It checks every cell in the grid for a blank space ('_'), which indicates an available move. When no blank spaces are found, it returns false, signaling that the game should end in a draw if no winner is determined at that point. This check is used frequently to terminate the main loop of the game or to signal a draw if the board is full and neither player has won .

The fairness in game moves is maintained by alternating turns systematically between the machine and the human player. The machine first makes a move using the Minimax algorithm to determine the optimal position ('O'). The board is then checked for any game-ending conditions (win or draw). If the game is still ongoing, control passes to the human player ('X'), who inputs their move via the console. This turn-based approach ensures that each player makes one move per cycle, respecting the game rules and avoiding bias toward either player .

The code includes a check in the player's input process that ensures only legal moves are made by the human player. This is done by verifying whether the chosen cell is within the board's bounds and not already occupied. The program prompts for input until a valid selection is entered, resting control with the player until a legitimate move is made. This prevents any illegal or incorrect specifications by rejecting invalid inputs and ensuring the game state remains consistent with the rules .

Winning conditions are handled by the 'evaluate' function, which checks the board after each move for possible winning combinations across rows, columns, and diagonals. If a player achieves three identical symbols in any of these configurations, the function returns a score indicating a win for 'O' or a loss for 'X'. This check is performed after each move by both the machine and the human, and if a win is detected, the game announces the result and ceases further play. This method ensures that any win is immediately registered and announced .

The Minimax algorithm evaluates the game board by recursively exploring all possible moves. It uses a scoring function to evaluate terminal positions, where 'X' results in a score of -1, 'O' results in a score of 1, and a tie yields a score of 0 . The algorithm applies a depth-first search with a maximum depth limit set at 5 to determine the best move for 'O', the maximizing player, by choosing moves that maximize the minimum guaranteed score, calculated through recursive calls to the 'minimax' function. The best move is updated each time a move with a higher score than previously recorded is found .

The MAX_DEPTH parameter limits the computation depth of the Minimax algorithm to avoid excessive computation time and resources, especially in a more complex game state. This constraint ensures the algorithm completes in a reasonable time by curbing the exponential growth of possible move evaluations required for deeper decision trees. However, it may result in suboptimal decisions if deeper consideration could optimize the position, particularly in scenarios where strategic depth exceeds this fixed limit, potentially affecting the machine's performance in choosing the best move with incomplete foresight .

While the minimax implementation is theoretically capable of finding the optimal move by examining all possible outcomes, practical constraints such as the MAX_DEPTH limitation can lead to suboptimal moves. Additionally, certain heuristic evaluations might not fully capture the strategic nuances of specific positions, leading to misjudgments about the true strength of certain moves. Finally, potential edge cases or unforeseen complexities of the game state beyond the scope of simplistic evaluation functions might result in decisions that do not always align with the comprehensive optimal strategy .

You might also like