我正在尝试动画Conway's game of life,但我陷入困境。我的代码如下。期望的行为是它采用二进制数组,根据Conway的规则多次更新它,并显示动画中的每一步。
请注意,我已经尝试实现它,以便宇宙被“包裹”,从上到下,从左到右:
import numpy as np
from matplotlib import animation
from matplotlib import pyplot as plt
def init_world():
test_world = [[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 0]]
return test_world
def get_neighbours(arr, r, c): # row and column
# gets list of the 8 neighbours' values
up = (r - 1) % len(arr)
down = (r + 1) % len(arr)
left = (c - 1) % len(arr[0])
right = (c + 1) % len(arr[0])
neighbours = [arr[up][left],
arr[up][c],
arr[up][right],
arr[r][left],
arr[r][right],
arr[down][left],
arr[down][c],
arr[down][right]]
return neighbours
fig = plt.figure()
ax = plt.axes()
grid, = ax.plot([])
def tick(arr):
# tick should update the grid by 1 step
updated_world = arr
for row in range(len(arr)): # move down rows
for col in range(len(arr[0])): # move across columns
neighbours = get_neighbours(arr, row, col)
# if live and (<2 nbrs | >3 nbrs), die
# dead and 3 nbrs, live
if arr[row][col] == 1 and (sum(neighbours) < 2 or sum(neighbours) > 3):
updated_world[row][col] = 0
elif arr[row][col] == 0 and sum(neighbours) == 3:
updated_world[row][col] = 1
else:
pass
return updated_world
def animate(arr):
# update the world, and make this into a new graph
arr = tick(arr)
grid.set_data(arr)
return grid
world = init_world()
fig = plt.figure()
plt.axis('off')
game = animation.FuncAnimation(fig, animate)
plt.show()
完整的错误消息如下所示。不知怎的,tick
没有提供数组,我不知道如何解决这个问题。非常感谢任何帮助。
Traceback (most recent call last):
File "C:\Miniconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 389, in process
proxy(*args, **kwargs)
File "C:\Miniconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 227, in __call__
return mtd(*args, **kwargs)
File "C:\Miniconda3\lib\site-packages\matplotlib\animation.py", line 1081, in _start
self._init_draw()
File "C:\Miniconda3\lib\site-packages\matplotlib\animation.py", line 1792, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Miniconda3\lib\site-packages\matplotlib\animation.py", line 1814, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
File "C:/Users/ocean/PycharmProjects/untitled1/animate.py", line 54, in animate
arr = tick(arr)
File "C:/Users/ocean/PycharmProjects/untitled1/animate.py", line 40, in tick
for row in range(len(arr)): # move down rows
TypeError: object of type 'int' has no len()
答案 0 :(得分:0)
matplotlib.animation.FuncAnimation
来自animate
,看起来您的函数frames
确实会一次调用一个整数,首先是0,然后是1,依此类推。如果您愿意,可以将if (HostingEnvironment.IsDevelopment())
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
else
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("azure")));
}
参数设置为传递某种数组。