[英]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()
返回[]
我已經嘗試重命名 class 和變量,但無濟於事。 任何想法/提示/解決方案? 我已經在這個程序上搞了半個小時了,我找不到問題所在。
對於第一個程序,預期的結果是它會打開一個 window,您可以在其中單擊以添加點以制作形狀。 我使用的是 class 而不僅僅是“線”,這樣我就可以添加更多仍然使用“線”的變量。 字首。
這里的問題是lines
不在全局 scope 中,因為它是 class line
的 class 成員。 您必須像在代碼的 rest 中那樣使用line.lines
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.