2017-08-04 54 views
-1

我有一個關於我的方法錯誤的小問題(就像在一個類中一樣),我目前正在研究一個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

+0

您必須在for循環之前爲'bestMove'賦值,因爲如果if條件爲false,'bestMove'沒有賦值,函數將返回'None'。 – ikreb

+0

檢查我的更新! @ikreb – PythonGirl

回答

2

看:

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]

嘗試在您的for循環之前放置bestMove = None,然後在呼叫代碼中處理None

+0

我完全理解你的意思,但它不起作用。檢查我的更新! – PythonGirl

+0

*「但它不起作用」*新的錯誤是什麼? –

+0

哦,我想我現在正在解決它,如果我需要更多的幫助,生病會回來! ty – PythonGirl

相關問題