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

问题描述:

在我的代码中,我做了同样的事情两次,但它只有第一次。第一次如何工作,但第二次失败?

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时,我可以看到它只在一秒钟后重复,但在游戏的显示屏上,没有任何变化,直到突然十个1变成0。 我该如何改变这一点,以便在每秒钟后显示更新?

+3

'如果SOM ==(2或3):'_does not_做你认为它确实如此。在尝试编写这样复杂的代码之前,请研究Python的基础知识。另外,如果'x == 0'会发生什么?你最终会做'矩阵[y-1] [x-1]',它不会超出范围,但会做一些比较奇怪的事情。 – ForceBru

+2

另一件事要检查:你正在修改你的矩阵。看起来你正在编写一个康威的生命游戏模拟器 - 如果是这样,你需要将新状态与旧状态分开存储。 –

如果循环使用enumerate的序列,则根据定义,有效索引是[0][x]。因此,当您索引[x+1]时,您将索引超出范围。

同样,x == 0索引时[x-1][-1]这将索引你的顺序,我怀疑的是你期待什么。

你的问题是,如果你在矩阵的第一行,你试图访问它上面的行(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 
+0

我试过这段代码,现在它没有错误,但它也不起作用 – AV13

+0

什么不行? –

+0

rects仍然保持相同的颜色,不再改变 – AV13