我不明白这个错误。 '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() 方法仅更新局部变量。
该值不是全局的。要使其全局化,您必须在“
global currentPlayer
”行之后添加一行“def ToggleTurn
”,以便修改函数中的值。如果您只想获得 currentPlayer
的值,那么您可以在代码的最开头添加行 glibal currentPlayer
。
在投反对票之前,请在评论中写下原因。我可以让我的答案更好。