Conway的生命游戏

Conway的生命游戏练习 Conway 生命小游戏

主要内容

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

今天的文章 Conway的生命游戏分享到此就结束了,感谢您的阅读。
编程小号
上一篇 2024-12-15 11:01
下一篇 2024-12-15 10:57

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/87182.html