使用FuncAnimation在python中对列表进行动画处理

时间:2020-09-27 13:30:11

标签: python animation

我正在编写一个程序,该程序以设置长度的1和0的随机列表开头(例如[0, 1, 0, 1, 0, 1, 0, 1, 1, 1])。该列表代表道路上的汽车,其中代表汽车,零代表空路。列表self.cars使用以下算法进行更新。

cars_update = [0]*len(self.cars)
for i, car in enumerate(self.cars):
    # Update method for all but the last index.
    if i < len(self.cars)-1:
        # If there is a car in the current index and no car in the
        # next index, move the car.
        if car == 1 and self.cars[i+1] == 0:
            cars_update[i] = 0
            cars_update[i+1] = 1
        # If there is a car at the current index and a car in the
        # next index, do not move the car.
        elif car == 1 and self.cars[i+1] == 1:
            cars_update[i] = 1
    # Update method for last index.
    else:
        # If the last index has a car and the first index does not,
        # move the car to the first index.
        if car == 1 and self.cars[0] == 0:
            cars_update[i] = 0
            cars_update[0] = 1
        # If the last index has a car and the first does too, keep
        # the car in the last index.
        elif car == 1 and self.cars[0] == 1:
            cars_update[i] = 1
# Update self.cars with movements.
self.cars = cars_update

我想使用FuncAnimation为该算法设置动画。从我的阅读中,我需要创建补丁以绘制在人物上。我已经用这段代码做到了:

for i, car in enumerate(self.cars):
    if car == 1:
        self.patches.append(plt.Rectangle((i, 0), 1, 1, angle=0.0,
                                          facecolor='r', edgecolor='b',
                                          animated=True))
    else:
        self.patches.append(plt.Rectangle((i, 0), 1, 1, angle=0.0,
                                          color='k', animated=True))
return self.patches

如何使用以上算法为补丁制作动画?

0 个答案:

没有答案