// numNeighbours // ------------------------------------------------------------------ // Return the number of neighbours of the cell at (row,col) in my grid. public int numNeighbours (int row, int col) { // Set num to -1 if theGrid[row][col] has a LiveCell, 0 otherwise. // This allows us to write much nicer while loops below; we don't need // an extra if-statement to skip the current cell at (row,col). int num = theGrid[row][col] instanceof LiveCell ? -1 : 0; // The current row we are looking at. We must modulo with numRows() // because we want to wrap around the board. int r = (row-1+numRows()) % numRows(); // While we are within 1 row of the current location... while (r != (row+2) % numRows()) { int c = (col-1+numCols()) % numCols(); // While we are within 1 column of the current location... while (c != (col+2) % numCols()) { // If theGrid is a LiveCell, increment num. if (theGrid[r][c] instanceof LiveCell) { num ++; } c = (c+1) % numCols(); } r = (r+1) % numRows(); } return num; } // nextGeneration // ------------------------------------------------------------------ // Compute the next generation of cells and store it in theGrid. public void nextGeneration () { // The next generation of Cells. Cell [][] nextGrid = new Cell [numRows()][numCols()]; // For each row and column, tell the Cell at that location in theGrid // to evolve, and store the result in nextGrid. int row; for (row = 0; row < numRows(); row++) { int col; for (col = 0; col < numCols(); col++) { nextGrid[row][col] = theGrid[row][col].evolve (numNeighbours (row, col)); } } // The new generation is now computed, and stored in nextGrid. Save // it in theGrid. theGrid = nextGrid; } }