minimax

mail@pastecode.io avatar
unknown
c_cpp
3 years ago
2.0 kB
3
Indexable
Never
int minimax(int d, short player, int alpha, int beta){
    int out, i, evaluatedMovesLength, value;
    EvaluatedMove_t* evaluatedMoves;
    Pawn_t movingPawnClone;
    short conquerorWeight;
    PawnBackup_t conqueredBackup;

    if(d < 1 || isGameOver()){
        return evalChessboard();
    }

    /* Initializing vital variables */
    out = player == WHITE? -1000001:1000001;
    evaluatedMovesLength = countAllAvailableMovesForPlayer(player);
    evaluatedMoves = calloc(evaluatedMovesLength, sizeof(struct EvaluatedMove));
    getAllEvaluatedMovesForPlayer(evaluatedMoves, player);

    for(i = 0; i<evaluatedMovesLength; i++){

        EvaluatedMove_t currentMove = evaluatedMoves[i];
        /* save data for undo*/
        if(currentMove.pawnConquered > 0){
            conquerorWeight = pawn[currentMove.pawnIndex].weight;
            conqueredBackup = createPawnBackup(pawn[currentMove.pawnConquered]);
        }
        movingPawnClone = pawn[currentMove.pawnIndex];
        /* finish saving data, start moving*/

        movePawn(currentMove.pawnIndex, currentMove.move);
        fillPawnsAvailableMoves();

        if(player == WHITE){
            value = minimax(d-1, -1, alpha, beta);
            out = max(out, value);
            alpha = max(alpha, value);
        } else {
            value = minimax(d-1, 1, alpha, beta);
            out = min(out, value);
            beta = min(beta, value);
        }

        /* restore previous state*/
        if(currentMove.pawnConquered > 0){
            undoConquer(currentMove.pawnIndex, currentMove.pawnConquered, conquerorWeight, conqueredBackup);
        }
        undoMove(currentMove.pawnIndex, movingPawnClone);
        fillPawnsAvailableMoves();
        /* finish restoring previous state */

        /* esco dal for perchè se assumiamo che il giocatore opposto farà la sua miglior mossa, lui non prenderà questa strada */
        if(beta <= alpha) break;

    }
    free(evaluatedMoves);
    return out;
}