Conway的“生命游戏”是细胞自动机的一个例子:一组规则控制由离散细胞组成的区域的行为。在实践中,它会创建一个漂亮的动画以供观看。你可以用方块作为细胞在方格纸上绘制每个步骤。实心方块是“活”的,空心方块是“死”的。 如果一个活的方块与两个或3个活的方块为邻,它在下一步将还是活的。如果一个死的方块正 好有3个活的邻居,那么下一步它就是活的。所有其他方块在下一步都会死亡或保持死亡。
#Conway's Game of Life
import random,time,copy
WIDTH=60
HEIGHT=20
#Create a list of list for the cells:
nextCells=[]
for x in range(WIDTH):
column=[] #Create a new column.
for y in range(HEIGHT):
if random.randint(0,1)==0:
column.append('#') #Add a living cell.
else:
column.append(' ') #Add a dead cell.
nextCells.append(column) #nextCells is a list of column lists.
while True: #Main program loop.
print('\n\n\n\n\n') #Separate eath step with newlines.
currentCells=copy.deepcopy(nextCells)
#print currentCells on the screen:
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='') #print the # or space.
print() #print a newline at the end of the row.
#Calculate the next step's cells based on current step's cell:
for x in range(WIDTH):
for y in range(HEIGHT):
#get neighboring coordinates:
#'% WIDTH' ensures leftCoord is always between 0 and WIDTH -1
leftCoord=(x-1)%WIDTH
rightCoord=(x+1)%WIDTH
aboveCoord=(y-1)%HEIGHT
belowCoord=(y+1)%HEIGHT
#Count number of living neighbors:
numNeighbors=0
if currentCells[leftCoord][aboveCoord]=='#':
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.
#set cell based on Conway's game of life rules:
if currentCells[x][y]=='#' and (numNeighbors==2 or numNeighbors==3):
#living cells with 2 or 3 neighbors stay alive:
nextCells[x][y]='#'
elif currentCells[x][y]=='' and numNeighbors==3:
#dead cells with 3 neighbors become alive:
nextCells[x][y]='#'
else:
#everything else dies or stays dead:
nextCells[x][y]=''
time.sleep(1) #add a 1-second pause to reduse flickering.
以上是今天要讲的内容,练习了Conway生命小游戏。