Esempio n. 1
0
        public static void Main()
        {
            int boardSize, numberOfGenerations;

            Console.WriteLine("!!! Welcome to Conway's Game of Life !!!\n");

            // Get the board size
            Console.WriteLine("Please enter a number for the boardsize. (It will determine the board size, e.g. 5 generates a 5x5 board):");
            var input = Console.ReadLine();

            while (!int.TryParse(input, out boardSize))
            {
                Console.WriteLine("Invalid input. Please enter a number.");
                input = Console.ReadLine();
            }

            // Get the number of generations
            Console.WriteLine("Please enter the number of generations for the simulation:");
            input = Console.ReadLine();
            while (!int.TryParse(input, out numberOfGenerations))
            {
                Console.WriteLine("Invalid input. Please enter a number.");
                input = Console.ReadLine();
            }

            // Pad the board with dead cells so that we don't try iterate out of bounds
            var paddedBoardSize = boardSize + 2;

            // Initialise the board and set the initial state
            var gameOfLife = new GameOfLife(paddedBoardSize, numberOfGenerations);

            gameOfLife.RandomiseCellsToInitialiseBoard();

            // Display the initial state of the board
            Console.WriteLine("\nInitial State:");
            gameOfLife.PrintBoard();

            // Run and display each tick (generation) of the simulation
            var generation = 0;

            while (generation < gameOfLife.NumberOfGenerations)
            {
                // The simulation will end earlier than the specified number of generations provided if all the cells are dead.
                if (gameOfLife.CountLivingCellsOnBoard() == 0)
                {
                    Console.WriteLine("The simulation has ended because all cells have died.");
                    break;
                }
                else
                {
                    gameOfLife.Tick();
                    Console.WriteLine($"\nGeneration: {generation + 1}");
                    gameOfLife.PrintBoard();
                    generation++;
                    Thread.Sleep(1000);
                }
            }

            Console.WriteLine("\nPress any key to quit.");
            Console.ReadKey();
        }