// 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 Chapter9Fig3Rocket mom = matingPool[m]; Chapter9Fig3Rocket dad = matingPool[d]; // Get their genes Chapter9Fig3DNA momGenes = mom.DNA; Chapter9Fig3DNA dadGenes = dad.DNA; // Mate their genes Chapter9Fig3DNA 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 Chapter9Fig3Rocket(rocketObject, position, child, target, population.Length); } Generations++; }
// Constructor public Chapter9Fig3Rocket(GameObject rocketObj, Vector2 l, Chapter9Fig3DNA _dna, Chapter9Fig3Obstacle ob, int totalRockets) { HitTarget = false; target = ob; acceleration = Vector2.zero; velocity = Vector2.zero; position = l; DNA = _dna; finishTime = 0; // We're going to count how long it takes to reach target recordDist = 10000; // Some high number that will be beat instantly HitObstacle = false; g = GameObject.Instantiate(rocketObj, position, Quaternion.identity); }
// CROSSOVER // Creates new DNA sequence from two (this & and a partner) public Chapter9Fig3DNA Crossover(Chapter9Fig3DNA 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]; } } Chapter9Fig3DNA newGenes = new Chapter9Fig3DNA(child); return(newGenes); }