一、簡介
1 元胞自動機CA
元胞自動機(cellular automata,CA) 是一種時間、空間、狀態都離散,空間相互作用和時間因果關系為區域的網格動力學模型,具有模擬復雜系統時空演化程序的能力,其中,元胞自動機又稱為細胞自動機,而生命游戲(Game of Life)又是一種十分典型的CA,
以下是我做的筆記,CA一共有四個要點:
2 生命游戲
The Game of Life (生命游戲) ,是由英國數學家 John Horton Conway于1970年提出的,作為元胞自動機系統,生命游戲是一個零玩家游戲,用戶確定初始狀態與演變的規則后,無須其他操作,便可模擬得到形態的演變程序,
元胞自動機的基本思想可以追溯到上世紀Von Neumann在“Theory of Self-Reproducing Automata”提出的“機器繁殖”一概念:由一群細胞構成的小機器根據一些簡單規則和初始圖形進行演化的動力系統,機器可以不斷自我進化和延續,
3 生命游戲的MatLab實作
我認為網上大多數代碼都沒有考慮到邊界問題,所以我進行了一定的改進,
游戲規則在注釋有詳細解釋,一共有三條,
下面這個表格幫助大家理解:(想象一下左下角是原點坐標)
二、源代碼
%元胞自動機之生命游戲
%規則:假設元胞只有生和死兩種狀態
%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
三、運行結果
其中初始狀態我用均勻分布初始化矩形框,在20*20的區域內,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/292804.html
標籤:其他
上一篇:ESP8266( 多)玩法
