forked from ermiyaeskandary/Slither.io-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlither.io deep-q-learning bot .user.js
2762 lines (2432 loc) · 106 KB
/
Slither.io deep-q-learning bot .user.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
/*
Copyright (c) 2016 Ermiya Eskandary & Théophile Cailliau and other contributors
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// ==UserScript==
// @name Slither.io deep-q-learning bot
// @namespace http://slither.io/
// @version 0.9.6
// @description Slither.io bot
// @author Ermiya Eskandary & Théophile Cailliau
// @match http://slither.io/
// @updateURL https://github.com/ErmiyaEskandary/Slither.io-bot/raw/master/bot.meta.js
// @downloadURL https://github.com/ErmiyaEskandary/Slither.io-bot/raw/master/bot.user.js
// @supportURL https://github.com/ErmiyaEskandary/Slither.io-bot/issues
// @require http://cs.stanford.edu/people/karpathy/convnetjs/build/convnet.js
// @require https://github.com/karpathy/convnetjs/raw/master/build/util.js
// @require https://github.com/karpathy/convnetjs/raw/master/build/vis.js
// @require https://github.com/karpathy/convnetjs/raw/master/build/deepqlearn.js
// @grant none
// ==/UserScript==
// Custom logging function - disabled by default
window.scores = [];
// Custom logging function - disabled by default
window.log = function() {
if (window.logDebugging) {
console.log.apply(console, arguments);
}
};
window.getWidth = function() {
return window.ww;
};
window.getHeight = function() {
return window.hh;
};
window.getX = function() {
return window.snake.xx;
};
window.getY = function() {
return window.snake.yy;
};
window.getPos = function() {
return {x:window.getX(), y:window.getY()};
};
window.getSnakeLength = function() {
return (Math.floor(150 * (window.fpsls[window.snake.sct] + window.snake
.fam /
window.fmlts[window.snake.sct] - 1) - 50) / 10);
};
window.getSnakeWidth = function(sc) {
sc = sc || window.snake.sc;
return sc * 14.5;
};
window.getSnakeWidthSqr = function(sc) {
sc = sc || window.snake.sc;
var width = window.getSnakeWidth();
return width*width;
};
var canvas = (function() {
return {
// Ratio of screen size divided by canvas size.
canvasRatio: [window.mc.width / window.ww, window.mc.height /
window.hh
],
getScale: function() {
return window.gsc;
},
//Screen coordinates
// X = (0->WindowWidth)
// Y = (0->WindowHeight)
//
//Mouse Coordinates
// X = -Width -> snake.xx -> Width
// Y = -Height -> snake.yy -> Height
//
//Map Coordinates
// X = 0 -> MapWidth
// Y = 0 -> MapHeight
//
//Canvas Coordinates
// X = 0 -> CanvasWidth
// Y = 0 -> CanvasHeight
// Spoofs moving the mouse to the provided coordinates.
setMouseCoordinates: function(point) {
window.xm = point.x;
window.ym = point.y;
},
// Convert snake-relative coordinates to absolute screen coordinates.
mouseToScreen: function(point) {
var screenX = point.x + (window.ww / 2);
var screenY = point.y + (window.hh / 2);
return {
x: screenX,
y: screenY
};
},
// Convert screen coordinates to canvas coordinates.
screenToCanvas: function(point) {
var canvasX = window.csc * (point.x * canvas.canvasRatio[
0]) - parseInt(window.mc.style.left);
var canvasY = window.csc * (point.y * canvas.canvasRatio[
1]) - parseInt(window.mc.style.top);
return {
x: canvasX,
y: canvasY
};
},
// Convert map coordinates to mouse coordinates.
mapToMouse: function(point) {
var mouseX = (point.x - window.snake.xx) * window.gsc;
var mouseY = (point.y - window.snake.yy) * window.gsc;
return {
x: mouseX,
y: mouseY
};
},
// Map cordinates to Canvas cordinate shortcut
mapToCanvas: function(point) {
var c = canvas.mapToMouse(point);
c = canvas.mouseToScreen(c);
c = canvas.screenToCanvas(c);
return c;
},
// Map to Canvas coordinate conversion for drawing circles.
// Radius also needs to scale by .gsc
circleMapToCanvas: function(circle) {
var newCircle = canvas.mapToCanvas(circle);
return canvas.circle(
newCircle.x,
newCircle.y,
circle.radius * window.gsc
);
},
// Constructor for circle type
circle: function(x, y, r) {
var c = {
x: Math.round(x),
y: Math.round(y),
radius: Math.round(r)
};
return c;
},
// Adjusts zoom in response to the mouse wheel.
setZoom: function(e) {
// Scaling ratio
if (window.gsc) {
window.gsc *= Math.pow(0.9, e.wheelDelta / -120 || e.detail / 2 || 0);
window.desired_gsc = window.gsc;
}
},
// Restores zoom to the default value.
resetZoom: function() {
window.gsc = 0.9;
window.desired_gsc = 0.9;
},
// Maintains Zoom
maintainZoom: function() {
if (window.desired_gsc !== undefined) {
window.gsc = window.desired_gsc;
}
},
// Sets background to the given image URL.
// Defaults to slither.io's own background.
setBackground: function(url) {
url = typeof url !== 'undefined' ? url : '/s/bg45.jpg';
window.ii.src = url;
},
// Manual mobile rendering
mobileRendering: function() {
// Set render mode
if (window.mobileRender) {
canvas.setBackground(
'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs'
);
window.render_mode = 1;
} else {
canvas.setBackground();
window.render_mode = 2;
}
},
drawText: function(pos, color, txt) {
var context = window.mc.getContext('2d');
context.font = "10px Arial";
context.fillStyle = color;
context.fillText(txt,pos.x, pos.y);
//context.fill();
},
// Draw a circle on the canvas.
drawCircle: function(circle, colour, fill, alpha) {
if (alpha === undefined) alpha = 1;
if (circle.radius === undefined) circle.radius = 5;
var context = window.mc.getContext('2d');
var drawCircle = canvas.circleMapToCanvas(circle);
context.save();
context.globalAlpha = alpha;
context.beginPath();
context.strokeStyle = colour;
context.arc(drawCircle.x, drawCircle.y, drawCircle.radius,
0, Math.PI * 2);
context.stroke();
if (fill) {
context.fillStyle = colour;
context.fill();
}
context.restore();
},
// Draw a rectangle
drawRect: function(x, y, width, height, color) {
var context = window.mc.getContext('2d');
context.beginPath();
context.rect(x, y, width, height);
context.fillStyle = color;
context.fill();
},
// Draw an angle.
// @param {number} start -- where to start the angle
// @param {number} angle -- width of the angle
// @param {bool} danger -- green if false, red if true
drawAngle: function(start, angle, danger) {
var context = window.mc.getContext('2d');
context.save();
context.globalAlpha = 0.6;
context.beginPath();
context.moveTo(window.mc.width / 2, window.mc.height /
2);
context.arc(window.mc.width / 2, window.mc.height / 2,
window.gsc * 100, start, angle);
context.lineTo(window.mc.width / 2, window.mc.height /
2);
context.closePath();
context.fillStyle = (danger) ? 'red' : 'green';
context.fill();
context.stroke();
context.restore();
},
// Draw a line on the canvas.
drawLine: function(p1, p2, colour, width) {
if (width === undefined) width = 5;
var context = window.mc.getContext('2d');
context.save();
context.beginPath();
context.lineWidth = width * window.gsc;
context.strokeStyle = colour;
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
context.stroke();
context.restore();
},
// Draw a line on the canvas.
drawLine2: function(x1, y1, x2, y2, width, colour) {
var context = window.mc.getContext('2d');
context.beginPath();
context.lineWidth = width * canvas.getScale();
context.strokeStyle = (colour === 'green') ? '#00FF00' : '#FF0000';
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
context.lineWidth = 1;
},
// Check if a point is between two vectors.
// The vectors have to be anticlockwise (sectorEnd on the left of sectorStart).
isBetweenVectors: function(point, sectorStart, sectorEnd) {
var center = [window.snake.xx, window.snake.yy];
if (point.xx) {
// Point coordinates relative to center
var relPoint = {
x: point.xx - center[0],
y: point.yy - center[1]
};
return (!canvas.areClockwise(sectorStart, relPoint) &&
canvas.areClockwise(sectorEnd, relPoint));
}
return false;
},
// Angles are given in radians. The overall angle (endAngle-startAngle)
// cannot be above Math.PI radians (180°).
isInsideAngle: function(point, startAngle, endAngle) {
// calculate normalized vectors from angle
var startAngleVector = {
x: Math.cos(startAngle),
y: Math.sin(startAngle)
};
var endAngleVector = {
x: Math.cos(endAngle),
y: Math.sin(endAngle)
};
// Use isBetweenVectors to check if the point belongs to the angle
return canvas.isBetweenVectors(point, startAngleVector,
endAngleVector);
},
/*
* Given two vectors, return a truthy/falsy value depending
* on their position relative to each other.
*/
areClockwise: function(vector1, vector2) {
// Calculate the dot product.
return -vector1.x * vector2.y + vector1.y * vector2.x >
0;
},
// Given an object (of which properties xx and yy are not null),
// return the object with an additional property 'distance'.
getDistanceFromSnake: function(point) {
point.distance = canvas.getDistance(window.snake.xx,
window.snake.yy,
point.xx, point.yy);
return point;
},
getDistance: function(x1, y1, x2, y2) {
var distance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(
y1 - y2, 2));
return distance;
},
// Get distance squared
getDistance2: function(x1, y1, x2, y2) {
var distance2 = Math.pow(x1 - x2, 2) + Math.pow(y1 - y2,
2);
return distance2;
},
getDistance2FromSnake: function(point) {
point.distance = canvas.getDistance2(window.snake.xx,
window.snake.yy,
point.xx, point.yy);
return point;
},
};
})();
// A 2D vector utility
var Vec = function(x, y) {
this.x = x;
this.y = y;
};
Vec.prototype = {
// utilities
dist_from: function(v) { return Math.sqrt(Math.pow(this.x-v.x,2) + Math.pow(this.y-v.y,2)); },
length: function() { return Math.sqrt(Math.pow(this.x,2) + Math.pow(this.y,2)); },
// new vector returning operations
add: function(v) { return new Vec(this.x + v.x, this.y + v.y); },
sub: function(v) { return new Vec(this.x - v.x, this.y - v.y); },
rotate: function(a) { // CLOCKWISE
return new Vec(this.x * Math.cos(a) + this.y * Math.sin(a),
-this.x * Math.sin(a) + this.y * Math.cos(a));
},
// in place operations
scale: function(s) { this.x *= s; this.y *= s; },
normalize: function() { var d = this.length(); this.scale(1.0/d); }
};
var line_intersect = function(p1,p2,p3,p4) {
var denom = (p4.y-p3.y)*(p2.x-p1.x)-(p4.x-p3.x)*(p2.y-p1.y);
if(denom===0.0) { return false; } // parallel lines
var ua = ((p4.x-p3.x)*(p1.y-p3.y)-(p4.y-p3.y)*(p1.x-p3.x))/denom;
var ub = ((p2.x-p1.x)*(p1.y-p3.y)-(p2.y-p1.y)*(p1.x-p3.x))/denom;
if(ua>0.0&&ua<1.0&&ub>0.0&&ub<1.0) {
var up = new Vec(p1.x+ua*(p2.x-p1.x), p1.y+ua*(p2.y-p1.y));
return {ua:ua, ub:ub, up:up}; // up is intersection point
}
return false;
};
var line_point_intersect = function(p1,p2,p0,rad) {
var v = new Vec(p2.y-p1.y,-(p2.x-p1.x)); // perpendicular vector
var d = Math.abs((p2.x-p1.x)*(p1.y-p0.y)-(p1.x-p0.x)*(p2.y-p1.y));
d = d / v.length();
if(d > rad) { return false; }
v.normalize();
v.scale(d);
var up = new Vec(0,0);
up.x = p0.x + v.x;
up.y = p0.y + v.y;
if(Math.abs(p2.x-p1.x)>Math.abs(p2.y-p1.y)) {
var ua = (up.x - p1.x) / (p2.x - p1.x);
} else {
var ua = (up.y - p1.y) / (p2.y - p1.y);
}
if(ua>0.0&&ua<1.0) {
return {ua:ua, up:up};
}
return false;
};
// Eye sensor has a maximum range and senses walls
var Eye = function(angle) {
this.angle = angle; // angle relative to agent its on
this.max_range = 600;
this.sensed_proximity = 600; // what the eye is seeing. will be set in world.tick()
this.sensed_type = -1; // what does the eye see?
};
// A single agent
var Agent = function() {
window.log("新規作成");
// positional information
this.p = new Vec(50,50);
this.op = this.p; // old position
this.angle = 0; // direction facing
this.actions = [];
this.actions.push([1,1]);
this.actions.push([0.8,1]);
this.actions.push([1,0.8]);
this.actions.push([0.5,0]);
this.actions.push([0,0.5]);
// properties
this.rad = 10;
this.eyes = [];
for(var k=0;k<9;k++) { this.eyes.push(new Eye((k-4)*0.25)); }
// braaain
//this.brain = new deepqlearn.Brain(this.eyes.length * 3, this.actions.length);
var num_inputs = 27; // 9 eyes, each sees 3 numbers (wall, green, red thing proximity)
var num_actions = 5; // 5 possible angles agent can turn
var temporal_window = 1; // amount of temporal memory. 0 = agent lives in-the-moment :)
var network_size = num_inputs*temporal_window + num_actions*temporal_window + num_inputs;
// the value function network computes a value of taking any of the possible actions
// given an input state. Here we specify one explicitly the hard way
// but user could also equivalently instead use opt.hidden_layer_sizes = [20,20]
// to just insert simple relu hidden layers.
var layer_defs = [];
layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:network_size});
layer_defs.push({type:'fc', num_neurons: 50, activation:'relu'});
layer_defs.push({type:'fc', num_neurons: 50, activation:'relu'});
layer_defs.push({type:'regression', num_neurons:num_actions});
// options for the Temporal Difference learner that trains the above net
// by backpropping the temporal difference learning rule.
var tdtrainer_options = {learning_rate:0.001, momentum:0.0, batch_size:64, l2_decay:0.01};
var opt = {};
opt.temporal_window = temporal_window;
opt.experience_size = 30000;
opt.start_learn_threshold = 1000;
opt.gamma = 0.7;
opt.learning_steps_total = 200000;
opt.learning_steps_burnin = 3000;
opt.epsilon_min = 0.05;
opt.epsilon_test_time = 0.05;
opt.layer_defs = layer_defs;
opt.tdtrainer_options = tdtrainer_options;
var brain = new deepqlearn.Brain(num_inputs, num_actions, opt); // woohoo
this.brain = brain;
this.reward_bonus = 0.0;
this.digestion_signal = 0.0;
// outputs on world
this.rot1 = 0.0; // rotation speed of 1st wheel
this.rot2 = 0.0; // rotation speed of 2nd wheel
this.prevactionix = -1;
this.oldleng = 0;
};
Agent.prototype = {
forward: function() {
// in forward pass the agent simply behaves in the environment
// create input to brain
var num_eyes = this.eyes.length;
var input_array = new Array(num_eyes * 3);
for(var i=0;i<num_eyes;i++) {
var e = this.eyes[i];
input_array[i*3] = 1.0;
input_array[i*3+1] = 1.0;
input_array[i*3+2] = 1.0;
if(e.sensed_type !== -1) {
// sensed_type is 0 for wall, 1 for food and 2 for poison.
// lets do a 1-of-k encoding into the input array
input_array[i*3 + e.sensed_type] = e.sensed_proximity/e.max_range; // normalize to [0,1]
}
}
// get action from brain
var actionix = this.brain.forward(input_array);
var action = this.actions[actionix];
this.actionix = actionix; //back this up
// demultiplex into behavior variables
this.rot1 = action[0]*1;
this.rot2 = action[1]*1;
//this.rot1 = 0;
//this.rot2 = 0;
},
backward: function() {
// in backward pass agent learns.
// compute reward
var proximity_reward = 0.0;
var num_eyes = this.eyes.length;
for(var i=0;i<num_eyes;i++) {
var e = this.eyes[i];
// agents dont like to see walls, especially up close
proximity_reward += e.sensed_type === 0 ? e.sensed_proximity/e.max_range : 1.0;
//if(e.sensed_type == 2) proximity_reward -= 0.25;
if(e.sensed_type == 0) proximity_reward -= (e.max_range - e.sensed_proximity )/50;
}
proximity_reward = proximity_reward/num_eyes;
proximity_reward = Math.min(1.0, proximity_reward * 2);
// agents like to go straight forward
var forward_reward = 0.0;
if(this.actionix === 0 && proximity_reward > 0.75) forward_reward = 0.1 * proximity_reward;
// agents like to eat good things
var digestion_reward = this.digestion_signal;
this.digestion_signal = 0.0;
var leng_reward = 0;
//if( window.getSnakeLength() - this.oldleng < 0){this.oldleng = window.getSnakeLength();console.log("He is dead");}
leng_reward += (window.getSnakeLength() - this.oldleng)/25;
leng_reward += window.getSnakeLength()/1000;
if( window.getSnakeLength() - this.oldleng > 20){leng_reward += window.getSnakeLength()/50;console.log("ボーナス!");}
if( this.oldleng - window.getSnakeLength() > 0){leng_reward -= 60.0;console.log("死亡確認");}
this.oldleng = window.getSnakeLength();
var reward = proximity_reward + forward_reward + digestion_reward + leng_reward;
// pass to brain for learning
this.brain.backward(reward);
}
};
var bot = (function() {
// Save the original slither.io onmousemove function so we can re enable it back later
var original_onmousemove = window.onmousemove;
var oldpos=0;
return {
ranOnce: false,
tickCounter: 0,
isBotRunning: false,
isBotEnabled: true,
collisionPoints: [],
currentPath: [],
radarResults: [],
followLine: 0,
hideTop: function () {
var nsidivs = document.querySelectorAll('div.nsi');
for (var i = 0; i < nsidivs.length; i++) {
if (nsidivs[i].style.top === '4px' && nsidivs[i].style
.width === '300px') {
nsidivs[i].style.visibility = 'hidden';
nsidivs[i].style.zIndex = -1;
bot.isTopHidden = true;
}
}
},
startBot: function() {
if (window.autoRespawn && !window.playing && bot.isBotEnabled &&
bot.ranOnce && !bot.isBotRunning) {
bot.connectBot();
if (document.querySelector('div#lastscore').childNodes
.length > 1) {
window.scores.push(parseInt(document.querySelector(
'div#lastscore').childNodes[1].innerHTML));
}
}
if (window.bso !== undefined) {
var generalStyle =
'<span style = "opacity: 0.35";>';
window.ip_overlay.innerHTML = generalStyle +
'Server: ' + window.bso.ip + ':' + window.bso.po;
}
},
launchBot: function() {
window.log('Starting Bot.');
bot.isBotRunning = true;
/*
* Removed the onmousemove listener so we can move the snake
* manually by setting coordinates
*/
userInterface.onPrefChange();
window.onmousemove = function() {};
bot.hideTop();
if(!bot.agents)bot.agents = new Agent();
},
// Stops the bot
stopBot: function() {
window.log('Stopping Bot.');
window.setAcceleration(0); // Stop boosting
// Re-enable the original onmousemove function
window.onmousemove = original_onmousemove;
bot.isBotRunning = false;
},
// Connects the bot
connectBot: function() {
if (!window.autoRespawn) return;
bot.stopBot(); // Just in case
window.log('Connecting...');
window.connect();
// Wait until we're playing to start the bot
window.botCanStart = setInterval(function() {
if (window.playing) {
bot.launchBot();
clearInterval(window.botCanStart);
}
}, 100);
},
forceConnect: function() {
if (!window.connect) {
return;
}
window.forcing = true;
if (!window.bso) {
window.bso = {};
}
window.currentIP = window.bso.ip + ':' + window.bso.po;
var srv = window.currentIP.trim().split(':');
window.bso.ip = srv[0];
window.bso.po = srv[1];
window.connect();
},
quickRespawn: function() {
window.dead_mtm = 0;
window.login_fr = 0;
bot.forceConnect();
},
changeSkin: function() {
if (window.playing && window.snake !== null) {
var skin = window.snake.rcv;
var max = window.max_skin_cv;
skin++;
if (skin > max) {
skin = 0;
}
window.setSkin(window.snake, skin);
}
},
rotateSkin: function() {
if (!window.rotateskin) {
return;
}
bot.changeSkin();
setTimeout(bot.rotateSkin, 500);
},
// Sorting by property 'distance'
sortDistance: function(a, b) {
return a.distance - b.distance;
},
startlearn : function() {
bot.agents.brain.learning = true;
},
stoplearn: function() {
bot.agents.brain.learning = false;
},
// Sorting function for food, from property 'clusterCount'
sortFood: function(a, b) {
return (a.clusterScore === b.clusterScore ? 0 :
a.clusterScore / a.distance > b.clusterScore / b.distance ? -1 :
1);
},
computeFoodGoal: function() {
var sortedFood = bot.getSortedFood();
// eslint-disable-next-line no-unused-vars
var bestClusterIndx = 0;
var bestClusterScore = 0;
var bestClusterAbsScore = 0;
var bestClusterX = 20000;
var bestClusterY = 20000;
var clusterScore = 0;
var clusterSize = 0;
var clusterAbsScore = 0;
var clusterSumX = 0;
var clusterSumY = 0;
// there is no need to view more points (for performance)
var nIter = Math.min(sortedFood.length, 300);
for (var i = 0; i < nIter; i += 2) {
clusterScore = 0;
clusterSize = 0;
clusterAbsScore = 0;
clusterSumX = 0;
clusterSumY = 0;
var p1 = sortedFood[i];
for (var j = 0; j < nIter; ++j) {
var p2 = sortedFood[j];
var dist = canvas.getDistance2(p1.xx, p1.yy, p2
.xx, p2.yy);
if (dist < 100 * 100) {
clusterScore += p2.sz;
clusterSumX += p2.xx * p2.sz;
clusterSumY += p2.yy * p2.sz;
clusterSize += 1;
}
}
clusterAbsScore = clusterScore;
clusterScore /= p1.distance;
if (clusterSize > 2 && clusterScore >
bestClusterScore) {
bestClusterScore = clusterScore;
bestClusterAbsScore = clusterAbsScore;
bestClusterX = clusterSumX / clusterAbsScore;
bestClusterY = clusterSumY / clusterAbsScore;
bestClusterIndx = i;
}
}
window.currentFoodX = bestClusterX;
window.currentFoodY = bestClusterY;
// if see a large cluster then use acceleration
if (bestClusterAbsScore > 50) {
window.foodAcceleration = 1;
} else {
window.foodAcceleration = 0;
}
},
processSurround: function() {
collisionGrid.initGrid(100, 100, 20);
//bot.radarResults = collisionHelper.radarScan(15,1000);
},
getCollisionPoints: function() {
bot.collisionPoints = [];
var scPoint;
for (var snake = 0, ls = window.snakes.length; snake <
ls; snake++) {
scPoint = undefined;
if (window.snakes[snake].nk !== window.snake.nk) {
if (window.visualDebugging) {
var hCircle = {
x: window.snakes[snake].xx,
y: window.snakes[snake].yy,
radius: window.getSnakeWidth(window
.snakes[snake].sc)
};
canvas.drawCircle(canvas.circleMapToCanvas(
hCircle), 'red', false);
}
for (var pts = 0, lp = window.snakes[snake].pts
.length; pts <
lp; pts++) {
if (!window.snakes[snake].pts[pts].dying) {
var collisionPoint = {
headxx: window.snakes[snake].xx,
headyy: window.snakes[snake].yy,
xx: window.snakes[snake].pts[
pts].xx,
yy: window.snakes[snake].pts[
pts].yy,
sc: window.snakes[snake].sc,
sp: window.snakes[snake].sp,
ang: window.snakes[snake].ang,
snake: snake
};
canvas.getDistance2FromSnake(
collisionPoint);
if (scPoint === undefined || scPoint.distance >
collisionPoint.distance) {
scPoint = collisionPoint;
}
}
}
}
if (scPoint !== undefined) {
bot.collisionPoints.push(scPoint);
if (window.visualDebugging) {
var cCircle = {
x: scPoint.xx,
y: scPoint.yy,
radius: window.getSnakeWidth(
scPoint.sc)
};
canvas.drawCircle(canvas.circleMapToCanvas(
cCircle), 'red', false);
}
}
}
bot.collisionPoints.sort(bot.sortDistance);
},
stuff_collide_: function(p1, p2, check_walls, check_items) {
var minres = false;
// collision(type:0)
// collide with walls
if(check_walls) {
bot.getCollisionPoints();
if (bot.collisionPoints.length === 0) return false;
for(var i=0,n=bot.collisionPoints.length;i<n;i++) {
var wallp = {
x : bot.collisionPoints[i].xx,
y : bot.collisionPoints[i].yy
};
var res = line_point_intersect(p1, p2, wallp ,300 );
if(res) {
res.type = 0; // 0 is wall
if(!minres) { minres=res; }
else {
// check if its closer
if(res.ua < minres.ua) {
// if yes replace it
minres = res;
}
}
}
}
}
if(res.type != 0) {
window.setAcceleration(0);
bot.processSurround();
// feed(type:1)
// collide with items
if(check_items) {
for(var j=0,k=window.foods.length;j<k;j++) {
if(window.foods[j]){
var foodPos = {x: window.foods[j].xx, y:window.foods[j].yy};
var res = line_point_intersect(p1, p2, foodPos, 50 );
if(res) {
res.type = 1; // store type of item
if(!minres) { minres=res; }
else {
if(res.ua < minres.ua) { minres = res; }
}
}
}
}
}
}
return minres;
},
tickAI : function () {
// process eyes
var a = bot.agents;
for(var ei=0,ne=a.eyes.length;ei<ne;ei++) {
var e = a.eyes[ei];
// we have a line from p to p->eyep
var eyep = new Vec(a.p.x + e.max_range * Math.cos(a.angle + e.angle),
a.p.y + e.max_range * Math.sin(a.angle + e.angle));
var res = bot.stuff_collide_(a.p, eyep, true, true);
if(res) {
// eye collided with wall
e.sensed_proximity = res.up.dist_from(a.p);
e.sensed_type = res.type;
//if(res.type == 0 && e.sensed_proximity < 40.0){a.digestion_signal += -6.0;console.log("-6")}
//if(res.type == 1 && e.sensed_proximity < 20.0){a.digestion_signal += 1.0;console.log("+1")}
} else {
e.sensed_proximity = e.max_range;
e.sensed_type = 2;
}
}
// let the agents behave in the world based on their input
bot.agents.forward();
// apply outputs of agents on evironment
a.op = a.p; // back up old position
a.oangle = a.angle; // and angle
// steer the agent according to outputs of wheel velocities
// There is no need to move the agent itself
a.p = new Vec(window.snake.xx, window.snake.yy);
a.angle = window.snake.ang;
// Update the eye
for(var ei=0,ne=bot.agents.eyes.length;ei<ne;ei++) {
var e = bot.agents.eyes[ei];
if (window.visualDebugging) {
var headCoord = {
x: a.p.x ,
y: a.p.y
};
var headCoord2 = {
x: a.p.x + e.max_range * Math.cos(a.angle + e.angle),
y: a.p.y + e.max_range * Math.sin(a.angle + e.angle)
};
var headCoord3 = {
x: a.p.x + e.sensed_proximity * Math.cos(a.angle + e.angle),
y: a.p.y + e.sensed_proximity * Math.sin(a.angle + e.angle)
};
//canvas.drawLine(canvas.mapToCanvas(headCoord),canvas.mapToCanvas(headCoord3),'white',1);
if(e.sensed_type == 0)canvas.drawLine(canvas.mapToCanvas(headCoord),canvas.mapToCanvas(headCoord3),'red',3);
if(e.sensed_type == 1)canvas.drawLine(canvas.mapToCanvas(headCoord),canvas.mapToCanvas(headCoord3),'green',3);
if(e.sensed_type == 2)canvas.drawLine(canvas.mapToCanvas(headCoord),canvas.mapToCanvas(headCoord3),'blue',3);
}
}
// Action decision
// steer the agent according to outputs of wheel velocities
var v = new Vec(0, bot.agents.rad / 2.0);
v = v.rotate(bot.agents.angle + Math.PI/2);
var w1p = bot.agents.p.add(v); // positions of wheel 1 and 2
var w2p = bot.agents.p.sub(v);
var vv = bot.agents.p.sub(w2p);
vv = vv.rotate(-bot.agents.rot1);
var vv2 = bot.agents.p.sub(w1p);
vv2 = vv2.rotate(bot.agents.rot2);
var np = w2p.add(vv);
np.scale(0.5);
var np2 = w1p.add(vv2);
np2.scale(0.5);
var newpos = np.add(np2);
var botangle = 0;
botangle = bot.agents.angle;
botangle -= bot.agents.rot1;
if(botangle<0)botangle+=2*Math.PI;
botangle += bot.agents.rot2;
if(botangle>2*Math.PI)botangle-=2*Math.PI;
//目標をセット
var golp = {
x : bot.agents.p.x + 300 * Math.cos(botangle),
y : bot.agents.p.y + 300 * Math.sin(botangle)
};
window.goalCoordinates = golp;
canvas.setMouseCoordinates(canvas.mapToMouse(
window.goalCoordinates));
// agents are given the opportunity to learn based on feedback of their action on environment
bot.agents.backward();
},
// bot main
// Called by the window loop, this is the main logic of the bot.
thinkAboutGoals: function() {
// If no enemies or obstacles, go after what you are going after
window.setAcceleration(0);
// It will not be updated while the dead
if( oldpos.x != window.getPos().x && oldpos.y != window.getPos().y)
{
bot.agents.brain.learning = true;
bot.tickAI();
}