简体   繁体   中英

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. 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. I'm using the class instead of just 'lines' so that I may add more variables that still use the 'line.' prefix.

The problem here is that lines is not in the global scope because it is a class member of the class line . You'd have to use line.lines like you do in the rest of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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