给我一份python代码,实现一个简单的二维元胞自动机
时间: 2023-02-07 19:03:50 浏览: 373
好的,这是一份简单的二维元胞自动机的 Python 代码:
```python
import numpy as np
def evolve(cells):
# 获取元胞自动机的当前状态
curr_state = cells[1:-1,1:-1]
# 初始化下一个状态
next_state = np.zeros(curr_state.shape, dtype=int)
# 遍历所有元胞
for i in range(1, cells.shape[0] - 1):
for j in range(1, cells.shape[1] - 1):
# 计算周围元胞细胞数量
num_neighbors = (cells[i-1:i+2,j-1:j+2] - curr_state[i-1][j-1]).sum()
# 根据元胞自动机的规则更新下一个状态
if curr_state[i-1][j-1] == 1 and num_neighbors in [2,3]:
next_state[i-1][j-1] = 1
elif curr_state[i-1][j-1] == 0 and num_neighbors == 3:
next_state[i-1][j-1] = 1
# 更新元胞自动机的状态
cells[1:-1,1:-1] = next_state
return cells
def main():
# 初始化元胞自动机
cells = np.zeros((5,5), dtype=int)
cells[2,2] = 1
cells[2,3] = 1
cells[3,3] = 1
# 进行多次迭代
for i in range(10):
print(cells)
cells = evolve(cells)
if __name__ == '__main__':
main()
```
这段代码实现了一个简单的二维元胞自动机,可以输出多次迭代后的元胞自动机的状态。
希望这份代码能够帮到你。
阅读全文