简体   繁体   English

使用 Pyglet 的 python 中的 Class 变量

[英]Class variables in python using Pyglet

I'm writing a piece of code for a game I am designing, but I keep running into the same error:我正在为我正在设计的游戏编写一段代码,但我一直遇到同样的错误:

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()

Raises the exception:引发异常:

      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

I wrote a second program as a test, and it seems to work fine:我写了第二个程序作为测试,它似乎工作正常:

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

Returns []返回[]

I've tried both renaming the class and the variables, to no avail.我已经尝试重命名 class 和变量,但无济于事。 Any ideas/tips/solutions?任何想法/提示/解决方案? I've been messing with this program for half an hour now and I can't find the problem.我已经在这个程序上搞了半个小时了,我找不到问题所在。

For the first program, the expected result is it opens a window where you can click to add points to make a shape.对于第一个程序,预期的结果是它会打开一个 window,您可以在其中单击以添加点以制作形状。 I'm using the class instead of just 'lines' so that I may add more variables that still use the 'line.'我使用的是 class 而不仅仅是“线”,这样我就可以添加更多仍然使用“线”的变量。 prefix.字首。

The problem here is that lines is not in the global scope because it is a class member of the class line .这里的问题是lines不在全局 scope 中,因为它是 class line的 class 成员。 You'd have to use line.lines like you do in the rest of your code.您必须像在代码的 rest 中那样使用line.lines

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM