使用 FuncAnimation 的康威生命游戏的简单动画

Simple animation for Conway's Game of Life with FuncAnimation

我在 Python 中制作了一个简单的康威生命游戏程序,我需要帮助使用 matplotlib 制作动画,因为老实说我很迷茫,我似乎无法理解它是怎么回事完成。

我的代码如下所示:

import matplotlib.pyplot as plt
import numpy as np


def initialize(size):
    grid = np.random.choice([0, 1], size*size, p=[0.8, 0.2]).reshape(size, size)
    plt.imshow(grid)
    plt.show(block=False)
    plt.pause(0.2)
    return grid


def conway_step(grid, size):
    new_grid = np.zeros_like(grid)
    for x in range(size):
        for y in range(size):
            total = sum([grid[(x+i) % size, (y+j) % size] for i in range(-1, 2) for j in range(-1, 2)])
            if grid[x, y] == 1 and total-1 in (2, 3):
                new_grid[x, y] = 1
            elif grid[x, y] == 0 and total == 3:
                new_grid[x, y] = 1
            else:
                new_grid[x, y] = 0
    grid = np.copy(new_grid)
    return grid


def conway(random=True, size=100):
    grid = initialize(size)
    for i in range(30):
        grid = conway_step(grid, size)
        plt.imshow(grid)
        plt.show(block=False)
        plt.pause(0.2)
    return


if __name__ == "__main__":
    conway(size=100)

这很好用,但我想将其实现为动画,并可能输出 mp4 文件。我试过这样的事情:

def conway(size):
    grid = initialize(size)
    fig, ax = plt.subplots()
    img = ax.imshow(grid)
    ani = animation.FuncAnimation(fig, conway_step, fargs=(grid, size))
    plt.show()

但是没用。有帮助吗?

FuncAnimation中的step函数通常会更新一个图形对象,这也应该return(return语句应该以逗号结尾,因为它需要是列表或元组)。

网格和图形对象(示例代码中的img_plot)需要是全局变量。如果要保存动画,FuncAnimation 需要一个 frames= 参数来避免无限期地 运行。

import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.colors import ListedColormap
import numpy as np

grid, grid_size, img_plot = None, None, None

def initialize(size):
    grid = np.random.choice([0, 1], size * size, p=[0.8, 0.2]).reshape(size, size)
    return grid

def conway_step(frame):
    global grid, grid_size, img_plot
    if frame < 3:   # no movement for the first few steps
        new_grid = grid
    else:
        new_grid = np.zeros_like(grid)
        for x in range(grid_size):
            for y in range(grid_size):
                total = sum(
                    [grid[(x + i) % grid_size, (y + j) % grid_size] for i in range(-1, 2) for j in range(-1, 2)])
                if grid[x, y] == 1 and total - 1 in (2, 3):
                    new_grid[x, y] = 1
                elif grid[x, y] == 0 and total == 3:
                    new_grid[x, y] = 1
                else:
                    new_grid[x, y] = 0
        grid = new_grid
    img_plot.set_data(new_grid)
    return img_plot,

def conway(random=True, size=100):
    global grid, grid_size, img_plot
    grid_size = size
    grid = initialize(size)
    fig, ax = plt.subplots(figsize=(10, 10))
    img_plot = ax.imshow(grid, interpolation='nearest', cmap=ListedColormap(['darkturquoise', 'yellow']))
    ax.set_xticks([])
    ax.set_yticks([])
    ani = animation.FuncAnimation(fig, frames=100, func=conway_step, interval=100)
    plt.tight_layout()
    ani.save('testconway.gif')
    plt.show()
    return ani

conway(size=100)