-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbrowser_engine.py
More file actions
1600 lines (1405 loc) · 71.5 KB
/
Copy pathbrowser_engine.py
File metadata and controls
1600 lines (1405 loc) · 71.5 KB
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
"""
Browser Engine for Slither.io Bot
Manages Chrome/Chromium instances and game communication.
"""
import time
import math
import os
import subprocess
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
def log(msg):
print(msg, flush=True)
class SlitherBrowser:
"""
Manages browser instance using Selenium.
Handles JS bridge to communicate with Slither.io client.
"""
# Limits for performance
MAX_FOODS = 300 # Max food items to process (Increased for better sensing)
MAX_ENEMIES = 50 # Max enemy snakes to process (Increased to fix invisible snakes)
MAX_BODY_PTS = 150 # Max body points per enemy (increased for better visibility)
def __init__(self, headless=True, nickname="NEATBot", base_url="http://slither.io",
use_cdp=False):
self.nickname = nickname
self.base_url = base_url
self._use_cdp = use_cdp
self._cdp = None # CDPInterceptor instance (if use_cdp=True)
self.options = Options()
if headless:
self.options.add_argument("--headless=new")
self.options.add_argument("--mute-audio")
self.options.add_argument("--disable-gpu")
self.options.add_argument("--disable-dev-shm-usage")
self.options.add_argument("--window-size=800,600")
self.options.add_argument("--disable-extensions")
self.options.add_argument("--disable-infobars")
self.options.add_argument("--disable-notifications")
# Performance optimizations
self.options.add_argument("--disable-software-rasterizer")
self.options.add_argument("--disable-background-networking")
self.options.add_argument("--disable-sync")
self.options.add_argument("--disable-translate")
self.options.add_argument("--metrics-recording-only")
self.options.add_argument("--no-first-run")
# CDP interception requires DevTools access
if use_cdp:
self.options.add_argument("--remote-debugging-port=0")
self.options.add_argument("--remote-allow-origins=*")
# Disable images for faster loading (optional - might affect gameplay detection)
prefs = {
"profile.managed_default_content_settings.images": 2,
"profile.default_content_setting_values.notifications": 2
}
self.options.add_experimental_option("prefs", prefs)
# Initialize driver
self.driver = webdriver.Chrome(options=self.options)
self.driver.set_page_load_timeout(30)
self._fast_getstate_injected = False
self._canvas_element = None # Cached canvas WebElement for ActionChains
# Health monitoring for zombie detection
self._chromedriver_pid = self.driver.service.process.pid if self.driver.service else None
self._last_health_check = time.time()
self._health_check_interval = 300 # 5 minutes
self._steps_since_health_check = 0
log(f"[BROWSER] Connecting to {self.base_url}...")
self.driver.get(self.base_url)
time.sleep(3)
# Start CDP network monitoring early so we capture WebSocket creation events
if self._use_cdp:
self._init_cdp_monitoring()
def _init_cdp_monitoring(self):
"""Initialize CDP connection and enable Network monitoring (before login)."""
try:
from cdp_intercept import CDPInterceptor
self._cdp = CDPInterceptor(self.driver)
self._cdp.start()
log("[CDP] Early monitoring started (waiting for game WS)")
except Exception as e:
log(f"[CDP] Failed to start early monitoring: {e}")
self._cdp = None
def health_check(self) -> bool:
"""
Check if Chrome driver is alive. Returns True if healthy, False if dead.
"""
try:
# Quick check: is chromedriver process still alive?
if self._chromedriver_pid and not _is_process_alive(self._chromedriver_pid):
log(f"[HEALTH] Chromedriver PID {self._chromedriver_pid} is DEAD")
return False
# Check if driver is responsive (lightweight ping)
_ = self.driver.current_url
return True
except Exception as e:
log(f"[HEALTH] Driver check failed: {e}")
return False
def cleanup_zombie_processes(self):
"""
Detect and kill orphaned Chrome/chromedriver processes.
Called periodically to prevent resource leaks.
"""
try:
# Find all Chrome processes without living parents
result = subprocess.run(
["ps", "aux"],
capture_output=True,
text=True,
timeout=5
)
lines = result.stdout.split('\n')
# Look for orphaned Chrome processes (no parent trainer or chrome driver)
zombie_pids = []
for line in lines:
if 'Chrome' not in line or 'grep' in line:
continue
parts = line.split()
if len(parts) < 8:
continue
try:
pid = int(parts[1])
ppid = int(parts[2])
cmd = ' '.join(parts[10:])
# Check if parent (ppid) is still alive
if not _is_process_alive(ppid) and 'Chrome' in cmd:
zombie_pids.append(pid)
except (ValueError, IndexError):
continue
# Kill zombies (skip our own driver)
for pid in zombie_pids:
if pid != self._chromedriver_pid:
try:
os.kill(pid, 9) # SIGKILL
log(f"[CLEANUP] Killed zombie Chrome PID {pid}")
except (OSError, ProcessLookupError):
pass
if zombie_pids:
log(f"[CLEANUP] Removed {len(zombie_pids)} zombie Chrome processes")
except Exception as e:
log(f"[CLEANUP] Zombie detection failed (non-critical): {e}")
def _periodic_health_check(self):
"""
Called periodically (every N steps) to check driver health.
If unhealthy, attempt cleanup.
"""
self._steps_since_health_check += 1
# Check every 100 steps OR every 5 minutes of wall time
if self._steps_since_health_check >= 100:
self._steps_since_health_check = 0
if not self.health_check():
log("[HEALTH] WARNING: Driver is unresponsive!")
self.cleanup_zombie_processes()
return False
self._last_health_check = time.time()
return True
# Also check by wall time (every 5 min)
if time.time() - self._last_health_check > self._health_check_interval:
self.cleanup_zombie_processes()
self._last_health_check = time.time()
return True
def _handle_login(self):
"""
Handles the initial login screen.
"""
try:
# Close extra windows (ads/popups)
time.sleep(1)
if len(self.driver.window_handles) > 1:
log(f"[BROWSER] Closing {len(self.driver.window_handles)-1} extra tabs.")
main_handle = self.driver.current_window_handle
for handle in self.driver.window_handles:
if handle != main_handle:
try:
self.driver.switch_to.window(handle)
self.driver.close()
except:
pass
self.driver.switch_to.window(main_handle)
log(f"[LOGIN] Attempting login: {self.nickname}")
# Fill nickname and click play
self.driver.execute_script(f"document.getElementById('nick').value = '{self.nickname}';")
login_js = """
var playBtn = document.querySelector('#playh .btnt') ||
document.querySelector('.btnt.btntg') ||
document.querySelector('#play-btn');
if (playBtn) {
playBtn.click();
return 'btn_clicked';
}
var divs = document.querySelectorAll('div, button, a');
for (var i = 0; i < divs.length; i++) {
if (divs[i].innerText && divs[i].innerText.trim() === 'Play') {
divs[i].click();
return 'text_btn_clicked';
}
}
if (typeof window.connect === 'function') {
window.connect();
return 'connect_called';
}
return 'not_found';
"""
result = self.driver.execute_script(login_js)
log(f"[LOGIN] Play attempt: {result}")
# Wait for game start
start_wait = time.time()
while time.time() - start_wait < 15:
try:
self.driver.switch_to.alert.accept()
except:
pass
is_playing = self.driver.execute_script("""
return (window.slither !== undefined && window.slither !== null) &&
(typeof window.dead_mtm === 'undefined' || window.dead_mtm === -1 || window.dead_mtm === null);
""")
if is_playing:
log("[LOGIN] Game started!")
self.inject_override_script()
self.inject_fast_getstate()
self._start_cdp_if_enabled()
return True
time.sleep(0.5)
log("[LOGIN] Warning: Game didn't start in time.")
return False
except Exception as e:
log(f"[LOGIN] Error: {e}")
return False
def _start_cdp_if_enabled(self):
"""Wait for CDP interceptor to detect game WS and become active."""
if not self._use_cdp or not self._cdp:
return
# Give CDP time to receive frames, then try to identify our snake
for i in range(30): # Up to 3 seconds
if self._cdp._frames_received > 10:
if self._cdp.try_activate():
return
time.sleep(0.1)
log(f"[CDP] Not yet active — frames={self._cdp._frames_received} "
f"ws_detected={self._cdp._game_ws_request_id is not None} "
f"snakes={len(self._cdp.state.snakes)} init={self._cdp._init_received.is_set()}")
def inject_override_script(self):
"""
Injects JS overrides for bot control.
Steering is done via CDP Input.dispatchMouseEvent (trusted mouse events).
This only handles graphics optimization and boost setup.
"""
js_code = """
// Graphics optimization
if (typeof window.want_quality !== 'undefined') window.want_quality = 0;
if (typeof window.high_quality !== 'undefined') window.high_quality = false;
if (typeof window.render_mode !== 'undefined') window.render_mode = 1;
// Disable visual effects
window.redraw = window.redraw || function(){};
window._botSteering = true;
window._botTargetAng = 0;
// Clean up old approaches
if (window._botSteerInterval) { clearInterval(window._botSteerInterval); window._botSteerInterval = null; }
// Undo any defineProperty on wang from previous injection
if (window.slither) {
try {
var desc = Object.getOwnPropertyDescriptor(window.slither, 'wang');
if (desc && (desc.get || desc.set)) {
delete window.slither.wang;
window.slither.wang = window.slither.ang || 0;
}
} catch(e) {}
}
// Store canvas dimensions
var canvas = document.getElementById('mc') || document.querySelector('canvas');
window._botCanvasW = canvas ? canvas.width : 800;
window._botCanvasH = canvas ? canvas.height : 600;
console.log("SlitherBot: Controls injected (CDP mouse steering).");
"""
try:
self.driver.execute_script(js_code)
except Exception as e:
log(f"[OVERRIDE] Failed: {e}")
def inject_fast_getstate(self):
"""
Inject persistent getGameState() JS function once.
Subsequent get_game_data() calls just invoke it by name instead of
sending ~8KB of JS each time. Also injects sendActionAndGetState()
for combined action+read in one round-trip.
"""
js = """
window._botGetState = function() {
var MAX_FOODS = %d;
var MAX_ENEMIES = %d;
var MAX_BODY_PTS = %d;
var hasSnake = (window.slither !== undefined && window.slither !== null &&
typeof window.slither.xx === 'number' && typeof window.slither.yy === 'number');
var isDeadFlag = (window.slither && typeof window.slither.dead !== 'undefined') ? window.slither.dead : false;
var deadMtm = window.dead_mtm;
var deadMtmActive = !(deadMtm === undefined || deadMtm === null || deadMtm === -1 || deadMtm === 0);
var playing = hasSnake && !isDeadFlag && !deadMtmActive;
if (!playing) {
return { dead: true, in_menu: document.querySelector('#nick, #playh .btnt') !== null };
}
var canvas = document.getElementById('mc') || document.querySelector('canvas');
var canvasW = canvas ? canvas.width : 800;
var canvasH = canvas ? canvas.height : 600;
var gsc = window.gsc || 0.9;
var viewWidth = canvasW / gsc;
var viewHeight = canvasH / gsc;
var viewRadius = Math.max(viewWidth, viewHeight) / 2;
var my_pts = [];
if (window.slither.pts) {
var ptsLen = window.slither.pts.length;
var trimCount = Math.floor(ptsLen * 0.15) + Math.floor((window.slither.sp || 5.7) * 2.0);
var startIndex = Math.min(ptsLen - 1, trimCount);
var step = Math.max(1, Math.floor(ptsLen / MAX_BODY_PTS));
for (var j = startIndex; j < ptsLen && my_pts.length < MAX_BODY_PTS; j += step) {
var p = window.slither.pts[j];
if (p.xx !== undefined) my_pts.push([p.xx, p.yy]);
else if (p.x !== undefined) my_pts.push([p.x, p.y]);
}
}
var my_snake = {
x: window.slither.xx, y: window.slither.yy,
ang: window.slither.ang, sp: window.slither.sp,
sc: window.slither.sc,
len: window.slither.pts ? window.slither.pts.length : 0,
pts: my_pts,
wang: window.slither.wang, eang: window.slither.ehang
};
// Server ID: bso.ip or WebSocket URL
var server_id = '';
try {
if (window.bso && window.bso.ip) server_id = window.bso.ip + ':' + (window.bso.po || '');
else if (window.ws && window.ws.url) server_id = window.ws.url;
} catch(e) {}
var visible_foods = [];
if (window.foods && window.foods.length) {
var myX = my_snake.x, myY = my_snake.y;
var viewRadSq = viewRadius * viewRadius * 1.2;
var foodList = [];
for (var i = 0; i < window.foods.length && foodList.length < MAX_FOODS * 2; i++) {
var f = window.foods[i];
if (f) {
var fx = (typeof f.xx === 'number') ? f.xx : (typeof f.x === 'number') ? f.x : (typeof f.rx === 'number') ? f.rx : null;
var fy = (typeof f.yy === 'number') ? f.yy : (typeof f.y === 'number') ? f.y : (typeof f.ry === 'number') ? f.ry : null;
if (fx === null || fy === null) continue;
var dx = fx - myX, dy = fy - myY;
var dist = dx*dx + dy*dy;
if (dist < viewRadSq) foodList.push([fx, fy, f.sz || 1, dist]);
}
}
foodList.sort(function(a, b) { return a[3] - b[3]; });
for (var i = 0; i < Math.min(foodList.length, MAX_FOODS); i++)
visible_foods.push([foodList[i][0], foodList[i][1], foodList[i][2]]);
}
var visible_enemies = [];
var totalSlithers = window.slithers ? window.slithers.length : 0;
if (window.slithers && window.slithers.length) {
var myX = my_snake.x, myY = my_snake.y;
var searchRadSq = viewRadius * viewRadius * 25;
var viewRadSq2 = viewRadius * viewRadius * 2.0;
var enemyList = [];
for (var i = 0; i < window.slithers.length; i++) {
var s = window.slithers[i];
if (s === window.slither || !s || !s.pts) continue;
var minDist = Infinity, hasVisiblePart = false;
var hdx = (s.xx||0)-myX, hdy = (s.yy||0)-myY;
var headDist = hdx*hdx+hdy*hdy;
if (headDist < viewRadSq2) hasVisiblePart = true;
minDist = Math.min(minDist, headDist);
if (!hasVisiblePart && s.pts.length > 0) {
var ptsLen = s.pts.length;
var trimCount2 = Math.floor(ptsLen*0.1)+Math.floor((s.sp||5.7)*2.0);
var startIndex2 = Math.min(ptsLen-1, trimCount2);
var step2 = Math.max(1, Math.floor(ptsLen/40));
for (var j = startIndex2; j < ptsLen; j += step2) {
var p = s.pts[j];
var px = p.xx !== undefined ? p.xx : (p.x||0);
var py = p.yy !== undefined ? p.yy : (p.y||0);
var bdx = px-myX, bdy = py-myY;
var bodyDist = bdx*bdx+bdy*bdy;
if (bodyDist < viewRadSq2) { hasVisiblePart = true; break; }
minDist = Math.min(minDist, bodyDist);
}
}
if (hasVisiblePart || minDist < searchRadSq)
enemyList.push([s, minDist, hasVisiblePart ? 0 : 1]);
}
enemyList.sort(function(a,b) { if(a[2]!==b[2])return a[2]-b[2]; return a[1]-b[1]; });
for (var i = 0; i < Math.min(enemyList.length, MAX_ENEMIES); i++) {
var s = enemyList[i][0];
var pts = [];
if (s.pts) {
var ptsLen = s.pts.length;
var trimCount3 = Math.floor(ptsLen*0.15)+Math.floor((s.sp||5.7)*2.0);
var startIndex3 = Math.min(ptsLen-1, trimCount3);
var step3 = Math.max(1, Math.floor(ptsLen/MAX_BODY_PTS));
for (var j = startIndex3; j < ptsLen && pts.length < MAX_BODY_PTS; j += step3) {
var p = s.pts[j];
var px = p.xx !== undefined ? p.xx : (p.x||0);
var py = p.yy !== undefined ? p.yy : (p.y||0);
var pdx = px-myX, pdy = py-myY;
if (pdx*pdx+pdy*pdy < searchRadSq) pts.push([px, py]);
}
}
visible_enemies.push({ id:s.id, x:s.xx||0, y:s.yy||0, ang:s.ang||0, sp:s.sp||0, sc:s.sc||1, pts:pts });
}
}
// Map boundary (simplified: circle via grd)
var mapCenterX = 21600, mapCenterY = 21600, mapRadius = 21600;
var boundaryType = 'circle', boundarySource = 'default';
if (typeof window.grd !== 'undefined' && window.grd > 1000) {
mapCenterX = window.grd; mapCenterY = window.grd;
if (typeof window.bsr !== 'undefined' && window.bsr > 1000) { mapRadius = window.bsr; boundarySource = 'bsr'; }
else if (typeof window.cst !== 'undefined' && window.cst > 0.1) { mapRadius = window.grd*window.cst; boundarySource = 'grd*cst'; }
else { mapRadius = window.grd * 0.98; boundarySource = 'grd'; }
}
var distFromCenter = Math.sqrt(Math.pow(my_snake.x-mapCenterX,2)+Math.pow(my_snake.y-mapCenterY,2));
var distToWall = mapRadius - distFromCenter;
if (distToWall > mapRadius) distToWall = mapRadius;
if (distToWall < -500) distToWall = -500;
return {
dead: false, self: my_snake, foods: visible_foods, enemies: visible_enemies,
view_radius: viewRadius, gsc: gsc, dist_to_wall: distToWall,
dist_from_center: distFromCenter, map_radius: mapRadius,
map_center_x: mapCenterX, map_center_y: mapCenterY,
boundary_type: boundaryType, boundary_vertices: [],
server_id: server_id,
debug: {
total_slithers: totalSlithers, visible_enemies: visible_enemies.length,
total_foods: window.foods ? window.foods.length : 0,
visible_foods: visible_foods.length,
dist_to_wall: Math.round(distToWall),
dist_from_center: Math.round(distFromCenter),
snake_x: Math.round(my_snake.x), snake_y: Math.round(my_snake.y),
boundary_source: boundarySource, boundary_type: boundaryType,
map_vars: {}
}
};
};
// Combined: set boost + return current state in one call
// (Steering is handled via CDP mouse events, not JS)
window._botActAndRead = function(ang, boost) {
// Set xm/ym directly — game computes wang = atan2(ym, xm)
xm = Math.cos(ang) * 300;
ym = Math.sin(ang) * 300;
window._botTargetAng = ang;
if (window.slither) {
if (boost) {
window.accelerating = true;
if (window.setAcceleration) window.setAcceleration(1);
} else {
window.accelerating = false;
if (window.setAcceleration) window.setAcceleration(0);
}
}
return window._botGetState();
};
console.log("SlitherBot: Fast getState injected.");
""" % (self.MAX_FOODS, self.MAX_ENEMIES, self.MAX_BODY_PTS)
try:
self.driver.execute_script(js)
self._fast_getstate_injected = True
log("[BROWSER] Fast getState injected.")
except Exception as e:
self._fast_getstate_injected = False
log(f"[BROWSER] Fast getState injection failed: {e}")
def scan_game_variables(self):
"""
One-time scan of ALL game variables to find boundary-related ones.
Returns a dict of potentially relevant variables.
"""
scan_js = """
var results = {};
// 1. Scan ALL window-level variables for numbers in map-size range
var numericVars = {};
var arrayVars = {};
var knownSkip = ['innerWidth','innerHeight','scrollX','scrollY','pageXOffset','pageYOffset',
'screenX','screenY','screenLeft','screenTop','outerWidth','outerHeight',
'devicePixelRatio','length','performance'];
for (var key in window) {
try {
if (knownSkip.indexOf(key) >= 0) continue;
var val = window[key];
// Numeric variables (potential radius, center, size)
if (typeof val === 'number' && !isNaN(val) && isFinite(val)) {
if (val > 100 && val < 200000) {
numericVars[key] = val;
}
}
// Arrays (potential boundary polygons)
if (Array.isArray(val) && val.length > 3 && val.length < 10000) {
// Check if it contains numbers
if (typeof val[0] === 'number') {
arrayVars[key] = {length: val.length, first3: val.slice(0,3), last3: val.slice(-3)};
}
}
} catch(e) {}
}
results['numeric'] = numericVars;
results['arrays'] = arrayVars;
// 2. Specific slither.io variables to check
var specific = {};
var checkVars = ['grd','msx','msy','msc','bsr','bsc','bsc2','border','map_size',
'arena_size','game_radius','rfbx','rfby','cst','sector_size',
'grid_size','world_size','fmlts','fpsls','protocol_version',
'mcp','mcx','mcy','gla','glr','bmx','bmy','bmr'];
for (var i = 0; i < checkVars.length; i++) {
var v = checkVars[i];
try {
if (typeof window[v] !== 'undefined') {
var val = window[v];
if (typeof val === 'number') specific[v] = val;
else if (typeof val === 'string') specific[v] = val;
else if (Array.isArray(val)) specific[v] = 'Array(' + val.length + ')';
else if (typeof val === 'object' && val !== null) specific[v] = 'Object';
else specific[v] = typeof val;
}
} catch(e) {}
}
results['specific'] = specific;
// 3. Snake position for reference
if (window.slither) {
results['snake_pos'] = {x: window.slither.xx, y: window.slither.yy};
}
// 4. Check for boundary drawing functions
var funcNames = [];
for (var key in window) {
try {
if (typeof window[key] === 'function') {
var src = window[key].toString().substring(0, 200);
if (src.indexOf('border') >= 0 || src.indexOf('bound') >= 0 ||
src.indexOf('pbx') >= 0 || src.indexOf('grd') >= 0 ||
src.indexOf('arena') >= 0 || src.indexOf('wall') >= 0) {
funcNames.push(key);
}
}
} catch(e) {}
}
results['boundary_funcs'] = funcNames;
return results;
"""
try:
result = self.driver.execute_script(scan_js)
return result
except Exception as e:
log(f"[SCAN] Failed: {e}")
return None
def get_game_data(self):
"""
Retrieves game state in a SINGLE JS call.
Includes limits on returned objects for performance.
Also returns the actual view dimensions for correct scaling.
"""
fetch_js = f"""
function getGameState() {{
var MAX_FOODS = {self.MAX_FOODS};
var MAX_ENEMIES = {self.MAX_ENEMIES};
var MAX_BODY_PTS = {self.MAX_BODY_PTS};
var hasSnake = (window.slither !== undefined && window.slither !== null &&
typeof window.slither.xx === 'number' && typeof window.slither.yy === 'number');
var isDeadFlag = (window.slither && typeof window.slither.dead !== 'undefined') ? window.slither.dead : false;
var deadMtm = window.dead_mtm;
var deadMtmActive = !(deadMtm === undefined || deadMtm === null || deadMtm === -1 || deadMtm === 0);
var playing = hasSnake && !isDeadFlag && !deadMtmActive;
var in_menu = document.querySelector('#nick, #playh .btnt') !== null;
if (!playing) {{
return {{ dead: true, in_menu: in_menu }};
}}
// Get actual view dimensions from game
// gsc = global scale, determines how much world space is visible
var canvas = document.getElementById('mc') || document.querySelector('canvas');
var canvasW = canvas ? canvas.width : 800;
var canvasH = canvas ? canvas.height : 600;
var gsc = window.gsc || 0.9; // global scale (zoom level)
// Calculate actual visible world area
// Visible width in world units = canvas pixels / scale
var viewWidth = canvasW / gsc;
var viewHeight = canvasH / gsc;
var viewRadius = Math.max(viewWidth, viewHeight) / 2;
// My snake data
var my_pts = [];
if (window.slither.pts) {{
var ptsLen = window.slither.pts.length;
// Trim ghost tail dynamically (Increased)
var trimCount = Math.floor(ptsLen * 0.15) + Math.floor((window.slither.sp || 5.7) * 2.0);
var startIndex = Math.min(ptsLen - 1, trimCount);
var step = Math.max(1, Math.floor(ptsLen / MAX_BODY_PTS));
for (var j = startIndex; j < ptsLen && my_pts.length < MAX_BODY_PTS; j += step) {{
var p = window.slither.pts[j];
if (p.xx !== undefined) my_pts.push([p.xx, p.yy]);
else if (p.x !== undefined) my_pts.push([p.x, p.y]);
}}
}}
var my_snake = {{
x: window.slither.xx,
y: window.slither.yy,
ang: window.slither.ang,
wang: window.slither.wang,
eang: window.slither.eang,
sp: window.slither.sp,
sc: window.slither.sc,
len: window.slither.pts ? window.slither.pts.length : 0,
pts: my_pts
}};
// Foods (limited for performance) - only within view radius
var visible_foods = [];
if (window.foods && window.foods.length) {{
var myX = my_snake.x;
var myY = my_snake.y;
var viewRadSq = viewRadius * viewRadius * 1.2; // slight buffer
// Get closest foods first
var foodList = [];
for (var i = 0; i < window.foods.length && foodList.length < MAX_FOODS * 2; i++) {{
var f = window.foods[i];
if (f) {{
var fx = (typeof f.xx === 'number') ? f.xx :
(typeof f.x === 'number') ? f.x :
(typeof f.rx === 'number') ? f.rx : null;
var fy = (typeof f.yy === 'number') ? f.yy :
(typeof f.y === 'number') ? f.y :
(typeof f.ry === 'number') ? f.ry : null;
if (fx === null || fy === null) continue;
var dx = fx - myX;
var dy = fy - myY;
var dist = dx*dx + dy*dy;
// Only include foods within view
if (dist < viewRadSq) {{
foodList.push([fx, fy, f.sz || 1, dist]);
}}
}}
}}
// Sort by distance and take closest
foodList.sort(function(a, b) {{ return a[3] - b[3]; }});
for (var i = 0; i < Math.min(foodList.length, MAX_FOODS); i++) {{
visible_foods.push([foodList[i][0], foodList[i][1], foodList[i][2]]);
}}
}}
// Enemies - check if ANY part (head or body) is within view
var visible_enemies = [];
var totalSlithers = window.slithers ? window.slithers.length : 0;
if (window.slithers && window.slithers.length) {{
var myX = my_snake.x;
var myY = my_snake.y;
// Expanded search radius to prevent "invisible snakes" on minimap edge
var searchRadSq = viewRadius * viewRadius * 25; // 5x radius for search (was 3x)
var viewRadSq = viewRadius * viewRadius * 2.0; // Expanded view for filtering points
var enemyList = [];
for (var i = 0; i < window.slithers.length; i++) {{
var s = window.slithers[i];
if (s === window.slither) continue;
if (!s || !s.pts) continue;
// Check if head OR any body part is potentially visible or close enough to be relevant
var minDist = Infinity;
var hasVisiblePart = false;
// Check head
var hdx = (s.xx || 0) - myX;
var hdy = (s.yy || 0) - myY;
var headDist = hdx*hdx + hdy*hdy;
if (headDist < viewRadSq) hasVisiblePart = true;
minDist = Math.min(minDist, headDist);
// Check some body points (sample every 10th for speed)
if (!hasVisiblePart && s.pts && s.pts.length > 0) {{
var ptsLen = s.pts.length;
var trimCount = Math.floor(ptsLen * 0.1) + Math.floor((s.sp || 5.7) * 2.0);
var startIndex = Math.min(ptsLen - 1, trimCount);
var step = Math.max(1, Math.floor(ptsLen / 40));
for (var j = startIndex; j < ptsLen; j += step) {{
var p = s.pts[j];
var px = p.xx !== undefined ? p.xx : (p.x || 0);
var py = p.yy !== undefined ? p.yy : (p.y || 0);
var bdx = px - myX;
var bdy = py - myY;
var bodyDist = bdx*bdx + bdy*bdy;
if (bodyDist < viewRadSq) {{
hasVisiblePart = true;
break;
}}
minDist = Math.min(minDist, bodyDist);
}}
}}
// Include if any part is visible OR if close enough to matter
if (hasVisiblePart || minDist < searchRadSq) {{
enemyList.push([s, minDist, hasVisiblePart ? 0 : 1]);
}}
}}
// Sort: visible first, then by distance
enemyList.sort(function(a, b) {{
if (a[2] !== b[2]) return a[2] - b[2];
return a[1] - b[1];
}});
// Take enemies (increased limit)
for (var i = 0; i < Math.min(enemyList.length, MAX_ENEMIES); i++) {{
var s = enemyList[i][0];
// Get body points - filter to only those in view
var pts = [];
if (s.pts) {{
var ptsLen = s.pts.length;
// Trim ghost tail dynamically (Increased)
var trimCount = Math.floor(ptsLen * 0.15) + Math.floor((s.sp || 5.7) * 2.0);
var startIndex = Math.min(ptsLen - 1, trimCount);
var step = Math.max(1, Math.floor(ptsLen / MAX_BODY_PTS));
for (var j = startIndex; j < ptsLen && pts.length < MAX_BODY_PTS; j += step) {{
var p = s.pts[j];
var px = p.xx !== undefined ? p.xx : (p.x || 0);
var py = p.yy !== undefined ? p.yy : (p.y || 0);
// Only include points within search radius (5x view)
var pdx = px - myX;
var pdy = py - myY;
if (pdx*pdx + pdy*pdy < searchRadSq) {{
pts.push([px, py]);
}}
}}
}}
visible_enemies.push({{
id: s.id,
x: s.xx || 0,
y: s.yy || 0,
ang: s.ang || 0,
sp: s.sp || 0,
sc: s.sc || 1,
pts: pts
}});
}}
}}
// DETECT MAP BOUNDARY
var possibleMapVars = {{}};
var boundarySource = 'none';
var boundaryType = 'circle';
var boundaryVertices = [];
var distToWall = 99999;
var distFromCenter = 99999;
var mapCenterX = 21600; // Default center
var mapCenterY = 21600; // Default center
var mapRadius = 21600; // Default radius
// Check for Polygon Boundary (pbx/pby)
var usePolygon = false;
var pbxCount = 0;
if (typeof window.pbx !== 'undefined' && window.pbx && window.pbx.length >= 3 &&
window.pbx.length < 500 &&
(typeof window.pby === 'undefined' || (window.pby && window.pby.length >= 3))) {{
usePolygon = true;
boundarySource = 'pbx';
boundaryType = 'polygon';
pbxCount = window.pbx.length;
// Extract vertices (limited to avoid huge payload)
var step = 1;
if (window.pbx.length > 200) step = Math.ceil(window.pbx.length / 200);
for (var i = 0; i < window.pbx.length; i+=step) {{
var pyVal = (window.pby && window.pby[i] !== undefined) ? window.pby[i] : window.pbx[i];
boundaryVertices.push([window.pbx[i], pyVal]);
}}
// Ensure we capture the start point for drawing
if (boundaryVertices.length > 0) {{
var last = boundaryVertices[boundaryVertices.length-1];
var first = boundaryVertices[0];
if (last[0] !== first[0] || last[1] !== first[1]) {{
boundaryVertices.push(first);
}}
}}
}}
if (!usePolygon) {{
if (typeof window.grd !== 'undefined' && window.grd > 1000) {{
mapCenterX = window.grd;
mapCenterY = window.grd;
possibleMapVars['grd'] = window.grd;
// Probe for eslither.io / modded server boundary vars
var foundSpecific = false;
// bsr = border/server radius (eslither)
if (typeof window.bsr !== 'undefined' && window.bsr > 1000) {{
mapRadius = window.bsr;
boundarySource = 'bsr';
foundSpecific = true;
possibleMapVars['bsr'] = window.bsr;
}}
// Some mods expose 'border' directly
if (!foundSpecific && typeof window.border !== 'undefined' && window.border > 1000) {{
mapRadius = window.border;
boundarySource = 'border';
foundSpecific = true;
possibleMapVars['border'] = window.border;
}}
// game_radius / arena_size
if (!foundSpecific && typeof window.game_radius !== 'undefined' && window.game_radius > 1000) {{
mapRadius = window.game_radius;
boundarySource = 'game_radius';
foundSpecific = true;
possibleMapVars['game_radius'] = window.game_radius;
}}
if (!foundSpecific && typeof window.arena_size !== 'undefined' && window.arena_size > 1000) {{
mapRadius = window.arena_size;
boundarySource = 'arena_size';
foundSpecific = true;
possibleMapVars['arena_size'] = window.arena_size;
}}
// Check cst (server scale factor) — works for all servers including standard slither.io
if (!foundSpecific && typeof window.cst !== 'undefined' && window.cst > 0.1) {{
mapRadius = window.grd * window.cst;
boundarySource = 'grd*cst';
foundSpecific = true;
possibleMapVars['cst'] = window.cst;
possibleMapVars['grd*cst'] = mapRadius;
}}
// Fallback: grd * 0.98 (only if cst is not available)
if (!foundSpecific) {{
mapRadius = window.grd * 0.98;
boundarySource = 'grd';
}}
boundaryType = 'circle';
// Log additional candidate vars for diagnostics
var probeVars = ['bsr','bsc','border','game_radius','arena_size','rfbx','rfby',
'mcp','mcx','mcy','bmx','bmy','bmr','gla','glr','cst','msc'];
for (var pi = 0; pi < probeVars.length; pi++) {{
var pv = probeVars[pi];
try {{
if (typeof window[pv] !== 'undefined') {{
possibleMapVars[pv] = window[pv];
}}
}} catch(e) {{}}
}}
}} else {{
boundarySource = 'default';
boundaryType = 'circle';
}}
}}
if (usePolygon) {{
// Calculate Distance to Polygon
distToWall = (function(x, y, pbx, pby) {{
var minD = 999999;
var inside = false;
var len = pbx.length;
// PIP (Ray Casting)
var j = len - 1;
for (var i = 0; i < len; i++) {{
var xi = pbx[i], yi = (pby && pby[i] !== undefined) ? pby[i] : pbx[i];
var xj = pbx[j], yj = (pby && pby[j] !== undefined) ? pby[j] : pbx[j];
if ((yi > y) != (yj > y) &&
(x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {{
inside = !inside;
}}
j = i;
}}
// Dist to edges
j = len - 1;
for (var i = 0; i < len; i++) {{
var x1 = pbx[i], y1 = (pby && pby[i] !== undefined) ? pby[i] : pbx[i];
var x2 = pbx[j], y2 = (pby && pby[j] !== undefined) ? pby[j] : pbx[j];
var A = x - x1;
var B = y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = -1;
if (len_sq != 0) param = dot / len_sq;
var xx, yy;
if (param < 0) {{ xx = x1; yy = y1; }}
else if (param > 1) {{ xx = x2; yy = y2; }}
else {{ xx = x1 + param * C; yy = y1 + param * D; }}
var dx = x - xx;
var dy = y - yy;
var d = Math.sqrt(dx*dx + dy*dy);
if (d < minD) minD = d;
j = i;
}}
return inside ? minD : -minD;
}})(my_snake.x, my_snake.y, window.pbx, window.pby);
// Use distToWall for center calc placeholder
distFromCenter = 0;
}} else {{
distFromCenter = Math.sqrt(
Math.pow(my_snake.x - mapCenterX, 2) +
Math.pow(my_snake.y - mapCenterY, 2)
);
distToWall = mapRadius - distFromCenter;
}}
// Sanity cap: distToWall should never exceed mapRadius
if (distToWall > mapRadius) distToWall = mapRadius;
if (distToWall < -500) distToWall = -500;
possibleMapVars['map_center'] = Math.round(mapCenterX) + ',' + Math.round(mapCenterY);
possibleMapVars['map_radius'] = Math.round(mapRadius);