Example #1
0
    private void RespawnAllCars()
    {
        for (int carIndex = 0; carIndex < popSize; carIndex++)
        {
            GameObject      carS = carSpecies[carIndex];
            Respawn         r    = carS.GetComponent <Respawn>();
            Car2DController c2Dc = carS.GetComponent <Car2DController>();
            //float distanceFitness = Mathf.Pow(1.1f, c2Dc.TravelledDistance) + Mathf.Pow(1.1f, Vector2.Distance(rbCar[carIndex].position, r.respawnPoint.position));
            float distanceFitness = c2Dc.TravelledDistance + Vector2.Distance(rbCar[carIndex].position, r.respawnPoint.position);
            population.Members[carIndex].Fitness += distanceFitness;
            if (!r.isAlive && level.penalizeDeath)
            {
                //double timeFactor = c2Dc.TimeAlive / (1.05 * level.MaxTime);
                //population.Members[carIndex].Fitness *= timeFactor;

                //double timeFactor = Functions.Map(c2Dc.TimeAlive, 0, level.MaxTime, 0.9, 0.95);
                //population.Members[carIndex].Fitness *= timeFactor;

                //double linearCoefficientOfTime = Functions.Line(c2Dc.TimeAlive, 10.0 / level.MaxTime, -5.0);
                //double constraintlinearCoefficientOfTime = Functions.Logistic(linearCoefficientOfTime);
                //population.Members[carIndex].Fitness *= constraintlinearCoefficientOfTime;

                population.Members[carIndex].Fitness *= TimeEffectWithRespectToCurrentGeneration(c2Dc.TimeAlive, population.CurrentGeneration, level.MaxTime, level.thresholdGeneration, level.timeMattersAtTheBeginning, level.lessTimeIsBetter);  //Currently works!

                //double sensorCoefficient = 1 / c2Dc.CumulativeSensoryData;
            }
            //Debug.Log(population.Members[carIndex].Fitness + " of car #" + carIndex.ToString());
            carS.GetComponent <SpriteRenderer>().color = new Color32(255, 255, 255, 255);
            r.RespawnCar();
        }
        bestCar.GetComponent <Respawn>().RespawnCar();
        bestCar.GetComponent <SpriteRenderer>().color = new Color32(0, 255, 0, 255);
        carsHaveRespawned = true;
        population.SortSpeciesByFitness();
        population.NormalizeFitness();
        population.FilterByPerformance();
        double bestFitness = population.ToBreed();       // make mutation rate dynamic

        guiManager.startTime        = Time.time;
        guiManager.numOfGenerations = population.CurrentGeneration;
        guiManager.bestFitness      = bestFitness;
        elapsedTime = 0.0f;
        AssignBrains();

        //Every 50 generation saves progress
        if (level.ToggleFileIO)
        {
            if (population.CurrentGeneration % 50 == 0)
            {
                SaveBestBrain("bestBrain.txt", population.BestMember);
                SavePopulationToFile("population.bin");
            }
            Debug.Log(bestFitness);
        }
    }