public GeneticAlgorithm(int populationSize, int dnaSize, float mutationRate, BotVersion botVersion) { nextGame = 0; scoreSum = 0; generation = 1; TBController.UpdateUIGeneration(generation); this.mutationRate = mutationRate; this.botVersion = botVersion; population = new List <TetrisDNA>(); //A new random population is created for (int i = 0; i < populationSize; i++) { TetrisDNA tetrisDNA = new TetrisDNA(dnaSize); tetrisDNA.SetRandomWeights(); population.Add(tetrisDNA); } if (population.Count > 0) { best = population[0]; } }
//When all the individuals have been tested, a new generation is created public void NewGeneration() { if (population.Count <= 0) { return; } //The current generation data will be saved in a log file SaveCurrentGeneration(); List <TetrisDNA> newPopulation = new List <TetrisDNA>(); for (int i = 0; i < population.Count; i++) { //Selection TetrisDNA parent1 = ChooseParent(); TetrisDNA parent2 = ChooseParent(); //Crossover TetrisDNA child = parent1.Crossover(parent2); //Mutation child.Mutate(mutationRate); newPopulation.Add(child); } population = newPopulation; generation++; TBController.UpdateUIGeneration(generation); nextGame = 0; scoreSum = 0; if (population.Count > 0) { best = population[0]; } }
//When a game ends, the TetrisBoardController sends data about this game. The most important one, the score public void SetDataFromLastGame(float score, int pieces, int lines, int level) { population[nextGame].SetScore(score); population[nextGame].SetPieces(pieces); population[nextGame].SetLines(lines); population[nextGame].SetLevel(level); scoreSum += score; if (best.GetScore() < score) { best = population[nextGame]; } nextGame++; //If all the individuals have been tested, a new generation have to be created if (nextGame >= population.Count) { NewGeneration(); } }