game of life help please

7 views (last 30 days)
androSLO
androSLO on 11 Apr 2013
Answered: arushi on 28 Aug 2024
Hello,
I have to do for school a game named "game of life". I have a network in which are some cells alive( matric, where are live cells marked with 1 and other with 0). Rules of survival are simple:
a)if has live cell less than 2 neighbours dies of loneliness
b)if has live cell more than 3 neighbours dies from overpopulation
c)if has dead cell exactly 3 neighbours it became alive
i really don't know how to do this..:( sorry Please help me i would be very gratefull everybody.

Answers (1)

arushi
arushi on 28 Aug 2024
Hi Androslo,
Here is an example implementation for your reference -
function gameOfLife(initialState, numIterations)
% initialState: Matrix representing the initial state of the grid
% numIterations: Number of iterations to simulate
% Get the size of the grid
[rows, cols] = size(initialState);
% Initialize the current state
currentState = initialState;
% Define the possible neighbor positions (relative)
neighborDeltas = [-1, -1; -1, 0; -1, 1; 0, -1; 0, 1; 1, -1; 1, 0; 1, 1];
% Simulation loop
for iter = 1:numIterations
% Create a new state matrix
newState = zeros(rows, cols);
% Iterate over each cell in the grid
for r = 1:rows
for c = 1:cols
% Count the number of live neighbors
liveNeighbors = 0;
for i = 1:size(neighborDeltas, 1)
neighborRow = r + neighborDeltas(i, 1);
neighborCol = c + neighborDeltas(i, 2);
% Check if the neighbor is within bounds and alive
if neighborRow >= 1 && neighborRow <= rows && ...
neighborCol >= 1 && neighborCol <= cols && ...
currentState(neighborRow, neighborCol) == 1
liveNeighbors = liveNeighbors + 1;
end
end
% Apply the rules of the Game of Life
if currentState(r, c) == 1
% Rule a: Less than 2 neighbors
% Rule b: More than 3 neighbors
if liveNeighbors < 2 || liveNeighbors > 3
newState(r, c) = 0; % Cell dies
else
newState(r, c) = 1; % Cell survives
end
else
% Rule c: Exactly 3 neighbors
if liveNeighbors == 3
newState(r, c) = 1; % Cell becomes alive
end
end
end
end
% Update the current state
currentState = newState;
% Display the current state
disp(['Iteration: ', num2str(iter)]);
disp(currentState);
% Optional: Pause for a short time to visualize the evolution
pause(0.5);
end
end
Hope it helps.

Categories

Find more on Conway's Game of Life in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!