效果展示
规则介绍
基于二维元胞自动机的生命游戏可视化实现
规则:蓝色方块代表生命
- 有颜色的方块代表生命,无颜色的方块代表死亡
- 一个细胞周围有八个细胞,对于一个活细胞来说,如果它周围的八个细胞中:
如果只有一个或没有一个是活的,那这个细胞就会死亡
如果其中两个或者三个细胞是活的,那这个细胞就能维持生命
如果超过3个细胞是活着的,那这个细胞就会因为过于拥挤而死亡 - 对于一个死细胞来说,如果这个细胞周围如果有三个细胞存活,该将获得新生。
附:所有规则都可以修改,种群初始密度也可以修改。本实验采用初始化人口随机分布,也可以自定义初始化人口分布以及网格大小得到滑翔机,播种机等复杂美观图形。
源码
'''
demoName:life simulation game
principle: cellular automata (two dimensional)
the rule of the game :
1. colored cell represents life, uncolored cell represents death
2. a cell has eight cells around it, to a live cell:
2.1 if only one or none of them are live, the cell will die
2.2 if two or three of them are live, the cell will sustain life
2.4 if more than three of them are live, the cell will die
3. to a dead cell, if there are three alive around it ,the cell will gain life
'''
import pygame
import sys
import math
import random
import copy
pygame.init()
chess_number=60 # 设置棋盘大小
LIVEDENSITY=0.3 #生命密度
TICK=10 #帧数
BG=(20,20,20) #背景色
LINECOLOR=(52,53,46) #网格色
LIFECOLOR=(31,97,189) #活细胞的颜色
CELL_LENGTH=int(600/chess_number) #每个格子的像素大小
LINE_WIDTH=4 #线的宽度
START_POSX=50
START_POSY=50
#239,60,57 红色 79,167,47绿色 188,69,229 紫色
#224,90,9 橙色 252,61,63大红
#188,69,229 紫色 239,60,57 红
#39,202,149 天绿 31,97,189蓝色 22,178,243 天蓝
# 设置背景框大小
size = width, height = 2*START_POSX+chess_number*CELL_LENGTH,2*START_POSY+chess_number*CELL_LENGTH
# 设置帧率,返回clock 类
clock = pygame.time.Clock()
screen = pygame.display.set_mode(size