public static int evaluate(Game game, char player) { if (game.isGameOver()) { for (int i = 0; i < Board.ROWS; i++) { for (int j = 0; j < Board.COLUMNS; j++) { if (game.getBoard().matrix[i][j] != Board.EMPTY) { int piece = game.getBoard().matrix[i][j]; if (piece == Board.BLACK_SOLDIER || piece == Board.BLACK_KING) { if (player == Move.BLACK) { return 100; } else { return -100; } } else if (piece == Board.RED_SOLDIER || piece == Board.RED_KING) { if (player == Move.RED) { return 100; } else { return -100; } } } } } } else { int numBlackKings = 0, numRedKings = 0; int numBlackPieces = 0, numRedPieces = 0; for (int i = 0; i < Board.ROWS; i++) { for (int j = 0; j < Board.COLUMNS; j++) { int piece = game.getBoard().matrix[i][j]; if (piece != Board.EMPTY) { if (piece == Board.BLACK_KING) { numBlackKings++; numBlackPieces++; } else if (piece == Board.RED_KING) { numRedKings++; numRedPieces++; } else if (piece == Board.BLACK_SOLDIER) { numBlackPieces++; } else if (piece == Board.RED_SOLDIER) { numRedPieces++; } } } } int score = 0; score += 6 * (numBlackPieces - numRedPieces); score += (28f / 12f) * (numBlackKings - numRedKings); if (player == Move.RED) { score *= -1; } return score; } return 0; }
public static int MiniMax(Game game, char player, int depth, int maxDepth) { if (depth == maxDepth || game.isGameOver()) { return evaluate(game, player); } Move bestMove = null; int bestScore; if (game.getTurn() == player) { bestScore = Integer.MIN_VALUE; } else { bestScore = Integer.MAX_VALUE; } List<Move> allMoves = getMoves(game, game.getTurn()); for (Move move : allMoves) { int[][] matrixCopy = game.getBoard().getMatrixCopy(); game.processMove(move.getCopy()); game.changeTurn(); int moveScore = MiniMax(game, player, depth + 1, maxDepth); game.changeTurn(); game.getBoard().setMatrix(matrixCopy); if (game.getTurn() == player) { if (moveScore > bestScore) { bestScore = moveScore; bestMove = move.getCopy(); } } else { if (moveScore < bestScore) { bestScore = moveScore; bestMove = move.getCopy(); } } } if (depth == 0) { computedBestMove = bestMove; } return bestScore; }