-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathZeachCobbler.user.js
5560 lines (5198 loc) · 219 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 Zeach Cobbler
// @namespace https://github.com/RealDebugMonkey/ZeachCobbler
// @updateURL http://bit.do/ZeachCobblerJS2
// @downloadURL http://bit.do/ZeachCobblerJS2
// @contributer See full list at https://github.com/RealDebugMonkey/ZeachCobbler#contributors-and-used-code
// @supportURL https://github.com/RealDebugMonkey/ZeachCobbler/issues
// @version 0.31.7
// @description Agario powerups
// @author DebugMonkey
// @match http://agar.io/*
// @match https://agar.io/*
// @icon https://raw.github.com/RealDebugMonkey/ZeachCobbler/master/icons/zeachcobbler_icon48.png
// @icon64 https://raw.github.com/RealDebugMonkey/ZeachCobbler/master/icons/zeachcobbler_icon64.png
// @icon128 https://raw.github.com/RealDebugMonkey/ZeachCobbler/master/icons/zeachcobbler_icon128.png
// @changes 0.31.0 - Added ability to split by mouse click
// - Also fixed semicolons, improved formating of console logs
// 1 - Small bug-fixes
// 2 - V28 protocol fixes
// 3 - fixed the mouse click handler
// 4 - Chromium's JS lint found a lot of crap
// 5 - updated message
// 6 - quick hack to stop flickering
// 7 - Positioning of ZC overlay
// 0.30.0 - Added GitHub, Contrib and Zeach Cobbler skins
// - Use " ' " before nick to use your GitHub avatar
// 1 - Fixed minimap screen-freezing bug
// 2 - Added strokecolor indiactors in teams mode
// 0.29.0 - Added option to edit keyboard binds
// - Now you can edit keys in options
// 1 - Added Contributors tab, bug fixes
// 0.28.0 - Revamped UI
// - Stats now detects viruses being eaten
// 1 - Updated @updateURL and @downloadURL to not use rawgit
// 2 - Upgraded zoom functions
// 3 - Some zoom bug fixes
// 4 - protocol breakage fix
// 5 - fixed my fuckup
// 0.27.0 - Click-to-lock added
// - Added ability to lock blob at some pos
// - Added ability to select n-th size blob
// 2 - Fixed virus shot counter, improved shots remaining calculation
// - General code cleanup
// - shots per ms field added
// - options screen cleanup/reorg
// 6 - Hack to get mod loading again.
// 7 - proper fix for xp bar rename
// 8 - added isAgitated
// - changed multiblob grazer var name to reset multiblob default to 'false'
// 0.26.0 - Configurable Minimap scale & Agariomod private server location update
// 0.25.0 - Facebook Update
// 1 - Tons of bug fixes
// 0.24.0 - Switched back to hacky method of loading & added hotkey reference
// 1 - Guest play fix
// 2 - UI Tweaks and a new message
// 0.23.0 - Agariomods.com private server support
// 0.22.0 - Added hybrid grazer option & fixed music
// 1 - music restored, viruses excluded from relocated names
// - Hybrid grazer goes back to old grazer if it loses enough mass
// 2 - Hybrid grazer checkbox fix
// 3 - volume fix
// 4 - Blank cell fix
// - Option to remove grid lines
// - Oldest cell now just displays name rather than negative Time To Remerge (TTR)
// 5 - Grazer auto-respawn
// 6 - G and H act equivalently in hybrid-grazer mode
// - if old grazer has no targets it will try to switch into new grazer mode
// 0.21.0 - Changed way script is loaded.
// 0.20.0 - Version leap due to updated grazer
// - Fixes for new client behavior
// 0.15.0 - Fixed Minimap (Zeach broke it)
// - Fixed Borders(Zeach broke them too)
// - Lite Brite mode added (and some UI issues fixed)
// 2 - Lite Brite, SFX, and BGM settings all saved
// 3 - hack for overflowing chart & updated hardcoded agariomods skins
// 0.14.0 - Major refactoring to help with future updates
// - Support for AgarioMods connect skins
// 0.13.0 - Fixed break caused by recent code changes
// 1 - bug fixes
// - removed direct connect UI (for now)
// 2 - grazer speed improved by removing debug logging & adding artifical 200ms throttle
// 3 - fixed virus poppers
// - fixed ttr calculation
// 6 - fixed flickering grazer lines
// 0.12.0 - Added music and sound effects.
// - Sound effects from agariomods.com
// - Music from http://incompetech.com/music/royalty-free/most/kerbalspaceprogram.php
// - Fix: scroll wheel function
// - Fixed blank cell not displaying % diff issue
// - Fixed key bindings triggering while changing name
// 4 - bug fix courtesy of Gjum
// 5 - updated handshake for v548
// 0.11.0 - Fix for v538 fix
// 1 - grazer fixed, time alive and ttr fixed
// 2 - more fixes for stuff I missed
// 3 - onDestroy bugfix
// 4 - update with mikeyk730's latest changes
// 5 - skins should now display in experimental
// @require https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// ==/UserScript==
var _version_ = GM_info.script.version;
var debugMonkeyReleaseMessage = "<h3>Quick Flicker issue fix</h3><p>" +
"Hey guys, Sorry to say I've lost interest in Agario a long time ago and am now addicted to SMITE (the MOBA).<br> " +
"I'll continue trying to keep this project going as time permits, but fixes may not be prompt.<br><br> " +
"This version fixes the recent issue with flickering. I know the minimap is still broken. will fix when I can.<br>" +
"<img src='http://i.imgur.com/p4zv6vx.jpg'><br><br>debugmonkey";
//if (window.top != window.self) //-- Don't run on frames or iframes
// return;
//https://cdn.rawgit.com/pockata/blackbird-js/1e4c9812f8e6266bf71a25e91cb12a553e7756f4/blackbird.js
//https://raw.githubusercontent.com/pockata/blackbird-js/cc2dc268b89e6345fa99ca6109ddaa6c22143ad0/blackbird.css
$.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;
(function(d, f) {
// Options that will always be reset on reload
var zoomFactor = 10;
var isGrazing = false;
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");
// cobbler 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 cobbler = {
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;
cobbler[backingVar] = GM_getValue(settingName, defaultValue);
Object.defineProperty(cobbler, 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 makeCobbler(){
var optionsAndDefaults = {
"isLiteBrite" : true,
"sfxVol" : 0.5,
"bgmVol" : 0.5,
"drawTail" : false,
"splitGuide" : true,
"rainbowPellets" : true,
"debugLevel" : 1,
"imgurSkins" : true,
"amExtendedSkins" : true,
"amConnectSkins" : true,
"namesUnderBlobs" : false,
"grazerMultiBlob2" : false,
"grazerHybridSwitch": false,
"grazerHybridSwitchMass" : 300,
"gridLines" : true,
"autoRespawn" : false,
"visualizeGrazing" : true,
"msDelayBetweenShots" : 100,
"miniMapScale" : false,
"miniMapScaleValue" : 64,
"enableBlobLock" : false,
"nextOnBlobLock" : false,
"rightClickFires" : false,
"clickToSplit" : false,
"showZcStats" : true,
"gitHubSkins" : true,
// Menu Binds Values
"MenuSwitchBlob" : false,
"MenuAcidMode" : false,
"MenuLiteBriteMode" : false,
"MenuShowVisual" : false,
"MenuFireAtVirCur" : false,
"MenuNewGrazer" : false,
"MenuOldGrazer" : false,
"MenuSuspendMouse" : false,
"MenuRightClick" : false,
"MenuGrazingFix" : false,
"MenuFireAtVirBlob" : false,
"MenuGrazerReset" : false,
"MenuGrazingVisual" : false,
"MenuZoomFactor" : false,
"MenuPointLock" : false,
"MenuClickToSplit" : false,
// Key Binds Defaults
"KeySwitchBlob" : "TAB",
"KeyAcidMode" : "A",
"KeyLiteBriteMode" : "L",
"KeyShowVisual" : "C",
"KeyFireAtVirCur" : "E",
"KeyNewGrazer" : "G",
"KeyOldGrazer" : "H",
"KeySuspendMouse" : "M",
"KeyRightClick" : "O",
"KeyGrazingFix" : "P",
"KeyFireAtVirBlob" : "R",
"KeyGrazerReset" : "T",
"KeyGrazingVisual" : "V",
"KeyZoomFactor" : "Z",
"KeyPointLock" : "S",
"KeyClickToSplit" : "U",
};
simpleSavedSettings(optionsAndDefaults);
}
makeCobbler();
window.cobbler = cobbler;
// ====================== Property & Var Name Restoration =======================================================
var zeach = {
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
// "g_showNames": "va",
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; }
});
});
}
// ====================== 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 ==================================================================
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(!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(!cobbler.grazerMultiBlob2);
for(i = 0; i < zeach.myPoints.length; i++) {
var point = zeach.myPoints[i];
if (!cobbler.grazerMultiBlob2 && point.id != getSelectedBlob().id) {
continue;
}
point.grazingMode = isGrazing;
if(cobbler.grazerHybridSwitch) {
var mass = getMass(point.nSize);
// switch over to new grazer once we pass the threshhold
if(1 === point.grazingMode && mass > cobbler.grazerHybridSwitchMass){
point.grazingMode = 2; // We gained enough much mass. Use new grazer.
}else if(2 === point.grazingMode && mass < cobbler.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 (!cobbler.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 (!cobbler.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 results;
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;
dist -= 11;
if(el.isVirus) {
if(zeach.myPoints.length >= 16 ) {
// Can't split anymore so viruses are actually a good food!
delete vec.gr_type; //vec.gr_type = null;
} else {
// Hate them a bit less than same-sized blobs.
dist *= 2;
}
}
dist = Math.max(dist, 0.01);
// Prioritize targets by size
dist /= el.nSize;
}
if(!vec.gr_type) {
//Not a threat. Make it attractive.
dist = -dist;
}
// 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
(vec.gr_type ? per_threat : per_food).push(vec);
// Sum forces per target type
var cumul = acc.cumulatives[!vec.gr_type ? 1 : 0];
cumul.x += vec.x;
cumul.y += vec.y;
});
// Sum forces from all sources
acc.fx += _.sum(_.pluck(acc.cumulatives, "x"));
acc.fy += _.sum(_.pluck(acc.cumulatives, "y"));
// Save resulting info for visualization
cell.grazeInfo = acc;
return acc;
});
if (useGradient) {
var funcs = accs.map(function(acc) {
return new dasMouseSpeedFunction(acc.id, acc.x, acc.y, 200, acc.fx, acc.fy);
});
// Pick gradient ascent step size for better convergence
// so that coord jumps don't exceed ~50 units
var step = _.sum(accs.map(function(acc) {
return Math.sqrt(acc.fx * acc.fx + acc.fy * acc.fy);
}));
step = 50 / step;
if(!isFinite(step)) {
step = 50;
}
var viewport = getViewport(false);
funcs.push(
new dasBorderFunction(
viewport.x - viewport.dx,
viewport.y - viewport.dy,
viewport.x + viewport.dx,
viewport.y + viewport.dy,
-1000
)
);
var func = new dasSumFunction(funcs);
results = accs.map(function(acc) {
return gradient_ascend(func, step, 100, acc.id, acc.x, acc.y);
});
} else {
results = accs.map(function(acc) {
var norm = Math.sqrt(acc.fx * acc.fx + acc.fy * acc.fy);
return {id: acc.id, x: acc.x + 200 * acc.fx / norm, y: acc.y + 200 * acc.fy / norm };
});
}
var reply = {};
for (var i = 0; i < results.length; i++) {
reply[results[i].id] = {id : -5, x : results[i].x, y : results[i].y, v : results[i].v};
}
return reply;
}
function findFoodToEat_old(cell, blobArray){
var edibles = [];
var densityResults = [];
var threats = getThreats(blobArray, getMass(cell.size));
blobArray.forEach(function (element){
var distance = lineDistance(cell, element);
if (!element.isSafeTarget) {
element.isSafeTarget = {};
}
element.isSafeTarget[cell.id] = null;
if( getMass(element.size) <= (getMass(cell.size) * 0.4) && !element.isVirus){
if(isSafeTarget(cell, element, threats)){
edibles.push({"distance":distance, "id":element.id});
element.isSafeTarget[cell.id] = true;
} else {
element.isSafeTarget[cell.id] = false;
}
}
});
edibles = edibles.sort(function(x,y){return x.distance<y.distance?-1:1;});
edibles.forEach(function (element){
var density = calcFoodDensity(cell, zeach.allNodes[element.id], blobArray)/(element.distance*2);
densityResults.push({"density":density, "id":element.id});
});
if(!densityResults.length){
//console.log("No target found");
return avoidThreats(threats, cell);
//return -1;
}
var target = densityResults.sort(function(x,y){return x.density>y.density?-1:1;});
//console.log("Choosing blob (" + target[0].id + ") with density of : "+ target[0].isVirusensity);
return zeach.allNodes[target[0].id];
}
function avoidThreats(threats, cell){
// Avoid walls too
threats.push({x: cell.x, y: zeach.mapTop - 1, size: 1});
threats.push({x: cell.x, y: zeach.mapBottom + 1, size: 1});
threats.push({y: cell.y, x: zeach.mapLeft - 1, size: 1});
threats.push({y: cell.y, x: zeach.mapRight + 1, size: 1});
var direction = threats.reduce(function(acc, el) {
// Calculate repulsion vector
var vec = { x: cell.x - el.x, y: cell.y - el.y };
var dist = Math.sqrt(vec.x * vec.x + vec.y * vec.y);
// Normalize it to unit length
vec.x /= dist;
vec.y /= dist;
// Take enemy cell size into account
dist -= el.size;
// The farther they're from us the less repulsive they are
vec.x /= dist;
vec.y /= dist;
// Sum forces from all threats
acc.x += vec.x;
acc.y += vec.y;
return acc;
}, {x: 0, y: 0});