我试图用python编写langton的ant代码,当我将其作为ASCII“模拟”进行测试时,代码确实可以工作,但在matplotlib中将其作为2d动画工作时遇到了问题。我从来没有真正弄乱过matplotlib,但我试图通过这样做来学习
import datetime,pprint,keyboard,time,os
from matplotlib import pyplot as plt
from matplotlib import animation
antLocation = (15,15) # (y,x)
antDirection = 270
grid = [[0 for i in range(30)].copy() for _ in range(30)]
def update(data):
global grid
global antLocation
global antDirection
if(grid[antLocation[0]][antLocation[1]] == 0):
antDirection +=90
grid[antLocation[0]][antLocation[1]] = 1
else:
antDirection -=90
grid[antLocation[0]][antLocation[1]] = 0
if (antDirection == 0 or antDirection == 360): #UP
antLocation = (antLocation[0]-1, antLocation[1])
antDirection = 0
elif (antDirection == 90): #RIGHT
antLocation = (antLocation[0], antLocation[1] + 1)
elif (antDirection == 180): # DOWN
antLocation = (antLocation[0]+1, antLocation[1])
else: #(antDirection == 270 or antDirection == -90): #LEFT
antLocation = (antLocation[0], antLocation[1] - 1)
antDirection = 270
mat.set_data(grid)
return [mat]
fig,ax = plt.subplots()
mat = ax.matshow(grid)
ani = animation.FuncAnimation(fig, update)
plt.show()
您需要一个函数来创建各个帧(对于每个时间点
t
)。然后将此函数传递给animation.FuncAnimation()
。由于您使用的是全局变量,update()
不需要返回任何内容相关问题 更多 >
编程相关推荐