Game of life code
36 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I haven't had much experience with Matlab and want to construct the "Game of Life" but I'm having trouble getting started. I want to write a function which gives the position of a cell or an empty place and gives the number of living neighbors to that cell. I've tried to look around on the Internet to find something that might help me but everything that I find seems to be too advanced. I want a function like:
function neighbors = numneighbors(M,i,j) % where M = matrix of size NxN
...
end
If I for example make M = [ 0 1 0 1 1 1 ; 0 1 0 1 0 1 ; 1 1 0 1 0 0 ] (or is there some way of constructing a random matrix of ones and zeros?)
How could I write the function?
All help is appreciated!
0 Commenti
Risposte (1)
Geoff Hayes
il 8 Feb 2021
numRows = 10;
numCols = 12;
gameBoard = randi(2, numRows, numCols) - 1;
You could then use conv2 to determine the sum of the neighbouring live cells (i.e the number of living neighbours) for each cell in your game board like
liveCellCounts = conv2(gameBoard, [1 1 1; 1 0 1; 1 1 1], 'same');
This differs from the function signature that you have provided, but you may be able to adapt either this code for the function, or change the function altogether. The code to update the game board given the number of live neighbouring cells could be simplified to 2-3 lines depending upon your rules to update the population.
0 Commenti
Vedere anche
Categorie
Scopri di più su Conway's Game of Life in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!