"""Conway's Game of Life),又称康威生命棋,是英国数学家约翰·何顿·康威在1970年发明的细胞自动机。
本程序用pygame模拟这种现象,作者:李兴球,风火轮少儿编程 www.scratch8.net
以前早就听说过Game of Life,以为好高大上的样子,今天仔细看下,好简单的模拟啊,基本原理就是遍历一个二维表格,然后判断周围的点数达到什么要求就把自己设为什么状态即可。这里的二维表格就是图片上的像素,它们每个点都有X,Y坐标。设一种非黑的颜色,表示这个点是活的。黑色的像素点表示它是死的。每遍历一次后,显示一次。再加点代码就能把所有的帧输出到gif文件里做成gif动画了。
"""
import pygame
from random import randint
pygame.init()
life_color = (222,211,0,255) #有颜色的代表活的,黑色代表死的
width,height = 200,200
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("生命游戏模拟_风火轮少儿编程李兴球")
life_image = pygame.Surface((width,height))
for i in range(5000): #初始化5000个活的
x = randint(0,width)
y = randint(0,height)
life_image.set_at((x,y),life_color)
def get_numbers(x,y):
"""得到周围颜色点数量,也就是活的数量"""
counter = 0
for i in range(-1,2):
for j in range(-1,2):
if i==0 and j ==0 :continue #自己就跳过
x1 = x + i ; y1 = y + j
if x1 >= 0 and x1< width and y1>=0 and y1<height:
color = life_image.get_at((x1,y1))
if color == life_color:counter = counter + 1
return counter
while True:
for x in range(width):
for y in range(height):
cell = life_image.get_at((x,y))
cell_number = get_numbers(x,y) #得到周围活的细胞数量
if cell == life_color: #该细胞为活的
if cell_number == 3 or cell_number==2 :continue #周围有2个或3个,它还是活的
if cell_number < 2 or cell_number >3 :life_image.set_at((x,y),(0,0,0)) #小于2个,大于3个,它死了
else:
if cell_number == 3 : life_image.set_at((x,y),life_color) #周围有3个,复活
screen.blit(life_image,(0,0)) #把life_image渲染到screen上.
pygame.display.update() #更新屏幕显示
"""
1、规则
生命游戏中,对于任意细胞,规则如下。每个细胞有两种状态:存活或死亡,每个细胞与以自身为中心的周围八格细胞产生互动。
当前细胞为存活状态时,当周围低于2个(不包含2个)存活细胞时, 该细胞变成死亡状态。(模拟生命数量稀少)
当前细胞为存活状态时,当周围有2个或3个存活细胞时, 该细胞保持原样。
当前细胞为存活状态时,当周围有3个以上的存活细胞时,该细胞变成死亡状态。(模拟生命数量过多)
当前细胞为死亡状态时,当周围有3个存活细胞时,该细胞变成存活状态。 (模拟繁殖)
---------------------
pygame.image.save(life_image,"te.png")
"""