필터 지우기
필터 지우기

Conway's Game of Life implementation

조회 수: 14 (최근 30일)
Limbert Palomino
Limbert Palomino 2019년 5월 14일
댓글: Geoff Hayes 2019년 5월 19일
Hello,
I am having trouble implementing my code for Conway's Game of Life. I know that the cases for killing cells are accurate and run well but for some reason the "birthing" cases don't seem to work. I am pretty sure my code covers all the cases so I don't know why my system just dies down eventually from the lack of new cells coming to life. Here is my code:
function GameOfLife(A)
B = conv2(full(A > 0),[0,0,0;0,1,0;0,0,0],'same');
while true
imshow(B);
drawnow;
for i=2:size(B,1)-1
for j=2:size(B,2)-1
C = B(i-1:i+1,j-1:j+1); % 3x3 Matrix with i,j point @ center
if B(i,j) == 1 % Cell is currently alive
if (sum(sum(C)) < 3) || (sum(sum(C)) > 4)
B(i,j) = 0; % Dies
elseif B(i,j) == 0 % Cell is currently dead
if sum(sum(C)) == 3
B(i,j) = 1; % Is born
end
end
end
end
end
end
end
Any ideas?

채택된 답변

Geoff Hayes
Geoff Hayes 2019년 5월 15일
편집: Geoff Hayes 2019년 5월 15일
Limbert - I think that part of the problem might be with how your if and elseif statements are not being properly "ended". For example, MATLAB may be interpreting this code
if B(i,j) == 1 % Cell is currently alive
if (sum(sum(C)) < 3) || (sum(sum(C)) > 4)
B(i,j) = 0; % Dies
elseif B(i,j) == 0 % Cell is currently dead
if sum(sum(C)) == 3
B(i,j) = 1; % Is born
end
end
end
as
if B(i,j) == 1 % Cell is currently alive
if (sum(sum(C)) < 3) || (sum(sum(C)) > 4)
B(i,j) = 0; % Dies
elseif B(i,j) == 0 % Cell is currently dead
if sum(sum(C)) == 3
B(i,j) = 1; % Is born
end
end
end
Once you have finished with an if/elseif/else block, then you need to properly close it with an end. Your code might then become
if B(i,j) == 1 % Cell is currently alive
if (sum(sum(C)) < 3) || (sum(sum(C)) > 4)
B(i,j) = 0; % Dies
end % <-------------------------- this is important!!
elseif B(i,j) == 0 % Cell is currently dead
if sum(sum(C)) == 3
B(i,j) = 1; % Is born
end
end
Also, rather than executing the same calculation 2-3 times, just do it once
numberOfNeighbours = sum(sum(C));
and use this variable when comparing against three or four.
  댓글 수: 2
Limbert Palomino
Limbert Palomino 2019년 5월 16일
Thank you!
I got it working almost right after I posted this but I found that the bug I had was because the for loops wasn't iterating through all my statements, so I wrote a second one. Would ending loops like this, and creating a variable to avoid repeating the operation many times increase the efficiency of the function overall?
Geoff Hayes
Geoff Hayes 2019년 5월 19일
I would have to see more of your code but adding a variable "to avoid repeating the operation many times" may not be the best way to go.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile 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!

Translated by