【发布时间】:2019-03-08 03:41:44
【问题描述】:
我编写了一个 Langton 的 ant 代码,我想让动画在 Colab 中运行,直到它被用户停止或在一定数量的帧之后。就像现在一样,它首先生成所有帧,然后将它们编译成动画,然后显示出来。如果有很多帧,则需要很长时间和/或 Colab 内存不足。这就是为什么我希望有一种方法可以一次生成一帧并不断更新图像。 FuncAnimation 似乎没有这种能力,但也许我只是没有看到它。 如果有人知道有用的方法或文档,请告诉我。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc, colors
from IPython.display import HTML
N = 40
ant = np.array([N//2, N//2])
move = {'N': [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]}
d = ['N', 'E', 'S', 'W']
facing = 1
board = np.zeros((N, N))
color = 0
board[ant[0]][ant[1]] = 4
cmap = colors.ListedColormap(['darkgreen', 'limegreen', 'greenyellow', 'yellow', 'red'])
def turn(direction):
if direction == 'R':
return (facing + 1) % 4
else:
return (facing - 1) % 4
def update(data):
global ant, board, facing, color
if color in [0, 1]:
facing = turn('R')
else:
facing = turn('L')
board[ant[0]][ant[1]] = (color + 1) % 4
ant += move[str(d[facing])]
color = board[ant[0]][ant[1]]
board[ant[0]][ant[1]] = 4
mat.set_data(board)
return [mat]
fig, ax = plt.subplots(figsize=(5, 5));
ax.grid(False)
plt.axis('off')
mat = ax.matshow(board, cmap=cmap)
ani = animation.FuncAnimation(fig, update, frames = 150, interval = 1, repeat=False, blit=True)
rc('animation', html='jshtml')
ani
【问题讨论】:
标签: python animation google-colaboratory