private int minimax(Desk desk, GameRules rules, int depth, short currentPlayer, bool maximizingPlayer) { movesInspected++; short oppositePlayer = rules.getOppositePlayer(currentPlayer); if (rules.isGameEnd(desk)) //check game end - both players have some fields and at least one can move { short nextPlayer = rules.getNextPlayer(desk); if (desk.getPlayerFields(GameVar.PLAYER_WHITE).Count != 0 && desk.getPlayerFields(GameVar.PLAYER_BLACK).Count != 0 && nextPlayer == -1) { return(0); //draw, neither of players can move } if (maximizingPlayer) { return(int.MinValue + depthMax - depth); } return(int.MaxValue - depthMax + depth); } if (depth == 0) //check depth level, return eval of current position { if (maximizingPlayer) { return(-rules.getGameEvaluation(desk, oppositePlayer)); } return(rules.getGameEvaluation(desk, oppositePlayer)); } //get new possible moves, make the moves and call recursively minmax ArrayList possibleMoves = rules.getPossibleMoves(desk, currentPlayer); int bestVal = 0; int currentVal = 0; //current player has no possible moves, play "nothing" and call minimax if (possibleMoves.Count == 0) { if (maximizingPlayer) { bestVal = int.MinValue; currentVal = minimax(desk, rules, depth, oppositePlayer, false); bestVal = Math.Max(bestVal, currentVal); } else { bestVal = int.MaxValue; currentVal = minimax(desk, rules, depth, oppositePlayer, true); bestVal = Math.Min(bestVal, currentVal); } return(bestVal); } if (maximizingPlayer) //current player's best move, looking for the highest rating move { bestVal = int.MinValue; foreach (Move move in possibleMoves) { desk.makeMove(move); currentVal = minimax(desk, rules, depth - 1, oppositePlayer, false); desk.undoMove(move); bestVal = Math.Max(bestVal, currentVal); } } else //opposite player's best move - the worst move for current player, looking for the lowest rating move { bestVal = int.MaxValue; foreach (Move move in possibleMoves) { desk.makeMove(move); currentVal = minimax(desk, rules, depth - 1, oppositePlayer, true); desk.undoMove(move); bestVal = Math.Min(bestVal, currentVal); } } return(bestVal); }