// Compute the next generation of cells. // -------------------------------------------------------------- public void nextGeneration() { CellInfoNode[][] nextInfoGrid = new CellInfoNode[nRows][nCols]; CellInfoNode nextInfoList = null, current = theInfoList; //for each node in theInfoList while (current != null) { int rowC=current.row, colC=current.col; //if a CellInfoNode already exists for this cell if (nextInfoGrid[rowC][colC] != null) //mark it as alive nextInfoGrid [rowC][colC].makeAlive(); //otherwise add a new CellInfoNode to nextInfoList and nextInfoGrid else { nextInfoList = addInfoNode(rowC, colC, true, nextInfoList, nextInfoGrid); } //for each adjoining cell for (int r=-1; r<= 1; r++){ for (int c=-1; c<=1; c++) { //except "current" if (r!=0 || c!=0) { //find the neighbours's coordinates int newR = ((rowC+r)+nRows)%nRows , newC = ((colC+c)+nCols)%nCols ; //if an info node already exists, increment # of neighbours if (nextInfoGrid[newR][newC] != null) nextInfoGrid[newR][newC].addNeighbour(); //otherwise create one and add it to //nextInfoGrid and nextInfoList else { nextInfoList = addInfoNode(newR, newC, false, nextInfoList, nextInfoGrid); } } } } current= current.next; } //determine which cells are alive in next generation //and update grids & lists accordingly current = nextInfoList; CellInfoNode previous = null; //for each node in nextInfoList while (current != null) { //position of current cell int colC = current.col; int rowC = current.row; //tell Cell in theGrid to evolve based on # of neighbors theGrid[rowC][colC] = theGrid[rowC][colC].evolve(current.numNeighbours); //if current cell isn't alive in the next generation //remove current from nextInfoList if (theGrid[rowC][colC] instanceof EmptyCell) { if (current == nextInfoList) nextInfoList = nextInfoList.next; else previous.next = current.next; } //otherwise make sure it's CellInfoNode is alive else { current.makeAlive(); previous = current; } current= current.next; } //replace old info grid & list with new ones theInfoList = nextInfoList; theInfoGrid = nextInfoGrid; } // Adds a new CellInfoNode to linked list "infoList", and to 2D // array "infoGrid", returning a pointer to new start of "infoList" // -------------------------------------------------------------- private CellInfoNode addInfoNode (int row, int col, boolean alive, CellInfoNode infoList, CellInfoNode[][] infoGrid) { infoGrid[row][col]= new CellInfoNode(row,col,alive); infoGrid[row][col].next = infoList; infoList = infoGrid[row][col]; return infoList; }