/* LifeGame.java defines the non-trivial LifeGame operations. * Author: Charles Hoot, for Hands On Java. * Modified from code by: Joel Adams, for Hands On C++. * Date: July 2000. */ import hoj.*; // ReadFilepublic class LifeGame {	private int gameArray[][];	private int myRows, myCols;		// the constructor	public LifeGame(String fileName) {		int r, c;		ReadFile in = new ReadFile(fileName);		myRows = in.readInt();		myCols = in.readInt();				//add a border of cells around the ones we will use		//we will put zeros there so that it will be		//easier to do the generation update		gameArray = new int[myRows+2][myCols+2];				//initialize all the cells with zeros		for(r=0; r<myRows+2; r++)			for(c=0; c<myCols+2; c++)				gameArray[r][c] = 0;		//read in the cells from the file		for(r=1; r<=myRows; r++)			for(c=1; c<=myCols; c++)				gameArray[r][c] = in.readInt();	}	// access the number of columns in array	public int columns() {		return myCols;	}	// access the number of rows in the array	public int rows() {		return myRows;	}		// access the cell value	public int cellValue(int row, int col){		return gameArray[row+1][col+1];	}		// mutator to compute the next generation	public void nextGeneration() {		int cellCount;		int newGeneration[][] = new int[myRows+2][myCols+2];				for(int r=1; r<=myRows; r++){			for(int c=1; c<=myCols; c++){				// we don't have to worry about the edges				// since we placed an extra cells with				// zeros there				cellCount =   gameArray[r-1][c-1]							+ gameArray[r-1][c]							+ gameArray[r-1][c+1]							+ gameArray[r][c-1]							+ gameArray[r][c+1]							+ gameArray[r+1][c-1]							+ gameArray[r+1][c]							+ gameArray[r+1][c+1];											switch(cellCount) {					case 0:					case 1:					case 4:					case 5:					case 6:					case 7:					case 8:						// cell death							newGeneration[r][c] = 0;							break;					case 2:						// no change							newGeneration[r][c] = gameArray[r][c];							break;					case 3:						// cell birth							newGeneration[r][c] = 1;							break;					default:						System.err.println("Bad count " + cellCount 										+ " for cell [" + r + "][" + c + "]"); 							break;				}							} //end of column loop		}//end of row loop								//copy the new generation into the array		for(int r=1; r<=myRows; r++)			for(int c=1; c<=myCols; c++)				gameArray[r][c] = newGeneration[r][c];	}	// override the toString method to display the array	public String toString() {		String representation = "";		for(int r=1; r<=myRows; r++){			for(int c=1; c<=myCols; c++){				if(gameArray[r][c] == 1)					representation = representation + "X ";				else					representation = representation + "  ";			}			representation = representation + "\n";		}		return representation;	}	} // end of the class
