【发布时间】:2014-04-13 20:33:27
【问题描述】:
在 Project Euler 上做一些问题时,我遇到了Langdon's Ant,并认为尝试用 Python 编写动画是一个好主意。作为基础,我去使用了matplotlib函数动画,一个很好的例子可以看这篇帖子here
我已经设法让一个版本正常工作,代码如下所示。这个想法是用一个大矩阵模拟蚂蚁移动的黑白网格,并用“imshow”绘制该矩阵。
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# Initialize the Simulation
dim=50
a=np.matrix(np.zeros((dim,dim)))
pos=np.matrix([[dim//2],[dim//2]]) # current position of ant
direction=np.matrix([[1],[0]]) # direction ant is currently moving
#Rotation Matrices
clock=np.matrix([[0,1],[-1,0]])
counter=np.matrix([[0,-1],[1,0]])
def takestep(a,pos,direction):
pos[:]=pos+direction
if a[pos[0,0],pos[1,0]]==0: #landed on white
a[pos[0,0],pos[1,0]]=1
direction[:]=clock*direction
else:
a[pos[0,0],pos[1,0]]=0
direction[:]=counter*direction
#Plotting
fig = plt.figure()
im=plt.imshow(a,interpolation='none')
def init():
im=plt.imshow(a,interpolation='none')
return [im]
def animate(i):
takestep(a,pos,direction)
im=plt.imshow(a,interpolation='none')
#im.set_data(np.array(a))
return [im]
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=0, blit=True)
这段代码可以正常工作,但我不清楚:
动画连续运行(直到蚂蚁出界)并且 200 帧后不重置
即使间隔设置为 0,动画运行也很慢,大约每秒更新两次
我想我可以通过使用 im.set_data() 函数(在代码中注释掉)来加速它,但在我的实现中这不起作用(不变的可视化)
如果有人能给我一些关于如何改进这个动画的建议,那就太好了,在此先感谢!
最好的问候, 拉斐尔
【问题讨论】:
-
这个问题更适合codereview.stackexchange.com,在那里你可能会得到更详细的答案。
-
谢谢,不知道codereview部分,下次会用!
标签: python animation matplotlib