生命游戏的Python代码
时间: 2023-11-19 11:58:51 浏览: 66
生命游戏源码Python代码实现
下面是Python实现的生命游戏代码:
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 设置初始状态
N = 100
ON = 255
OFF = 0
vals = [ON, OFF]
grid = np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N)
# 定义更新函数
def update(frameNum, img, grid, N):
newGrid = grid.copy()
for i in range(N):
for j in range(N):
# 计算周围细胞的状态
total = int((grid[i, (j-1)%N] + grid[i, (j+1)%N] +
grid[(i-1)%N, j] + grid[(i+1)%N, j] +
grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] +
grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N])/255)
# 更新细胞状态
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newGrid[i, j] = OFF
else:
if total == 3:
newGrid[i, j] = ON
# 更新图像
img.set_data(newGrid)
grid[:] = newGrid[:]
return img,
# 创建动画
fig, ax = plt.subplots()
img = ax.imshow(grid, interpolation='nearest')
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N), frames=10, interval=50, save_count=50)
plt.show()
```
运行代码后,会生成一个动画窗口,展示生命游戏的演化过程。在代码中,我们使用numpy库生成了一个随机的初始状态,然后通过matplotlib.animation库实现了动画效果。在更新函数中,我们根据生命游戏的规则计算细胞的状态,并更新图像。
阅读全文