我正在尝试以网格形式绘制精灵。子画面位于2D数组self.components
中。问题在于,所有子画面都将绘制在网格中最后一个子画面应位于的位置。
class Padding(Alignment):
def __init__(self, spacing, components, columns):
self.spacing = spacing
self.components = components
self.columns = columns
def update_constraints(self, win):
for row in range(0, self.columns):
for column in range(0, len(self.components)//2):
for i in self.components:
for j in i:
print(column * (win.s_width * self.spacing))
j.rect.x = column * (win.s_width * self.spacing)
j.rect.y = row * (win.s_height * self.spacing)
我正在使用padding类在插槽网格中绘制UI元素。我添加了一个约束,以将slots
中的所有内容绘制在网格中,列大小为2。
class Inventory(UILib.UIContainer):
def __init__(self):
super().__init__()
self.add_alignment(UILib.UIConstraints.relative_width)
self.add_alignment(UILib.UIConstraints.relative_height)
self.slot_count = 10
self.slots = []
self.add_constraint(UILib.Padding(0.05, self.slots, 2))
实施Padding
后,结果如下:
https://i.stack.imgur.com/mdmuY.png
每个pg.rect
和表面都应使用完全相同的坐标进行绘制。 (它们都包含在同一个子列表中,所以我不知道为什么会这样)。另外,由于有10个插槽和2行,因此它应该绘制得更像:
https://i.stack.imgur.com/2kn3W.png
答案 0 :(得分:1)
要创建网格,仅需要2个嵌套循环。使用enumerate
遍历嵌套列表self.components
:
class Padding(Alignment):
def __init__(self, spacing, components, columns):
self.spacing = spacing
self.components = components
self.columns = columns
def update_constraints(self, win):
for column, rows in enumerate(self.components):
for row, cell in enumerate(rows):
print(column * (win.s_width * self.spacing))
cell.rect.x = column * (win.s_width * self.spacing)
cell.rect.y = row * (win.s_height * self.spacing)