LoginSignup
1
1

More than 3 years have passed since last update.

Pythonで簡単なライフゲームアニメーション

Last updated at Posted at 2020-12-06

はじめに

jupyter notebook上で、できるだけシンプルにライフゲームを再現してみる。

下準備

%matplotlib notebookはjupyter notebookにアニメーションを描画するためのおまじない。(%matplotlib nbaggでもできそう)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib notebook

フィールド

最初にサイズheight×widthのランダムな01領域を作る。今回は50×50領域で作成。

height=50
width=50
fig=plt.figure() #figオブジェクト作成
ims=[]
field=np.random.randint(0,2,(height,width))

初期状態の例
ランダム.png

状態の更新

100回更新する。

for i in range(100):
    im=plt.imshow(field)
    ims.append([im]) #リストに突っ込んでいく
    field=update(field) #更新

update関数

見ているマスが生存している場合、
隣接するマスの2または3つが生きている→生存

見ているマスが生存していない場合、
隣接しているマスの3つが生きている→生存
と遷移させていく。

def update(field):
    field2=np.zeros((height,width))
    dx=[1,1,1,0,0,-1,-1,-1]
    dy=[1,0,-1,1,-1,1,0,-1]
    for i in range(height):
        for j in range(width):
            count=0
            for k in range(8):
                count+=field[(i+dx[k])%height][(j+dy[k])%width]
            if(field[i][j]==1):
                if(count==2 or count==3):
                    field2[i][j]=1
            else:
                if(count==3):
                    field2[i][j]=1
    return field2

アニメーション描画

0.1秒ごとに切り替わる。

ani=animation.ArtistAnimation(fig,ims,interval=100)
plt.show()

コード全体

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib nbagg

def update(field):
    field2=np.zeros((height,width))
    dx=[1,1,1,0,0,-1,-1,-1]
    dy=[1,0,-1,1,-1,1,0,-1]
    for i in range(height):
        for j in range(width):
            count=0
            for k in range(8):
                count+=field[(i+dx[k])%height][(j+dy[k])%width]
            if(field[i][j]==1):
                if(count==3 or count==2):
                    field2[i][j]=1
            else:
                if(count==3):
                    field2[i][j]=1
    return field2

height=50
width=50
fig=plt.figure()
ims=[]
field=np.random.randint(0,2,(height,width))

for i in range(100):
    im=plt.imshow(field)
    ims.append([im])
    field=update(field)

ani=animation.ArtistAnimation(fig,ims,interval=100)
plt.show()

test.gif

良さげ。一瞬グライダーがいる。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1