Class 个变量 python 使用 Pyglet

Class variables in python using Pyglet

我正在为我正在设计的游戏编写一段代码,但我一直运行陷入同样的​​错误:

import pyglet
class line:
    lines = []
print(line.lines)
def DrawBackground():
    pass
def DrawMidground():
    pyglet.graphics.draw(int(len(lines)/2), pyglet.gl.GL_POLYGON, ('v2i', tuple(line.lines)))
def DrawForeground():
    pass
config = pyglet.gl.Config(sample_buffers=1, samples=4)
window = pyglet.window.Window(config = config, fullscreen = True)
@window.event
def on_mouse_press(x, y, button, modifiers):
    line.lines.append(x)
    line.lines.append(y)
@window.event
def on_draw():
    window.clear()
    DrawBackground()
    DrawMidground()
    DrawForeground()
pyglet.app.run()

引发异常:

      6     pass
      7 def DrawMidground():
----> 8     pyglet.graphics.draw(int(len(lines)/2), pyglet.gl.GL_POLYGON, ('v2i', tuple(line.lines)))
      9 def DrawForeground():
     10     pass

NameError: name 'lines' is not defined

我写了第二个程序作为测试,它似乎工作正常:

class line:
    lines = []
def prints():
    print(line.lines)
prints()

Returns []

我试过重命名 class 和变量,但无济于事。有 ideas/tips/solutions 吗?我已经把这个程序弄乱了半个小时了,我找不到问题。

对于第一个程序,预期的结果是它会打开一个 window,您可以在其中单击以添加点以形成形状。我正在使用 class 而不是 'lines' 这样我可以添加更多仍然使用 'line.' 前缀的变量。

这里的问题是 lines 不在全局范围内,因为它是 class line 的 class 成员。您必须像在其余代码中一样使用 line.lines