Skip to main content
 首页 » 编程设计

python之使用 Matplotlib 在 Python 中为兰登的 Ant 制作动画

2025年05月04日798°冷暖

在 Project Euler 上做一些问题,我遇到了 Langdon's Ant并认为尝试用 Python 编写动画代码是个好主意。作为基础,我使用了 matplotlib 函数动画,在这篇文章中可以看到一个非常好的例子 here

我已经设法让一个版本工作,代码如下所示。这个想法是用一个大矩阵模拟 Ant 移动的黑白网格,并用“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) 

这段代码是有效的,但我不清楚某些地方:

  • 动画连续运行(直到 Ant 出界)并且 200帧后不重置

  • 即使间隔设置为0,动画运行也相当缓慢,大约一秒更新两次

  • 我想我可以通过使用 im.set_data() 函数(在代码中注释掉)来加速它,但在我的实现中这不起作用(不变的可视化)

如果有人能给我一些关于如何改进此动画的指示,那就太好了,在此先感谢!

最好的问候, 拉斐尔

请您参考如下方法:

下面是如何使用 im.set_data 提高每秒帧数。

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 
 
fig = plt.figure() 
im = plt.imshow(a, interpolation='none', vmin=0, vmax=1) 
 
def animate(i): 
    takestep(a, pos, direction) 
    im.set_data(a) 
    return [im] 
 
 
anim = animation.FuncAnimation(fig, animate, 
                               frames=200, interval=0, blit=True, 
                               repeat=False) 
plt.show() 

  • 使用 repeat=False 在 200 帧后停止动画。
  • 在对 imshow 的初始调用中设置 vmin=0, vmax=1。对 plt.imshow 的初始调用设置了 vmin 和 vmax,它们控制值和颜色之间的对应关系。该设置用于 imshow AxesImage 的所有后续渲染。由于初始 plt.imshow 使用全零数据,vmin 和 vmax 都设置为 0(初始数据的最小值和最大值).这使得所有 值都显示为相同的颜色。因此,要阻止这种情况发生,请自行提供 vmin 和 vmax。