0

I have the following function that I need help debugging. I am getting an error saying

"in checkValidMove i UnboundLocalError: local variable 'i' referenced before assignment"

How can I fix this? Please see the function below. Thanks!

def checkValidMove(board, row, col, tile):
    #check if spot is valid to place tile at 
    #check the row first

    for i in range(col -1, -1, -1):
        if board[row][i] == '.':
            break
    
    left = i + 1  <--- **ERROR HERE**

    for i in range(col + 1, len(board[0])):
        if board[row][i] == '.':
            break
    
    right = i - 1
    rowTotal = 0

    for i in range(left, right + 1):
        rowTotal += int(board[row][i])
    
    if not multipleOfFiveCheck(rowTotal + int(tile)):
        return False

    #check columns
    for i in range(row -1, -1, -1):
        if board[i][col] == '.':
            break

    up = i + 1

    for i in range(row + 1, len(board)):
        if board[i][col] == '.':
            break

    down = i - 1
    colTotal = 0

    for i in range(up, down + 1):
        colTotal += int(board[i][col])
    
    if not multipleOfFiveCheck(colTotal + int(tile)):
        return False
    
    return True
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • 3
    `for i in range(col -1, -1, -1)` Depending on the value of `col`, this loop might not run at all, and in that case `i` would not be created. – John Gordon Nov 16 '22 at 02:38
  • Similar question: ["UnboundLocalError: local variable referenced before assignment" after an if statement](/q/15367760/4518341) – wjandrea Nov 16 '22 at 02:45

1 Answers1

0

I'm assuming that since you want to access the value of i, it should be properly indented under the appropriate loops.

for i in range(col -1, -1, -1):
    if board[row][i] == '.':
        break
    left = i + 1  

(Do the same for the others)

Trooper Z
  • 1,617
  • 14
  • 31
  • The code is part of a program used to play the game of Quinto. The game is played on an 18x18 board with tiles of various values. The goal of the game is to score the most points by creating sequences of tiles that sum to a multiple of five. The checkValidMove function is supposed to check if a given move is valid. First, it is supposed to check the row that the tile will be placed in. It's then supposed to find the leftmost and rightmost occupied positions in the row, and then sum the values of the tiles between these positions. – Bingolina_Ava Nov 16 '22 at 20:02
  • Once I indented like you suggested, I got an error that 'left' was referenced before assignment in " for i in range(left, right + 1):". Am I misplacing something logically? – Bingolina_Ava Nov 16 '22 at 20:04
  • @Bingolina_Ava In that case, initialize left and the other 3 variables at the beginning of the function such as `left = 0` – Trooper Z Nov 16 '22 at 20:07