1 简介 生命游戏是在一定规则下,在划分的网格上根据元胞的局部空间状态来判断生死。 2 完整代码 %元胞自动机之生命游戏 %规则:假设元胞只有生和死两种状态 %1. 如果一个活细胞周围
1 简介
生命游戏是在一定规则下,在划分的网格上根据元胞的局部空间状态来判断生死。
2 完整代码
%元胞自动机之生命游戏%规则:假设元胞只有生和死两种状态
%1. 如果一个活细胞周围(包括对角相邻)有2或3个细胞为生,则该细胞保持为生;
%2. 如果一个死细胞周围有3个细胞为生,则该细胞转为生;
%3. 在其它情况下,死细胞保持死,活细胞转为死。
clc;
clear;
%定义元胞空间的大小为100,也即是100个元胞
x = 20;
y = 20;
%定义迭代次数
epoch = 100;
%初始化网格点
net = rand(x,y);
game = zeros(x,y);
for i = 1:x
for j = 1:y
if net(i,j)<= 0.3
% 按照(i-1,j)->(i,j)->(i,j-1)->(i-1,j-1)进行勾勒图形
fx = [i-1,i,i,i-1];
fy = [j,j,j-1,j-1];
fill(fx,fy,'g')
%表示元胞状态为生
game(i,j)=1;
hold on
end
end
end
pause(0.1)
for k = 1:epoch
temp = zeros(x,y);
fx=[0,x,x,0];
fy=[0,0,y,y];
fill(fx,fy,'w');
hold on;
for i = 1:x
for j = 1:y
if i~=1 && i~= x && j~=1 && j~=y
%在四个角邻居只有三个,在边界邻居只有五个
a = game(i-1,j-1)+game(i,j-1)+game(i+1,j-1)+game(i-1,j)+game(i+1,j)+game(i-1,j+1)+game(i,j+1)+game(i+1,j+1);
if game(i,j) == 1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a== 3
temp(i,j) = 1;
end
end
elseif i==1
if j==1
a = game(i,j+1)+game(i+1,j)+game(i+1,j+1);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
elseif j==y
a = game(i,j-1)+game(i+1,j-1)+game(i+1,j);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
else
a = game(i,j-1)+game(i+1,j-1)+game(i+1,j)+game(i,j+1)+game(i+1,j+1);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
end
elseif i == x
if j==1
a = game(i-1,j)+game(i-1,j+1)+game(i,j+1);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
elseif j==y
a = game(i-1,j-1)+game(i-1,j)+game(i,j-1);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
else
a = game(i-1,j-1)+game(i,j-1)+game(i-1,j)+game(i-1,j+1)+game(i,j+1);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
end
elseif j == 1
a = game(i-1,j)+game(i+1,j)+game(i-1,j+1)+game(i,j+1)+game(i+1,j+1);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
elseif j == y
a = game(i-1,j-1)+game(i,j-1)+game(i+1,j-1)+game(i-1,j)+game(i+1,j);
if game(i,j)==1
if a == 3 || a ==2
temp(i,j) = 1;
end
else
if a == 3
temp(i,j) = 1;
end
end
end
end
end
if game == temp
disp(strcat('在第',num2str(k),'轮元胞自动机达到稳态'))
for i=1:x
for j=1:y
if temp(i,j)==1
fx=[i-1,i-1,i,i];
fy=[j-1,j,j,j-1];
fill(fx,fy,'g');
hold on;
end
end
end
break;
end
game = temp;
for i=1:x
for j=1:y
if game(i,j)==1
fx=[i-1,i-1,i,i];
fy=[j-1,j,j,j-1];
fill(fx,fy,'g');
hold on;
end
end
end
pause(0.1)
end
3 仿真结果
4 参考文献
[1]黄嘉诚. 基于元胞自动机的生命游戏[J]. 信息与电脑, 2020, 32(23):3.