% Game of Life

n = 32;
A = zeros(n);
B = zeros(n);

a = 5;
b = 3;
c = round(n/2);

% stato iniziale
type = input('type: ');
switch type
	case 1
		A(c-1:c, c-1:c) = 1;
	case 2
		A(c-1, c:c+1) = 1;
		A(c, [c-1 c+2]) = 1;
		A(c+1, c:c+1) = 1;
	case 3
		A(c, c-1:c+1) = 1;
	case 4
		A(c, c:c+2) = 1;
		A(c+1, c-1:c+1) = 1;
	case 5
		A([c-1 c-6 c+1 c+6], [c-4:c-2 c+2:c+4]) = 1;
		A([c-4:c-2 c+2:c+4], [c-1 c-6 c+1 c+6]) = 1;
	case 6
		A(a-1, b) = 1;
		A(a, b+1) = 1;
		A(a+1, b-1:b+1) = 1;
	case 7
		A(a-1, [b-1 b+2]) = 1;
		A(a, b+3) = 1;
		A(a+1, [b-1 b+3]) = 1;
		A(a+2, b:b+3) = 1;
	otherwise
		% random
		A = round(.6*rand(n));
		A(1, :) = 0;
		A(:, 1) = 0;
		A(end, :) = 0;
		A(:, end) = 0;
end

k = 0;
imagesc(A)
title(['Game of Life: generazione ' num2str(k)])
axis square
axis off
pause

while 1
	k = k+1;
	for i = 2:n-1
		for j = 2:n-1
			% versione base
			%s = A(i-1,j-1)+A(i-1,j)+A(i-1,j+1) ...
			%   +A(i,j-1)           +A(i,j+1) ...
			%   +A(i+1,j-1)+A(i+1,j)+A(i+1,j+1);
			% versione più efficiente
			C = A(i-1:i+1,j-1:j+1); 
			C(2,2) = 0; 
			s = sum(sum(C));
			if (s<2) || (s>3)
				B(i,j) = 0;
			elseif (s==3) && (A(i,j)==0)
				B(i,j) = 1;
			else
				B(i,j) = A(i,j);
			end
		end
	end
	A = B;
	imagesc(A)
	title(['Game of Life: generazione ' num2str(k)])
	axis square
	axis off
	pause(0.2) % pausa temporizzata
end

