-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAnimal.cpp
More file actions
597 lines (527 loc) · 15.6 KB
/
Animal.cpp
File metadata and controls
597 lines (527 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#include "Animal.h"
#include "Water.h"
#include "Vegetal.h"
#include "World.h"
#include <iostream>
#include <iomanip>
#include <random>
#include <algorithm>
#include <cmath>
using namespace std;
Animal::Animal(double x, double y, int maxSpeed, double damage, double energy, unsigned int maxMating, unsigned int generationNumber, World * world) :
Solid(x, y, config::INITIAL_RADIUS),
m_health(config::MAX_HEALTH),
m_hunger(0),
m_thirst(0),
m_mating(0),
m_maxMating(maxMating),
m_speed(0),
m_energy(energy),
m_generationNumber(generationNumber),
m_world(world),
m_age(0),
m_maxSpeed(maxSpeed),
m_damage(damage),
m_rotation(0),
m_speedPercentage(0),
m_angle(0),
m_fear(0),
m_dead(false),
m_vision(new Vision(*this, m_angle, world->getGridOfEntities()))
{
//Determine if Animal is female or not (1/2 chance)
static std::mt19937 generator(random_device{}());
bernoulli_distribution distribution(0.5);
m_female = distribution(generator);
vector<unsigned int> layerSizes;
for(unsigned int i = 0; i < NB_LAYERS; i++)
{
layerSizes.push_back(LAYER_SIZES[i]);
}
m_brain = new NeuralNetwork(layerSizes);
setCreationDate(world->getWorldAge());
}
Animal::Animal(double x, double y, int maxSpeed, double damage, double energy, unsigned int maxMating, unsigned int generationNumber, World * world, bool sex) : Animal(x, y, maxSpeed, damage, energy, maxMating, generationNumber, world)
{
m_female = sex;
}
Animal::Animal(double x, double y, int maxSpeed, double damage, double energy, unsigned int maxMating, unsigned int generationNumber, World * world, NeuralNetwork * brain, unsigned int mating) :
Animal(x,y,maxSpeed,damage,energy,maxMating,generationNumber,world)
{
m_mating = mating;
m_brain = brain;
}
Animal::~Animal()
{
delete(m_vision);
delete(m_brain);
//delete m_collisionList;
}
int Animal::play()
{
m_age++;
m_energy += config::ENERGY_RECUP;
if(m_energy > config::DEFAULT_ENERGY)
m_energy = config::DEFAULT_ENERGY;
if(m_health <= 0 || m_dead)
{
m_dead = true;
return 0;// if dead no need to continue playing.
//m_world->killEntity(this); // RIP
}
else
{
m_hunger++;
m_thirst++;
}
if(m_hunger >= config::MAX_HUNGER)
{
m_health -= 10;
m_hunger = config::MAX_HUNGER;
}
else if(m_hunger > config::MAX_HUNGER*3/4)
{
m_health--;
}
if(m_thirst >= config::MAX_THIRST)
{
m_health -= 10;
m_thirst = config::MAX_THIRST;
}
else if(m_thirst > config::MAX_THIRST*3/4)
{
m_health--;
}
if(m_mating != m_maxMating)
{
m_mating++;
}
// The animal looks around itself
m_vision->see();
// get mapping of inputs
mappageInput();
// The animal decides what to do
m_nnOutputs = m_brain->run(m_nnInputs);
// get mapping of outputs
mappageOutput();
// The animal moves
// First it turns, then it moves
if(m_rotation != 0)
{
turn(m_rotation);
}
/*if(m_speed > 0)
{
World::mutexCollisionList.lock();
World::mutexGridOfEntities.lock();
move();
World::mutexCollisionList.unlock();
World::mutexGridOfEntities.unlock();
}
else // calcul of collisionList hasn't been effectuated
{
m_world->updateListCollision(this->shared_from_this());
}*/
attack();
eat();
drink();
mate();
m_radius = sqrt(m_age) * config::FATNESS_HERBIVORE + config::INITIAL_RADIUS; // TODO: used FATNESS_ANIMAL, and put it in the parametersWidget
return 0;
}
void Animal::move()
{
if(m_speedPercentage > 0)
{
m_speed = m_speedPercentage * m_maxSpeed / 100.0;
if(m_speed * config::MOVE_ENERGY_LOSS > m_energy)
m_speed = m_energy / config::MOVE_ENERGY_LOSS / 2;
m_energy -= m_speed * config::MOVE_ENERGY_LOSS / 2;
int oldX = getX();
int oldY = getY();
setCoordinate(getX() + cos(m_angle) * m_speed, getY() + sin(m_angle) * m_speed);
m_world->updateGridOfEntities(this->shared_from_this(), oldX, oldY, getX(), getY());
}
m_world->updateListCollision(this->shared_from_this());
//Colision disabled !!!
// vector<weak_ptr<Entity>> animalCollisionList = getSubListSolidCollision();
// if(animalCollisionList.size() != 0)
// {
// //setCoordinate(getX() - cos(m_angle)*m_speed, getY() - sin(m_angle)*m_speed);
// }
}
//TODO: TO FINISH
void Animal::mappageInput()
{
m_nnInputs.clear();
m_nnInputs.push_back((double)m_hunger / (double)config::MAX_HUNGER);
m_nnInputs.push_back((double)m_thirst / (double)config::MAX_THIRST);
m_nnInputs.push_back((double)m_health / (double)config::MAX_HEALTH);
m_nnInputs.push_back((double)m_mating / (double)m_maxMating);
vector<std::shared_ptr<Percepted> > percepted = m_vision->getPercepted();
for(std::shared_ptr<Percepted> p:percepted)
{
shared_ptr<Entity> e = p->getEntity();
if(e != nullptr) {
double typeInputVal = (double)p->getEntity()->getNeralNetworkId();
// Simplify input: remove unuseful information
if((getTypeId() == ID_HERBIVORE && p->getEntity()->getTypeId() == ID_MEAT)
|| (getTypeId() == ID_CARNIVORE && p->getEntity()->getTypeId() == ID_VEGETAL)) {
typeInputVal = 0.0;
}
// Ponderate input with quantity
if(shared_ptr<Resource> res = dynamic_pointer_cast<Resource>(p->getEntity()))
{
typeInputVal *= (double)(res->getQuantity()) / (double)(res->getMaxQuantity());
}
m_nnInputs.push_back(typeInputVal);
m_nnInputs.push_back(p->getDistance() == -1 || typeInputVal == 0.0 ? 0 : ((double)p->getVisionRange() - p->getDistance()) / (double)p->getVisionRange());
}
else //if nothing is percepted
{
m_nnInputs.push_back(0);
m_nnInputs.push_back(0);
}
}
// Memory of the last tick
m_nnInputs.push_back(m_speedPercentage/7);
m_nnInputs.push_back(m_rotation*5);
m_nnInputs.push_back((double)m_fear / (double)config::MAX_FEAR);
}
void Animal::mappageOutput()
{
#ifdef DEBUG
if(m_nnOutputs.size() == 3)
{
std::cerr << "incorect number of nn outputs" << std::endl;
exit(-1);
}
#endif
m_speedPercentage = m_nnOutputs[0]*7;
m_rotation = m_nnOutputs[1]/5;
m_fear = m_nnOutputs[2]*config::MAX_FEAR;
}
void Animal::turn(double angle)
{
if(fabs(angle) * config::TURN_ENERGY_LOSS > m_energy)
angle = m_energy / config::TURN_ENERGY_LOSS / 2;
m_energy -= fabs(angle) * config::TURN_ENERGY_LOSS / 2;
m_angle += angle;
m_angle = Coordinate::modulo2PI(m_angle);
}
// The animal drink one time for each pool it is on
void Animal::drink()
{
if(m_speedPercentage * m_maxSpeed / 100.0 <= config::MAX_SPEED_TO_EAT)
{
vector<weak_ptr<Entity>> waterCollisionList = getSubListCollision(ID_WATER);
for (weak_ptr<Entity> weakWater:waterCollisionList)
{
// remove element from the list with a lambda expression because weak_pointer doesn't have == operator
/*m_collisionList.remove_if([weakWater](weak_ptr<Entity> p)
{ return !( p.owner_before(weakWater) || weakWater.owner_before(p) ); }
);*/
shared_ptr<Entity> waterEntity = weakWater.lock();
if(waterEntity)
{
shared_ptr<Water> water;
if(water = dynamic_pointer_cast<Water>(waterEntity))
{
if(m_thirst > 0)
{
int quantity = std::min(100,(int)m_thirst); //don't drink more than needed (no negative thirst)
World::mutexDrink.lock();
m_thirst -= water->drink(quantity); //drink as much as possible on the water source
World::mutexDrink.unlock();
}
}
}
}
}
}
// The animal drink one time for each pool it is on
void Animal::eat()
{
if(m_speedPercentage * m_maxSpeed / 100.0 <= config::MAX_SPEED_TO_EAT)
{
vector<weak_ptr<Entity>> foodCollisionList = getSubListResourceCollision();
for (weak_ptr<Entity> weakFood:foodCollisionList)
{
// remove element from the list with a lambda expression because weak_pointer doesn't have == operator
/*m_collisionList.remove_if([weakFood](weak_ptr<Entity> p)
{ return !( p.owner_before(weakFood) || weakFood.owner_before(p) ); }
);*/
shared_ptr<Entity> foodEntity = weakFood.lock();
if(foodEntity)
{
tryToEat(foodEntity);
}
}
}
}
void Animal::tryToEat(std::shared_ptr<Entity> food)
{
//yes animal are herbivore...
if(shared_ptr<Vegetal> vegetal = dynamic_pointer_cast<Vegetal>(food))
{
if(m_hunger > 0)
{
int quantity = std::min(config::EAT_MAX_VEGETAL_QUANTITY,(unsigned)m_hunger);
World::mutexVegetal.lock();
m_hunger -= vegetal->eat(quantity);
World::mutexVegetal.unlock();
}
//heal himself
if(m_health < config::MAX_HEALTH && m_thirst < config::MAX_THIRST*3/4)
{
m_health += std::min(config::EAT_MAX_HEALING_VALUE,(unsigned)(config::MAX_HEALTH-m_health));
}
}
}
void Animal::mate()
{
vector<weak_ptr<Entity>> animalCollisionList = getSubListCollision(this->getTypeId());
for(weak_ptr<Entity> weakAnimal:animalCollisionList)
{
shared_ptr<Entity> animalEntity = weakAnimal.lock();
if(animalEntity)
{
if(tryToMate(animalEntity)) //virtual -> try to mate in the good way
{
break;
}
}
}
}
bool Animal::tryToMate(std::shared_ptr<Entity> animalEntity)
{
if(shared_ptr<Animal> animalToMate = dynamic_pointer_cast<Animal>(animalEntity))
{
// this Animal is the female
if(m_female && !animalToMate->isFemale())
{
if(m_mating >= m_maxMating && animalToMate->getMating() == animalToMate->getMaxMating())
{
World::mutexMateList.lock();
m_world->updateMateList(this, animalToMate);
World::mutexMateList.unlock();
//this->reproduce(animalToMate);
return true;
}
}
}
return false;
}
void Animal::attack()
/**
* attack the Animal which are not of the same type as himself
* and if they are in front of him (angle defined in config.h)
* The attack value is stored in m_damage.
*/
{
vector<weak_ptr<Entity>> animalCollisionList = getSubListSolidCollision();
for(weak_ptr<Entity> weakAnimal:animalCollisionList)
{
shared_ptr<Entity> animalEntity = weakAnimal.lock();
if(animalEntity)
{
if(animalEntity->getTypeId() != this->getTypeId())
{
double angle = Coordinate::getAngle(this->getCoordinate(),animalEntity->getCoordinate())-m_angle;
if(std::abs(angle)<=config::MAX_ATTACK_ANGLE)
{
if(shared_ptr<Animal> a=dynamic_pointer_cast<Animal>(animalEntity))
{
World::mutexAttackList.lock();
m_world->updateAttackList(a, m_damage);
World::mutexAttackList.unlock();
}
}
}
}
}
}
void Animal::evolve(NeuralNetwork *bestNN)
// Modify the neuronal network of the animal closer to the best one
{
NeuralNetwork* NN = evolveNN();
std::vector<NeuronLayer> layers = NN->getL();
std::vector<NeuronLayer> bestLayers = bestNN->getL();
const unsigned int layersNum=layers.size();
//for each layer
for (unsigned int layer=0; layer<layersNum; layer++)
{
std::vector<Neuron> neurons = layers.at(layer).getN();
std::vector<Neuron> bestNeurons = bestLayers.at(layer).getN();
const unsigned int neuronsNum = neurons.size();
//for each neuron
for (unsigned int neuron=0; neuron<neuronsNum; neuron++)
{
const std::vector<double> weights = neurons.at(neuron).getWeights();
const std::vector<double> bestWeights = bestNeurons.at(neuron).getWeights();
std::vector<double> newWeights;
//for each weight
for(unsigned int w=0; w<weights.size(); w++)
{ newWeights.push_back(weights.at(neuron)+(bestWeights.at(neuron)-weights.at(neuron))*0.1);
}
neurons.at(neuron).setWeights(newWeights);
}
}
}
void Animal::loseLive(unsigned liveToLose)
{
m_health -= liveToLose;
}
void Animal::addEntityInListCollision(weak_ptr<Entity> e)
{
m_collisionList.push_back(e);
}
void Animal::clearEntityListCollision()
{
m_collisionList.clear();
}
vector<weak_ptr<Entity>> Animal::getSubListCollision(unsigned int idEntity)
{
vector<weak_ptr<Entity>> subListCollision;
for(weak_ptr<Entity> weakEntity:m_collisionList)
{
shared_ptr<Entity> e = weakEntity.lock();
if(e)//if lock worked
{
if(e->getTypeId() == idEntity)
{
subListCollision.push_back(e);
}
}
}
return subListCollision;
}
vector<weak_ptr<Entity>> Animal::getSubListSolidCollision()
{
vector<weak_ptr<Entity>> subListCollision;
for(weak_ptr<Entity> weakEntity:m_collisionList)
{
shared_ptr<Entity> e = weakEntity.lock();
if(e)//if lock worked
{
if(e->getTypeId() >= ID_ANIMAL)
{
subListCollision.push_back(e);
}
}
}
return subListCollision;
}
vector<weak_ptr<Entity>> Animal::getSubListResourceCollision()
{
vector<weak_ptr<Entity>> subListCollision;
for(weak_ptr<Entity> weakEntity:m_collisionList)
{
shared_ptr<Entity> e = weakEntity.lock();
if(e)//if lock worked
{
if(e->getTypeId() < ID_ANIMAL)
{
subListCollision.push_back(e);
}
}
}
return subListCollision;
}
unsigned int Animal::getAge() const
{
return m_age;
}
unsigned int Animal::getMaxSpeed() const
{
return m_maxSpeed;
}
int Animal::getHealth() const
{
return m_health;
}
unsigned int Animal::getHunger() const
{
return m_hunger;
}
unsigned int Animal::getThirst() const
{
return m_thirst;
}
int Animal::getFear() const
{
return m_fear;
}
unsigned int Animal::getMating() const
{
return m_mating;
}
unsigned int Animal::getMaxMating() const
{
return m_maxMating;
}
unsigned int Animal::getEnergy() const
{
return m_energy;
}
double Animal::getScore() const
{
return m_score;
}
double Animal::getDamage() const
{
return m_damage;
}
double Animal::getAngle() const
{
return m_angle;
}
const Vision * Animal::getVision() const
{
return m_vision;
}
const NeuralNetwork * Animal::getBrain() const
{
return m_brain;
}
NeuralNetwork *Animal::evolveNN()
{
return m_brain;
}
bool Animal::isDead() const
{
return m_dead;
}
bool Animal::isFemale() const
{
return m_female;
}
double Animal::getSpeed() const
{
return m_speed;
}
double Animal::getRotation() const
{
return m_rotation;
}
void Animal::resetMating()
{
m_mating = 0;
}
void Animal::setBrain(NeuralNetwork *newBrain)
{
delete(m_brain);
m_brain = newBrain;
}
void Animal::setSex(bool sex)
{
m_female = sex;
}
int Animal::getCurrentCellX() const
{
return getX() / m_world->getCellSizeX();
}
int Animal::getCurrentCellY() const
{
return getY() / m_world->getCellSizeY();
}