int abMax(int** board, int alpha, int beta, list<Move>& actions, Move move, int depth) { switch(terminalState(board, move)) { case Draw: return 0; break; case Win: return -INFINITE_SCORE; break; } //Depth handling if(depth==0) return staticEvaluation(board); if(depth != -1) depth--; list<Move>* children = legalMoves(board); int v = -INFINITE_SCORE; int w; for(list<Move>::iterator it = children->begin(); it != children->end(); ++it) { list<Move> &tmp = list<Move>(); int i = it->x; int j = it->y; doMove(board, *it, PLAYER_COLOR); display(board); w = abMin(board, alpha, beta, tmp, *it,depth); undoMove(board, *it); if(w > v) { v = w; actions = tmp; actions.push_front(*it); } if(v >= beta) return v; alpha = max(alpha, v); } return v; }
/** * Alph-Beta Pruning *@param depth how deep to search the tree *@param alpha the minimax value for alpha *@param beta the minimax value for beta *@return x y coordinates for move */ int AlphaBetaAI::alpha_beta(AlphaBetaNode* node, int depth, int maxPlayer, int myScore, int otherScore, int pointsRemaining) { node->myScore = myScore; node->otherScore = otherScore; node->generateBoard(heapBoard); if (depth <= 0 || pointsRemaining == 0) // or is a terminal node? { //printf("leaf node!\n"); int eval = evaluate(heapBoard, myScore, otherScore, maxPlayer); return eval; } vector<int> legalMoves(node->getMoves()); //std::vector<int> moves; //generateLegalMoves(_board, legalMoves); //vector of all possible legal moves to make while (legalMoves.size()) //for each child node of max and min player { //printf("legal moves: %d\n", legalMoves.size()); int myPoints = myScore; int otherPoints = otherScore; int pointsLeft = pointsRemaining; bool scored = makeNextMove(heapBoard, legalMoves[legalMoves.size()-1], maxPlayer, myPoints, otherPoints, pointsLeft); AlphaBetaNode* kid = find_root(heapBoard, node, pointsLeft); node->hasKid(kid); kid->hasParent(node); //printf("getting eval %d\n", kid); float eval = alpha_beta(kid, 0, scored?maxPlayer:!maxPlayer, myPoints, otherPoints, pointsLeft); /*if (scored) { eval += eval+1; }*/ //printf("got! eval %d\n", kid); if (maxPlayer) { if (eval > node->alpha) { node->alpha = eval; } //printf("%d %d\n", node->alpha, node->beta); if (node->beta <= node->alpha) { //printf("max-cut\n"); unmakeLastMove(heapBoard, legalMoves[legalMoves.size()-1]); break; //beta cut-off } } else { if (eval < node->beta) { node->beta = eval; } //printf("\t\t\t%d %d\n", node->alpha, node->beta); if (node->beta <= node->alpha) { //printf("min-cut\n"); unmakeLastMove(heapBoard, legalMoves[legalMoves.size()-1]); break; //alpha cut-off } } //while (moves.size()) { unmakeLastMove(heapBoard, legalMoves[legalMoves.size()-1]); // moves.pop_back(); //} legalMoves.pop_back(); break; }//end while loop of all legalMoves //printf("about to return thingy\n"); if (maxPlayer) { return node->alpha; } return node->beta; }