Local variable '' referenced before assignment

时间:2017-08-04 12:14:51

标签: python python-3.x

I have a small problem concerning an error in my method (as inside a class), I am currently working on a AI wanting to sort out the best move the bot can do, but when I want to return bestMove, it tells me the error.

def computerMove(self, tile, newBoard, legalMoves, isOnCorner):
        legitMoves = self.getLegalMoves(self.board, tile)
        for x, y in legitMoves:
             if self.isOnCorner(x, y):
                 return [x, y]
        highestPoints = -1
        for x, y in legitMoves:
            computerBoard = self.getComputerBoard(self.newBoard)
            makeYourMove(computerBoard, tile, x, y)
            points = countPoints(computerBoard)[tile]
            if points > highestPoints:
                highestPoints = points
                bestMove = [x][y]
        return bestMove

but the error states

UnboundLocalError: local variable 'bestMove' referenced before assignment

1 个答案:

答案 0 :(得分:2)

Look at this bit of code:

for x, y in legitMoves:
    computerBoard = self.getComputerBoard(self.newBoard)
    makeYourMove(computerBoard, tile, x, y)
    points = countPoints(computerBoard)[tile]
    if points > highestPoints:
        highestPoints = points
        bestMove = [x][y]
return bestMove

If there are no legitMoves or no moves scoring points > highestPoints (I assume this will never be the case as countPoints most likely returns at least 0) then bestMove will never be defined, also bestMove = [x][y] should be bestMove = [x, y].

Try putting bestMove = None before your for loop and then handle the None in the calling code.