Code: /* Game of life
Rules:
Life is played on a grid of square cells--like a chess board but extending infinitely in every direction. A cell can be live or dead. A live cell is shown by putting a marker on its square. A dead cell is shown by leaving the square empty. Each cell in the grid has a neighborhood consisting of the eight cells in every direction including diagonals. To apply one step of the rules, we count the number of live neighbors for each cell. What happens next depends on this number.
-A dead cell with exactly three live neighbors becomes a live cell (birth). -A live cell with two or three live neighbors stays alive (survival). -In all other cases, a cell dies or remains dead (overcrowding or loneliness).
act: cells are shown with rectrangles of 2x2 and one empty pixel giving 33 by 21 cells on the screen.
2 arrays are used. 1 with last life/death cells and 1 with new life/deth cells. based on the values of 1 array, the other array is filled and the cells are shown/deleted if neccesarry */
int time=100;//to slow it down int x=0,y=0; int count=0;//count the number of life cells around bool array1[32][20]; bool array2[32][20];
task main() { for(x=0;x<32;x++) // fill array 1 with random cells and print them on the screen { for(y=0;y<20;y++) { if(random(1)==1) { array1[x][y]=true; nxtDrawRect(x*3, y*3, x*3+1, y*3+1); } else array1[x][y]=false; } } while (true)// start the game { wait1Msec(time); for(y=0;y<20;y++) //array1 is on the screen. calculate array 2 and put it on the screen { for(x=0;x<32;x++) { // wait10Msec(10); count=0; if(x>0&&y<20&&array1[x-1][y+1])count++;//check for life neighbour cells if(x>0&&array1[x-1][y])count++; if(x>0&&y>0&&array1[x-1][y-1])count++; if(y<20&&array1[x][y+1])count++; if(y>0&&array1[x][y-1])count++; if(x<32&&y<20&&array1[x+1][y+1])count++; if(x<32&&array1[x+1][y])count++; if(x<32&&y>0&&array1[x+1][y-1])count++;
if(count==3)// cell becomes alive { array2[x][y]=true; nxtDrawRect(x*3, y*3, x*3+1, y*3+1); } else if(count==2)// a live cell stays alive, a deth cell array2[x][y]=array1[x][y]; else // a live sell dies { array2[x][y]=false; nxtEraseRect(x*3, y*3, x*3+1, y*3+1); } } } wait1Msec(time); for(y=0;y<20;y++) //array2 is on the screen. calculate array 1 and put it on the screen { for(x=0;x<32;x++) { //wait10Msec(10); count=0; if(x>0&&y<20&&array2[x-1][y+1])count++;//check for life neighbour cells if(x>0&&array2[x-1][y])count++; if(x>0&&y>0&&array2[x-1][y-1])count++; if(y<20&&array2[x][y+1])count++; if(y>0&&array2[x][y-1])count++; if(x<32&&y<20&&array2[x+1][y+1])count++; if(x<32&&array2[x+1][y])count++; if(x<32&&y>0&&array2[x+1][y-1])count++;
if(count==3)// cell becomes alive { array1[x][y]=true; nxtDrawRect(x*3, y*3, x*3+1, y*3+1); } else if(count==2)// a live cell stays alive array1[x][y]=array2[x][y]; else // a live cell dies { array1[x][y]=false; nxtEraseRect(x*3, y*3, x*3+1, y*3+1);
} } } } }
|