全局变量是否成为 Pyglet window.event 函数中的局部变量

Do global variables become local variables in a Pyglet window.event function

最近在用Pyglet做游戏的时候反复遇到问题。游戏基本上是一个变道游戏,你需要变道以防止与追赶者相撞,导致你输掉比赛并出现结束画面让你重新开始游戏。

我设置了一个变量 loose 来存储布尔数据。如果我们与追赶者发生碰撞,loose 将是 True,如果没有,则将是 False。此变量最初设置为 False,但在我的碰撞检测算法中(位于我的更新函数中)它设置为 True.

global loose
loose = False 
...
def update(dt):
    ...
    if collision:
        loose = True
    ...

稍后当我使用检测到点击重启按钮的鼠标事件时,

@window.event
def on_mouse_press(x, y, button, modifiers):
    global loose
    if mouse_clicked:
        if loose:
           ...
           loose = False
           ...

if loose: 中出现错误

UnboundLocalError: local variable 'loose' referenced before assignment

我不明白为什么会这样,我能做些什么来修复这个错误。

注意:代码已简化以保持问题简短。如果我注释掉我引用的实例 loose,代码将完美运行。

你误解了 global statement:

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.

global loose 在全局范围内没有任何意义。您必须将 global loose 放入函数 update:

# global loose <--- DELETE

loose = False 

# [...]

def update(dt):
    global loose # <--- ADD

    # [...]

    if collision:
        loose = True
    
    # [...]

另见 Python Global Keyword