-
Notifications
You must be signed in to change notification settings - Fork 1
/
Neat.js
2324 lines (1972 loc) · 82.4 KB
/
Neat.js
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//this is a template to add a NEAT ai to any game
class Player {
constructor(differentWorld) {
this.fitness = 0;
this.vision = []; //the input array fed into the neuralNet
this.decision = []; //the out put of the NN
this.unadjustedFitness;
this.lifespan = 0; //how long the player lived for this.fitness
this.bestScore = 0; //stores the this.score achieved used for replay
this.dead = false;
this.kindaDead = false; //this is true when the player has died but deadcount isn't up
this.score = 0;
this.gen = 0;
if (differentWorld) {
this.world = otherWorld;
} else {
this.world = getFreeWorld();
}
this.shirtColorR = floor(random(255));
this.shirtColorG = floor(random(255));
this.shirtColorB = floor(random(255));
this.lastGrounded = 0;
this.genomeInputs = 5;
this.genomeOutputs = 2;
this.brain = new Genome(this.genomeInputs, this.genomeOutputs);
this.car;
// this.world.SetContactListener(listener);
//
// this.ground = new Ground(this.world);
// this.ground.cloneFrom(groundTemplate);
// var timer = millis();
//
// this.ground.setBodies(this.world);
// timer = millis() - timer;
this.isCB = (floor(random(2)) == 0) ? true : false;
this.deadCount = 50;
this.motorState = 2;
}
addToWorld() {
this.car = new Car(350, spawningY, this.world, this);
this.car.setShirt();
this.car.person.head.isCB = this.isCB;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
show() {
if (!this.kindaDead || this.deadCount > 0) {
this.car.show();
if (!shownGround) {
grounds[0].show();
shownGround = true;
}
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
move() {}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
update() {
if (this.car.dead) {
this.kindaDead = true;
}
if (!this.kindaDead || this.deadCount > 0) {
// this.world.Step(1 / 30, 10, 10);
this.lifespan++;
this.car.update();
} else {
this.dead = true;
}
if (this.kindaDead) {
this.deadCount--;
}
this.score = max(1, floor((this.car.maxDistance - 349) / 10));
if (this.score > currentBestPlayer.score || currentBestPlayer.dead) {
currentBestPlayer = this;
}
if (this.dead) {
this.removePlayerFromWorld();
}
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
look() {
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<replace
this.vision = [];
this.vision[0] = this.car.chassisBody.GetAngle();
while (this.vision[0] < 0) {
this.vision[0] += 2 * PI;
}
this.vision[0] = (this.vision[0] + PI) % (2 * PI);
this.vision[0] = map(this.vision[0], 0, 2 * PI, 0, 1);
this.lastGrounded++;
if (this.car.wheels[0].onGround || this.car.wheels[1].onGround) {
this.vision[1] = 1;
this.lastGrounded = 0;
} else {
if (this.lastGrounded < 10) {
this.vision[1] = 1;
} else {
this.vision[1] = 0;
}
}
//
// this.vision[2] = map(this.car.chassisBody.GetLinearVelocity().x, -17, 17, -1, 1);
// this.vision[3] = map(this.car.chassisBody.GetLinearVelocity().y, -12, 12, -1, 1);
this.vision.push(map(this.car.chassisBody.GetAngularVelocity(), -4, 4, -1, 1));
// this.vision[3] = this.car.chassisBody.GetLinearVelocity().y;
// this.vision[4] = this.car.chassisBody.GetAngularVelocity();
//
//
//
let temp = (groundTemplate.getPositions(this.car.chassisBody.GetPosition().x, 2, 5));
let first = temp[0];
this.vision.push(map(constrain(first - this.car.chassisBody.GetPosition().y - this.car.chassisHeight / SCALE, 0, 10), 0, 10, 0, 1));
for (var i = 1; i < temp.length; i++) {
temp[i] -= first;
temp[i] = map(temp[i], -3, 3, -1, 1);
this.vision.push(temp[i]);
}
//
// let oi = groundTemplate.getPositions(this.car.chassisBody.GetPosition().x, 10, 1);
//
// var totalDifference = 0;
// for (var i = 1; i < oi.length; i++) {
// totalDifference += max(0, oi[i - 1] - oi[i]);
// }
//
// if (frameCount % 100 == 0) {
// console.log(totalDifference);
// }
// groundTemplate.showPoints(this.car.chassisBody.GetPosition().x, 10, 1);
// createDiv(this.vision[0]);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//gets the output of the this.brain then converts them to actions
think() {
var max = 0;
var maxIndex = 0;
//get the output of the neural network
this.decision = this.brain.feedForward(this.vision);
for (var i = 0; i < this.decision.length; i++) {
if (this.decision[i] > max) {
max = this.decision[i];
maxIndex = i;
}
}
if (max < 0.6) {
if (this.motorState == 2) {
return;
}
this.car.motorOff();
this.motorState = 2;
return;
}
switch (maxIndex) {
case 0:
if (this.motorState == 0) {
return;
}
this.car.motorOn(true);
this.motorState = 0;
break;
case 1:
if (this.motorState == 1) {
return;
}
this.car.motorOn(false);
this.motorState = 1;
break;
// case 2:
// if (this.motorState == 2) {
// return;
// }
//
// this.car.motorOff();
// this.motorState = 2;
// break;
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<replace
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//returns a clone of this player with the same brian
clone() {
var clone = new Player();
clone.brain = this.brain.clone();
clone.fitness = this.fitness;
clone.brain.generateNetwork();
clone.gen = this.gen;
clone.bestScore = this.score;
clone.shirtColorR = this.shirtColorR + random(-2, 2);
clone.shirtColorG = this.shirtColorG + random(-2, 2);
clone.shirtColorB = this.shirtColorB + random(-2, 2);
clone.addToWorld();
return clone;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//since there is some randomness in games sometimes when we want to replay the game we need to remove that randomness
//this fuction does that
cloneForReplay() {
var clone = new Player(true);
if (!this.dead && this.car != null) {
this.removePlayerFromWorld();
}
clone.brain = this.brain.clone();
clone.fitness = this.fitness;
clone.brain.generateNetwork();
clone.gen = this.gen;
clone.bestScore = this.score;
clone.shirtColorR = this.shirtColorR;
clone.shirtColorG = this.shirtColorG;
clone.shirtColorB = this.shirtColorB;
clone.isCB = this.isCB;
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<replace
return clone;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//fot Genetic algorithm
calculateFitness() {
this.fitness = this.score;
// this.score = this.fitness;
this.fitness *= this.fitness;
this.fitness *= map(this.score / this.lifespan, 0, 1, 0.9, 1);
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<replace
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
crossover(parent2) {
var child = new Player();
child.brain = this.brain.crossover(parent2.brain);
child.brain.generateNetwork();
child.shirtColorR = this.shirtColorR + random(-10, 10);
child.shirtColorG = this.shirtColorG + random(-10, 10);
child.shirtColorB = this.shirtColorB + random(-10, 10);
// child.shirtColorR = constrain((1.5 * this.shirtColorR + 0.5 * parent2.shortColorR) / 2 + random(-2, 2), 0, 255);
// child.shirtColorG = constrain((1.5 * this.shirtColorG + 0.5 * parent2.shortColorG) / 2 + random(-2, 2), 0, 255);
// child.shirtColorB = constrain((1.5 * this.shirtColorB + 0.5 * parent2.shortColorB) / 2 + random(-2, 2), 0, 255);
child.addToWorld();
// child.car.setShirt();
if (random(1) < 0.99) {
child.isCB = this.isCB;
} else {
child.isCB = !this.isCB;
}
return child;
}
removePlayerFromWorld() {
this.world.DestroyBody(this.car.chassisBody);
this.world.DestroyBody(this.car.wheels[0].body);
this.world.DestroyBody(this.car.wheels[0].rimBody);
this.world.DestroyBody(this.car.wheels[1].body);
this.world.DestroyBody(this.car.wheels[1].rimBody);
this.world.DestroyBody(this.car.person.head.body);
this.world.DestroyBody(this.car.person.torso.body);
}
resetCar() {
this.world.DestroyBody(this.car.chassisBody);
this.world.DestroyBody(this.car.wheels[0].body);
this.world.DestroyBody(this.car.wheels[0].rimBody);
this.world.DestroyBody(this.car.wheels[1].body);
this.world.DestroyBody(this.car.wheels[1].rimBody);
this.world.DestroyBody(this.car.person.head.body);
this.world.DestroyBody(this.car.person.torso.body);
this.car = new Car(150, 0, this.world, this);
reset = false;
resetCounter = 120;
panX = 0;
}
}
class Population {
constructor() {
this.players = []; //new ArrayList<Player>();
this.bestPlayer; //the best ever player
this.bestScore = 0; //the score of the best ever player
this.globalBestScore = 0;
this.gen = 1;
this.innovationHistory = []; // new ArrayList<connectionHistory>();
this.genPlayers = []; //new ArrayList<Player>();
this.species = []; //new ArrayList<Species>();
this.massExtinctionEvent = false;
this.newStage = false;
this.gensSinceNewWorld = 0;
this.batchNo = 0;
this.worldsPerBatch = 5;
for (var i = 0; i < numberOfWorlds; i++) {
for (var j = 0; j < playersPerWorld; j++) {
this.players.push(new Player());
this.players[this.players.length - 1].brain.fullyConnect(this.innovationHistory);
this.players[this.players.length - 1].brain.generateNetwork();
//
// this.players[this.players.length - 1].brain.mutate(this.innovationHistory);
// this.players[this.players.length - 1].brain.mutate(this.innovationHistory);
// if (random(1) < 0.5) {
// this.players[this.players.length - 1].brain.addConnection(this.innovationHistory);
// this.players[this.players.length - 1].brain.addNode(this.innovationHistory);
// }
this.players[this.players.length - 1].addToWorld();
this.players[this.players.length - 1].car.number = i;
}
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
//update all the players which are alive
updateAlive() {
let aliveCount = 0;
for (var i = 0; i < this.players.length; i++) {
if (this.playerInBatch(this.players[i])) {
if (!this.players[i].dead) {
aliveCount++;
this.players[i].look(); //get inputs for brain
this.players[i].think(); //use outputs from neural network
this.players[i].update(); //move the player according to the outputs from the neural network
if (!showNothing && (!showBest || i == 0)) {
this.players[i].show();
}
if (this.players[i].score > this.globalBestScore) {
this.globalBestScore = this.players[i].score;
}
}
}
}
if (aliveCount == 0) {
this.batchNo++;
}
}
playerInBatch(player) {
for (var i = this.batchNo * this.worldsPerBatch; i < min((this.batchNo + 1) * this.worldsPerBatch, worlds.length); i++) {
if (player.world == worlds[i]) {
return true;
}
}
return false;
}
stepWorldsInBatch() {
for (var i = this.batchNo * this.worldsPerBatch; i < min((this.batchNo + 1) * this.worldsPerBatch, worlds.length); i++) {
worlds[i].Step(1 / 30, 10, 10);
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
//returns true if all the players are dead sad
batchDead() {
for (var i = this.batchNo * this.playersPerBatch; i < min((this.batchNo + 1) * this.playersPerBatch, this.players.length); i++) {
if (!this.players[i].dead) {
return false;
}
}
return true;
}
//------------------------------------------------------------------------------------------------------------------------------------------
//returns true if all the players are dead sad
done() {
for (var i = 0; i < this.players.length; i++) {
if (!this.players[i].dead) {
return false;
}
}
clearWorlds();
return true;
}
//------------------------------------------------------------------------------------------------------------------------------------------
//sets the best player globally and for thisthis.gen
setBestPlayer() {
var tempBest = this.species[0].players[0];
tempBest.gen = this.gen;
//if best thisthis.gen is better than the global best score then set the global best as the best thisthis.gen
if (tempBest.score >= this.bestScore) {
this.genPlayers.push(tempBest.cloneForReplay());
console.log("old best: " + this.bestScore);
console.log("new best: " + tempBest.score);
this.bestScore = tempBest.score;
this.bestPlayer = tempBest.cloneForReplay();
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------
//this function is called when all the players in the this.players are dead and a newthis.generation needs to be made
naturalSelection() {
// if (this.gen % 2 == 0 && playersPerWorld < 15) {
// playersPerWorld += 1;
// }
this.batchNo = 0;
var previousBest = this.players[0];
this.speciate(); //seperate the this.players varo this.species
this.calculateFitness(); //calculate the fitness of each player
this.sortSpecies(); //sort the this.species to be ranked in fitness order, best first
if (this.massExtinctionEvent) {
this.massExtinction();
this.massExtinctionEvent = false;
}
this.cullSpecies(); //kill off the bottom half of each this.species
this.setBestPlayer(); //save the best player of thisthis.gen
this.killStaleSpecies(); //remove this.species which haven't improved in the last 15(ish)this.generations
this.killBadSpecies(); //kill this.species which are so bad that they cant reproduce
if (this.gensSinceNewWorld >= 0 || this.bestScore > (grounds[0].distance - 350) / 10) {
this.gensSinceNewWorld = 0;
console.log(this.gensSinceNewWorld);
console.log(this.bestScore);
console.log(grounds[0].distance);
newWorlds();
}
// console.log("generation " + this.gen + " Number of mutations " + this.innovationHistory.length + " species: " + this.species.length + " <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
var averageSum = this.getAvgFitnessSum();
var children = []; //new ArrayList<Player>();//the nextthis.generation
// console.log("Species:");
for (var j = 0; j < this.species.length; j++) { //for each this.species
// // console.log("best unadjusted fitness:" + this.species[j].bestFitness);
// for (var i = 0; i < this.species[j].players.length; i++) {
// console.log("player " + i + " fitness: " + this.species[j].players[i].fitness + " score " + this.species[j].players[i].score + ' ');
// }
// console.log();
children.push(this.species[j].champ.clone()); //add champion without any mutation
var NoOfChildren = floor(this.species[j].averageFitness / averageSum * this.players.length) - 1; //the number of children this this.species is allowed, note -1 is because the champ is already added
for (var i = 0; i < NoOfChildren; i++) { //get the calculated amount of children from this this.species
children.push(this.species[j].giveMeBaby(this.innovationHistory));
}
}
if (children.length < this.players.length) {
children.push(previousBest.clone());
}
// while (children.length < this.players.length) { //if not enough babies (due to flooring the number of children to get a whole var)
// children.push(this.species[0].giveMeBaby(this.innovationHistory)); //get babies from the best this.species
// }
while (children.length < playersPerWorld * numberOfWorlds) { //if not enough babies (due to flooring the number of children to get a whole var)
children.push(this.species[0].giveMeBaby(this.innovationHistory)); //get babies from the best this.species
}
this.players = [];
arrayCopy(children, this.players); //set the children as the current this.playersulation
this.gen += 1;
this.gensSinceNewWorld++;
for (var i = 0; i < this.players.length; i++) { //generate networks for each of the children
this.players[i].brain.generateNetwork();
this.players[i].car.number = i;
}
console.log("LOOOK HERE THERE ARE " + this.players.length + " Players in this gen");
}
//------------------------------------------------------------------------------------------------------------------------------------------
//seperate this.players into this.species based on how similar they are to the leaders of each this.species in the previousthis.gen
speciate() {
for (var s of this.species) { //empty this.species
s.players = [];
}
for (var i = 0; i < this.players.length; i++) { //for each player
var speciesFound = false;
for (var s of this.species) { //for each this.species
if (s.sameSpecies(this.players[i].brain)) { //if the player is similar enough to be considered in the same this.species
s.addToSpecies(this.players[i]); //add it to the this.species
speciesFound = true;
break;
}
}
if (!speciesFound) { //if no this.species was similar enough then add a new this.species with this as its champion
this.species.push(new Species(this.players[i]));
}
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
//calculates the fitness of all of the players
calculateFitness() {
for (var i = 1; i < this.players.length; i++) {
this.players[i].calculateFitness();
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
//sorts the players within a this.species and the this.species by their fitnesses
sortSpecies() {
//sort the players within a this.species
for (var s of this.species) {
s.sortSpecies();
}
//sort the this.species by the fitness of its best player
//using selection sort like a loser
var temp = []; //new ArrayList<Species>();
for (var i = 0; i < this.species.length; i++) {
var max = 0;
var maxIndex = 0;
for (var j = 0; j < this.species.length; j++) {
if (this.species[j].bestFitness > max) {
max = this.species[j].bestFitness;
maxIndex = j;
}
}
temp.push(this.species[maxIndex]);
this.species.splice(maxIndex, 1);
// this.species.remove(maxIndex);
i--;
}
this.species = [];
arrayCopy(temp, this.species);
}
//------------------------------------------------------------------------------------------------------------------------------------------
//kills all this.species which haven't improved in 15this.generations
killStaleSpecies() {
for (var i = 2; i < this.species.length; i++) {
if (this.species[i].staleness >= 15) {
// .remove(i);
// splice(this.species, i)
this.species.splice(i, 1);
i--;
}
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
//if a this.species sucks so much that it wont even be allocated 1 child for the nextthis.generation then kill it now
killBadSpecies() {
var averageSum = this.getAvgFitnessSum();
for (var i = 1; i < this.species.length; i++) {
if (this.species[i].averageFitness / averageSum * this.players.length < 1) { //if wont be given a single child
// this.species.remove(i); //sad
this.species.splice(i, 1);
i--;
}
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
//returns the sum of each this.species average fitness
getAvgFitnessSum() {
var averageSum = 0;
for (var s of this.species) {
averageSum += s.averageFitness;
}
return averageSum;
}
//------------------------------------------------------------------------------------------------------------------------------------------
//kill the bottom half of each this.species
cullSpecies() {
for (var s of this.species) {
s.cull(); //kill bottom half
s.fitnessSharing(); //also while we're at it lets do fitness sharing
s.setAverage(); //reset averages because they will have changed
}
}
massExtinction() {
for (var i = 5; i < this.species.length; i++) {
// this.species.remove(i); //sad
this.species.splice(i, 1);
i--;
}
}
}
class Species {
constructor(p) {
this.players = [];
this.bestFitness = 0;
this.champ;
this.averageFitness = 0;
this.staleness = 0; //how many generations the species has gone without an improvement
this.rep;
//--------------------------------------------
//coefficients for testing compatibility
this.excessCoeff = 1;
this.weightDiffCoeff = 0.5;
this.compatibilityThreshold = 3;
if (p) {
this.players.push(p);
//since it is the only one in the species it is by default the best
this.bestFitness = p.fitness;
this.rep = p.brain.clone();
this.champ = p.cloneForReplay();
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//returns whether the parameter genome is in this species
sameSpecies(g) {
var compatibility;
var excessAndDisjoint = this.getExcessDisjoint(g, this.rep); //get the number of excess and disjoint genes between this player and the current species this.rep
var averageWeightDiff = this.averageWeightDiff(g, this.rep); //get the average weight difference between matching genes
var largeGenomeNormaliser = g.genes.length - 20;
if (largeGenomeNormaliser < 1) {
largeGenomeNormaliser = 1;
}
compatibility = (this.excessCoeff * excessAndDisjoint / largeGenomeNormaliser) + (this.weightDiffCoeff * averageWeightDiff); //compatibility formula
return (this.compatibilityThreshold > compatibility);
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//add a player to the species
addToSpecies(p) {
this.players.push(p);
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//returns the number of excess and disjoint genes between the 2 input genomes
//i.e. returns the number of genes which dont match
getExcessDisjoint(brain1, brain2) {
var matching = 0.0;
for (var i = 0; i < brain1.genes.length; i++) {
for (var j = 0; j < brain2.genes.length; j++) {
if (brain1.genes[i].innovationNo == brain2.genes[j].innovationNo) {
matching++;
break;
}
}
}
return (brain1.genes.length + brain2.genes.length - 2 * (matching)); //return no of excess and disjoint genes
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//returns the avereage weight difference between matching genes in the input genomes
averageWeightDiff(brain1, brain2) {
if (brain1.genes.length == 0 || brain2.genes.length == 0) {
return 0;
}
var matching = 0;
var totalDiff = 0;
for (var i = 0; i < brain1.genes.length; i++) {
for (var j = 0; j < brain2.genes.length; j++) {
if (brain1.genes[i].innovationNo == brain2.genes[j].innovationNo) {
matching++;
totalDiff += abs(brain1.genes[i].weight - brain2.genes[j].weight);
break;
}
}
}
if (matching == 0) { //divide by 0 error
return 100;
}
return totalDiff / matching;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//sorts the species by fitness
sortSpecies() {
var temp = []; // new ArrayList < Player > ();
//selection short
for (var i = 0; i < this.players.length; i++) {
var max = 0;
var maxIndex = 0;
for (var j = 0; j < this.players.length; j++) {
if (this.players[j].fitness > max) {
max = this.players[j].fitness;
maxIndex = j;
}
}
temp.push(this.players[maxIndex]);
this.players.splice(maxIndex, 1);
// this.players.remove(maxIndex);
i--;
}
// this.players = (ArrayList) temp.clone();
arrayCopy(temp, this.players);
if (this.players.length == 0) {
this.staleness = 200;
return;
}
//if new best player
if (this.players[0].fitness > this.bestFitness) {
this.staleness = 0;
this.bestFitness = this.players[0].fitness;
this.rep = this.players[0].brain.clone();
this.champ = this.players[0].cloneForReplay();
} else { //if no new best player
this.staleness++;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//simple stuff
setAverage() {
var sum = 0;
for (var i = 0; i < this.players.length; i++) {
sum += this.players[i].fitness;
}
this.averageFitness = sum / this.players.length;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//gets baby from the this.players in this species
giveMeBaby(innovationHistory) {
var baby;
if (random(1) < 0.25) { //25% of the time there is no crossover and the child is simply a clone of a random(ish) player
baby = this.selectPlayer().clone();
} else { //75% of the time do crossover
//get 2 random(ish) parents
var parent1 = this.selectPlayer();
var parent2 = this.selectPlayer();
//the crossover function expects the highest fitness parent to be the object and the lowest as the argument
if (parent1.fitness < parent2.fitness) {
baby = parent2.crossover(parent1);
} else {
baby = parent1.crossover(parent2);
}
}
baby.brain.mutate(innovationHistory); //mutate that baby brain
return baby;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//selects a player based on it fitness
selectPlayer() {
var fitnessSum = 0;
for (var i = 0; i < this.players.length; i++) {
fitnessSum += this.players[i].fitness;
}
var rand = random(fitnessSum);
var runningSum = 0;
for (var i = 0; i < this.players.length; i++) {
runningSum += this.players[i].fitness;
if (runningSum > rand) {
return this.players[i];
}
}
//unreachable code to make the parser happy
return this.players[0];
}
//------------------------------------------------------------------------------------------------------------------------------------------
//kills off bottom half of the species
cull() {
if (this.players.length > 2) {
for (var i = this.players.length / 2; i < this.players.length; i++) {
// this.players.remove(i);
this.players.splice(i, 1);
i--;
}
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
//in order to protect unique this.players, the fitnesses of each player is divided by the number of this.players in the species that that player belongs to
fitnessSharing() {
for (var i = 0; i < this.players.length; i++) {
this.players[i].fitness /= this.players.length;
}
}
}
//note //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<replace
//this means that there is some information specific to the game to input here
var Vec2 = Box2D.Common.Math.b2Vec2;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2World = Box2D.Dynamics.b2World;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2StaticBody = Box2D.Dynamics.b2Body.b2_staticBody;
var b2DynamicBody = Box2D.Dynamics.b2Body.b2_dynamicBody;
var b2RevoluteJoint = Box2D.Dynamics.Joints.b2RevoluteJoint;
var b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef;
var b2PrismaticJoint = Box2D.Dynamics.Joints.b2PrismaticJoint;
var b2PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef;
var b2FilterData = Box2D.Dynamics.b2FilterData;
var b2DistanceJoint = Box2D.Dynamics.Joints.b2DistanceJoint;
var b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef;
var b2WeldJoint = Box2D.Dynamics.Joints.b2WeldJoint;
var b2WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef;
//------------------------------------------GLOBALS
var SCALE = 30;
var groundBody;
var wheels = [];
var groundTemplate;
var pause = false;
var panX = 0;
var targetPanX = 0;
var maxPanSpeed = 100;
var panSpeed = 50;
var panAcc = 10;
var panY = 0;
var leftDown = false;
var rightDown = false;
var listener = new Box2D.Dynamics.b2ContactListener;
// var listener2 = new Box2D.Dynamics.b2ContactListener;
var carSprite;
var headSprite;
var cbHead = false;
var wheelSprite;
var shownGround = false;
var spawningY = 0;
//collisionCatagories i.e what it is
var WHEEL_CATEGORY = 0x0001;
var CHASSIS_CATEGORY = 0X0002;
var GRASS_CATEGORY = 0X0004;
var DIRT_CATEGORY = 0x0008;
var PERSON_CATEGORY = 0x0010;
//collision Masks ie. what it collides with
var WHEEL_MASK = (GRASS_CATEGORY);
var CHASSIS_MASK = (DIRT_CATEGORY);
var GRASS_MASK = (WHEEL_CATEGORY | PERSON_CATEGORY);
var DIRT_MASK = (CHASSIS_CATEGORY);
var PERSON_MASK = (GRASS_CATEGORY);
var resetCounter = 120;
var reset = false;
var p;
var p2;
var nextPanX = 0;
var nextConnectionNo = 1000;
var population;
var speed = 60;
var showBest = false; //true if only show the best of the previous generation
var runBest = false; //true if replaying the best ever game
var humanPlaying = false; //true if the user is playing
var fightMode = false; //true when the player is fighting the best every player
var humanPlayer;
var showBrain = false;
var showBestEachGen = false;
var upToGen = 0;
var genPlayerTemp; //player
var showNothing = false;
var currentBestPlayer;
var spawnHeight = 0;
//--------------
var playersInEachWorld = [];
var grassSprites = [];
// var ground;
// var world;
var otherWorld; // for human, gen replay, species, best
var worlds = [];
var grounds = [];
var numberOfWorlds = 50;
var playersPerWorld = 15;
var skySprite;
var darknessSprite;
var difficulty = 50;
listener.BeginContact = function(contact) {
let world = contact.GetFixtureA().GetBody().GetWorld();
if (reset) {
return;
}
if (contact.GetFixtureA().GetBody().GetUserData().id == "head") {
if (contact.GetFixtureB().GetBody().GetUserData().id == "ground") {
if (contact.GetFixtureA().GetBody().GetJointList() == null) {
return;
}
let car = contact.GetFixtureA().GetBody().GetJointList().other.GetJointList().other.GetUserData(); //i think that is the grossest code i have ever written
world.DestroyJoint(car.distJoint);
world.DestroyJoint(car.person.distJoint);
world.DestroyJoint(car.revJoint);
world.DestroyJoint(car.person.headJoint);
car.player.kindaDead = true;
}
}
if (contact.GetFixtureB().GetBody().GetUserData().id == "head") {
if (contact.GetFixtureA().GetBody().GetUserData().id == "ground") {
if (contact.GetFixtureB().GetBody().GetJointList() == null) {
return;
}
let car = contact.GetFixtureB().GetBody().GetJointList().other.GetJointList().other.GetUserData(); //i think that is the grossest code i have ever written
world.DestroyJoint(car.distJoint);
world.DestroyJoint(car.person.distJoint);
world.DestroyJoint(car.revJoint);
world.DestroyJoint(car.person.headJoint);
car.player.kindaDead = true;
}
}
if (contact.GetFixtureA().GetBody().GetUserData().id == "wheel") {
if (contact.GetFixtureB().GetBody().GetUserData().id == "ground") {
createDiv("oi fuck");
contact.GetFixtureA().GetBody().GetUserData().onGround = true;
}
}