forked from RealDebugMonkey/ZeachCobbler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZeachCobbler.user.js
5296 lines (4906 loc) · 215 KB
/
ZeachCobbler.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
// ==UserScript==
// @name Agar.io Ilboued Bot
//
// @namespace https://github.com/corand98/ZeachCobbler/
//
// @updateURL https://raw.githubusercontent.com/corando98/ZeachCobbler/master/ZeachCobbler.user.js
// @downloadURL https://raw.githubusercontent.com/corando98/ZeachCobbler/master/ZeachCobbler.user.js
//
// @contributer See full list at https://github.com/RealDebugMonkey/ZeachCobbler#contributors-and-used-code
//
// @version 0.5
//
// @description Agario powerups and bot
//
// @author Daigo (based on liboued and IBR ZeachCobbler)
//
// @match http://agar.io
// @match https://agar.io
//
// @changes 0.5 - add voice volume tuning + online map
// 0.4 - voice message at each mass big step (300-600-1000)
// 0.3 - app name change
// - tab title include a circle colored vs mass + a digit :
// - 0:0->99, 1:100->199, 2:200->199, 3: ...
// - black(0-300)/red(300-600)/orange(600-1000)/green(>1000)
// or magentaga + 'X' if on the leader board
// 0.2 - change version for testing
// 0.1 - fork from https://github.com/RealDebugMonkey/ZeachCobbler
// @require https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js
// @require https://cdn.firebase.com/js/client/2.2.9/firebase.js
// xxxxxx https://cdnjs.cloudflare.com/ajax/libs/annyang/2.0.0/annyang.min.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// ==/UserScript==
var _version_ = GM_info.script.version;
var debugMonkeyReleaseMessage = "<h3>Protocol Changes and Burnout</h3><p>" +
"Hey guys. I've patched the no-movement issue. Sorry for the inconvenience and for the delay in making a fix. <br><br>" +
"I've been a bit burnt out on Agar.io so I've been taking it easy. I'd like to thank PepinCZ, Gjum, and all " +
"the others who have been helpful in the github issues area during my away time. You guys are the real MVPs.<br>" +
"<img src='http://i.imgur.com/p4zv6vx.jpg'><br><br>-debugmonkey";
$.getScript("https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.4.1/canvas.min.js");
$.getScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js");
unsafeWindow.connect2 = unsafeWindow.connect;
jQuery("#canvas").remove();
jQuery("#connecting").after('<canvas id="canvas" width="800" height="600"></canvas>');
// ========================================================================================
// ========================================================================================
// A = Original Agar.io code + hack...
// ========================================================================================
// ========================================================================================
(function(d, f) {
// Options that will always be reset on reload
var zoomFactor = 10;
var isGrazing = 2;
var serverIP = "";
var showVisualCues = true;
// Game State & Info
var highScore = 0;
var timeSpawned = null;
var grazzerTargetResetRequest = false;
var nearestVirusID;
var suspendMouseUpdates = false;
var grazingTargetFixation = false;
var selectedBlobID = null;
// Constants
var Huge = 2.66,
Large = 1.25,
Small = 0.7,
Tiny = 0.375;
var Huge_Color = "#FF3C3C",
Large_Color = "#FFBF3D",
Same_Color = "#FFFF00",
Small_Color = "#00AA00",
Tiny_Color = "#CC66FF",
myColor ="#3371FF",
virusColor ="#666666";
var lastMouseCoords = { x: 0, y: 0 };
var ghostBlobs = [];
var miniMapCtx = jQuery('<canvas id="mini-map" width="175" height="175" style="border:2px solid #999;text-align:center;position:fixed;bottom:5px;right:5px;"></canvas>')
.appendTo(jQuery('body'))
.get(0)
.getContext("2d");
// nonPersistantUserOptions is the object that holds all user options. Options that should never be persisted can be defined here.
// If an option setting should be remembered it can
var nonPersistantUserOptions = {
set grazingMode(val) {isGrazing = val;},
get grazingMode() {return isGrazing;},
_isAcid : false,
set isAcid(val) {this._isAcid = val; setAcid(val);},
get isAcid() {return this._isAcid;},
minimapScaleCurrentValue : 1,
"displayMiniMap" : true,
};
// utility function to simplify creation of options whose state should be persisted to disk
function simpleSavedSettings(optionsObject){
_.forEach(optionsObject, function(defaultValue, settingName){
var backingVar = '_' + settingName;
nonPersistantUserOptions[backingVar] = GM_getValue(settingName, defaultValue),
Object.defineProperty(nonPersistantUserOptions, settingName, {
get: function() { return this[backingVar];},
set: function(val) { this[backingVar] = val; GM_setValue(settingName, val); }
});
});
}
// defines all options that should be persisted along with their default values.
function makeNonPersistantUserOptions(){
var optionsAndDefaults = {
"isLiteBrite" : true,
"sfxVol" : 0.0,
"bgmVol" : 0.0,
"voiceVol" : 0.0,
"drawTail" : false,
"splitGuide" : true,
"rainbowPellets" : true,
"debugLevel" : 0,
"imgurSkins" : true,
"amExtendedSkins" : true,
"amConnectSkins" : true,
"namesUnderBlobs" : false,
"grazerMultiBlob2" : false,
"grazerHybridSwitch": false,
"grazerHybridSwitchMass" : 300,
"gridLines" : true,
"autoRespawn" : true,
"visualizeGrazing" : true,
"msDelayBetweenShots" : 100,
"miniMapScale" : false,
"miniMapScaleValue" : 64,
"enableBlobLock" : false,
'nextOnBlobLock' : false,
'rightClickFires' : false,
'showZcStats' : false,
};
simpleSavedSettings(optionsAndDefaults);
}
makeNonPersistantUserOptions();
window.nonPersistantUserOptions = nonPersistantUserOptions;
// ====================== Property & Var Name Restoration =======================================================
var zeach = {
// ilboued AddOn
leaderBoard : 0,
nickName : 'no name',
simpleBlobList : {},
get serverIP() {return serverIP;},
get mass() {return ~~(wb()/100);},
get autopilot() {return isGrazing;},
get posX() {return getSelectedBlob().x;},
get posY() {return getSelectedBlob().y;},
get version() {return GM_info.script.version;},
get isAlive() {return !!zeach.myPoints.length;},
get connect() {return Aa;}, // Connect
get ctx() {return g;}, // g_context
get webSocket() {return r;}, // g_socket
get myIDs() {return K;}, // g_playerCellIds
get myPoints() {return m;}, // g_playerCells
get allNodes() {return D;}, // g_cellsById
get allItems() {return v;}, // g_cells
get mouseX2() {return fa;}, // g_moveX
get mouseY2() {return ga;}, // g_moveY
get mapLeft() {return oa;}, // g_minX
get mapTop() {return pa;}, // g_minY
get mapRight() {return qa;}, // g_maxX
get mapBottom() {return ra;}, // g_maxY
get isShowSkins() {return fb;}, // g_showSkins
get isNightMode() {return sa;}, // ??
get isShowMass() {return gb;}, // ??
get gameMode() {return O;}, // g_mode
get fireFunction() {return G;}, // SendCmd
get isColors() {return Ka;}, // g_noColors
get defaultSkins() {return jb;}, // g_skinNamesA
get imgCache() {return T;}, // ???
get textFunc() {return ua;}, // CachedCanvas
get textBlobs() {return Bb;}, // g_skinNamesB
get hasNickname() {return va;}, // g_showNames
get scale() {return k;}, //
// Classes
get CachedCanvas() {return ua;}, // CachedCanvas
get Cell() {return aa;}, //
// These never existed before but are useful
get mapWidth() {return ~~(Math.abs(zeach.mapLeft) + zeach.mapRight);},
get mapHeight() {return ~~(Math.abs(zeach.mapTop) + zeach.mapBottom);},
};
function restoreCanvasElementObj(objPrototype){
var canvasElementPropMap = {
'setValue' : 'C', //
'render' : 'L', //
'setScale' : 'ea', //
'setSize' : 'M', //
};
_.forEach(canvasElementPropMap, function(newPropName,oldPropName){
Object.defineProperty(objPrototype, oldPropName, {
get: function() { return this[newPropName];},
set: function(val) { this[newPropName] = val; }
});
});
}
// Cell
function restorePointObj(objPrototype){
var pointPropMap = {
'isVirus' : 'h', //
'nx' : 'J', //
'ny' : 'K', //
'setName' : 'B', //
'nSize' : 'q', //
'ox' : 's', //
'oy' : 't', //
'oSize' : 'r', //
'destroy' : 'X', //
'maxNameSize' : 'l', //
'massText' : 'O', //
'nameCache' : 'o', //
'isAgitated' : 'n'
};
_.forEach(pointPropMap, function(newPropName,oldPropName){
Object.defineProperty(objPrototype, oldPropName, {
get: function() { return this[newPropName];},
set: function(val) { this[newPropName] = val; }
});
});
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//
// main ilboued main
//
//
// connect to cloud database to store mass, pos, name....
var myFirebaseRef2 = new Firebase("https://ilboued10.firebaseio.com/");
//
// 0.5Hz timer : store parameters + refresh tab title
//
function timer2s() {
window.document.title = zeach.mass + ' ' + zeach.nickName; // current mass
if (zeach.isAlive) {
myFirebaseRef2.child('allPlayers/' + zeach.nickName).set({
version : zeach.version,
mass : zeach.mass,
autopilot : zeach.autopilot,
serverIP : zeach.serverIP,
dividedIn : zeach.myPoints.length,
position : {
x : zeach.posX,
y : zeach.posY
}
});
}
// myFirebaseRef2.child('allBlobs').set(zeach.simpleBlobList);
// console.log('#fired => ' + zeach.simpleBlobList);
if (zeach.leaderBoard>0) {
setFavicon('magenta');
} else if (zeach.mass < 300) {
setFavicon("black");
} else if (zeach.mass < 600 ) {
setFavicon("red");
} else if (zeach.mass < 1000 ) {
setFavicon("orange");
} else {
setFavicon("green");
}
sayIfLevelChange(zeach.nickName, zeach.mass, window.nonPersistantUserOptions.voiceVol);
}
//
function timer30Hz() {
if (zeach.isAlive) {
zeach.simpleBlobList[0] = {
isVirus : false,
name : zeach.nickName,
size : 0,
x : zeach.posX,
y : zeach.posY
}
myFirebaseRef2.child('allBlobs').set(zeach.simpleBlobList);
}
}
window.setInterval(timer30Hz,33);
window.setInterval(timer2s,2000);
//
// keyboard
//
function onKeyPressed(key) {
if ('I'.charCodeAt(0) === key) {
//setFavicon("#FFF");
} else if ('F'.charCodeAt(0) === key) {
toggleFullScreen();
}
}
//
// speech synthesis
//
function sayIfLevelChange(name,mass,volume) {
// Check to see if the counter has been initialized
if ( typeof sayIfLevelChange.currentLevel == 'undefined' ) {
// It has not... perform the initialization
sayIfLevelChange.currentLevel = 0;
}
var newLevel = 0;
if (mass<300) {
newLevel = 0;
} else if (mass<600) {
newLevel = 300;
} else if (mass<900) {
newLevel = 600;
} else if (mass<1200) {
newLevel = 900;
} else {
newLevel = 1200;
}
// console.log('current level : ' + sayIfLevelChange.currentLevel);
if (newLevel>sayIfLevelChange.currentLevel) {
say(name + ' dépasse les ' + newLevel, volume);
}
sayIfLevelChange.currentLevel = newLevel;
}
//
//
function say(message, volume) {
var msg = new SpeechSynthesisUtterance(message);
msg.lang = 'fr-FR';
msg.volume = volume;
speechSynthesis.speak(msg);
}
//unsafeWindow.say = say;
//$('#gamemode').val(':teams');
//$('#nick').val('ilboued')
// Speech recognition...
/*
if (annyang) {
// Let's define a command.
console.log('annyang started !');
var commands = {
'bonjour': function() { toggleFullScreen(); say('ok !'); }
};
// Add our commands to annyang
annyang.addCommands(commands);
// Start listening.
annyang.setLanguage('fr-FR');
annyang.start();
} else {
console.log('annyang not started :-(');
}
*/
//
// favicon update (called by 0.5Hz timer
//
function setFavicon(color) {
document.head = document.head || document.getElementsByTagName('head')[0];
var canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
var ctx = canvas.getContext('2d');
var img = new Image();
ctx.drawImage(img, 0, 0);
ctx.lineWidth = 0
ctx.beginPath();
ctx.arc(16, 16, 16, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
ctx.strokeStyle = color;
ctx.stroke();
ctx.fillStyle = 'white';
ctx.font = 'bold 32px sans-serif';
var aDigit = (~~(zeach.mass/100.0)).toString();
if (zeach.mass > 1000) {
aDigit = 'X';
}
ctx.fillText(aDigit, 7, 27);
var link = document.createElement('link');
var oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = canvas.toDataURL("image/x-icon");
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}
//
// toggleFullScreen (called by keyboard)
//
function toggleFullScreen() {
if (!document.fullscreenElement && // alternative standard method
!document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) { // current working methods
say("mode plein écran !");
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.msRequestFullscreen) {
document.documentElement.msRequestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
say("mode fenêtré !");
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
/*
myFirebaseRef.child("location/city").on("value", function(snapshot) {
alert(snapshot.val()); // Alerts "San Francisco"
});
*/
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
// ====================== Utility code ==================================================================
function isFood(blob){
return (blob.nSize < 15);
}
function getSelectedBlob(){
if(!_.contains(zeach.myIDs, selectedBlobID)){
selectedBlobID = zeach.myPoints[0].id;
//console.log("Had to select new blob. Its id is " + selectedBlobID);
}
return zeach.allNodes[selectedBlobID];
}
function isPlayerAlive(){
return !!zeach.myPoints.length;
}
function sendMouseUpdate(ws, mouseX2, mouseY2, blob) {
lastMouseCoords = {x: mouseX2, y: mouseY2};
if (ws && ws.readyState == ws.OPEN) {
var blobId = blob ? blob.id : 0;
var z0 = new ArrayBuffer(13);
var z1 = new DataView(z0);
z1.setUint8(0, 16);
z1.setInt32(1, mouseX2, true);
z1.setInt32(5, mouseY2, true);
z1.setUint32(9, blobId, true);
ws.send(z0);
}
}
function getMass(x){
return x*x/100;
}
function lineDistance( point1, point2 ){
var xs = point2.nx - point1.nx;
var ys = point2.ny - point1.ny;
return Math.sqrt( xs * xs + ys * ys );
}
function getVirusShotsNeededForSplit(cellSize){
return ~~((149-cellSize)/7);
}
function calcTTR(element){
var totalMass = _.sum(_.pluck(zeach.myPoints, "nSize").map(getMass));
return ~~((((totalMass*0.02)*1000)+30000) / 1000) - ~~((Date.now() - element.splitTime) / 1000);
}
function getBlobShotsAvailable(blob) {
return ~~(Math.max(0, (getMass(blob.nSize)-(35-18))/18));
}
function distanceFromCellZero(blob) {
return isPlayerAlive() ? lineDistance(blob, getSelectedBlob()) :
Math.sqrt((zeach.mapRight - zeach.mapLeft) * (zeach.mapRight - zeach.mapLeft) + (zeach.mapBottom - zeach.mapTop) * (zeach.mapBottom - zeach.mapTop));
}
function getViewport(interpolated) {
var x = _.sum(_.pluck(zeach.myPoints, interpolated ? "x" : "nx")) / zeach.myPoints.length;
var y = _.sum(_.pluck(zeach.myPoints, interpolated ? "y" : "ny")) / zeach.myPoints.length;
var totalRadius = _.sum(_.pluck(zeach.myPoints, interpolated ? "size" : "nSize"));
var zoomFactor = Math.pow(Math.min(64.0 / totalRadius, 1), 0.4);
var deltaX = 1024 / zoomFactor;
var deltaY = 600 / zoomFactor;
return { x: x, y: y, dx: deltaX, dy: deltaY };
}
function getMouseCoordsAsPseudoBlob(){
return {
"x": zeach.mouseX2,
"y": zeach.mouseY2,
"nx": zeach.mouseX2,
"ny": zeach.mouseY2,
};
}
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
// ====================== Grazing code ==================================================================
function checkCollision(myBlob, targetBlob, potential){
// Calculate distance to target
var dtt = lineDistance(myBlob, targetBlob);
// Slope and normal slope
var sl = (targetBlob.ny-myBlob.ny)/(targetBlob.nx-myBlob.nx);
var ns = -1/sl;
// y-int of ptt
var yint1 = myBlob.ny - myBlob.nx*sl;
if(!(lineDistance(myBlob, potential) < dtt)){
// get second y-int
var yint2 = potential.ny - potential.nx * ns;
var interx = (yint2-yint1)/(sl-ns);
var intery = sl*interx + yint1;
var pseudoblob = {};
pseudoblob.nx = interx;
pseudoblob.ny = intery;
if (((targetBlob.nx < myBlob.nx && targetBlob.nx < interx && interx < myBlob.nx) ||
(targetBlob.nx > myBlob.nx && targetBlob.nx > interx && interx > myBlob.nx)) &&
((targetBlob.ny < myBlob.ny && targetBlob.ny < intery && intery < myBlob.ny) ||
(targetBlob.ny > myBlob.ny && targetBlob.ny > intery && intery > myBlob.ny))){
if(lineDistance(potential, pseudoblob) < potential.size+100){
return true;
}
}
}
return false;
}
function isSafeTarget(myBlob, targetBlob, threats){
var isSafe = true;
// check target against each enemy to make sure no collision is possible
threats.forEach(function (threat){
if(isSafe) {
if(threat.isVirus) {
//todo once we are big enough, our center might still be far enough
// away that it doesn't cross virus but we still pop
if(checkCollision(myBlob, targetBlob, threat) ) {
isSafe = false;
}
}
else {
if ( checkCollision(myBlob, targetBlob, threat) || lineDistance(threat, targetBlob) <= threat.size + 200) {
isSafe = false;
}
}
}
});
return isSafe;
}
// All blobs that aren't mine
function getOtherBlobs(){
return _.omit(zeach.allNodes, zeach.myIDs);
}
// Gets any item which is a threat including bigger players and viruses
function getThreats(blobArray, myMass) {
// start by omitting all my IDs
// then look for viruses smaller than us and blobs substantially bigger than us
return _.filter(getOtherBlobs(), function(possibleThreat){
var possibleThreatMass = getMass(possibleThreat.size);
if(possibleThreat.isVirus) {
// Viruses are only a threat if we are bigger than them
return myMass >= possibleThreatMass;
}
// other blobs are only a threat if they cross the 'Large' threshhold
return possibleThreatMass > myMass * Large;
});
}
var throttledResetGrazingTargetId = null;
function doGrazing() {
var i;
if(!isPlayerAlive()) {
//isGrazing = false;
return;
}
if(null === throttledResetGrazingTargetId){
throttledResetGrazingTargetId = _.throttle(function (){
grazzerTargetResetRequest = 'all';
//console.log(~~(Date.now()/1000));
}, 200);
}
if (grazzerTargetResetRequest == 'all') {
grazzerTargetResetRequest = false;
for(i = 0; i < zeach.myPoints.length; i++) {
zeach.myPoints[i].grazingTargetID = false;
}
} else if (grazzerTargetResetRequest == 'current') {
var pseudoBlob = getMouseCoordsAsPseudoBlob();
pseudoBlob.size = getSelectedBlob().size;
//pseudoBlob.scoreboard = scoreboard;
var newTarget = findFoodToEat_old(pseudoBlob,zeach.allItems);
if(-1 == newTarget){
isGrazing = false;
return;
}
getSelectedBlob().grazingTargetID = newTarget.id;
}
// with target fixation on, target remains until it's eaten by someone or
// otherwise disappears. With it off target is constantly recalculated
// at the expense of CPU
if(!grazingTargetFixation) {
throttledResetGrazingTargetId();
}
var target;
var targets = findFoodToEat(!nonPersistantUserOptions.grazerMultiBlob2);
for(i = 0; i < zeach.myPoints.length; i++) {
var point = zeach.myPoints[i];
if (!nonPersistantUserOptions.grazerMultiBlob2 && point.id != getSelectedBlob().id) {
continue;
}
point.grazingMode = isGrazing;
if(nonPersistantUserOptions.grazerHybridSwitch) {
var mass = getMass(point.nSize);
// switch over to new grazer once we pass the threshhold
if(1 === point.grazingMode && mass > nonPersistantUserOptions.grazerHybridSwitchMass){
point.grazingMode = 2; // We gained enough much mass. Use new grazer.
}else if(2 === point.grazingMode && mass < nonPersistantUserOptions.grazerHybridSwitchMass ){
point.grazingMode = 1; // We lost too much mass. Use old grazer.
}
}
switch(point.grazingMode) {
case 1: {
if(!zeach.allNodes.hasOwnProperty(point.grazingTargetID)) {
target = findFoodToEat_old(point, zeach.allItems);
if(-1 == target){
point.grazingMode = 2;
return;
}
point.grazingTargetID = target.id;
} else {
target = zeach.allNodes[point.grazingTargetID];
}
if (!nonPersistantUserOptions.grazerMultiBlob2) {
sendMouseUpdate(zeach.webSocket, target.x + Math.random(), target.y + Math.random());
} else {
sendMouseUpdate(zeach.webSocket, target.x + Math.random(), target.y + Math.random(), point);
}
break;
}
case 2: {
if (!nonPersistantUserOptions.grazerMultiBlob2) {
target = _.max(targets, "v");
sendMouseUpdate(zeach.webSocket, target.x + Math.random(), target.y + Math.random());
} else {
target = targets[point.id];
sendMouseUpdate(zeach.webSocket, target.x + Math.random(), target.y + Math.random(), point);
}
break;
}
}
}
}
function dasMouseSpeedFunction(id, cx, cy, radius, nx, ny) {
this.cx = cx; this.cy = cy; this.radius = radius; this.nx = nx; this.ny = ny;
this.value = function(x, y) {
x -= this.cx; y -= this.cy;
var lensq = x*x + y*y;
var len = Math.sqrt(lensq);
var val = x * this.nx + y * this.ny;
if (len > this.radius) {
return {
id : id,
v: val / len,
dx: y * (this.nx * y - this.ny * x) / (lensq * len),
dy: x * (this.ny * x - this.nx * y) / (lensq * len),
};
} else {
return {id: id, v: val / this.radius, dx: this.nx, dy: this.ny};
}
};
}
function dasBorderFunction(l, t, r, b, w) {
this.l = l;
this.t = t;
this.r = r;
this.b = b;
this.w = w;
this.value = function(x, y) {
var v = 0, dx = 0, dy = 0;
if (x < this.l) {
v += this.l - x;
dx = -this.w;
} else if (x > this.r) {
v += x - this.r;
dx = this.w;
}
if (y < this.t) {
v += this.t - y;
dy = -this.w;
} else if (y > this.b) {
v += y - this.b;
dy = this.w;
}
return {v: v * this.w, dx: dx, dy: dy};
};
}
function dasSumFunction(sumfuncs) {
this.sumfuncs = sumfuncs;
this.value = function(x, y) {
return sumfuncs.map(function(func) {
return func.value(x, y);
}).reduce(function (acc, val) {
acc.v += val.v; acc.dx += val.dx; acc.dy += val.dy;
return acc;
});
};
}
function gradient_ascend(func, step, iters, id, x, y) {
var max_step = step;
var last = func.value(x, y);
while(iters > 0) {
iters -= 1;
x += last.dx * step;
y += last.dy * step;
var tmp = func.value(x, y);
if (tmp.v < last.v) {
step /= 2;
} else {
step = Math.min(2 * step, max_step);
}
//console.log([x, y, tmp[0], step]);
last.v = tmp.v;
last.dx = (last.dx + tmp.dx)/2.0;
last.dy = (last.dy + tmp.dy)/2.0;
}
return {id: id, x: x, y: y, v: last.v};
}
function augmentBlobArray(blobArray) {
blobArray = blobArray.slice();
var curTimestamp = Date.now();
// Outdated blob id set
var ghostSet = [];
blobArray.forEach(function (element) {
ghostSet[element.id] = true;
element.lastTimestamp = curTimestamp;
});
var viewport = getViewport(false);
ghostBlobs = _.filter(ghostBlobs, function (element) {
return !ghostSet[element.id] && // a fresher blob with the same id doesn't exist in blobArray already
(curTimestamp - element.lastTimestamp < 10000) && // last seen no more than 10 seconds ago
(
(Math.abs(viewport.x - element.nx) > (viewport.dx + element.nSize) * 0.9) ||
(Math.abs(viewport.y - element.ny) > (viewport.dy + element.nSize) * 0.9)
); // outside of firmly visible area, otherwise there's no need to remember it
});
ghostBlobs.forEach(function (element) {
blobArray.push(element);
});
ghostBlobs = blobArray;
return blobArray;
}
function findFoodToEat(useGradient) {
blobArray = augmentBlobArray(zeach.allItems);
zeach.myPoints.forEach(function(cell) {
cell.gr_is_mine = true;
});
var accs = zeach.myPoints.map(function (cell) {
var per_food = [], per_threat = [];
var acc = {
id : cell.id,
fx: 0,
fy: 0,
x: cell.nx,
y: cell.ny,
size : cell.nSize,
per_food: per_food,
per_threat: per_threat,
cumulatives: [ { x: 0, y: 0}, { x: 0, y: 0} ],
};
if (!useGradient && cell.grazingMode != 2) {
return acc;
}
var totalMass = _.sum(_.pluck(zeach.myPoints, "nSize").map(getMass));
// Avoid walls too
var wallArray = [];
wallArray.push({id: -2, nx: cell.nx, ny: zeach.mapTop - 1, nSize: cell.nSize * 30});
wallArray.push({id: -3, nx: cell.nx, ny: zeach.mapBottom + 1, nSize: cell.nSize * 30});
wallArray.push({id: -4, ny: cell.ny, nx: zeach.mapLeft - 1, nSize: cell.nSize * 30});
wallArray.push({id: -5, ny: cell.ny, nx: zeach.mapRight + 1, nSize: cell.nSize * 30});
wallArray.forEach(function(el) {
// Calculate repulsion vector
var vec = { id: el.id, gr_type: true, x: cell.nx - el.nx, y: cell.ny - el.ny };
var dist = Math.sqrt(vec.x * vec.x + vec.y * vec.y);
// Normalize it to unit length
vec.x /= dist;
vec.y /= dist;
// Walls have pseudo-size to generate repulsion, but we can move farther.
dist += cell.nSize / 2.0;
dist = Math.max(dist, 0.01);
// Walls. Hate them muchly.
dist /= 10;
// The more we're split and the more we're to lose, the more we should be afraid.
dist /= cell.nSize * Math.sqrt(zeach.myPoints.length);
// The farther they're from us the less repulsive/attractive they are.
vec.x /= dist;
vec.y /= dist;
if(!isFinite(vec.x) || !isFinite(vec.y)) {
return;
}
// Save element-produced force for visualization
per_threat.push(vec);
// Sum forces from all threats
acc.fx += vec.x;
acc.fy += vec.y;
});
blobArray.forEach(function(el) {
var vec = { id: el.id, x: cell.nx - el.nx, y: cell.ny - el.ny };
if(el.gr_is_mine) {
return; //our cell, ignore
} else if( !el.isVirus && (getMass(el.nSize) * 4 <= getMass(cell.nSize) * 3)) {
//if(!el.isVirus && (getMass(el.nSize) <= 9)) {
//vec.gr_type = null; //edible
} else if (!el.isVirus && (getMass(el.nSize) * 3 < (getMass(cell.nSize) * 4))) {
return; //not edible ignorable
// TODO: shouldn't really be so clear-cut. Must generate minor repulsion/attraction depending on size.
} else {
vec.gr_type = true; //threat
}
// Calculate repulsion vector
var dist = Math.sqrt(vec.x * vec.x + vec.y * vec.y);
// Normalize it to unit length
vec.x /= dist;
vec.y /= dist;
if(el.nSize > cell.nSize) {
if(el.isVirus) {
// Viruses are only a threat if they're smaller than us
return;
}
// Distance till consuming
dist -= el.nSize;
dist += cell.nSize / 3.0;
dist -= 11;
dist = Math.max(dist, 0.01);
// Prioritize targets by size
if(!vec.gr_type) {
//Non-threat
dist /= el.nSize;
} else {
var ratio = getMass(el.nSize) / getMass(cell.nSize);
// Cells that 1 to 8 times bigger are the most dangerous.
// Prioritize them by a truncated parabola up to 6 times.
// when we are fractured into small parts, we might underestimate
// how cells a lot bigger than us can be interested in us as a conglomerate of mass.
// So calculate threat index for our total mass too.
var ratio2 = getMass(el.nSize) / totalMass;
if(ratio2 < 4.5 && ratio > 4.5) {
ratio2 = 4.5;
}
ratio = Math.min(5, Math.max(0, - (ratio - 1) * (ratio - 8))) + 1;
ratio2 = Math.min(5, Math.max(0, - (ratio2 - 1) * (ratio2 - 8))) + 1;
ratio = Math.max(ratio, ratio2);
// The more we're split and the more we're to lose, the more we should be afraid.
dist /= ratio * cell.nSize * Math.sqrt(zeach.myPoints.length);
}
} else {
// Distance till consuming
dist += el.nSize * 1 / 3;
dist -= cell.nSize;