|
1 | 1 | #include <cstdint> |
| 2 | +#include <stdexcept> |
2 | 3 | #include <unistd.h> |
3 | 4 | #include "population.h" |
4 | 5 | #include "../game/board.h" |
5 | 6 | #include "../helpers/utils.h" |
| 7 | +#include "chromosome.h" |
| 8 | +#include "gene.h" |
6 | 9 |
|
| 10 | +using std::invalid_argument; |
7 | 11 | using Game::Board; |
| 12 | +using Chromosomes::Chromosome; |
| 13 | +using Genes::Gene; |
8 | 14 | using Utils::random_int; |
9 | 15 |
|
10 | 16 | namespace Genetic{ |
@@ -38,7 +44,7 @@ namespace Genetic{ |
38 | 44 |
|
39 | 45 | void Population::generate_food_positions(uint8_t total, uint8_t w, uint8_t h){ |
40 | 46 | for(size_t _ = 0; _ < total; _++) |
41 | | - this->food_positions.push_back(vec2{random_int(0, h-1), random_int(0, w-1)}); |
| 47 | + this->food_positions.push_back(vec2{(int16_t)random_int(0, h-1), (int16_t)random_int(0, w-1)}); |
42 | 48 | // TODO: refactor this random position to a especialist class or something like this |
43 | 49 | } |
44 | 50 |
|
@@ -134,7 +140,8 @@ namespace Genetic{ |
134 | 140 |
|
135 | 141 | void Population::next_gen(){ |
136 | 142 | Individual** parents = this->select_parents(); |
137 | | - //generate the offspring |
| 143 | + Chromosome* offspring = this->generate_offspring(parents[0]->player->get_chromossome(), parents[1]->player->get_chromossome()); |
| 144 | + |
138 | 145 | //reset individuals |
139 | 146 | //replicate |
140 | 147 | //mutate |
@@ -170,6 +177,30 @@ namespace Genetic{ |
170 | 177 | return parents; |
171 | 178 | } |
172 | 179 |
|
| 180 | + Chromosome* Population::generate_offspring(Chromosome* ch1, Chromosome* ch2){ |
| 181 | + if(ch1->get_size() != ch2->get_size()) |
| 182 | + throw invalid_argument("Both Chromosomes must have the same size!"); |
| 183 | + |
| 184 | + uint64_t ch_size = ch1->get_size(); |
| 185 | + |
| 186 | + Chromosome* offspring = new Chromosome(ch_size); |
| 187 | + Gene* offspring_genes = new Gene[ch_size]; |
| 188 | + |
| 189 | + Gene* ch1_genes = ch1->get_genes(); |
| 190 | + Gene* ch2_genes = ch2->get_genes(); |
| 191 | + |
| 192 | + uint64_t pivot = random_int(0, ch_size); |
| 193 | + for(size_t i = 0; i < ch_size; i++){ |
| 194 | + if(i < pivot) |
| 195 | + offspring_genes[i].set_gene_value(ch1_genes[i].get_gene_value()); |
| 196 | + else |
| 197 | + offspring_genes[i].set_gene_value(ch2_genes[i].get_gene_value()); |
| 198 | + } |
| 199 | + offspring->copy_genes(offspring_genes); |
| 200 | + |
| 201 | + return offspring; |
| 202 | + } |
| 203 | + |
173 | 204 | void Population::append_individual(Individual* ind){ |
174 | 205 | this->individuals.push_back(ind); |
175 | 206 | } |
|
0 commit comments