123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- #include "CheckersAI.h"
- CheckerBoard CheckersAI::findBestMove(const CheckerBoard& board, int depth) {
- int alpha = std::numeric_limits<int>::min();
- int beta = std::numeric_limits<int>::max();
- int bestValue = isWhite ? std::numeric_limits<int>::min() : std::numeric_limits<int>::max();
- CheckerBoard bestMove;
- std::vector<CheckerBoard> moves = board.generateLegalMoves(isWhite);
- if (moves.size() == 0) throw exception();
- for (const auto& move : moves) {
- int value = minimax(move, depth - 1, alpha, beta, !isWhite);
- if (isWhite && value > bestValue) {
- bestValue = value;
- bestMove = move;
- alpha = std::max(alpha, bestValue);
- }
- else if (!isWhite && value < bestValue) {
- bestValue = value;
- bestMove = move;
- beta = std::min(beta, bestValue);
- }
- if (alpha >= beta) break;
- }
- wcout << "Best move: " << bestMove.move.c_str() << endl;
- return bestMove;
- }
- int CheckersAI::minimax(CheckerBoard board, int depth, int alpha, int beta, bool isMaximizing) {
- if (depth == 0 || board.isGameOver()) {
- return board.evaluate();
- }
- std::vector<CheckerBoard> moves = board.generateLegalMoves(isMaximizing);
- if (isMaximizing) {
- int maxEval = std::numeric_limits<int>::min();
- for (const auto& move : moves) {
- int eval = minimax(move, depth - 1, alpha, beta, false);
- maxEval = std::max(maxEval, eval);
- alpha = std::max(alpha, eval);
- if (beta <= alpha) break;
- }
- return maxEval;
- }
- else {
- int minEval = std::numeric_limits<int>::max();
- for (const auto& move : moves) {
- int eval = minimax(move, depth - 1, alpha, beta, true);
- minEval = std::min(minEval, eval);
- beta = std::min(beta, eval);
- if (beta <= alpha) break;
- }
- return minEval;
- }
- }
|