在循环中使用并添加到 pygame 批次

using and adding to a pygame batch within a loop

我正在使用 Pyglet 开发一个简单的烛台图表绘图程序。当我尝试在一个循环中批处理形状时,pyglet 只绘制第一个形状(我认为)。我已经包含了一些最少的代码来解释我的问题。此代码应在 window 上显示 10 个又细又长的矩形,但我只得到一个矩形。

import pyglet
from pyglet import shapes

window = pyglet.window.Window(960, 540)
batch = pyglet.graphics.Batch()

for i in range(10):
    rectangle = shapes.Rectangle(10*i, 100, 5, 100, color=(0,255,0), batch=batch)

@window.event
def on_draw():
    window.clear()
    batch.draw()

pyglet.app.run()
print(batch)

像这样的东西很好用:

rectangle1 = shapes.Rectangle(10, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle2 = shapes.Rectangle(20, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle3 = shapes.Rectangle(30, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle4 = shapes.Rectangle(40, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle5 = shapes.Rectangle(50, 100, 5, 100, color=(0,255,0), batch=batch)

但这不是:

rectangle = shapes.Rectangle(10, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(20, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(30, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(40, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(50, 100, 5, 100, color=(0,255,0), batch=batch)

这对我来说意味着批处理对象只是指批处理中的形状对象,这将使我无法使用 pyglet 批处理绘制图形数据的计划,我的这个假设是否正确?

感谢您的帮助

我建议将形状添加到列表中:

rectangles = [] 
for i in range(10): 
    rectangles.append(shapes.Rectangle(10*i, 100, 5, 100, color=(0,255,0), batch=batch))

分别

rectangles = [shapes.Rectangle(10*i, 100, 5, 100, color=(0,255,0), batch=batch) for i in range(10)]