UnboundLocalError: cannot access local variable 'currentPlayer' where it is not associated with a value

60 Views Asked by At

I do not understand this error. 'currentPlayer' is declared and defined on line 13, which exists globally. Why is it unbound in my ToggleTurn() method?

The error:

Traceback (most recent call last):
  File "...main.py", line 83, in <module>
    PlacePiece(currentPlayer,5)
  File "...main.py", line 51, in PlacePiece
    ToggleTurn()
  File "...main.py", line 28, in ToggleTurn
    if currentPlayer == 1:
       ^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'currentPlayer' where it is not associated with a value
import pygame as pg
pg.init()

currentPlayer = 2 # 1 = o and 2 = x

def ToggleTurn():
    if currentPlayer == 1:
        currentPlayer = 2
    elif currentPlayer == 2:
        currentPlayer = 1
    else:
        print("ERROR: Could not progress to the next turn!")
        return False
    return True

def PlacePiece(piece,slot):
    if not (1,slot) in pieceList or not (2,slot) in pieceList:
        pieceList.append((piece,slot))
        ToggleTurn()
    else:
        print("GAME NOTE: A piece has already been placed there!")



RUN = True
while RUN:
    #event handler
    for event in pg.event.get():
        if event.type == pg.QUIT:
            RUN = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_KP1:
                PlacePiece(currentPlayer,1)
            #elif for the other numpad buttons
    pg.display.update()

I tried passing currentPlayer by value but then the TogglePlayer() method only updates the local variable.

1

There are 1 best solutions below

0
Qualcuno2 On

The value is not global. To make it global, you have to add a line 'global currentPlayer' after the line 'def ToggleTurn' in order to modify a value in a function. If you only want to have the value of currentPlayer without editing it then you would add the line glibal currentPlayer at the very beginning of the code.