我有一個關於我的方法錯誤的小問題(就像在一個類中一樣),我目前正在研究一個AI,想要理清bot最好的移動方式,但是當我想要在該位的代碼返回bestMove,它告訴我的錯誤...分配之前引用的局部變量
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
您必須在for循環之前爲'bestMove'賦值,因爲如果if條件爲false,'bestMove'沒有賦值,函數將返回'None'。 – ikreb
檢查我的更新! @ikreb – PythonGirl