"""这是一个活的生命游戏"""
import random, time, copy
WIDTH = 10
HEIGHT = 5
"""为细胞创建一个二维列表"""
nextCells = []
for x in range(WIDTH):
"""创建一个新的column"""
column = []
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
"""活细胞动向"""
column.append('#')
else:
"""死细胞动向"""
column.append(' ')
nextCells.append(column)
while True:
"""用换行符分隔每个步骤"""
print('\n\n\n')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end=' ')
"""在末尾打上换行符"""
print()
"""细胞下一步主要来源于它周围的邻居"""
for x in range(WIDTH):
for y in range(HEIGHT):
leftCoord = (x-1) % WIDTH # 左面
rightCoord = (x+1) % WIDTH # 右面
aboveCoord = (y-1) % HEIGHT # 上面
belowCoord = (y+1) % HEIGHT # 下面
""""计算周围活邻居的数量"""
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#': # 左上
numNeighbors += 1
if currentCells[x][aboveCoord] == '#': # 上面
numNeighbors += 1
if currentCells[rightCoord][aboveCoord] == '#': # 右上
numNeighbors += 1
if currentCells[leftCoord][y] == '#': # 左面
numNeighbors += 1
if currentCells[rightCoord][y] == '#': # 右面
numNeighbors += 1
if currentCells[leftCoord][belowCoord] == '#': # 左下
numNeighbors += 1
if currentCells[x][belowCoord] == "#": # 下面
numNeighbors += 1
if currentCells[rightCoord][belowCoord] == '#': # 右下
numNeighbors += 1
"""判断是不是活着的细胞并且活着的邻居为2或者3"""
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
nextCells[x][y] = '#'
else:
nextCells[x][y] = ' '
time.sleep(0.5)
从运行结果图,我们可以看到方块在不断变化着。这个程序的核心思想:如果一个活的方块与两个或三个活的方块为邻居,那么下一步它也将是活的;如果一个死的方块正好有三个活的方块,那么下一步它将是活的。