维基百科上有个有意思的话题叫细胞自动机:https://en.wikipedia.org/wiki/Cellular_automaton
在20世纪70年代,一种名为生命游戏的二维细胞自动机变得广为人知,特别是在早期的计算机界。由约翰 · 康威发明,马丁 · 加德纳在《科学美国人》的一篇文章中推广,其规则如下:
- Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
- Any live cell with two or three live neighbours lives on to the next generation.
- Any live cell with more than three live neighbours dies, as if by overpopulation.
- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
总结就是:任何活细胞在有两到三个活邻居时能活到下一代,否则死亡。任何有三个活邻居的死细胞会变成活细胞,表示繁殖。
在Conway’s Game of Life中,展示了几种初始状态:
下面我们用python来模拟,首先尝试表示Beacon:
可以看到已经成功的打印出了Beacon的形状,下面我们继续编写细胞自动机的演化规则:
ArtistAnimation动画
基于此我们可以制作matplotlib的动画,下面直接将Blinker、Toad、Beacon都放上去:
然后我们画一下Pulsar:
FuncAnimation动画
另一种创建matplotlib动画的方法是使用FuncAnimation,完整代码:
这种动画生成速度较慢,好处是可以导出html文件:
还可以保存MP4视频:
或gif动画:
注意:保存MP4视频或GIF动画,需要事先将ffmpeg配置到环境变量中
ffmpeg下载地址:https://pan.baidu.com/s/1Cfu198zvz57BCy5yR4e0qA?pwd=a729
随机生命游戏
接下来,我们创建一个50*50的二维生命棋盘,并选取其中1500个位置作为初始活细胞点,我们看看最终生成的动画如何。
完整代码如下: