它如何在第一次工作,但第二次失败?

时间:2017-07-27 17:31:36

标签: python loops matrix pygame

在我的代码中,我做了两次同样的事情,但它只是第一次工作。

for y, row in enumerate(matrix):
    for x, color in enumerate(row):
        if matrix[y][x] == 1:
            som = (matrix[y-1][x-1] + matrix[y-1][x] + matrix[y-1][x+1] + matrix[y][x-1] + matrix[y][x+1] + matrix[y+1][x-1] + matrix[y+1][x] + matrix[y+1][x+1])

            if som == (2 or 3):
                matrix[y][x] = 1
            else:
                matrix[y][x] = 0
                pygame.display.update()
                time.sleep(1)        
        else:
            #here somewhere it goes wrong
            som = (matrix[y-1][x-1] + matrix[y-1][x] + matrix[y-1][x+1] + matrix[y][x-1] + matrix[y][x+1] + matrix[y+1][x-1] + matrix[y+1][x] + matrix[y+1][x+1])

            if som == 3:
                matrix[y][x] = 1
            else:
                matrix[y][x] = 0

当我在没有第二个的情况下尝试这个代码时,它工作得很完美。现在它给出了一个错误:IndexError: list index out of range

此外,我希望循环仅在1秒后重复。当我打印som时,我可以看到它只在一秒钟之后重复,但在游戏的显示屏上,没有任何变化,直到突然十一个变为0。 如何更改此设置,以便每隔一秒后显示更新?

2 个答案:

答案 0 :(得分:1)

如果使用enumerate循环序列,则根据定义,有效索引为[0][x]。因此,当您索引[x+1]时,您将索引越界。

同样,当x == 0您的索引[x-1][-1]时,它将为您的序列的返回编制索引,我怀疑您是什么'期待。

答案 1 :(得分:0)

您的问题是,如果您位于矩阵的第一行,则您尝试访问其上方的行(y-1),该行不存在。当您在最后一行并访问y+1时,同样适用于x轴。

当您访问索引y-1y0时,它不会抛出异常,但它实际上会从列表末尾为您提供值。当列表中不存在索引时抛出异常。

我对您的代码进行了很多更改以减少重复。理解正在发生的事情应该要容易得多,而且我还在评论中实施了检查以停止IndexError和@ForceBru提到的条件。

我已经假设如果索引不存在,则将值默认为0.

for y,row in enumerate(matrix):
    for x,color in enumerate(row):
        center = matrix[y][x]
        top = matrix[y-1][x] if y > 0 else 0
        top_right = matrix[y-1][x+1] if y > 0 and x < len(row)-1 else 0
        right = matrix[y][x+1] if x < len(row)-1 else 0
        bottom_right = matrix[y+1][x+1] if y < len(matrix)-1 and x < len(row)-1 else 0
        bottom = matrix[y+1][x] if y < len(matrix)-1 else 0
        bottom_left = matrix[y+1][x-1] if y < len(matrix)-1 and x > 0 else 0
        left = matrix[y][x-1] if x > 0 else 0
        top_left = matrix[y-1][x-1] if y > 0 and x > 0 else 0
        surround_sum = (top_left + top + top_right + left + right + bottom_left + bottom + bottom_right)
        if center == 1:
            if surround_sum == 2 or surround_sum == 3:
                matrix[y][x] = 1
            else:
                center = 0
                pygame.display.update()
                time.sleep(1)

        else:
            #here somewhere it goes wrong
            if surround_sum == 3:
                matrix[y][x] = 1
            else:
                matrix[y][x] = 0
相关问题