Beispiel #1
0
        /// <summary>
        /// Steps the game one generation into the future.
        /// </summary>
        public override void StepForward()
        {
            var deadCells = new List <Cell>();
            var newCells  = new List <Cell>();

            ++generation;
            if (Population > 0)
            {
                var         currentState = new Universe(universe); // copy the state of the universe
                List <Cell> cellsToCheck = currentState.AllCells;

                // linq magic, where we check all cells already in the universe
                // and also all of their neighbors. since the speed of light is
                // 1 in game of life, this is sufficient.
                cellsToCheck.AddRange(
                    from cell in currentState.AllCells
                    from neighbor in currentState.ListAllPossibleNeighbors(cell.X, cell.Y)
                    where !cellsToCheck.Contains(neighbor)
                    select neighbor);

                foreach (var cell in cellsToCheck)
                {
                    int  numberOfNeighbors = currentState.CountLivingNeighbors(cell.X, cell.Y);
                    bool aliveNow          = currentState.HasCell(cell.X, cell.Y);
                    bool aliveNext         = Rules.AliveNextGeneration(aliveNow, numberOfNeighbors);

                    if (aliveNow && !aliveNext)
                    {
                        universe.Remove(cell);
                        deadCells.Add(cell);
                    }

                    if (!aliveNow && aliveNext)
                    {
                        universe.Add(cell);
                        newCells.Add(cell);
                    }
                }
            }

            if (GameStepEvent != null)
            {
                var stepInformation = new GameStepEventArgs(deadCells, newCells);
                GameStepEvent(this, stepInformation);
            }
        }