You need to enable JavaScript to run this app. 如何使用matplotlib实现2D网格动画 解决Langton's ant可视化问题
优惠活动
大模型
产品
解决方案
定价
更多

如何使用matplotlib实现2D网格动画 解决Langton's ant可视化问题

兰顿蚂蚁matplotlib动画实现修复方案

修改后可正常运行的完整代码如下:

from matplotlib import pyplot as plt
from matplotlib import animation

antLocation = (15,15) # (y,x)
antDirection = 270
GRID_SIZE = 30
grid = [[0 for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]

def update(frame):
    global grid
    global antLocation
    global antDirection
    current_y, current_x = antLocation
    # 翻转当前格子颜色、调整蚂蚁朝向
    if grid[current_y][current_x] == 0:
        antDirection += 90
        grid[current_y][current_x] = 1
    else:
        antDirection -= 90
        grid[current_y][current_x] = 0
    # 朝向归一化,避免数值累加溢出
    antDirection = antDirection % 360
    # 计算移动后坐标
    if antDirection == 0: # 向上
        new_y, new_x = current_y - 1, current_x
    elif antDirection == 90: # 向右
        new_y, new_x = current_y, current_x + 1
    elif antDirection == 180: # 向下
        new_y, new_x = current_y + 1, current_x
    else: # 270 向左
        new_y, new_x = current_y, current_x - 1
    # 边界循环处理,避免索引越界报错,也可按需改为停止模拟逻辑
    new_y = new_y % GRID_SIZE
    new_x = new_x % GRID_SIZE
    antLocation = (new_y, new_x)
    # 更新画布内容
    mat.set_data(grid)
    return [mat]
    
fig,ax = plt.subplots(figsize=(6,6))
# 隐藏坐标轴提升观感
ax.set_axis_off()
# 使用灰阶配色符合常规兰顿蚂蚁演示效果
mat = ax.matshow(grid, cmap='gray_r')
# 配置动画参数
ani = animation.FuncAnimation(
    fig,
    update,
    interval=50, # 帧间隔,单位毫秒,数值越小动画速度越快
    blit=True, # 开启局部重绘提升运行流畅度
    cache_frame_data=False # 避免内存占用随运行时间持续升高
)
plt.show()

主要修改点说明:

  • 移除了冗余导入包:原代码导入的datetime、pprint、keyboard等依赖在动画实现中未使用,移除后减少不必要的环境依赖
  • 新增边界处理逻辑:原代码未处理蚂蚁走出网格的场景,运行一段时间后会触发索引越界报错,新增取余逻辑实现边界循环效果
  • 优化朝向处理逻辑:增加朝向模360的归一化操作,避免长时间运行后朝向数值累加溢出
  • 优化可视化效果:调整配色为常见的黑白色系、关闭坐标轴刻度,提升展示效果
  • 补全动画配置参数:明确指定动画播放速度、重绘逻辑等参数,提升兼容性和运行稳定性

内容的提问来源于stack exchange,提问作者Anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 17:48:03