-1

我有这个程序试图将它周围的网格空间的数量相加为某个值,并且它不断给出错误“IndexError:list out of range”。我尝试将其设置为晚开始列和行,并提前结束一列和行以达到相同的效果。错误点特别指向 [x+1][y+1]。

for l in range(loops):
    for x in range(self.width):
        for y in range(self.height):
            neighbors = 0

            if tiles_copy[x-1][y-1] == 1:
                neighbors += 1
            if tiles_copy[x][y-1] == 1:
                neighbors += 1
            if tiles_copy[x+1][y-1] == 1:
                neighbors += 1
            if tiles_copy[x+1][y] == 1:
                neighbors += 1
            if tiles_copy[x+1][y+1] == 1:
                neighbors += 1
            if tiles_copy[x][y+1] == 1:
                neighbors += 1
            if tiles_copy[x-1][y+1] == 1:
                neighbors += 1
            if tiles_copy[x-1][y] == 1:
                neighbors += 1
4

2 回答 2

0

不是答案

您可以将循环的开始更改为

print(self.width, len(tiles_copy))
for x in range(1, self.width):
    print(self.height, len(tiles_copy[x-1]), len(tiles_copy[x]), len(tiles_copy[x+1]))
    for y in range(1, self.height):

len(tiles_copy) 应该等于 self.width 并且循环中的 3 个值应该等于 self.height。猜测一下,有些值会更少。

于 2020-04-13T05:53:27.823 回答
0

您必须防止不存在的索引,例如 -1 和 self.width、self.width + 1 等...

我认为制作一个检查每个 xy 组合周围 8 点的函数更容易

# =========================================
def count_neighbors(self, x , y):

    if self.width < 3 or self.height < 3:
        return 0

    neighbors = 0
    x_range = []
    y_range = []

    # get only the valid x and y indexes ------------
    if x > 0:
        if x < self.width - 1:
            x_range = range(x - 1, x + 1 + 1)   # x-1, x, x+1
        else:
            x_range = range(x - 1, x + 1)  # x-1, x
    else:
        # x == 0
        x_range = range(x, x + 1 + 1)   # x, x+1

    if y > 0:
        if y < self.width - 1:
            y_range = range(y - 1, y + 1 + 1)  # y-1, y, y+1
        else:
            y_range = range(y - 1, y + 1)    # y-1, y
    else:
        # y == 0
        y_range = range(y, y + 1 + 1)   #  y, y+1


    for x_index in x_range:
        for y_index in y_range:

            if x_range == x and y_index == y:
                # don't compare with itself
                continue

            if tiles_copy[x_index][y_index] == 1:
                neighbors += 1

    return neighbors


# ============================================
neighbors = 0
for l in range(loops):
    for x in range(self.width):
        for y in range(self.height):
            neighbors += count_neighbors(x, y)

这有点棘手您必须自己测试和调试。

于 2020-04-13T08:41:32.260 回答