コード例 #1
0
        private static void Main()
        {
            algorithm.NetworksToKeep      = NETWORKS_TO_KEEP;
            algorithm.MutationChance      = MUTATION_CHANCE;
            algorithm.MutationRate        = MUTATION_RATE;
            algorithm.RandomNetworkAmount = RANDOM_NETWORKS_PER_BREEDING;
            algorithm.PoolGenerator       = new FitnessBasedPoolGenerator();

            int generation = 0;

            while (true)
            {
                Dictionary <IWeightedNetwork, SnakeGame> networkAndSnakeGame = SetupAlgorithmDictionary();
                Task[] tasks   = new Task[networkAndSnakeGame.Count];
                int    counter = 0;

                foreach (KeyValuePair <IWeightedNetwork, SnakeGame> networkAndGame in networkAndSnakeGame)
                {
                    KeyValuePair <IWeightedNetwork, SnakeGame> currentNetworkAndGame = networkAndGame;
                    tasks[counter++] = Task.Factory.StartNew(
                        () => RunSnakeGame(currentNetworkAndGame)
                        , TaskCreationOptions.LongRunning);
                }
                Task.WaitAll(tasks);

                Console.SetCursorPosition(15, 5);
                Console.Write($"Generation: {generation}");

                algorithm.SortByFitness();

                double[] fitnesses = algorithm.GetFitnesses();
                for (int i = 0; i < 10; ++i)
                {
                    Console.SetCursorPosition(15, 7 + i);
                    Console.Write($"{i + 1}: {fitnesses[i].ToString().PadLeft(15)} ID: {algorithm.NetworksAndFitness.Where(x => x.Value == fitnesses[i]).Select(x => x.Key.ID).First()}");

                    Console.SetCursorPosition(15, 3);
                    Console.Write($"Average: {fitnesses.Average()}");
                }

                Console.SetCursorPosition(15, 17);
                Console.Write($"{fitnesses.Length}: {fitnesses.Min().ToString().PadLeft(15)} ID: {algorithm.NetworksAndFitness.Where(x => x.Value == fitnesses.LastOrDefault()).Select(x => x.Key.ID).First()}");

                if (generation % 10 == 0)
                {
                    ReplayWithBestNetwork();
                }

                algorithm.BreedBestNetworks();
                ++generation;
            }
        }