Conway Game of Life Help
显示 更早的评论
We would like our code to display the changes of every iteration on the image but when it is run now, we just get a black grid. Also, we would like to do a count on the number of "live" cells (1s), and have the program end when the number stabilizes.
Any ideas? Thank you!
% function [n] = Life_m(n)
n=45;
board= zeros(100,100); % pre-allocate board size
v = [1*ones(n,1) ; 0*ones(100-n,1)];
colormap(gray(2));
for ii = 1:100
board(:,ii) = v(randperm(100));
end
for m = 1:100
%calculate neighbors for left edge w/o corners
for ii = 1
for jj = 2:99
neighbors = board(ii+1,jj)+board(ii,jj+1)+board(ii,jj-1)...
+board(ii+1,jj+1)+board(ii+1,jj-1);
end
end
% calculate neighbors for right edge w/o corners
for ii = 100
for jj = 2:99
neighbors = board(ii-1,jj)+board(ii,jj+1)+board(ii,jj-1)...
+board(ii-1,jj+1)+board(ii-1,jj-1);
end
end
% calculate neighbors for top edge w/o corners
for ii = 2:99
for jj = 1
neighbors = board(ii-1,jj)+board(ii,jj+1)+board(ii+1,jj)...
+board(ii-1,jj+1)+board(ii+1,jj+1);
end
end
% calculate neighbors for bottom edge w/o corners
for ii = 2:99
for jj = 100
neighbors = board(ii-1,jj)+board(ii,jj-1)+board(ii+1,jj)...
+board(ii-1,jj-1)+board(ii+1,jj-1);
end
end
%Top Left
for ii = 1
for jj = 1
neighbors = board(ii,jj+1)+board(ii+1,jj+1)+board(ii+1,jj);
end
end
%Top Right
for ii = 1
for jj = 100
neighbors = board(1,99)+board(2,99)+board(2,100);
end
end
%Bottom Left
for ii = 100
for jj = 1
neighbors = board(100,2)+board(99,2)+board(99,1);
end
end
%Bottom Right
for ii = 100
for jj = 100
neighbors = board(100,99)+board(99,99)+board(99,100);
end
end
%count neighbors for internal
for ii = 2:99
for jj = 2:99
neighbors = board(ii+1,jj)+board(ii-1,jj)+board(ii,jj+1)+board(ii,jj-1)...
+board(ii+1,jj+1)+board(ii-1,jj-1)+board(ii+1,jj-1)+board(ii-1,jj+1);
end
end
for ii = 1:100
for jj = 1:100
%determine cell death, birth, or survival
if neighbors <=1
board(ii,jj)=0;
elseif neighbors >3
board(ii,jj) = 0;
else
board(ii,jj) = 1;
end
image(board);
pause;
end
end
end
回答(1 个)
A Jenkins
2013-8-30
0 个投票
1) neighbors(ii,jj) not neighbors
2) I prefer spy(board) to image(board)
3) You can count nonzero elements with nnz(board)
Also, if you think this problem is cool, check out Cleve's version on the file exchange http://www.mathworks.com/matlabcentral/fileexchange/37959-game-of-life
类别
在 帮助中心 和 File Exchange 中查找有关 Conway's Game of Life 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!