Search code examples
pythonartificial-intelligencechessminimaxalpha-beta-pruning

Collecting and retrieving the principal variation from an alphabeta framework


I am trying to write a chess engine in python, i can find the best move given a position, but i am struggling to collect the principal variation from that position, the following is what i have tried so far:

def alphabeta(board, alpha, beta, depth, pvtable):

    if depth == 0:
        return evaluate.eval(board)

    for move in board.legal_moves:
        board.push(move)
        score = -alphabeta(board, -beta, -alpha, depth - 1, pvtable)
        board.pop()
        if score >= beta:
            return beta
        if score > alpha:
            alpha = score
            pvtable[depth-1] = str(move)
    return alpha

i am using pvtable[depth - 1] = str(move) to append moves but in the end i find that pvtable contains random non consistent moves, things like ['g1h3', 'g8h6', 'h3g5', 'd8g5'] for the starting position.

I know that similar questions about that have been asked but i still didn't figure out how i can solve this problem.


Solution

  • I think your moves are overwritten when the search reaches the same depth again (in a different branch of the game tree).

    This site explains quite good how to retrieve the principal variation: https://web.archive.org/web/20071031100114/http://www.brucemo.com:80/compchess/programming/pv.htm

    Applied to your code example, it should be something like this (I didn't test it):

    def alphabeta(board, alpha, beta, depth, pline):
    
        line = []
        if depth == 0:
            return evaluate.eval(board)
    
        for move in board.legal_moves:
            board.push(move)
            score = -alphabeta(board, -beta, -alpha, depth - 1, line)
            board.pop()
            if score >= beta:
                return beta
            if score > alpha:
                alpha = score
            pline[:] = [str(move)] + line
    
        return alpha