以网格形式绘制精灵

Drawing sprites in a grid formation

我正在尝试以网格形式绘制精灵。精灵在二维数组中,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)

我正在使用填充 class 在插槽网格中绘制 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


https://i.stack.imgur.com/McRrr.png

要创建网格,只需要 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)