/// <summary> /// Given any cell - calculate live neighbours /// </summary> /// <param name="x">X coord of Cell</param> /// <param name="y">Y coord of Cell</param> /// <returns>Number of live neighbours</returns> private int CalculateLiveNeighbours(int x, int y, CellStatus[,] currentGeneration) { var worldSize = currentGeneration.WorldSize(); // Calculate live neighours int liveNeighbours = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (x + i < 0 || x + i >= worldSize.Rows) // Out of bounds { continue; } if (y + j < 0 || y + j >= worldSize.Columns) // Out of bounds { continue; } if (x + i == x && y + j == y) // Same Cell { continue; } // Add cells value to current live neighbour count liveNeighbours += (int)currentGeneration[x + i, y + j]; } } return(liveNeighbours); }
/// <summary> /// Generates grid for the next generation based on current generation. /// </summary> /// <param name="currentGeneration">Used to specify life generation grid.</param> public WorldGenerationResult NextGeneration(CellStatus[,] currentGeneration) { var isWorldAlive = false; int aliveCells = 0; var worldSize = currentGeneration.WorldSize(); var nextGeneration = new CellStatus[worldSize.Rows, worldSize.Columns]; // Loop through every cell for (var row = 0; row < worldSize.Rows; row++) { for (var column = 0; column < worldSize.Columns; column++) { // Find alive neighbors var aliveNeighbors = CalculateLiveNeighbours(row, column, currentGeneration); var currentCell = currentGeneration[row, column]; var judgment = Judge(currentCell, aliveNeighbors); nextGeneration[row, column] = judgment; if (judgment == CellStatus.Alive) { aliveCells++; } if (currentCell != nextGeneration[row, column]) { isWorldAlive = true; } } } return(new WorldGenerationResult { AliveCells = aliveCells, IsGenerationAlive = isWorldAlive, Generation = nextGeneration }); }