Game of Life

Conway's "Game of Life" er et eksempel på en Cellular Automaton.

n = 100; % grid size
X = randi(2,n,n)-1;
Y = X;
    colormap bone
for t=1:1000000 % number of steps
    image(18.18182*Y) % change colour

    for x=1:size(X,1)
        for y=1:size(X,2)
              if x == 1
                  if y == 1
                      s = sum(sum(X(x:x+1, y:y+1))) - X(x,y);
                  elseif y == size(X,2)
                      s = sum(sum(X(x:x+1, y-1:y))) - X(x,y);
                  else
                      s = sum(sum(X(x:x+1, y-1:y+1))) - X(x,y);
                  end 
              elseif x == size(X,1)
                  if y == 1
                      s = sum(sum(X(x-1:x, y:y+1))) - X(x,y);
                  elseif y == size(X,2)
                      s = sum(sum(X(x-1:x, y-1:y))) - X(x,y);
                  else
                      s = sum(sum(X(x-1:x, y-1:y+1))) - X(x,y);
                  end
              else
                  if y == 1
                      s = sum(sum(X(x-1:x+1, y:y+1))) - X(x,y);
                  elseif y == size(X,2)
                      s = sum(sum(X(x-1:x+1, y-1:y))) - X(x,y);
                  else
                      s = sum(sum(X(x-1:x+1, y-1:y+1))) - X(x,y);
                  end

              end
              if X(x,y) == 1 && s < 2 % Too few neighbours, underpopulation
                  Y(x,y) = 0;
              elseif X(x,y) == 1 && (s == 2 || s == 3) % balance
                  Y(x,y) = X(x,y); 
              elseif X(x,y) == 1 && s > 3 % over-population
                  Y(x,y) = 0;
              elseif X(x,y) == 0 && s == 3 % Spawn new cell
                  Y(x,y) = 1;
              end
        end
    end
    pause(0.01)
    X = Y;
end
% life.m - Conway's Game of Life
%
% A grid of dead and living cells is made.
% Cells are born to three adjacent parents,
% and die of overcrowding or loneliness.
%        Iain Haslam, December 2005
 
len=50; GRID=int8(rand(len,len));
up=[2:len 1]; down=[len 1:len-1]; %the world is round
colormap(gray(2));
for i=1:100
    neighbours=GRID(up,:)+GRID(down,:)+GRID(:,up)+GRID(:,down)+...
        GRID(up,up)+GRID(up,down)+GRID(down,up)+GRID(down,down);
    GRID = neighbours==3 | GRID & neighbours==2;
    image(GRID*2); pause(0.02);
end