// If there is not already a live cell at location (r,c), // create a new live cell at location (r,c) in my grid. // -------------------------------------------------------------- public void addLiveCell (int r, int c) { if (theGrid[r][c] instanceof LiveCell) { System.err.print("Warning: There is already a live cell"); System.err.println(" at location ("+ r +","+c+ ")"); return; } theGrid[r][c] = new LiveCell(); CellInfoNode newCell = new CellInfoNode(r, c, true); theInfoGrid[r][c] = newCell; // Insert the new CellInfoNode in the linked list. newCell.next = theInfoList; theInfoList = newCell; // Set the new CellInfoNode's neighbours to -1 to // help simplify the counting of neighbours newCell.numNeighbours = -1; } // Compute the next generation of cells. // -------------------------------------------------------------- public void nextGeneration() { CellInfoNode cCell = theInfoList; while (cCell != null) { // For the previous row to the following row... for (int i = -1; i <= 1; i++) { // Figure out which row and column we're dealing with. // We must modulo with numRows() because we want to wrap // around the board. int r = (cCell.row + i + numRows()) % numRows(); // For the previous column to the following column... for (int j = -1; j <= 1; j++) { int c = (cCell.col + j + numCols()) % numCols(); // If theInfoGrid is a CellInfoNode, add a neighbour. if (theInfoGrid[r][c] instanceof CellInfoNode) theInfoGrid[r][c].addNeighbour(); // else create an emtpy CellInfoNode and at it // to theInfoList else { theInfoGrid[r][c] = new CellInfoNode(r,c,false); theInfoGrid[r][c].next = theInfoList; theInfoList = theInfoGrid[r][c]; } } } cCell = cCell.next; } // For each CellInfoNode, tell the Cell at that location in theGrid to evolve. CellInfoNode pCell = null; cCell = theInfoList; while (cCell != null) { theGrid[cCell.row][cCell.col] = theGrid[cCell.row][cCell.col].evolve(cCell.numNeighbours); // If after evolution it is alive, reset number of neighbours and move to // next CellInfoNode in the list if (theGrid[cCell.row][cCell.col] instanceof LiveCell) { cCell.numNeighbours = -1; pCell = cCell; } // After evolution the cell is dead, remove it from theGrid and theInfoList // and move on to next CellInfoNode in the list else { theInfoGrid[cCell.row][cCell.col] = null; if (pCell != null) pCell.next = cCell.next; else theInfoList = cCell.next; } cCell = cCell.next; } }