Q2: Conway's Game of Life
作業資訊
題目敘述
康威生命遊戲是用一個矩陣代表世界,而矩陣的每個元素代表一個活著或死亡的細胞。每個細胞在下一時刻的生死,取決於相鄰細胞的狀態:例如若相鄰的活細胞過多,則這個細胞或在下一刻因缺乏資源而死去活來;而若相鄰的細胞過少,則這個細胞又會因為太過孤獨而死去。在本題中,設定的規則如下:輸入說明
一個 numpy array,元素只有 0 或 1 兩種,0 代表死細胞,1 代表活細胞。矩陣固定為二維,row 和 column 的數目皆為正整數。輸出說明
同輸入說明。Sample Input
[[0 1 1 0]Sample Output
[[1 1 1 0]提示與注意事項
import numpy as np def get_next(mat): pass if __name__ == '__main__': pass
import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np fig = plt.figure() mat = np.zeros((100, 100)) mat[10:12, 3] = 1 mat[9, 4] = 1 mat[12, 4:9] = 1 mat[10, 7:9] = 1 mat[11, 9] = 1 mat[8, 12] = 1 mat[8, 13] = 1 mat[9, 12] = 1 mat[14, 12] = 1 mat[13, 12] = 1 mat[14, 13] = 1 mat[9, 15] = 1 mat[13, 15] = 1 mat[10:13, 16] = 1 mat[12, 24] = 1 mat[13, 25] = 1 mat[14, 23:26] = 1 mat[9, 27] = 1 mat[8:11, 28] = 1 mat[7:12, 29] = 1 mat[6:8, 30] = 1 mat[11:13, 30] = 1 mat[7:12, 31] = 1 mat[7, 32] = 1 mat[8, 33] = 1 mat[9, 34] = 1 mat[10, 33] = 1 mat[11, 32] = 1 mat[8:10, 37:39] = 1 im = plt.imshow(mat, animated=True) plt.colorbar() def get_next(mat): pass def updatefig(*args): global mat mat = get_next(mat) im.set_array(mat) return im, ani = animation.FuncAnimation(fig, updatefig, interval=10, blit=True) plt.show()