Im trying to code a tic tac toe game using the minimax algorithm. but the method failing, it always says "This method must return a result of type int"
the method is allways is going to return a result of type int
static int minimax(String[][] board, int depth, boolean maxPlayer)
{
if (depth == 0 || gameOver(board) == true)
{
return gameEvaluation(board);
}
if (maxPlayer == true)
{
int maxEval = -100;
for (int x = 0; x < 3; x )
{
for (int y = 0; y < 3; y )
{
if (board[x][y].equals(" "))
{
board[x][y] = "x";
int eval = minimax(board, (depth - 1), false);
maxEval = Math.max(maxEval, eval);
board[x][y] = " ";
return maxEval;
}
}
}
}
else
{
int minEval = 100;
for (int x = 0; x < 3; x )
{
for (int y = 0; y < 3; y )
{
if (board[x][y].equals(" "))
{
String[][] tempBoard = board;
tempBoard[x][y] = "o";
int eval = minimax(tempBoard, (depth - 1), true);
minEval = Math.max(minEval, eval);
return minEval;
}
}
}
}
}
CodePudding user response:
You need to break up your logic in smaller methods. For started, everything in your second if{} should go into one method and everything your else{} should go in another method. Then you can unit test each one independently for debugging.
if a method has a return value, ALWAYS have the last line in that method to either return a known value or throw an exception. This is your problem. Whatever use case you have isn't hitting your other return statements so the method reaches the end with no return and throws the exception.
