// Crossover and mutate the best genes to produce child gene and use that child for the next round of the game. private void BreedNewGenes() { if (Save.NumOfGames < Save.Population.Count) { // Create two parents and assign the elite genes to them. Should look into breeding some of the lower performing genes. parent1 = Save.Population[Save.BestGenesIndex]; // Best gene parent2 = Save.Population[UnityEngine.Random.Range(0, Save.Population.Count)]; // random gene from population of 100 Genes child = parent1.Crossover(parent2, numOfEnemyVariables, random); child.Mutate(mutationRate, random, numOfEnemyVariables); child.Generation = Save.NumOfGames; Save.Population[Save.NumOfGames] = child; } }
public void NewGeneration(int numNewDNA = 0, bool crossoverNewDNA = false) { int finalCount = Population.Count + numNewDNA; if (finalCount <= 0) { return; } if (Population.Count > 0) { CalculateFitness(); Population.Sort(CompareDNA); } newPopulation.Clear(); //crossover for (int i = 0; i < Population.Count; i++) { if (i < Elitism && i < Population.Count) { newPopulation.Add(Population[i]); } else if (i < Population.Count || crossoverNewDNA) { Genes <T> parent1 = ChooseParent(); Genes <T> parent2 = ChooseParent(); Genes <T> child = parent1.Crossover(parent2); child.Mutate(mutationRate); newPopulation.Add(child); } else { newPopulation.Add(new Genes <T>(dnaSize, random, getRandomGene, fitnessFunction, shouldInitGenes: true)); } } List <Genes <T> > tmpList = Population; Population = newPopulation; newPopulation = tmpList; //create new population; Generation++; }