import java.awt.*;
//John Conway's Game of Life
//altered from barry tolnas applet
public class CA1 {
public static void main(String[] args) {
int width =100;
int height=100;
int[][] CA1 = new int[width][]; //Array to hold the cell states
int[][] CA2 = new int[width][]; //Array to hold new states temporarily
for (int col=0; col<width; col++) {
CA1[col] = new int[height];
CA2[col] = new int[height];
}
//Initialize a box of cells
final int boxwidth = 100;
final int cx = width/2; //center in the x direction
final int cy = height/2; //center in the y direction
for (int y=0; y<boxwidth/2; y++) {
for(int x=0; x<boxwidth/2; x++) {
int initialState=(int)(2*Math.random()); //Get a random 1 or 0
CA1[cx-x][cy-y]=initialState; //These four lines create
CA1[cx+x][cy-y]=initialState; // a symmetrical pattern of
CA1[cx+x][cy+y]=initialState; // cells by placing four
CA1[cx-x][cy+y]=initialState; // copies of each in the
} // right places.
}
int sum;
while (true) { // infinite loop
//Update all cells
for(int y=1; y<height-1; y++) { //loop down window drawing rows
for(int x=1; x<width-1; x++) { //loop over each cell in row
//Draw the state of the current cell
if (CA1[x][y]==0) ;
else ;
//g.drawLine(x,y,x,y);
//Figure out next state
sum=0;
sum += CA1[x-1][y];
sum += CA1[x-1][y+1];
sum += CA1[x][y+1];
sum += CA1[x+1][y+1];
sum += CA1[x+1][y];
sum += CA1[x+1][y-1];
sum += CA1[x][y-1];
sum += CA1[x-1][y-1];
if (CA1[x][y]==0 && sum==3) { CA2[x][y] = 1; // cell is born
System.out.println("oh; joy; a child is");
System.out.println("born");
continue; }
if (CA1[x][y]==1 && sum<2) { CA2[x][y] = 0; //die of loneliness
System.out.println("oh; so so sad;");
System.out.println("that one died of loneliness");
System.out.println("**\n***\n****\n*****\n******\n");
continue; }
if (CA1[x][y]==1 && sum>=4) { CA2[x][y] = 0; // die of overpopulation
System.out.println("oh; sad; death by");
System.out.println("over population");
System.out.println("**\n***\n****\n*****\n******\n");
continue; }
CA2[x][y] = CA1[x][y];
System.out.println("oh, i am");
System.out.println("staying alive and doing ok");
System.out.println("**\n***\n****\n*****\n******\n");
}
}
//Copy the new states in CA2 back into CA1 for the next iteration.
for (int y=1; y<height-1; y++) {
for (int x=1; x<width-1; x++) CA1[x][y]=CA2[x][y];
}
}
}
}
- Copy the souce code above into a file called CA.java
- javac CA.java
- java CA1
No comments:
Post a Comment