clear 
clc

n = 128;
X = zeros(n);
% for i=1:n
%     for j=1:n
%         X(i,j) = floor(rand()+0.05);
%     end
% end

X(34,64) = 1;
X(54,53) = 1;
X(64,65) = 1;
X(:,14:39) = 1;
X(102,24) = 1;
X(72,13) = 1;
X(92,45) = 1;

iter = 400;
numiter = 1; 
h = image(X+1); colormap(colorcube(2))
xlabel x; ylabel y;
while numiter <= iter
    padX = (padarray((padarray(X,1))',1))';
    padX(1,2:end-1) = X(end,:);
    padX(2:end-1,1) = X(:,end);
    padX(end,2:end-1) = X(1,:);
    padX(2:end-1,end) = X(:,1);
    padX(1,1) = X(end,end);
    padX(1,end) = X(end,1);
    padX(end,end) = X(1,1);
    padX(end,1) = X(1,end);
    
    newX = zeros(n);
    for i=1:n
        for j=1:n
            neighbors = padX(i,j)+padX(i+1,j)+padX(i,j+1)+padX(i+2,j+2)+ ...
                padX(i+2,j)+padX(i,j+2)+padX(i+2,j+1)+padX(i+1,j+2);
            if (neighbors == 1 || neighbors == 1)&& ~X(i,j)
                newX(i,j) = 1;
            %elseif ((neighbors == 2 || neighbors == 3 || neighbors == 1 || neighbors == 4|| neighbors == 5)&& X(i,j))
            %     newX(i,j) = 1;
            elseif ((neighbors > 1)&& X(i,j))
                newX(i,j) = 0;
            end
        end
    end
    X = newX;
    %[a,b] = meshgrid(1:n,1:n);
    %axis([0,120,0,120,0,2]);
    %surf(abs(X-1));
    
    h = imagesc(~X+1); colormap(colorcube(2))
    axis off; axis image;
    view([0,90]);
    saveas(gcf, ['game_of_life_iter',sprintf('%03d',numiter),'.png'])
    numiter = numiter+1;
end





