Ali Doggaz
Ali Doggaz

Reputation: 105

Local variable 'q' referenced before assignment

Whenever I use the minimax function, I get that error. RQ: If player(board) == X, k will always be superior to -2 If player(board) == O, k will always be inferior to 2

def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board):
    return None

if player(board) == X:
    p=-2
    for a in actions(board):
        k=Min_Value(result(board,a))
        if p < k:
            p = k
            q = a

elif player(board) == O:
    p = 2
    for a in actions(board):
        k = Max_Value(result(board, a))
        if p > k:
            p = k
            q = a
return (q)

Upvotes: 0

Views: 263

Answers (1)

JarroVGIT
JarroVGIT

Reputation: 5324

In your function, the two elif functions do not return anything. So if both player(board) == X and player(board) == 0 are false, then the variable q is not yet set and thus the return statement will throw that error. Try setting q=None at the beginning of the function, this will solve the error but you probably should look at the logic you are applying as it doesn't seem to be complete.

Upvotes: 1

Related Questions