UnboundLocalError: 无法访问未赋值的局部变量 'currentPlayer
我不太明白这个错误。'currentPlayer'在第13行被声明和定义了,而且是全局的。为什么在我的ToggleTurn()方法里它会变成未绑定的呢?
错误信息:
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()
我试着通过值传递currentPlayer,但这样TogglePlayer()方法只更新了局部变量。
1 个回答
-1
这个值不是全局的。如果想让它变成全局的,你需要在'def ToggleTurn
'这一行后面加上一行'global currentPlayer
',这样才能在函数里修改这个值。如果你只是想获取currentPlayer
的值,而不想修改它,那么你应该在代码的最开始加上'global currentPlayer
'这一行。