本系列旨在通过一系列由浅入深的python实战代码或项目,使普通人也能感受到编程的乐趣,编程能够在平时的工作生活上有所帮助。欢迎查看系列的开篇词和前面的文章。
生命游戏由英国数学家约翰·H·康威设计的,是一种类似于生物社会的兴衰和交替的游戏。
游戏使用无限大小的矩形网格,其中每个网格都是空的或被有机体占据。被占用的细胞是活的,而空的细胞是死的。
游戏在特定时期内进行,每一轮都会根据当前配置中生物体的排列创建一个新的世代。
下一代网格的状态,是通过将以下四个基本规则应用于当前配置的每个网格来确定的:
"""
Conway's Game of Life, by Al Sweigart al@inventwithpython.com
The classic cellular automata simulation. Press Ctrl-C to stop.
More info at: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: short, artistic, simulation
"""
import copy, random, sys, time
# 设置常量,
WIDTH = 20 # 游戏画面宽度.
HEIGHT = 10 # 游戏画面高度.
ALIVE = '1' # 代表活细胞的字符.
DEAD = '0' # 代表死细胞的字符.
# 表示细胞的下一个状态,存活或者死亡
nextCells = {}
# 将随机的死细胞和活细胞放入 nextCells:
for x in range(WIDTH): # 遍历所有可能的列.
for y in range(HEIGHT): # 遍历所有可能的行w.
if random.randint(0, 1) == 0:#根据在0,1中随机选择赋予细胞状态,50几率
nextCells[(x, y)] = ALIVE
else:
nextCells[(x, y)] = DEAD
while True: # 进入主程序的无线循环.
print("###############################一次循环###############################")
print('
' * 50) # 用换行符分隔每一步.
cells = copy.deepcopy(nextCells)
# 在屏幕上打印细胞:
for y in range(HEIGHT):
for x in range(WIDTH):
print(cells[(x, y)], end='')
print() # 在行尾打印一个换行符.
print('按 Ctrl-C 退出.')
# 根据游戏规则计算细胞的下一步状态
for x in range(WIDTH):
for y in range(HEIGHT):
# 获得细胞的相邻细胞的坐标
left = (x - 1) % WIDTH
right = (x + 1) % WIDTH
above = (y - 1) % HEIGHT
below = (y + 1) % HEIGHT
# 计算活着的邻居细胞的数量:
numNeighbors = 0
if cells[(left, above)] == ALIVE:
numNeighbors += 1 # 左上角的邻居细胞还活着.
if cells[(x, above)] == ALIVE:
numNeighbors += 1 # 顶部邻居细胞还活着.
if cells[(right, above)] == ALIVE:
numNeighbors += 1 # 右上角的邻居细胞还活着.
if cells[(left, y)] == ALIVE:
numNeighbors += 1 # 左邻居细胞还活着.
if cells[(right, y)] == ALIVE:
numNeighbors += 1 # 右邻居细胞还活着.
if cells[(left, below)] == ALIVE:
numNeighbors += 1 # 左下邻居细胞还活着.
if cells[(x, below)] == ALIVE:
numNeighbors += 1 # 底部邻居细胞还活着.
if cells[(right, below)] == ALIVE:
numNeighbors += 1 # 右下角的邻居细胞还活着.
# 根据康威的生命游戏规则设置单元格:
if cells[(x, y)] == ALIVE and (numNeighbors == 2
or numNeighbors == 3):
# 有 2 或 3 个邻居的活细胞保持活力:
nextCells[(x, y)] = ALIVE
elif cells[(x, y)] == DEAD and numNeighbors == 3:
# 有 3 个邻居的死细胞变得活跃:
nextCells[(x, y)] = ALIVE
else:
# 其他类型的细胞死亡:
nextCells[(x, y)] = DEAD
try:
time.sleep(1) # 添加一秒暂停.
except KeyboardInterrupt:
print("康威的生命游戏")
sys.exit() # 当按下 Ctrl-C 时,结束程序.
模拟结果,可以看到,细胞的生死状态根据规则进行变换
留言与评论(共有 0 条评论) “” |