我正在尝试为我自己的自我发展项目创建 John Conway 的人生游戏。我遇到的一般问题是让动画在 GUI 上可视化,现在我收到的错误消息如下:
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Software\Python\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "gameoflife.py", line 70, in one_cycle
apply_rules()
File "gameoflife.py", line 56, in apply_rules
updated_grid[row][column] = 0
IndexError: list index out of range
但是如果我第二次运行它,我会在它最初说错误的下面的不同行上得到同样的错误。我知道实际的错误是告诉我我试图访问的索引不在列表中,但我不明白为什么它会出现在下面的行中,就好像上一行已被更正一样。我的代码如下:
from tkinter import *
from random import *
import time
import numpy as np
PIXEL_SIZE = 10
ROW = 910
COLUMN = 700
grid = []
updated_grid = [[]]
def create_grid():
for row in range(0, ROW):
grid2 = []
for column in range(0, COLUMN):
grid2.append(randint(0, 1))
grid.append(grid2)
def draw_grid():
for row in range(0, ROW):
for column in range(0, COLUMN):
if grid[row][column] == 1:
x0 = row*PIXEL_SIZE
y0 = column*PIXEL_SIZE
x1 = x0+PIXEL_SIZE
y1 = y0+PIXEL_SIZE
canvas.create_rectangle(x0, y0, x1, y1, fill='red')
def apply_rules():
for row in range(1, ROW - 1):
for column in range(1, COLUMN - 1):
neighbours_count = 0
# will count the neighbours for each cell
neighbours_count += grid[row-1][column-1] # top left
neighbours_count += grid[row][column-1] # top center
neighbours_count += grid[row+1][column-1] # top right
neighbours_count += grid[row-1][column] # middle left
neighbours_count += grid[row+1][column] # middle right
neighbours_count += grid[row-1][column+1] # bottom left
neighbours_count += grid[row][column+1] # bottom center
neighbours_count += grid[row+1][column+1] # bottom right
MMTTMM
POPMUISE
相关分类