-
Notifications
You must be signed in to change notification settings - Fork 0
/
smart_minesweepers.html
1340 lines (1157 loc) · 41.4 KB
/
smart_minesweepers.html
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
<html>
<head>
<title>Smart sweepers in JS</title>
<style>
#info {
border: 1px dotted black;
border-radius: 5px;
display: block;
position: fixed;
padding: 15px;
top: 30px;
left: 10px;
background-color:cornsilk;
}
#info > div {
padding: 0;
}
#info > div > p {
margin: 0;
padding-bottom: 3px;
}
</style>
</head>
<body>
<div id='generation'></div>
<canvas id="battlefield" width="0" height="0"></canvas>
<div id="info">
<table>
<tr>
<td>Hidden layers:</td>
<td><span id="hiddenLayers"></span></td>
</tr>
<tr>
<td>Neurons per hidden layer:</td>
<td><span id="neuronsPerHiddenLayer"></span></td>
</tr>
<tr>
<td>Population:</td>
<td><span id="popSize"></span></td>
</tr>
<tr>
<td>Mines:</td>
<td><span id="minesCount"></span></td>
</tr>
<tr>
<td>Mutation Rate:</td>
<td><span id="mutationRate"></span></td>
</tr>
<tr>
<td>Crossover Rate:</td>
<td><span id="crossoverRate"></span></td>
</tr>
<tr>
<td colspan=2><br/><b>HELP:</b></td>
</tr>
<tr>
<td><b>Keyboard<br/>Key</b></td>
<td><b>Action</b></td>
</tr>
<tr>
<td><b>S</b></td>
<td>Save custom state</td>
</tr>
<tr><td><b>L</b></td>
<td>Load custom state</td>
</tr>
<tr>
<td><b>R</b></td>
<td>Reset to initial state</td>
</tr>
<tr>
<td><b>P</b></td>
<td>Pause / Unpause</td>
</tr>
<tr>
<td><b>Up Arrow</b></td>
<td>Increase mines</td>
</tr>
<tr>
<td><b>Down Arrow</b></td>
<td>Decrease mines</td>
</tr>
<tr>
<td><b>Spacebar</b></td>
<td>Switch between fast mode (stats)<br/>and visual mode (movements)</td>
</tr>
</table>
</div>
<script>
class Params {
static get FastRender() {return true; }
static get NumMines() { return 30; }
static get NumSweepers() { return 50; }
static get NumHidden() { return 3; }
static get NeuronsPerHiddenLayer() { return 40; }
static get NumTicks() { return 5000; }
static get MaxTurnRate() { return 0.13; }
static get MaxForwardSpeed() { return 1.75; }
static get MaxBackwardSpeed() { return -1.25; }
static get SweeperScale() { return 2; }
static get MineScale() { return 3; }
static get NumInputs() { return 6; }
static get NumOutputs() { return 2; }
static get ActivationResponse() { return 1; }
static get Bias() { return 0; }
static get MineSenseDistance() { return Math.pow(350, 2); }
static get MineSenseRadius() { return Math.pow(15, 2); }
static get CrossoverRate() { return 0.7; }
static get MutationRate() { return 0.13; }
static get MaxPerturbation() { return 0.37; }
static get NumElite() { return (~~(Params.NumSweepers * 0.2) & 0xFE); }
static get NumCopiesElite() { return 1; }
static get HalfPi() { return Math.PI / 2; }
static get TwoPi() { return Math.PI * 2; }
static get WindowWidth() { return 1400; }
static get WindowHeight() { return 640; }
}
function SPoint(x, y) {
return {x, y};
}
const SweeperImageDots = [
SPoint(-5, -5),
SPoint(-5, 3),
SPoint(-3, 3),
SPoint(-3, 4),
SPoint(-2, 5),
SPoint(2, 5),
SPoint(3, 4),
SPoint(3, 3),
SPoint(5, 3),
SPoint(5, -5),
SPoint(3, -5),
SPoint(3, -3),
SPoint(-3, -3),
SPoint(-3, -5)
];
const MineImageDots = [
SPoint(-1, -1),
SPoint(-1, 1),
SPoint(1, 1),
SPoint(1, -1)
];
//-------------------------------------Clamp()-----------------------------------------
//
// clamps the first argument between the second two
//
//-------------------------------------------------------------------------------------
function Clamp(arg, min, max)
{
return arg < min ? min : arg > max ? max : arg;
}
//returns a random integer between x and y
function RandInt(x, y) {
return ~~((Math.random() * y + x) % (y + 1));
}
//returns a random bool
function RandBool() {
return !!RandInt(0,1);
}
//returns a random float in the range -1 < n < 1
function RandomClamped() {
return Math.random() - Math.random();
}
/////////////////////////////////////////////////////////////////////
//
// 2D Vector class and methods
//
/////////////////////////////////////////////////////////////////////
class Vector2D {
constructor(x, y) {
if (x instanceof Vector2D) {
this.x = x.x || 0.0;
this.y = x.y || 0.0;
} else {
this.x = x || 0.0;
this.y = y || 0.0;
}
}
Add(rhs) {
this.x += rhs.x;
this.y += rhs.y;
return this;
}
static Add(lhs, rhs) {
return new Vector2D (lhs.x + rhs.x, lhs.y + rhs.y);
}
Substract(rhs) {
this.x -= rhs.x;
this.y -= rhs.y;
return this;
}
static Substract(lhs, rhs) {
return new Vector2D (lhs.x - rhs.x, lhs.y - rhs.y);
}
Multiply(rhs) {
this.x *= rhs;
this.y *= rhs;
return this;
}
static Multiply(lhs, rhs) {
return new Vector2D (lhs.x * rhs, lhs.y * rhs);
}
Divide(rhs) {
this.x /= rhs;
this.y /= rhs;
return this;
}
static Divide(lhs, rhs) {
return new Vector2D (lhs.x / rhs, lhs.y / rhs);
}
get Length()
{
return Math.sqrt(this.x * this.x + this.y * this.y);
}
get SquaredLength()
{
return this.x * this.x + this.y * this.y;
}
//------------------------------------------------------
// normalizes a 2D Vector
//------------------------------------------------------
Normalize()
{
let len = this.Length;
if (len == 0) {
this.x = 0;
this.y = 0;
} else {
this.x = this.x / len;
this.y = this.y / len;
}
return this;
}
static Normalize(v)
{
let result = new Vector2D(v);
let len = result.Length;
result.x = result.x / len;
result.y = result.y / len;
return result;
}
NormalizeBy(v)
{
this.x = this.x / v.x;
this.y = this.y / v.y;
return this;
}
Dot(v)
{
return this.x * v.x + this.y * v.y;
}
static Dot(v1, v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
//------------------------ Sign --------------------------------
//
// returns positive if v2 is clockwise of v1, minus if anticlockwise
//-------------------------------------------------------------------
Sign(v)
{
return (this.y * v.x > this.x * v.y) ? 1 : -1;
}
static Sign(v1, v2)
{
return (v1.y * v2.x > v1.x * v2.y) ? 1 : -1;
}
}
class Minesweeper {
constructor(world) {
this.brain = new NeuralNet();
this.rotation = Math.random() * Params.TwoPi;
this.lTrack = 0.16;
this.rTrack = 0.16;
this.fitness = 0;
this.closestMine = -1;
this.lookAt = new Vector2D();
//create a random start position
this.position = new Vector2D( RandInt(0, Params.WindowWidth), RandInt(0, Params.WindowHeight));
this.world = world;
}
get Position() {
return this.position;
}
IncrementFitness() {
++this.fitness;
}
get Fitness() {
return this.fitness;
}
get Weights() {
return this.brain.Weights;
}
set Weights(w) {
this.brain.Weights = w;
}
get NumberOfWeights() {
return this.brain.NumberOfWeights;
}
//-------------------------------------------Reset()--------------------
//
// Resets the sweepers position, fitness and rotation
//
//----------------------------------------------------------------------
Reset()
{
this.rotation = Math.random() * Params.TwoPi;
this.fitness = 0;
this.closestMine = -1;
this.position = new Vector2D(RandInt(0, Params.WindowWidth), RandInt(0, Params.WindowHeight));
}
//-------------------------------Update()--------------------------------
//
// First we take sensor readings and feed these into the sweepers brain.
//
// The inputs are:
//
// A vector to the closest mine (x, y)
// The sweepers 'look at' vector (x, y)
//
// We receive two outputs from the brain.. lTrack & rTrack.
// So given a force for each track we calculate the resultant rotation
// and acceleration and apply to current velocity vector.
//
//-----------------------------------------------------------------------
Update() {
//this will store all the inputs for the NN
let inputs = [];
//get vector to closest mine
let deltaVector = this.GetClosestMine();
//normalise it
deltaVector.Normalize();
// add current rotation and speed
inputs.push((this.rotation || 0.001) / Params.TwoPi);
let normalizedSpeed = this.speed > 0 ? this.speed / Params.MaxForwardSpeed : -this.speed / Params.MaxBackwardSpeed;
inputs.push(normalizedSpeed || 0.001);
//add in vector to closest mine
inputs.push(deltaVector.x || 0.001);
inputs.push(deltaVector.y || 0.001);
// Add in sweepers look at vector
let lookAtVector = new Vector2D(this.lookAt);
lookAtVector.Normalize();
inputs.push(lookAtVector.x || 0.001);
inputs.push(lookAtVector.y || 0.001);
//update the brain and get feedback
let output = this.brain.Update(inputs);
//make sure there were no errors in calculating the
//output
if (output.length < Params.NumOutputs)
{
return false;
}
//assign the outputs to the sweepers left & right tracks
if (isNaN(output[0]) || isNaN(output[1])) {
console.error('output is NaN');
}
this.lTrack = output[0];
this.rTrack = output[1];
//calculate steering forces
let RotForce = this.lTrack - this.rTrack;
//clamp rotation
RotForce = Clamp(RotForce, -Params.MaxTurnRate, Params.MaxTurnRate);
this.rotation += RotForce;
this.rotation %= Params.TwoPi;
this.speed = (this.lTrack + this.rTrack);
this.speed = Clamp(this.speed, Params.MaxBackwardSpeed, Params.MaxForwardSpeed);
//update Look At
this.lookAt.x = -Math.sin(this.rotation);
this.lookAt.y = Math.cos(this.rotation);
//update position
this.position.Add(Vector2D.Multiply(this.lookAt, this.speed));
//wrap around window limits
if (this.position.x >= Params.WindowWidth) this.position.x = Params.WindowWidth - 3;
if (this.position.x <= 0) this.position.x = 3;
if (this.position.y >= Params.WindowHeight) this.position.y = Params.WindowHeight - 3;
if (this.position.y <= 0) this.position.y = 3;
return true;
}
//----------------------GetClosestObject()---------------------------------
//
// returns the vector from the sweeper to the closest mine
//
//-----------------------------------------------------------------------
GetClosestMine() {
let closestSoFar = 9999999;
let vClosestObject = new Vector2D();
if (this.closestMine > -1 && this.closestMine < this.world.mines.length && Vector2D.Substract(this.position, this.world.mines[this.closestMine]).SquaredLength < Params.MineSenseDistance) {
vClosestObject = Vector2D.Substract(this.position, this.world.mines[this.closestMine]);
} else {
//cycle through mines to find closest
for (let i = 0; i < this.world.mines.length; i++)
{
let distanceToObject = Vector2D.Substract(this.world.mines[i], this.position).SquaredLength;
if (distanceToObject < closestSoFar)
{
closestSoFar = distanceToObject;
vClosestObject = Vector2D.Substract(this.position, this.world.mines[i]);
this.closestMine = i;
}
}
}
return vClosestObject;
}
//----------------------------- CheckForMine -----------------------------
//
// this function checks for collision with its closest mine (calculated
// earlier and stored in m_iClosestMine)
//-----------------------------------------------------------------------
CheckForMine() {
if (this.closestMine < 0 && this.closestMine >= this.world.mines.length) {
return -1;
}
let distToObject = Vector2D.Substract(this.position, this.world.mines[this.closestMine]);
if (distToObject.SquaredLength < (Params.MineScale + Params.MineSenseRadius))
{
return this.closestMine;
}
return -1;
}
}
class Controller {
constructor() {
this.Idle = true;
this.numSweepers = Params.NumSweepers;
this.GA = null;
this.fastRender = Params.FastRender;
this.ticks = 0;
this.numMines = Params.NumMines;
this.wndMain = null;
this.generations = 0;
this.xClient = Params.WindowWidth;
this.yClient = Params.WindowHeight;
this.sweepers = [];
this.mines = [];
this.avFitness = [];
this.bestFitness = [];
this.canvas = document.getElementById('battlefield');
this.canvas.width = this.xClient;
this.canvas.height = this.yClient;
this.renderContext = this.canvas.getContext('2d');
//let's create the mine sweepers
for (let i=0; i<this.numSweepers; ++i)
{
this.sweepers.push(new Minesweeper(this));
}
//get the total number of weights used in the sweepers
//NN so we can initialise the GA
this.numWeightsInNN = this.sweepers[0].NumberOfWeights;
//initialize the Genetic Algorithm class
this.GA = new GenAlg(this.numSweepers,
Params.MutationRate,
Params.CrossoverRate,
this.numWeightsInNN);
//Get the weights from the GA and insert into the sweepers brains
this.thePopulation = this.GA.Chromos;
for (let i = 0; i < this.numSweepers; i++) {
this.sweepers[i].Weights = this.thePopulation[i].weights;
}
//initialize mines in random positions within the application window
for (let i = 0; i < this.numMines; ++i) {
this.createNewMine();
}
}
displayAIInfo() {
let brain = this.sweepers[0].brain;
let ga = this.GA;
this.DrawText("hiddenLayers", brain.numHiddenLayers)
this.DrawText("neuronsPerHiddenLayer", brain.neuronsPerHiddenLayer);
this.DrawText("popSize", ga.popSize);
this.DrawText("minesCount", this.mines.length);
this.DrawText("mutationRate", ga.mutationRate);
this.DrawText("crossoverRate", ga.crossoverRate);
}
saveState(name, showAlert) {
let copy = JSON.parse(JSON.stringify(this, (k, v) => k == 'world' ? undefined : v));
for(let sweeper of copy.sweepers) {
delete sweeper.brain.layers;
}
delete copy.GA.pop;
delete copy.canvas;
delete copy.renderContext;
let json = JSON.stringify(copy);
localStorage.setItem(name, json);
if (showAlert) {
alert("Custom state is saved");
}
}
loadState(name, showAlert) {
let json = localStorage.getItem(name);
if (json) {
let data = JSON.parse(json);
let firstSweeper = data.sweepers[0];
if (data.sweepers && data.sweepers.length > 0 &&
firstSweeper.brain.neuronsPerHiddenLayer == Params.NeuronsPerHiddenLayer &&
firstSweeper.brain.numHiddenLayers == Params.NumHidden) {
Object.assign(this, data);
this.Idle = true;
this.GA = new GenAlg(0);
Object.assign(this.GA, data.GA);
let pop = [];
for (let genome of data.thePopulation) {
pop.push(new Genome(genome.weights, genome.fitness));
}
this.thePopulation = pop;
this.GA.pop = pop;
this.GA.bestEverGenome = new Genome(data.GA.bestEverGenome.weights, data.GA.bestEverGenome.fitness);
this.displayAIInfo(firstSweeper, this.GA);
//let's restore the mine sweepers
this.sweepers = [];
for (let i=0; i<this.numSweepers; ++i)
{
this.sweepers.push(new Minesweeper(this));
Object.assign(this.sweepers[i],data.sweepers[i]);
let brain = new NeuralNet();
let oldBrain = data.sweepers[i].brain;
brain.numInputs = oldBrain.numInputs;
brain.numOutputs = oldBrain.numOutputs;
brain.numHiddenLayers = oldBrain.numHiddenLayers;
brain.neuronsPerHiddenLayer = oldBrain.neuronsPerHiddenLayer;
brain.layers = [];
this.sweepers[i].brain = brain;
this.sweepers[i].brain.CreateNet();
Object.assign(this.sweepers[i], {
lookAt: new Vector2D(data.sweepers[i].lookAt.x, data.sweepers[i].lookAt.y),
position: new Vector2D(data.sweepers[i].position.x, data.sweepers[i].position.y)
});
}
for (let i = 0; i < this.numSweepers; i++) {
this.sweepers[i].Weights = this.thePopulation[i].weights;
}
// Respore the mines positions from the loaded data
this.mines = [];
for (let i = 0; i < data.mines.length; ++i)
{
this.mines.push(new Vector2D(data.mines[i].x,data.mines[i].y));
}
}
}
if (showAlert) {
alert("Custom state is loaded");
}
}
increaseMines() {
this.createNewMine();
}
decreaseMines() {
if (this.mines.length > 1) {
this.mines.length--;
}
}
createNewMine(idx) {
let mineCoords = new Vector2D(RandInt(0, this.xClient), RandInt(0, this.yClient));
if (idx !== undefined && idx >= 0 && idx < this.mines.length) {
this.mines[idx] = mineCoords;
} else {
this.mines.push(mineCoords);
}
}
CurrentBestFitness() {
let bestFitness = 0;
this.sweepers.forEach(sweeper => {bestFitness = Math.max(bestFitness, sweeper.fitness)});
return bestFitness;
}
get PercentDone() {
return ~~(this.ticks / Params.NumTicks * 100.0) + '%';
}
//-------------------------------------Update-----------------------------
//
// This is the main workhorse. The entire simulation is controlled from here.
//
// The comments should explain what is going on adequately.
//-------------------------------------------------------------------------
updateMineSweepers() {
for (let i = 0; i < this.numSweepers; ++i)
{
// Update the NN and position of the minesweeper
if (!this.sweepers[i].Update())
{
// Error in processing the neural net
// TODO: Should we use Alert here?
console.log("Wrong amount of NN inputs!");
return false;
}
// Lets see if mine was found
let grabHit = this.sweepers[i].CheckForMine();
if (grabHit >= 0 && grabHit < this.mines.length)
{
// We have discovered a mine so increase fitness
this.sweepers[i].IncrementFitness();
// All other minesweepers are less lucky so we reset their targets
for (let sweeper of this.sweepers) {
if(sweeper.closestMine == grabHit) {
sweeper.closestMine = -1;
}
}
// Mine was found so replace the mine with another at a random
// position
this.createNewMine(grabHit);
}
// Uupdate the chromos fitness score
this.thePopulation[i].fitness = this.sweepers[i].Fitness;
}
}
UpdateGeneration() {
// Update the stats to be used in our stat window
this.avFitness.push(this.GA.AverageFitness());
this.bestFitness.push(this.GA.BestFitness());
// Increment the generation counter
++this.generations;
//r Rset cycles
this.ticks = 0;
// Run the GA to create a new population
this.thePopulation = this.GA.Epoch(this.thePopulation);
// Insert the new (and hopefully) improved brains back into the sweepers
// and reset their positions etc
for (let i = 0; i < this.numSweepers; ++i) {
if (!this.sweepers[i] || !this.thePopulation[i]) {
continue;
}
this.sweepers[i].Weights = this.thePopulation[i].weights;
this.sweepers[i].Reset();
}
controller.saveState("default");
this.Idle = true;
}
Update()
{
// Run the sweepers through Params.NumTicks amount of cycles.
// During this loop each sweepers NN is constantly updated with the appropriate
// information from its surroundings.
// The output from the NN is obtained and the sweeper is moved.
// If it encounters a mine its fitness is updated appropriately,
this.Idle = false;
if (this.ticks++ < Params.NumTicks)
{
this.updateMineSweepers();
}
// Another generation has been completed.
// Time to run the GA and update the sweepers with their new NNs
else
{
this.UpdateGeneration();
}
return true;
}
//------------------------------------Render()--------------------------------------
//
//----------------------------------------------------------------------------------
FastUpdate()
{
// In fast update we are simulating all ticks at once without any render
// so it speeds up the simulation
this.Idle = false;
while (this.ticks++ < Params.NumTicks)
{
this.updateMineSweepers();
}
this.UpdateGeneration();
this.PlotStats();
this.Idle = true;
return true;
}
//------------------------------------Render()--------------------------------------
//
//----------------------------------------------------------------------------------
DrawText(id, text) {
let el = document.getElementById(id);
if (el){
el.innerHTML = text;
}
}
DisplayState(id, isShown) {
let el = document.getElementById(id);
if (el){
el.style.display = isShown ? "block" : "none";
}
}
DrawObject(type, obj, color, fitness) {
let ctx = this.renderContext;
let scale = type == 'mine' ? Params.MineScale : Params.SweeperScale;
let pos = type == 'mine' ? obj : obj.position;
let x = ~~pos.x,
y = ~~pos.y;
let tmpl = type == 'mine' ? MineImageDots : SweeperImageDots;
ctx.save()
ctx.fillStyle = color;
ctx.beginPath();
ctx.translate(x, y)
ctx.scale(scale, scale);
if(obj.rotation) {
ctx.rotate(obj.rotation);
}
ctx.moveTo(tmpl[0].x,tmpl[0].y);
for(let idx = 1; idx < tmpl.length; idx++) {
let pt = tmpl[idx];
ctx.lineTo(pt.x,pt.y);
}
ctx.closePath();
ctx.fill();
ctx.restore();
if (type != "mine") {
ctx.font = "20px Arial";
ctx.fillColor = "green";
ctx.fillText(fitness, x - 5, y - 10);
}
}
Render() {
let ctx = this.renderContext;
ctx.clearRect(0,0, this.canvas.width, this.canvas.height);
this.DrawText('generation', `Generation: ${this.generations}, Best fitness: ${this.CurrentBestFitness()}, Done: ${this.PercentDone}, Press <b>Spacebar</b> - to switch to fast mode (stats)`); //render the stats
//do not render if running at accelerated speed
if (!this.fastRender) {
for (let mine of this.mines) { //render the mines
this.DrawObject('mine', mine, 'green');
}
this.sweepers.sort((lhs, rhs) => {
return (rhs.fitness - lhs.fitness);
});
let color = 'red';
for (let i = 0; i < this.numSweepers; i++) { //render the sweepers
let sweeper = this.sweepers[i];
if (i == Params.NumElite) {
color = 'blue';
}
this.DrawObject('sweeper', sweeper, color, sweeper.Fitness);
if (i == 0) {
ctx.strokeStyle = 'purple';
ctx.beginPath();
ctx.arc(sweeper.position.x, sweeper.position.y, 15, 0, 2 * Math.PI);
ctx.stroke();
}
if (sweeper.closestMine > -1) {
let mine = this.mines[sweeper.closestMine];
ctx.strokeStyle = 'green';
ctx.setLineDash([1,2]); // drawing a dotted line
ctx.beginPath();
ctx.moveTo(~~sweeper.position.x, ~~sweeper.position.y);
ctx.lineTo(~~mine.x, ~~mine.y);
ctx.stroke();
ctx.setLineDash([]); // resetting a style to the solid line.
}
}
}
this.Idle = true;
}
//--------------------------PlotStats-------------------------------------
//
// Given a surface to draw on this function displays stats and a crude
// graph showing best and average fitness
//------------------------------------------------------------------------
PlotStats() {
let ctx = this.renderContext;
let totalBestFitness = Math.max(...this.bestFitness);
totalBestFitness = isFinite(totalBestFitness) ? totalBestFitness : 0;
this.DrawText('generation', `Generation: ${this.generations}, Best Ever Fitness: ${this.GA.bestEverFitness}, Total Average Fitness: ${this.GA.AverageFitness()}`);
//render the graph
let HSlice = Params.WindowWidth / (this.generations);
let VSlice = Params.WindowHeight / (totalBestFitness + 1);
//plot the graph for the best fitness
let x = 0;
ctx.clearRect(0,0, this.canvas.width, this.canvas.height);
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(0, Params.WindowHeight);
for (let idx = 0; idx < this.bestFitness.length; idx++)
{
ctx.lineTo( ~~x, ~~(Params.WindowHeight - VSlice * this.bestFitness[idx]));
x += HSlice;
}
ctx.stroke();
//plot the graph for the average fitness
x = 0;
ctx.beginPath();
ctx.strokeStyle = 'blue';
ctx.moveTo(0, Params.WindowHeight);
for (let idx = 0; idx < this.avFitness.length; idx++)
{
ctx.lineTo(~~x, ~~(Params.WindowHeight - VSlice * this.avFitness[idx]));
x += HSlice;
}
ctx.stroke();
}
}
class Neuron {
constructor(numInputs) {
this.weights = [];
this.numInputs = numInputs; //we need an additional weight for the bias hence the +1
for (let i = 0; i < this.numInputs; ++i)
{
//set up the weights with an initial random value
this.weights.push(RandomClamped());
}
}
}
class NeuronLayer {
constructor (numNeurons, numInputsPerNeuron) {
this.numNeurons = numNeurons;
this.neurons = [];
for (let i = 0; i < numNeurons; ++i) {
this.neurons.push(new Neuron(numInputsPerNeuron));
}
}
}
class NeuralNet {
layers = [];
constructor()
{
this.numInputs = Params.NumInputs;
this.numOutputs = Params.NumOutputs;
this.numHiddenLayers = Params.NumHidden;
this.neuronsPerHiddenLayer = Params.NeuronsPerHiddenLayer;
this.CreateNet();
}
//------------------------------createNet()------------------------------
//
// this method builds the ANN. The weights are all initially set to
// random values -1 < w < 1
//------------------------------------------------------------------------
CreateNet()
{
//create the layers of the network
if (this.numHiddenLayers > 0) {
this.layers.push(new NeuronLayer(this.neuronsPerHiddenLayer, this.numInputs));
for (let i = 0; i < this.numHiddenLayers - 1; ++i) {
this.layers.push(new NeuronLayer(this.neuronsPerHiddenLayer, this.neuronsPerHiddenLayer));
}
//create output layer
this.layers.push(new NeuronLayer(this.numOutputs, this.neuronsPerHiddenLayer));
} else {
//create output layer
this.layers.push(new NeuronLayer(this.numOutputs, this.numInputs));
}
}
get Weights() {
let weights = [];
for (let i = 0; i < this.numHiddenLayers + 1; ++i) {
for (let j = 0; j < this.layers[i].numNeurons; ++j) {
for (let k = 0; k < this.layers[i].neurons[j].numInputs; ++k) {
weights.push(this.layers[i].neurons[j].weights[k]);
}
}
}
return weights;
}
set Weights(weights) {
let weightIndex = 0;
if (!weights || weights.length < 39) { // Just to debug
console.log('Something weird!');
}
for (let i = 0; i < this.numHiddenLayers + 1; ++i) {
for (let j = 0; j < this.layers[i].numNeurons; ++j) {
for (let k = 0; k < this.layers[i].neurons[j].numInputs; ++k) {
if (weightIndex < weights.length) {
this.layers[i].neurons[j].weights[k] = weights[weightIndex++];
}
}
}
}
}
// TODO: Refactor this ugly code. It can be done in one line
get NumberOfWeights() {
let weights = 0;
for (let i=0; i<this.numHiddenLayers + 1; ++i) {