-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.cpp
522 lines (474 loc) · 14.3 KB
/
agent.cpp
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
#include "agent.h"
int Agent::idCounter;
/**
* A helper function for moveWCombat.
* Returns boolean true if site is vulnerable to retaliation
**/
bool isVulnerableToRetaliation(Agent* agent[GRIDW*GRIDH], int x, int y, int myGroup, int myVision, double myWealth){
for(int cx=x-myVision; cx<=x+myVision; ++cx){
for(int cy=y-myVision; cy<=y+myVision; ++cy){
int pcx = cx < 0 ? GRIDW+cx : cx >= GRIDW ? cx-GRIDW : cx;
int pcy = cy < 0 ? GRIDH+cy : cy >= GRIDH ? cy-GRIDH : cy;
if(pcx!=x && pcy!=y) continue;
if(agent[pcy*GRIDW + pcx]==NULL) continue;
Agent* temp = agent[pcy*GRIDW + pcx];
if(temp->tagString.getGroup() != myGroup && temp->getWealth() > myWealth)
return true;
}
}
return false;
}
Agent::Agent(){
this->setVariables();
}
Agent::Agent(int x, int y){
this->setVariables();
this->x= x;
this->y= y;
this->setPosition((float) x*TILEW, (float) y*TILEH);
}
Agent::Agent(int x, int y, double wealth, double met, int vis, TagString tags, ImmuneSys immuneSys)
: genotype(immuneSys) {
this->setVariables();
this->x= x;
this->y= y;
this->sugar= wealth;
this->sugarStart= static_cast<int>(wealth);
this->vision= vis;
this->metabolism= met;
this->setPosition((float) x*TILEW, (float) y*TILEH);
this->tagString = tags;
this->phenotype = immuneSys;
}
void Agent::setVariables(){
this->setPointCount(12);
this->id = ++idCounter;
this->setFillColor(sf::Color::Red);
this->x = 0;
this->y = 0;
this->setPosition((float) x*TILEW, (float) y*TILEH);
this->setRadius(RADIUS);
this->maxAge = ((rand()% (40 * AGEM)) + 60 * AGEM); // 600 - 1000
this->age= ((rand()% (50 * AGEM))+ 0 * AGEM); //0 - 500
this->gender = (rand()% 2) ? M : F; //shortcut for M=0 F=1;
this->sugar= (rand()% 50)+50;
this->sugarStart= static_cast<int>(sugar);
this->spices= (rand()% 50)+50;
this->vision= (rand()% MAXVISION)+1;
this->metabolism= (rand()% MAXMETABOL)+1;
this->metabolismSpice=(rand()% MAXMETABOL)+1;
this->puberty = ((rand()% (4 * AGEM))+ 12 * AGEM); //12 - 15
this->endFertility =( (gender==F) ? ((rand()% (11 * AGEM))+ 40 * AGEM) : ((rand()% (11 * AGEM))+ 50 * AGEM) );
this->dead = false;
this->phenotype = this->genotype;
this->metabolicFee =0;
this->moved = false;
}
void Agent::update(Tile grid[][GRIDH], Agent * agent[GRIDW*GRIDH]){
//coloring
if(tagString.getGroup())
setFillColor(sf::Color::Blue);
else
setFillColor(sf::Color::Red);
sugar -= metabolism + metabolicFee;
if(MOVEMENT==WithTrade){
spices -= metabolismSpice + metabolicFee;
}
//pollution
if(MOVEMENT==WithPollution){
grid[x][y].genPollutionM(metabolism);
}
age++;
//death rule
if(isDead()){
this->dead = true;
//taken
std::list<Loan>::iterator it = loansTaken.begin();
while(it!=loansTaken.end()){
it->lender->removeLoanGiven((*it));
it = loansTaken.erase(it);
}
//given
it = loansGiven.begin();
while(it!=loansGiven.end()){
it->borrower->removeLoanTaken((*it));
it = loansGiven.erase(it);
}
return;
}
//movement rule
if(MOVEMENT==WithCombat)
moveWCombat(grid, agent);
else
move(grid);
return;
}
void Agent::move(Tile grid[][GRIDH]){
std::vector<sf::Vector2i> points;
double high = 0;
double lvl = 0;
int minDist = vision;
for(int a=x-vision; a<=x+vision; a++){
for(int b=y-vision; b<=y+vision; b++){
if(a!=x && b!=y) continue;
int Cx = a < 0 ? GRIDW+a : a >= GRIDW ? a-GRIDW : a;
int Cy = b < 0 ? GRIDH+b : b >= GRIDH ? b-GRIDH : b;
if(grid[Cx][Cy].isTaken()) continue;
if(MOVEMENT==WithPollution){
lvl = grid[Cx][Cy].getS_Pratio();
}
else if(MOVEMENT==WithTrade){
//welfare
double sug = grid[Cx][Cy].getSugarLvl();
double spi = grid[Cx][Cy].getSpiceLvl();
lvl = static_cast<double>(this->welfare(this->sugar+sug, this->spices+spi));
}
else{
lvl = grid[Cx][Cy].getSugarLvl();
}
int dist = abs(x-a + y-b);
if(lvl == high && dist==minDist){
points.push_back(sf::Vector2i(Cx,Cy));
}
else if(lvl >= high && dist <= minDist){
points.clear();
points.push_back(sf::Vector2i(Cx,Cy));
high = lvl;
minDist = dist;
}
}
}
if(points.size()){
// if we have more than one possible destination then pick one randomly
int random = rand() % points.size();
int oldx = x; int oldy = y;
this->x= points.at(random).x;
this->y= points.at(random).y;
grid[oldx][oldy].freeUp();
setPosition((float) x*TILEW, (float) y*TILEH);
}
sugar += grid[x][y].eat();
spices += grid[x][y].eatSpice();
//else stay on the same tile cause you cant move
}
// code copying;
//should be fixed the same way as normal move function
void Agent::moveWCombat(Tile grid[][GRIDH], Agent* agent[GRIDW*GRIDH]){
std::vector<pointWCombat> points;
int high = 0;
int myGroup = this->tagString.getGroup();
for(int a=x-vision; a<=x+vision; a++){
int aT = a < 0 ? GRIDW+a : a >= GRIDW ? a-GRIDW : a;
Agent* temp = agent[y*GRIDW + aT];
if(grid[aT][y].isTaken()
&& (temp->tagString.getGroup()==myGroup
|| temp->getWealth() > this->getWealth()
|| isVulnerableToRetaliation(agent, aT, y, myGroup, this->getVision(), this->getWealth()) )) {
continue;
}
int lvl = grid[aT][y].getSugarLvl();
int bonusSugar = 0;
if(temp)
bonusSugar = static_cast<int>(MIN(LOOTLIMIT, floor(temp->getWealth())));
lvl += bonusSugar;
if(lvl == high){
points.push_back(pointWCombat(aT,y,abs(x-a), bonusSugar, temp));
}
else if(lvl > high){
points.clear();
high = lvl;
points.push_back(pointWCombat(aT,y,abs(x-a), bonusSugar, temp));
}
}
for(int a=y-vision; a<=y+vision; a++){
int aT = a < 0 ? GRIDH+a : a >= GRIDH ? a-GRIDH : a;
Agent* temp = agent[aT*GRIDW + x];
if(grid[x][aT].isTaken()
&& (temp->tagString.getGroup()==myGroup
|| temp->getWealth() > this->getWealth()
|| isVulnerableToRetaliation(agent, x, aT, myGroup, this->getVision(), this->getWealth()) )) {
continue;
}
int lvl = grid[x][aT].getSugarLvl();
int bonusSugar=0;
if(temp)
bonusSugar = static_cast<int>(MIN(LOOTLIMIT, floor(temp->getWealth())));
lvl += bonusSugar;
if(lvl == high){
points.push_back(pointWCombat(x,aT,abs(y-a), bonusSugar, temp));
}
else if(lvl > high){
points.clear();
high = lvl;
points.push_back(pointWCombat(x,aT,abs(y-a), bonusSugar, temp));
}
}
int random;
if(points.size()){
//find the largest CLOSEST sugar tile
std::sort( points.begin(), points.end() );
int min = points.at(0).dist;
for(unsigned int i=1;i<points.size();++i){
if(points.at(i).dist>min){
points.erase(points.begin()+i);
i--;
}
}
// if we have more than one possible destination then pick one randomly
random = rand() % points.size();
int oldx = x; int oldy = y;
this->x= points.at(random).x;
this->y= points.at(random).y;
grid[oldx][oldy].freeUp();
if(points.at(random).agent)
points.at(random).agent->kill( points.at(random).sugar );
this->addSugar( points.at(random).sugar);
setPosition((float) x*TILEW, (float) y*TILEH);
}
sugar += grid[x][y].eat();
//else stay on the same tile cause you cant move
}
void Agent::sex(Tile grid[][GRIDH], Agent* agent[GRIDW*GRIDH], Agent* &a){
int xT = a->getCoord().x;
int yT = a->getCoord().y;
if((*a).isFertile() && this->isFertile() && (*a).gender != this->gender ){
//possible children locations
std::vector<sf::Vector2i> fields;
fields.push_back(sf::Vector2i((x+1)>=GRIDW?x+1-GRIDW:x+1, y));
fields.push_back(sf::Vector2i((x-1)<0?x-1+GRIDW:x-1, y));
fields.push_back(sf::Vector2i(x, (y+1)>=GRIDH?y+1-GRIDH:y+1));
fields.push_back(sf::Vector2i(x, (y-1)<0?y-1+GRIDH:y-1));
fields.push_back(sf::Vector2i((xT+1)>=GRIDW?xT+1-GRIDW:xT+1, yT));
fields.push_back(sf::Vector2i((xT-1)<0?xT-1+GRIDW:xT-1, yT));
fields.push_back(sf::Vector2i(xT, (yT+1)>=GRIDH?yT+1-GRIDH:yT+1));
fields.push_back(sf::Vector2i(xT, (yT-1)<0?yT-1+GRIDH:yT-1));
std::vector<sf::Vector2i>::iterator fieldsIt= fields.begin();
while(fieldsIt != fields.end()){
if(!grid[(*fieldsIt).x][(*fieldsIt).y].isTaken()){
break;
}
fieldsIt++;
}
if(fieldsIt == fields.end())
return;
double childMet = (rand()%2) ? this->getMetabolRate() : (*a).getMetabolRate() ;
int childVis = (rand()%2) ? this->vision : (*a).vision ;
TagString tempTag;
tempTag.setFromParents(this->tagString, a->tagString);
ImmuneSys tempImmu;
tempImmu.setFromParents(this->genotype, a->genotype);
//childMet = this->getMetabolRate() | (*it).getMetabolRate();
//childVis = this->vision & (*it).vision;
Agent *child = new Agent((*fieldsIt).x, (*fieldsIt).y,
this->sugarStart/2+(*a).sugarStart/2,
childMet,
childVis,
tempTag,
tempImmu);
this->sugar -= this->sugarStart/2;
(*a).sugar -= (*a).sugarStart/2;
int s = grid[(*fieldsIt).x][(*fieldsIt).y].eat();
child->addSugar(s);
agent[(*fieldsIt).y * GRIDW + (*fieldsIt).x] = child;
int childId = (child)->getId();
(*a).addChild(childId);
this->addChild(childId);
}
}
void Agent::trade(Agent* &a){
double myMRS = this-> getMRS();
double hisMRS = a-> getMRS();
if(myMRS == hisMRS) return;
double p = sqrt(myMRS * hisMRS);//geometric mean
double sugarExch = 1;
double spicesExch = 1;
if(p>1) spicesExch = p;
else if(p<1) sugarExch = 1/p;
//sugar ->>> a
//spice <<<- a
if(myMRS < hisMRS){
double wPre1 = this->welfare(this->sugar, this->spices);
double wPost1 = this->welfare(this->sugar - sugarExch, this->spices + spicesExch);
double wPre2 = a->welfare(a->getWealth(), a->getSpices());
double wPost2 = a->welfare(a->getWealth() + sugarExch, a->getSpices() - spicesExch);
double myMRSnew = this->getMRS(-sugarExch, +spicesExch);
double hisMRSnew = a->getMRS(+sugarExch, -spicesExch);
//are they better off, is there a crossover?
if(wPre1<wPost1 && wPre2<wPost2 && myMRSnew<hisMRSnew){
//make trade
this->subSugar(sugarExch);
this->addSpices(spicesExch);
a->addSugar(sugarExch);
a->subSpices(spicesExch);
this->trade(a);
}
}
//sugar <<<- a
//spice ->>> a
else if(myMRS > hisMRS){
double wPre1 = this->welfare(this->sugar, this->spices);
double wPost1 = this->welfare(this->sugar + sugarExch, this->spices - spicesExch);
double wPre2 = a->welfare(a->getWealth(), a->getSpices());
double wPost2 = a->welfare(a->getWealth() - sugarExch, a->getSpices() + spicesExch);
double myMRSnew = this->getMRS(+sugarExch, -spicesExch);
double hisMRSnew = a->getMRS(-sugarExch, +spicesExch);
//are they better off, is there a crossover?
if(wPre1<wPost1 && wPre2<wPost2 && myMRSnew>hisMRSnew){
//make trade
this->addSugar(sugarExch);
this->subSpices(spicesExch);
a->subSugar(sugarExch);
a->addSpices(spicesExch);
this->trade(a);
}
}
}
double Agent::welfare(double w1, double w2){
double mt = metabolism+metabolismSpice;
return std::pow(w1, metabolism/mt) * std::pow(w2, metabolismSpice/mt);
}
double Agent::getMRS(double sug, double spi){
return (metabolism*(spices+spi))/(metabolismSpice*(sugar+sug));
}
bool Agent::isFertile(){
return (age>=puberty && age<endFertility && sugar>=sugarStart);
}
double Agent::getWealth(){
return sugar;
}
double Agent::getSpices(){
return spices;
}
double Agent::getMetabolRate(){
return metabolism;
}
sf::Vector2i Agent::getCoord(){
return sf::Vector2i((x), (y));
}
Sex Agent::getGender(){
return gender;
}
int Agent::getVision(){
return vision;
}
void Agent::addChild(int child){
children.push_back(child);
}
void Agent::addSugar(double amount){
if(amount>0) sugar+= amount;
}
void Agent::subSugar(double amount){
if(amount>0) sugar-= amount;
}
void Agent::addSpices(double amount){
if(amount>0) spices+= amount;
}
void Agent::subSpices(double amount){
if(amount>0) spices-= amount;
}
void Agent::leaveLegacy(Agent* agent[GRIDW*GRIDH]){
if(sugar<=0) return;
//what if no children?
int sugareach = (int)floor(sugar/children.size());
std::vector<int>::iterator cit=children.begin();
while(cit!=children.end()){
for(int i=0; i<GRIDW*GRIDH; ++i){
if(agent[i])
if( (*(agent[i])).getId() == (*cit) )
{
(*(agent[i])).addSugar(sugareach);
break;
}
}
++cit;
}
}
int Agent::getId(){
return id;
}
void Agent::kill(int sugarTaken){
this->sugar -= sugarTaken>0 ? sugarTaken : 0;
this->dead = true;
}
bool Agent::isDead(){
return dead || (sugar <=0 || age>maxAge || (MOVEMENT==WithTrade && spices<=0));
}
void Agent::receiveDisease(Disease disease){
if(phenotype.isSubstring(disease)) return;
for (std::vector<Disease>::iterator it = diseases.begin(); it != diseases.end(); ++it)
if((*it)==disease) return;
diseases.push_back(disease);
metabolicFee += 0.5;
}
void Agent::giveDisease(Agent* &a){
if(diseases.size()==0) return;
int random = 0;
if(diseases.size() > 1)
random = rand() % diseases.size();
a->receiveDisease(diseases.at(random));
}
void Agent::immuneResponse(){
for (std::vector<Disease>::iterator it = diseases.begin(); it != diseases.end(); ){
if(phenotype.affected((*it)))
{
//assuming the disease cannot be deleted, only its symptoms can be cured
//it = diseases.erase(it);
++it;
}
else
++it;
}
metabolicFee = diseases.size() * 0.5;
}
int Agent::canLend(){
if(age>=endFertility) return sugar/2;
if(age>=puberty && sugar>sugarStart) return sugar-sugarStart;
return 0;
}
bool Agent::wantsToBorrow(){
int total=0;
for(std::list<Loan>::iterator it = loansTaken.begin(); it!=loansTaken.end(); ++it){
total += (*it).toRepay();
}
return ((age>=puberty && age<endFertility && sugar<sugarStart) && (sugar>(metabolism+total)));
}
void Agent::takesLoan(Loan l){
sugar += l.amount;
loansTaken.push_back(l);
}
void Agent::givesLoan(Loan l){
sugar -= l.amount;
loansGiven.push_back(l);
}
void Agent::removeLoanGiven(Loan l){
loansGiven.erase(std::remove(loansGiven.begin(), loansGiven.end(), l), loansGiven.end());
}
void Agent::removeLoanTaken(Loan l){
loansTaken.erase(std::remove(loansTaken.begin(), loansTaken.end(), l), loansTaken.end());
}
void Agent::payDebts(int time){
std::list<Loan>::iterator it = loansTaken.begin();
while(it!=loansTaken.end()){
if(it->takenOn + CREDITDURATION <= time){
int amount = it->toRepay();
if(sugar<amount){
int half = amount/2;
it->lender->addSugar(half);
this->subSugar(half);
Loan loan(it->lender, this, half, time);
loansTaken.push_front(loan);
it->lender->removeLoanGiven(*it);
loan.lender->givesLoan(loan);
it = loansTaken.erase(it);
}
else{
it->lender->addSugar(amount);
this->subSugar(amount);
it->lender->removeLoanGiven(*it);
it = loansTaken.erase(it);
}
}
else
++it;
}
}