关于python:在赋值之前引用的局部变量”

Local variable '' referenced before assignment

我有一个小问题,关于我的方法中的一个错误(就像在类中一样),我目前正在研究一个人工智能,它想找出bot能做的最好的移动,但是当我想返回best move时,它会告诉我错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

但错误表明

UnboundLocalError: local variable 'bestMove' referenced before assignment


看看这段代码:

1
2
3
4
5
6
7
8
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

如果没有legitMoves或没有任何动作得分points > highestPoints(我认为这永远不会发生,因为countPoints最有可能返回至少0,那么bestMove将永远不会被定义,bestMove = [x][y]也应该是bestMove = [x, y]

尝试将bestMove = None放在for循环之前,然后在调用代码中处理None