Search code examples
pythonpython-2.7matrixartificial-intelligencetic-tac-toe

NameError: global name 'Player1_row' is not defined


I wrote this tic tac toe game against AI (I am improving the AI right now):

Matrix = [[0, 0, 0], 
          [0, 0, 0], 
          [0, 0, 0]]
Matrix_2 = [[" ", " ", " "], 
            [" ", " ", " "], 
            [" ", " ", " "]]
def turnX():
    Player1_row = int(raw_input("P1 What row do you want?"))
    Player1_row = Player1_row - 1
    Player1_column = int(raw_input("P1 What column do you want?"))
    Player1_column = Player1_column - 1
    if Player1_row > Matrix:
        turnX()
    if Player1_column > Matrix:
        turnX()
    if (1 == Matrix[Player1_column][Player1_row] or 500 == Matrix[Player1_column][Player1_row]):
        print "This is an invaild move!"
        turnX()
    else:
        Matrix[Player1_column][Player1_row] = 1
        Matrix_2[Player1_column][Player1_row] = "X"

def turnY():
      global Player1_row
      Player2_row = int(random.randint(1, boardX))
      Player2_row = Player2_row - 1
      Player2_column = int(random.randint(Player1_row, boardY))
      Player2_column = Player2_column - 1
      if (1 == Matrix[Player2_column][Player2_row] or 500 == Matrix[Player2_column][Player2_row]):
          turnY()
      else:
          print "AI Turn:"
          Matrix[Player2_column][Player2_row] = 500
          Matrix_2[Player2_column][Player2_row] = "O"

But I am getting this error:

NameError: global name 'Player1_row' is not defined`. 

I am trying to make the AI block the player's last move.


Solution

  • Player1_row is not a global variable, but a local variable for the function turn_X.

    To solve this, try setting Player1_row to a global variable in turn_X.