CheckersAI.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "CheckersAI.h"
  2. CheckerBoard CheckersAI::findBestMove(const CheckerBoard& board, int depth) {
  3. int alpha = std::numeric_limits<int>::min();
  4. int beta = std::numeric_limits<int>::max();
  5. int bestValue = isWhite ? std::numeric_limits<int>::min() : std::numeric_limits<int>::max();
  6. CheckerBoard bestMove;
  7. std::vector<CheckerBoard> moves = board.generateLegalMoves(isWhite);
  8. if (moves.size() == 0) throw exception();
  9. for (const auto& move : moves) {
  10. int value = minimax(move, depth - 1, alpha, beta, !isWhite);
  11. if (isWhite && value > bestValue) {
  12. bestValue = value;
  13. bestMove = move;
  14. alpha = std::max(alpha, bestValue);
  15. }
  16. else if (!isWhite && value < bestValue) {
  17. bestValue = value;
  18. bestMove = move;
  19. beta = std::min(beta, bestValue);
  20. }
  21. if (alpha >= beta) break;
  22. }
  23. wcout << "Best move: " << bestMove.move.c_str() << endl;
  24. return bestMove;
  25. }
  26. int CheckersAI::minimax(CheckerBoard board, int depth, int alpha, int beta, bool isMaximizing) {
  27. if (depth == 0 || board.isGameOver()) {
  28. return board.evaluate();
  29. }
  30. std::vector<CheckerBoard> moves = board.generateLegalMoves(isMaximizing);
  31. if (isMaximizing) {
  32. int maxEval = std::numeric_limits<int>::min();
  33. for (const auto& move : moves) {
  34. int eval = minimax(move, depth - 1, alpha, beta, false);
  35. maxEval = std::max(maxEval, eval);
  36. alpha = std::max(alpha, eval);
  37. if (beta <= alpha) break;
  38. }
  39. return maxEval;
  40. }
  41. else {
  42. int minEval = std::numeric_limits<int>::max();
  43. for (const auto& move : moves) {
  44. int eval = minimax(move, depth - 1, alpha, beta, true);
  45. minEval = std::min(minEval, eval);
  46. beta = std::min(beta, eval);
  47. if (beta <= alpha) break;
  48. }
  49. return minEval;
  50. }
  51. }