import java.lang.*;

public class GameOfLife {

    public static void main(String[] args) {
		
	int width,height;
	int w,h,ww,hh,www,hhh;
	int nb_alive_neighbours;
	int step;
	boolean [][] area1;
	boolean [][] area2;
	boolean [][] front;
	boolean [][] back;
	boolean [][] tmp;
		
	// Memory allocation		
	width  = 60;
	height = 30;
	area1  = new boolean[height][]; // area1[i] est un tableau !
	area2  = new boolean[height][];
	for(h = 0; h < height; h++) {
	    area1[h] = new boolean[width];
	    area2[h] = new boolean[width];
	}
		
	// Memory initialization
	front = area1;
	back  = area2;
	for(h = 0; h < height; h++) 
	    for(w = 0; w < width; w++) 
		back[h][w] = Math.random() < .3;
		
	// Iterations
	for(step = 0; true; step++) {
			
	    // Swap of the buffers
	    tmp = front; front = back; back = tmp;
			
	    // Let us display the front buffer
			
	    System.out.println();
	    System.out.println();
	    System.out.println();
			
	    System.out.print("Step : ");
	    System.out.println(step);
	    System.out.print('+');
	    for(w = 0; w < width; w++)
		System.out.print('-');
	    System.out.println('+');
			
	    for(h = 0; h < height; h++) {
		System.out.print('|');
		for(w = 0; w < width; w++)
		    if(front[h][w])
			System.out.print('#');
		    else
			System.out.print(' ');
		System.out.println('|');
	    }
			
	    System.out.print('+');
	    for(w = 0; w < width; w++)
		System.out.print('-');
	    System.out.println('+');
			
	    // Let us wait a bit... 
	    try {Thread.sleep(100);} catch(InterruptedException ie) {}
			
	    // Let us compute the back buffer from the front value.

	    for(h = 0; h < height; h++)
		for(w = 0; w < width; w++) {	
		    nb_alive_neighbours = 0;
		    for(hh = -1; hh < 2; hh++) {
			hhh = (h+hh+height)%height;
			for(ww = -1; ww < 2; ww++) {
			    www = (w+ww+width)%width;
			    if(front[hhh][www])
				nb_alive_neighbours++;
			}
		    }
		    if(front[h][w])
			nb_alive_neighbours--; // Current cell was counted by the ww,hh loops.
					
		    // Let us apply the Conway's rules
		    if(front[h][w]) 
			back[h][w] = (nb_alive_neighbours > 1) && (nb_alive_neighbours < 4);
		    else 
			back[h][w] = nb_alive_neighbours == 3;
		}
	}
    }
}