在学习到数组和字典时有这样一个例子:小程序:Conway的生命游戏,书上解析的不是很清楚,今天我就详细解析一下。
学习工具:Python编程快速上手-让繁琐工作自动化(第2版)、Python3.12.1、Mu编辑工具
import random, time, copy
WIDTH = 3 #数组里面共几个小列,如[(),(),(),(),......] 后面用数组a表示
HEIGHT = 3 #小列里面有几个数据,如[(*,*,*,*),(*,*,*,*),......] 后面用数组b表示
nextCells = [] #定义数组a
for x in range(WIDTH): #从a的第0个小列开始填数据
column = [] #定义数组b
for y in range(HEIGHT): #这个循环是把数据填入b
if random.randint(0, 1) == 0:
column.append("#") #把数据添加到数组b,往后添加
else:
column.append("*")
nextCells.append(column) #把数组b添加进数组a,如[(#,*,#)]
while True:
print("\n")
currentCells = copy.deepcopy(nextCells) #复制数组a,因为数组a里面还有很多数组b,所以用copy.deepcopy
for y in range(HEIGHT): #这个循环是把每一个数组b,打印出来,一个数组b为一列(后附图1)
for x in range(WIDTH):
print(currentCells[x][y], end=" ") # Print the # or space.
print(1)
for x in range(WIDTH): #这个是判断点位循环
for y in range(HEIGHT):
leftCoord = (x - 1) % WIDTH #取模,具体取模是如何运算的看这个:https://blog.youkuaiyun.com/qq_41051690/article/details/100026508,
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == "#": #看图2
numNeighbors += 1 # Top-left neighbor is alive.
if currentCells[x][aboveCoord] == "#":
numNeighbors += 1 # Top neighbor is alive.
if currentCells[rightCoord][aboveCoord] == "#":
numNeighbors += 1 # Top-right neighbor is alive.
if currentCells[leftCoord][y] == "#":
numNeighbors += 1 # Left neighbor is alive.
if currentCells[rightCoord][y] == "#":
numNeighbors += 1 # Right neighbor is alive.
if currentCells[leftCoord][belowCoord] == "#":
numNeighbors += 1 # Bottom-left neighbor is alive.
if currentCells[x][belowCoord] == "#":
numNeighbors += 1 # Bottom neighbor is alive.
if currentCells[rightCoord][belowCoord] == "#":
numNeighbors += 1 # Bottom-right neighbor is alive.
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(60) # Add a 1-second pause to reduce flickering. #间隔多久循环一个
图1↑↑↑↑↑↑
图2↓↓↓↓↓