Conway的生命游戏

发布时间:2024年01月19日

主要内容

一.Conway的“生命游戏”

1.玩法

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生命小游戏。

文章来源:https://blog.csdn.net/weixin_59994613/article/details/135678703
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。