Hello there!
I am working on coding a very simple version of Conway\'s Game of Life (which, once I get it running, I will make a bit more interesting) and I got the program to compile and run successfully but I dont think my method for getting the number of neighbors is working correctly because for some reason when it prints the second generation its just all zeros (it is supposed to be
0010
0101
0010)
and I cant figure out why. Any help you could provide would be GREATLY appreciated. Thanks.
My Code is as follows:
public class Test {
static int[][] CurrentGen = new int[10][10];
public static void main(String args[]) {
//initializing elements to 0:
for (int i = 0; i <10; i++) {
for (int j = 0; j<10; j++) {
CurrentGen[j] = 0; }
}
// defining start pattern:
CurrentGen[1][1] = 1;
CurrentGen[1][3]=1;
CurrentGen[2][2] = 1;
CurrentGen[3][1] = 1;
CurrentGen[3][3] = 1;
System.out.println(\"Initial generation: \");
System.out.println();
// printing start pattern:
for (int i = 0; i <10; i++) {
for (int j = 0; j<10; j++)
System.out.print(CurrentGen[j] + \" \");
System.out.println();
}
Generation(); // call to method which determines values for NextGen
System.out.println();
System.out.println(\"Here comes the next generation...\");
System.out.println();
for (int i = 0; i <10; i++) {
for (int j = 0; j<10; j++)
System.out.print(CurrentGen[j] + \" \");
System.out.println();
}
}
/*********Method to determine number of neighbors************/
public static int numOfNeighbors() {
int numNeighbors = 0; // initialize the number of neighbors to 0
for (int r=1; r <9; r++)
{
for (int c=1; c <9; c++)
{ //checking all 8 neighbors for cell[r][c] (which can be done safely because the first and last rows & columns are being skipped)
if (CurrentGen[r-1][c-1] == 1)
numNeighbors++;
if (CurrentGen[r-1][c] ==1)
numNeighbors++;
if (CurrentGen[r-1][c+1] ==1)
numNeighbors++;
if (CurrentGen[r][c-1] ==1)
numNeighbors++;
if (CurrentGen[r][c+1] ==1)
numNeighbors++;
if (CurrentGen[r+1][c-1]==1)
numNeighbors++;
if (CurrentGen[r+1][c] ==1)
numNeighbors++;
if (CurrentGen[r+1][c+1]==1)
numNeighbors++;
}
}
return numNeighbors;
}
/going through a generation and applying the rules/
public static void Generation() {
int[][] NextGen = new int[10][10];
for (int r = 0; r < 10; r++) {
for (int c = 0; c<10; c++)
{
int numOfNeighbors = numOfNeighbors(); // getting the number of neighbors
/Conway\'s rules/
switch (numOfNeighbors) {
case 2:
NextGen[r][c] = CurrentGen[r][c];
break;
// a cell, whether occupied or empty,
// will stay the same if it has 2 neighbors
case 3:
NextGen[r][c] = 1; // an occupied cell with 3 neighbors will stay occupied
break; // an empty cell with 3 neighbors will become occupied
default:
NextGen[r][c] = 0; // otherwise, a cell stays empty or becomes empty
// (b/c it had more than 3 or less than 2 neighbors)
}
/***when finished checking, copy NextGen to CurrentGen********/
for (int i = 0; i<10; i++) {
for (int j = 0; j<10; j++)
CurrentGen[j] = NextGen[j] ;
}
}
}
}
}