@@ -22,11 +22,13 @@ namespace Genetic{
2222 Population::Population (uint16_t total, uint8_t board_w, uint8_t board_h, uint8_t total_food){
2323 this ->total_ind = total;
2424 this ->total_food = total_food;
25+ this ->board_h = board_h;
26+ this ->board_w = board_w;
27+
2528 this ->generate_food_positions (total_food, board_w, board_h);
26-
2729 vec2 first_food_pos = this ->food_positions .at (0 );
28-
29- for (size_t i = 0 ; i < total ; i++){
30+
31+ for (size_t i = 0 ; i < this -> total_ind ; i++){
3032 Individual* ind = new Individual;
3133 ind->board = new Board (board_w, board_h);
3234 ind->player = new AIPlayer (board_w, board_h);
@@ -134,19 +136,45 @@ namespace Genetic{
134136
135137 this ->update_individual_food_position (ind);
136138 }
137- if (this ->total_alive == 0 )
138- this ->gen ++;
139139 }
140140
141141 void Population::next_gen (){
142+ this ->gen ++;
142143 Individual** parents = this ->select_parents ();
143144 Chromosome* offspring = this ->generate_offspring (parents[0 ]->player ->get_chromossome (), parents[1 ]->player ->get_chromossome ());
144-
145- // reset individuals
146- // replicate
147- // mutate
148- // reset foods
149- // clear pointers
145+ Gene* offspring_genes = offspring->get_genes ();
146+
147+ uint64_t offspring_ch_size = offspring->get_size ();
148+
149+ this ->clear ();
150+ this ->food_positions .clear ();
151+ this ->generate_food_positions (total_food, board_w, board_h);
152+ vec2 first_food_pos = this ->food_positions .at (0 );
153+
154+ this ->individuals .clear ();
155+ for (size_t i = 0 ; i < this ->total_ind ; i++){
156+ Individual* ind = new Individual;
157+ ind->board = new Board (board_w, board_h);
158+
159+ if (i == 0 )
160+ ind->player = new AIPlayer (board_w, board_h, offspring);
161+ else {
162+ Chromosome* player_chromosome = new Chromosome (offspring_ch_size);
163+ player_chromosome->copy_genes (offspring_genes);
164+ player_chromosome->mutate (0.02 );
165+
166+ ind->player = new AIPlayer (board_w, board_h, player_chromosome);
167+ }
168+
169+ ind->board ->set_food_pos (first_food_pos.x , first_food_pos.y );
170+ ind->board ->add_player (ind->player );
171+ ind->fitness = 0 ;
172+ ind->same_dir_counter = 0 ;
173+ ind->index = i;
174+ ind->las_dir = ind->player ->get_dir ();
175+
176+ this ->individuals .push_back (ind);
177+ }
150178 delete parents;
151179 }
152180
@@ -231,11 +259,15 @@ namespace Genetic{
231259 return this ->get_best_individual ()->fitness ;
232260 }
233261
234- Population::~Population (){
262+ void Population::clear (){
235263 for (Individual* ind : this ->individuals ){
236264 delete ind->board ;
237265 delete ind->player ;
238266 delete ind;
239267 }
240268 }
269+
270+ Population::~Population (){
271+ this ->clear ();
272+ }
241273};
0 commit comments