forked from lastleon/EvolutionSimulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreature.pde
557 lines (490 loc) · 16.7 KB
/
Creature.pde
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
public class Creature {
//// Bewegung
// Position x & y
PVector position;
// Geschwindigkeit in x & y Richtung gespeichert
PVector velocity;
// Verbrauch Land & Wasser
float movementConsumption = 2;
float additionalMovementConsumptionInWater = 10;
// Wasserreibung
float waterFriction = 0.2;
//// Gene
float eatingRate = World.stdEatingRate; // GEN
float maxVelocity = World.stdMaxVelocity; //GEN
float attackValue = World.stdAttackValue; // GEN
float immuneValue = World.stdImmuneValue; // GEN
float meatRate = World.stdMeatRate;
//aussehen
color furColour;
PImage complete;
//// wichtige Werte für die Kreatur
float energy = 1000.0;
float reproductionWaitingPeriod = 0.25;
// wird an Welt & Energielevel skaliert
float diameter;
boolean readyToGiveBirth = false;
double age = 0;
int generation;
//// statische Werte
final static float mutationRate = 0.15;
final static float maxEnergy = 2500.0;
final static float energyConsumption = 5;
final static float birthEnergy = 800;
final static float reproductionWill = 0.4;
final static float reproductionThreshold = 0.5;
final static float mixingThreshold = 0.3;
final static int maxMovementRotationAngle = 20; // Grad
final static float energyConsumptionRotation = 2;
//// Berechnungsvariablen
float lastBirth = 0;
boolean red = false;
float redtime = 0;
boolean inTop10 = false;
int id;
boolean updated = false;
boolean sick = false;
//// Neuronales Netzwerk
NeuralNetwork NN;
// Hiddenlayerwerte
final static int hLAmount = 1;
final static int hLLength = 7;
float memory = 1;
float memory2 = 1;
float fitness = 0;
//// Fühler
Sensor sensor;
// sollte bei 1. Generation verwendet werden
Creature(int x, int y, World world, int ID) {
id = ID;
diameter = world.fW*world.diameterMultiplier;
PGraphics comp = createGraphics(74, 70, JAVA2D);
PImage headR = createImage(head.width,head.height,ARGB);
for(int i = 0; i < headR.width; i++){
for(int j = 0; j < headR.height;j++){
color c = head.get(i,j);
if(c == color(255,0,255)){
c = color(255*meatRate,255*(1-meatRate),0);
fill(c);
}
if(c != color(255)) headR.set(i,j,c);
else headR.set(i,j,color(0,0,0,0));
}
}
comp.beginDraw();
comp.image(bod, 0, 0);
comp.image(headR, 49, 24);
comp.endDraw();
complete = comp.get();
generation = 1;
NN = new NeuralNetwork(hLLength, hLAmount);
velocity = new PVector(maxVelocity, maxVelocity);
velocity.limit(maxVelocity);
position = new PVector(x, y);
sensor = new Sensor(this);
furColour = color((int)random(0, 256), (int)random(0, 256), (int)random(0, 256));
eatingRate += random(-World.stdEatingRate/100, World.stdEatingRate/100); // GEN
maxVelocity += random(-World.stdMaxVelocity/100, World.stdMaxVelocity/100); //GEN
attackValue += random(-World.stdAttackValue/100, World.stdAttackValue/100); // GEN
immuneValue += random(-World.stdImmuneValue/100, World.stdImmuneValue/100); // GEN
meatRate += random(-World.stdMeatRate/100, World.stdMeatRate/100);
}
// 2. Konstruktor, damit die Farbe bei den Nachkommen berücksichtigt werden kann und die Gewichte übergeben werden können
// Elternweights Elternfellfarben g: Generation, f1, f2: Fressrate, mG1, mG2: maxGeschwindigkeit, a1, a2: Angriffswert
Creature(int x, int y, Matrix[] weights1, Matrix[] weights2, color furColour1, color furColour2, int g, float f1, float mG1, float a1, float m1, float f2, float mG2, float a2,float m2, int ID) {
bod = loadImage("Body.png");
head = loadImage("Head.png");
PImage headR = createImage(head.width,head.height,ARGB);
for(int i = 0; i < headR.width; i++){
for(int j = 0; j < headR.height;j++){
color c = head.get(i,j);
if(c == color(255,0,255)){
c = color(255*meatRate,255*(1-meatRate),0);
fill(c);
}
headR.set(i,j,c);
}
}
PGraphics comp = createGraphics(74, 70, JAVA2D);
comp.beginDraw();
comp.image(bod, 0, 0);
comp.image(headR, 49, 24);
comp.endDraw();
complete = comp.get();
id = ID;
diameter = map.getFieldWidth()*map.diameterMultiplier;
// Gene der Eltern werden vermischt & mutiert
eatingRate = mutate(mixGenes(f1, f2));
maxVelocity = mutate(mixGenes(mG1, mG2));
attackValue = mutate(mixGenes(a1, a2));
meatRate = mutate(mixGenes(m1,m2));
generation = g+1;
// furColour wird random aus beiden Elternteilen gewählt
if (random(0, 1)>0.5) {
furColour = furColour1;
} else {
furColour = furColour2;
}
// Fellfarbe wird mutiert
furColour = mutateFurColour(furColour);
// Gewichtmatrizen der Eltern werden vermischt & mutiert
NN = new NeuralNetwork(hLLength, mutate(mixMatrix(weights1, weights2)));
velocity = new PVector(maxVelocity, maxVelocity);
velocity.limit(maxVelocity);
position = new PVector(x, y);
sensor = new Sensor(this);
}
// Kreatur wird gemalt
public void drawCreature() {
// Durchmesser an Energielevel angepasst
diameter = map.stdDiameter * energy/500 + 5 ;
for (int x = 0; x < 74; x++) {
for (int y = 0; y < 70; y++) {
if (complete.get(x, y) == color(66, 255, 0) || complete.get(x, y) == color(255, 66, 0) || complete.get(x, y) == color(125) ) {
complete.set(x, y, furColour);
}
}
}
// nach Angriff blinkt Kreatur 30 Frames rot
if (!sick) {
if (redtime != 0) {
redtime--;
if (red) {
for (int x = 0; x < 74; x++) {
for (int y = 0; y < 70; y++) {
if (complete.get(x, y) == furColour) {
complete.set(x, y, color(255, 66, 0));
}
}
}
}
}
} else {
for (int x = 0; x < 74; x++) {
for (int y = 0; y < 70; y++) {
if (complete.get(x, y) == furColour) {
complete.set(x, y, color(125));
}
}
}
}
if (redtime %4==0) {
red = !red;
}
stroke(0);
sensor.drawSensor();
// Körper
pushMatrix();
translate(position.x, position.y);
rotate(velocity.heading());
translate(-position.x, -position.y);
int newW = floor(complete.width*diameter/map.stdDiameter);
int newH = floor(complete.width*diameter/map.stdDiameter);
image(complete, position.x - newW/2, position.y - newH/2,newW,newH);
popMatrix();
//ellipse(position.x, position.y, diameter, diameter );
// wenn in Top 10, dann werden Werte angezeigt
/*if (inTop10) {
textSize(15*(diameter/(map.stdDiameter+5)));
textAlign(CENTER);
text("E: " + int(energy), position.x, position.y - 54);
text("FR: " + round(eatingRate*100)/100, position.x, position.y-43);
text("V: " + round(maxVelocity*100)/100, position.x, position.y-32);
text("RW: " + round(reproductionWaitingPeriod*100)/100, position.x, position.y-21);
text("A: " + round(attackValue*100)/100, position.x, position.y-10);
}*/
}
void updateFitness() {
fitness = this.calculateFitnessStandard();
if (map.fitnessMaximum<fitness) {
map.fitnessMaximum = fitness;
}
}
// NeuralNetwork input
public void input() {
// Werte auf 0 bis 1 genormt
// Geschwindigkeit
NN.setInputNVelocity(map(velocity.mag()/maxVelocity, 0, 1, -1, 1));
// eigene Energie
NN.setInputNEnergy(map(energy/maxEnergy, 0, 1, -1, 1));
// Feldart
NN.setInputNFieldType(map(map.getField((int)position.x, (int)position.y).isLandInt(), 0, 1, -1, 1));
// Memory
NN.setInputNMemory(memory);
NN.setInputNMemory2(memory2);
/*
// Bias // immer 6
NN.setInputNBias(6);
// Richtung
NN.setInputNDirection(map(degrees(velocity.heading()), -180, 180, -6, 6));
// Paarungspartner/Gegner Fitness
*/
Creature c = sensor.getSensorPartner();
if (c != null) {
NN.setInputNPartnerFitness(map(c.fitness/map.fitnessMaximum, 0, 1, -1, 1));
} else {
NN.setInputNPartnerFitness(0);
}
//// Fühler
// Gegnerenergie
NN.setInputNSensorEnemyEnergy(map(sensor.getSensorEnemyEnergy()/maxEnergy, 0, 1, -1, 1));
// Feldenergie
NN.setInputNSensorFieldEnergy(map(sensor.getSensorFieldEnergy()/Field.maxOverallEnergy, 0, 1, -1, 1));
// Feldart
NN.setInputNSensorFieldType(map(sensor.getSensorFieldType(), 0, 1, -1, 1));
}
// Bewewgung
public void move(float v, float angle) { // Rotationswinkel in Grad
if (v<maxVelocity && v>=0) { // Bewegungsverbrauch passt sich an momentane Geschwindigkeit an
energy -= movementConsumption*(v/World.stdMaxVelocity);
velocity.rotate(radians(angle));
this.sensor.rotateSensor(angle);
energy -= (angle/maxMovementRotationAngle)*energyConsumptionRotation;
velocity.setMag(v);
// im Wasser bewegt sich die Kreatur langsamer und verbraucht mehr Energie
if (!map.getField((int)position.x, (int)position.y).isLand()) {
position.add(velocity.mult(1-waterFriction));
energy -= additionalMovementConsumptionInWater;
} else {
position.add(velocity);
}
// Kreatur wird auf die gegenüberliegende Seite teleportiert, wenn sie außerhalb der Map ist
if (position.x > map.worldBounds) { // wenn zu weit rechts
position.set(position.x-map.worldBounds, position.y);
}
if (position.x < 0) { // wenn zu weit links
position.set(map.worldBounds+position.x, position.y); // + position.x, weil es immer ein negativer Wert ist
}
if (position.y > map.worldBounds) { // wenn zu weit unten
position.set(position.x, position.y-map.worldBounds);
}
if (position.y < 0) { // wenn zu weit oben
position.set(position.x, map.worldBounds+position.y); // + position.y, weil es immer ein negativer Wert ist
}
}
}
// Angriff auf Gegner
public void attack(float will) {
if (will > 0.5) {
addEnergy(-energyConsumption*(attackValue/World.stdAttackValue));
// Opfer nur DIREKT vor dem Kreatur (d.h. in Geschwindigkeitsrichtung) kann angegriffen werden
PVector victimPosition = new PVector(cos(velocity.heading())*(diameter/2)+position.x, sin(velocity.heading())*(diameter/2)+position.y);
Creature victim = map.getCreature(victimPosition);
// verhindert, dass Kreatur sich selbst angreift
if (victim==this) {
victim = null;
}
if (!(victim == null)) {
victim.addEnergy(-attackValue);
this.addEnergy((attackValue/World.stdAttackValue)*100 * meatRate);
if (energy>maxEnergy) { // Kreatur-Energie ist über dem Maximum
energy = maxEnergy;
}
victim.hit();
}
}
}
// Grundverbrauch
public void live() {
energy -= energyConsumption*(age/15);
if (sick) {
energy -= energyConsumption * age/15;
if (random(immuneValue, 200) > 199) {
sick = false;
}
}
}
public void hit() {
redtime = 30;
}
// Fitnessfunktion
public float calculateFitnessStandard() { // berechnet die Fitness der Kreatur im Bezug auf die Standardwerte
float bias = 0.1;
float a = log((float)(age+1));
float g = log((float)(generation))*1.5;
float eatingRate = ((this.getEatingRate() - World.stdEatingRate)/World.stdEatingRate)*2;
float maxV = ((this.getMaxVelocity() - World.stdMaxVelocity)/World.stdMaxVelocity)*2;
float attack = ((this.getAttackValue() - World.stdAttackValue)/World.stdAttackValue)*2;
float result = (bias + a + g + eatingRate + maxV + attack);
if (result < 0) {
result = 0;
}
return result;
}
// Fressen
public void eat(float will) {
Field field = map.getField((int)position.x, (int)position.y);
if (will > 0.5 && field.isLand()) {
energy -= energyConsumption*(age/20);
float newFieldEnergy = field.getEnergy() - eatingRate;
if (newFieldEnergy>=0) { // Feld hat genug Energie
energy += eatingRate;
field.setEnergy((int)newFieldEnergy);
} else { // Feld hat zu wenig Energie
energy += field.getEnergy();
field.setEnergy(0);
}
if (energy>maxEnergy) { // Kreatur-Energie ist über dem Maximum
field.setEnergy((int)(field.getEnergy()+(energy-maxEnergy)));
energy = maxEnergy;
}
}
}
public boolean collision(Creature c) {
return map.creatureDistance(this, c) <= diameter;
}
public color mutateFurColour(color furColour) {
float r = red(furColour) + red(furColour) * random(-0.3, 0.3);
float g = green(furColour) + green(furColour) * random(-0.3, 0.3);
float b = blue(furColour) + blue(furColour) * random(-0.3, 0.3);
if (r < 0) {
r = 0;
} else if (r > 255) {
r = 255;
}
if (g < 0) {
g = 0;
} else if (g > 255) {
g = 255;
}
if (b < 0) {
b = 0;
} else if (b > 255) {
b = 255;
}
return color(r, g, b);
}
// mutiert Gewichte
public Matrix mutate(Matrix m) {
for (int x=0; x<m.rows; x++) {
for (int y=0; y<m.cols; y++) {
if (random(0, 1)>0.3) {
float newValue = mutate(m.get(x, y));
if (newValue > 1) {
newValue = 1;
} else if (newValue < 0) {
newValue = 0;
}
m.set(x, y, newValue);
}
}
}
return m;
}
// mutiert einzelnen Wert
public float mutate(float x) { // x ist der Wert, der mutiert wird
if (x > 0 && random(0, 1)>0.5) {
x += random(-mutationRate, mutationRate)*((log(x)/log(10))+1);
}
if (x<0) x = 0;
return x;
}
// mutiert ganze Matrix
public Matrix[] mutate(Matrix[] m) {
Matrix[] returnMatrix = new Matrix[m.length];
for (int i=0; i<m.length; i++) {
returnMatrix[i] = mutate(m[i]);
}
return returnMatrix;
}
// vermischt zwei Matrizen
public Matrix mixMatrix(Matrix c1, Matrix c2) { // nimmt an, dass c1 und c2 gleich gross sind
Matrix mixedMatrix = new Matrix(c1.rows, c1.cols);
mixedMatrix.copyM(c1);
// mixedMatrix wird zu Kopie von c1
// Gewichte werden vermischt
for (int x=0; x<c1.rows; x++) {
for (int y=0; y<c1.cols; y++) {
if (random(0, 1) > mixingThreshold) {
mixedMatrix.set(x, y, c2.get(x, y));
}
}
}
return mixedMatrix;
}
// vermischt zweit Matrizen-Arrays
public Matrix[] mixMatrix(Matrix[] m1, Matrix[] m2) {
Matrix[] returnMatrix = new Matrix[m1.length];
for (int i=0; i<returnMatrix.length; i++) {
returnMatrix[i] = this.mixMatrix(m1[i], m2[i]);
}
return returnMatrix;
}
public float mixGenes(float g1, float g2) {
if (random(0, 1)>reproductionThreshold) {
return g1;
} else return g2;
}
public void age() {
age += map.getTimePerFrame();
// Alter wird gerundet
float newAge = (float)(age * map.getTimeMultiplier());
age = (double)floor(newAge) / (double)map.getTimeMultiplier();
// check, ob Kreatur geburtsbereit ist
if (age - lastBirth >= reproductionWaitingPeriod) {
readyToGiveBirth = true;
} else {
readyToGiveBirth = false;
}
}
////speichern und laden
public void memorise(float m, float m2) {
memory = m;
memory2 = m2;
}
public void addEnergy(float e) {
energy += e;
}
public void setEnergy(float e) {
energy = e;
}
public void setLastBirth(float lB) {
lastBirth = lB;
}
// getter
public boolean getStatus() {
return energy>0;
}
public float getMaxVelocity() {
return maxVelocity;
}
public float getEnergy() {
return energy;
}
public float getMaxEnergy() {
return maxEnergy;
}
public PVector getPosition() {
return position;
}
public double getAge() {
return age;
}
public boolean isReadyToGiveBirth() {
return readyToGiveBirth;
}
public color getFurColour() {
return furColour;
}
public float getDiameter() {
return diameter;
}
public int getGeneration() {
return generation;
}
public float getEatingRate() {
return eatingRate;
}
public float getAttackValue() {
return attackValue;
}
public float getMeatRate(){
return meatRate;
}
public float getReproductionWaitingPeriod() {
return reproductionWaitingPeriod;
}
public int getID() {
return id;
}
}