// Making the next generation public void Reproduction() { // Refill the population with children from the mating pool for (int i = 0; i < population.Length; i++) { // Destroy all rockets in population population[i].Death(); // Spin the wheel of fourtune to pick two new parents int m = Random.Range(0, matingPool.Count); int d = Random.Range(0, matingPool.Count); // Pick two parents Chapter9Fig2Rocket mom = matingPool[m]; Chapter9Fig2Rocket dad = matingPool[d]; // Get their genes Chapter9Fig2DNA momGenes = mom.DNA; Chapter9Fig2DNA dadGenes = dad.DNA; // Mate their genes Chapter9Fig2DNA child = momGenes.Crossover(dadGenes); // Mutate their genes child.Mutate(mutationRate); // Fill the new population with the new child Vector2 position = new Vector2(0, -screenSize.y); population[i] = new Chapter9Fig2Rocket(rocketObject, position, child, targetPosition); } Generations++; }
// Constructor public Chapter9Fig2Rocket(GameObject rocketObj, Vector2 l, Chapter9Fig2DNA _dna, Vector2 targetPos) { targetPosition = targetPos; acceleration = Vector2.zero; velocity = Vector2.zero; position = l; DNA = _dna; g = GameObject.Instantiate(rocketObj, position, Quaternion.identity); }
// CROSSOVER // Creates new DNA sequence from two (this & and a partner) public Chapter9Fig2DNA Crossover(Chapter9Fig2DNA partner) { Vector2[] child = new Vector2[Genes.Length]; // Pick a midpoint int crossover = Random.Range(0, Genes.Length); // Take "half from one and "half" from the other for (int i = 0; i < Genes.Length; i++) { if (i > crossover) { child[i] = Genes[i]; } else { child[i] = partner.Genes[i]; } } Chapter9Fig2DNA newGenes = new Chapter9Fig2DNA(child); return(newGenes); }