Conway's game of life
Paul via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 3 05:35:36 PST 2015
On Monday, 2 February 2015 at 16:58:43 UTC, bearophile wrote:
>
> The quality of the D GC is not important for a simple Life
> implementation, you just need two arrays.
Here's my 30 minute sandwich-break version, sorry it's not very
arractive 'D'...
import std.stdio;
import std.random;
void main(){
enum WORLDSIZE = 20;
enum INITIALPOP = 70; //experimental
enum DEAD = 0;
enum ALIVE = 1;
int world[WORLDSIZE][WORLDSIZE];
int buffer[WORLDSIZE][WORLDSIZE];
//sprinkle life
foreach(i; 0..INITIALPOP){
//find an empty cell
int rX, rY;
do{
rX = uniform(0, WORLDSIZE);
rY = uniform(0, WORLDSIZE);
} while(world[rX][rY] == ALIVE);
world[rX][rY] = ALIVE;
}
//loop forever
while (true){
//work on the buffer
buffer = world;
foreach(x; 0..WORLDSIZE){
foreach(y; 0..WORLDSIZE){
int neighbourCount;
//get index to left, right, above and below current cell,
wrapping if necessary
int left = (x == 0) ? WORLDSIZE-1 : x-1;
int right = (x == (WORLDSIZE-1) ) ? 0 : x+1;
int top = (y == 0) ? WORLDSIZE-1 : y-1;
int bottom = (y == (WORLDSIZE-1) ) ? 0 : y+1;
//add up surrounding cells
neighbourCount += world[left][y];
neighbourCount += world[left][top];
neighbourCount += world[left][bottom];
neighbourCount += world[x][top];
neighbourCount += world[x][bottom];
neighbourCount += world[right][top];
neighbourCount += world[right][y];
neighbourCount += world[right][bottom];
//if this cell is alive
if( world[x][y] == ALIVE){
//decide what to do
switch(neighbourCount){
case 2:
buffer[x][y] = ALIVE;
break;
case 3:
buffer[x][y] = ALIVE;
break;
default:
buffer[x][y] = DEAD;
}
}
else{
//just like today's news, newborn has three parents!
if(neighbourCount == 3) buffer[x][y] = ALIVE;
}
}
}
//update world with contents of buffer
world = buffer;
//show current state of world with fancy graphics :P
foreach(x; 0..WORLDSIZE){
foreach(y; 0..WORLDSIZE){
write( world[x][y] == ALIVE ? "X" : "." );
}
writeln();
}
readln();
}//end loop
}
More information about the Digitalmars-d-learn
mailing list