-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcerabot v6.py
More file actions
1531 lines (1308 loc) · 60.8 KB
/
cerabot v6.py
File metadata and controls
1531 lines (1308 loc) · 60.8 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
#WIP -- FUCKING PERFECT KITING
import os
import pydirectinput
import time
import pymem
import pymem.exception
import threading
import frida
import pyautogui
import bresenham
import json
import random
import tkinter as tk
from pynput import mouse, keyboard
from tkinter import ttk
from queue import PriorityQueue
CONFIG_PATH = "cerabot_config.json"
walkAddress = "0xEDC35"
npcAddress = "0x1EFC8E"
directionalAddress = "0x6CAEE"
varOffset = 0xA0
totalExp = None
WEIGHT_WRITE_ADDRS = [0xFC3C9, 0xFCD40]
START_ADDR = 0x00180000
END_ADDR = 0x0019FFFF
STEP = 4
DEBUG_PROTECTED = True
STALE_NPC_SECONDS = 12
# --- attack state + grace windows ---
ATTACK_RECENCY_S = 0.3 # treat as "attacking" for this long after we start/continue
PRE_HIT_GRACE_S = 0.3 # delay protection this long after a hit to avoid locking our own hit
ctrl_engaged = False
last_attack_time = 0.0
last_attack_addr = None
# --- Flank/kiting settings ---
FLANK_RANGE = 3 # desired distance from target (try 2–4)
RECOVER_SECS = 0.6 # after a backstep, wait this long before holding again
recover_to_range_until = 0.0
HOLD_AT_RANGE_LOCK = True # set False to return to normal kiting
flank_hold_target = None
AGRO_OFFSET = -90 # byte offset from NPC base ("npc data")
AGRO_VALUE = 2 # 0 = not agro, 2 = agro
AGRO_TIMEOUT_S = 4.0 # seconds to wait after pressing Ctrl
BOTCHECK_PAUSE_S = 300.0 # 5 minutes
x_address = None
y_address = None
directional_address = None
combat_baseline_exp = None
current_target_npc = None
xstarted = 0
debug = 0
pyautogui.PAUSE = 0
last_direction = None
wandering_target = None
pm = None # Global pymem instance
POST_PROTECT_GRACE_S = 2.0
botcheck_guard = threading.Event()
def initialize_pymem():
global pm
if pm is None:
pm = pymem.Pymem("Endless.exe")
def press_key(key, presses=2, delay=0.1):
"""
Presses a key and optionally waits for a specified delay.
"""
pydirectinput.press(key, presses)
time.sleep(delay)
def hold_key(key):
pydirectinput.keyDown(key)
def release_key(key):
pydirectinput.keyUp(key)
attack_lock = threading.Lock()
def load_config():
if os.path.exists(CONFIG_PATH):
try:
with open(CONFIG_PATH, "r") as f:
return json.load(f)
except Exception:
return {}
return {}
def save_config(cfg: dict):
try:
with open(CONFIG_PATH, "w") as f:
json.dump(cfg, f, indent=2)
except Exception:
pass
# --- Apply saved config values ---
try:
_cfg = load_config()
if isinstance(_cfg.get("FLANK_RANGE"), int):
FLANK_RANGE = max(1, _cfg["FLANK_RANGE"]) # clamp to >=1
if isinstance(_cfg.get("HOLD_AT_RANGE_LOCK"), bool):
HOLD_AT_RANGE_LOCK = _cfg["HOLD_AT_RANGE_LOCK"]
except Exception:
pass
class UniversalStuck:
def __init__(self, step_timeout_s=1.2, fire_cooldown_s=0.2, arrive_eps=0):
self.step_timeout_s = step_timeout_s
self.fire_cooldown_s = fire_cooldown_s
self.arrive_eps = arrive_eps
self.goal = None # (x, y)
self.started_at = None # time we began trying this goal
self.last_fire_at = 0.0 # to prevent duplicate fires
def _same_tile(self, a, b):
if a is None or b is None: return False
# integer tiles; keep eps if you sometimes use floats
return abs(a[0]-b[0]) <= self.arrive_eps and abs(a[1]-b[1]) <= self.arrive_eps
def begin_or_continue(self, goal_xy, player_xy, now):
"""Call every tick with the pathfinder's next_step (goal_xy) and real player_xy.
Returns: None or ('timeout', blocked_tile_xy) exactly once per timeout window."""
# If goal changed or we arrived, reset timer.
arrived = self._same_tile(goal_xy, player_xy)
if self.goal != goal_xy or arrived:
self.goal = goal_xy
self.started_at = now if not arrived else None
return None
# No goal? nothing to do.
if self.goal is None or self.started_at is None:
return None
# Timeout check.
if (now - self.started_at) >= self.step_timeout_s:
# Debounce so we only fire once per goal.
if (now - self.last_fire_at) >= self.fire_cooldown_s:
self.last_fire_at = now
# Reset so next tick can pick a fresh route/goal.
timed_out_tile = self.goal
self.goal = None
self.started_at = None
return ('timeout', timed_out_tile)
return None
def pause_for(seconds: float, reason: str = "bot_check"):
global pause_flag
try:
print(f"[pause] Reason={reason}. Pausing for {int(seconds)}s...")
pause_flag = True # <<< set first
set_attack(False) # then release
release_key('ctrl') # belt-and-suspenders
time.sleep(seconds)
finally:
pause_flag = False
print("[pause] Resuming combat/wandering.")
def pause_for_and_clear_guard():
try:
pause_for(BOTCHECK_PAUSE_S, reason="bot_check") # your existing pause function
finally:
botcheck_guard.clear()
def read_agro(addr_hex: str) -> int | None:
"""Reads 1 byte at (npc_base + AGRO_OFFSET). Returns int or None on failure."""
global pm
if not addr_hex:
return None
try:
npc_base = int(addr_hex, 16)
agro_addr = npc_base + AGRO_OFFSET
return pm.read_bytes(agro_addr, 1)[0]
except Exception as e:
# Optional: print(f"[agro] read failed @ {addr_hex} ({e})")
return None
def agro_watchdog(target_addr_hex: str, started_at: float):
global pause_flag
"""Within AGRO_TIMEOUT_S of starting Ctrl, ensure target's agro==2; else pause."""
if not target_addr_hex:
return
deadline = started_at + AGRO_TIMEOUT_S
while time.time() < deadline:
val = read_agro(target_addr_hex)
if val == AGRO_VALUE:
# target went agro; we're good
# Optional: print(f"[agro] target {target_addr_hex} went agro (2).")
return
time.sleep(0.2)
# Timed out: only trigger if we're still attacking and target hasn't changed
# (avoid false positives if you disengaged or retargeted)
if is_attacking() and target_addr_hex == last_attack_addr:
# Debounce: if another trigger already fired, bail.
if botcheck_guard.is_set():
return
botcheck_guard.set()
print(f"[agro] target {target_addr_hex} did NOT go agro (2) within {AGRO_TIMEOUT_S}s.")
pause_flag = True
set_attack(False)
release_key('ctrl')
threading.Thread(target=pause_for_and_clear_guard, daemon=True).start()
def set_attack(state: bool):
"""Hold/release Ctrl and stamp last-attack info atomically."""
global ctrl_engaged, last_attack_time, last_attack_addr, current_target_npc, pause_flag
with attack_lock:
if state:
# Don't allow Ctrl engage while paused
if pause_flag:
if ctrl_engaged:
release_key('ctrl')
ctrl_engaged = False
return
# Engage only on transition
if not ctrl_engaged:
hold_key('ctrl')
ctrl_engaged = True
last_attack_time = time.time()
last_attack_addr = current_target_npc
threading.Thread(
target=agro_watchdog,
args=(current_target_npc, last_attack_time),
daemon=True
).start()
else:
# Clean release on transition
if ctrl_engaged:
release_key('ctrl')
ctrl_engaged = False
def is_attacking() -> bool:
return ctrl_engaged
def recently_attacking(addr: str | None, window: float = ATTACK_RECENCY_S) -> bool:
return (addr is not None
and addr == last_attack_addr
and (time.time() - last_attack_time) < window)
def get_flank_candidates(npc_x, npc_y, r):
# four tiles exactly r away on same row/col
return [(npc_x - r, npc_y), (npc_x + r, npc_y),
(npc_x, npc_y - r), (npc_x, npc_y + r)]
def on_message_xy(message, data):
global xstarted, x_address, y_address
if message['type'] == 'send':
addresses = message['payload']
x_address = int(addresses['x_address'], 16)
y_address = int(addresses['y_address'], 16)
if debug == 1:
print(f"X Address: {hex(x_address)}, Y Address: {hex(y_address)}")
# Mark as completed and detach session
xstarted = 1
session.detach()
else:
print(f"Error: {message}")
def scan_for_exp_address(pm: pymem.Pymem, search_value: int) -> int:
"""
Scan memory from START_ADDR up to END_ADDR in 4‑byte steps.
Returns the first address where pm.read_int(addr) == search_value.
"""
for addr in range(START_ADDR, END_ADDR, STEP):
try:
value = pm.read_int(addr)
except pymem.exception.MemoryReadError:
# some pages can’t be read—just skip them
continue
if value == search_value:
print(f"[+] Found EXP value {search_value} at {hex(addr)}")
return addr
raise RuntimeError(f"Couldn’t find {search_value} in 0x{START_ADDR:X}–0x{END_ADDR:X}")
def start_frida_session_xy(walk_address):
global session
session = frida.attach("Endless.exe")
print("XY Started - Waiting for you to move to begin")
script_code = f"""
var baseAddress = Module.findBaseAddress("Endless.exe").add(ptr({walk_address}));
Interceptor.attach(baseAddress, {{
onEnter: function(args) {{
var xAddress = this.context.ecx.add(0x08);
var yAddress = xAddress.add(0x04);
send({{x_address: xAddress.toString(), y_address: yAddress.toString()}});
}}
}});
"""
script = session.create_script(script_code)
script.on('message', on_message_xy)
script.load()
while xstarted == 0:
continue
print("Session completed and detached.")
def on_message_directional(message, data):
global directional_address, xstarted
if message['type'] == 'send':
payload = message['payload']
directional_address = int(payload.get('directional_address'), 16)
character_direction = payload.get('character_direction')
if debug == 1:
print(f"Character Direction Address: {directional_address}")
print(f"Character Direction Value: {character_direction}")
xstarted = 2
session.detach()
elif message['type'] == 'error':
print(f"Error: {message['stack']}")
def start_frida_session_directional(target_address):
global session
session = frida.attach("Endless.exe")
print("Directional Started - Waiting for mov [ebx+55],dl to execute")
script_code = f"""
var baseAddress = Module.findBaseAddress("Endless.exe").add(ptr("{target_address}"));
Interceptor.attach(baseAddress, {{
onEnter: function(args) {{
var ebxValue = this.context.ebx;
var characterDirectionAddress = ebxValue.add(0x55);
var characterDirection = characterDirectionAddress.readU8();
send({{directional_address: characterDirectionAddress.toString(), character_direction: characterDirection.toString()}});
}}
}});
"""
script = session.create_script(script_code)
script.on('message', on_message_directional)
script.load()
while xstarted == 1:
continue
print("Directional Session Completed.")
def patch_adds_with_nops():
# attach to the process
session = frida.attach("Endless.exe")
# inline the two absolute addresses you want to NOP
js = """
[0x005EE862, 0x005EE87C].forEach(function(addr) {
// make the 7 bytes at addr writeable
Memory.protect(ptr(addr), 7, 'rwx');
// overwrite them with NOP (0x90)
for (var i = 0; i < 7; i++) {
Memory.writeU8(ptr(addr).add(i), 0x90);
}
// restore as RX
Memory.protect(ptr(addr), 7, 'r-x');
});
"""
script = session.create_script(js)
script.load()
session.detach()
def start_frida_weight_lock(weight_write_offsets):
"""
Hooks the instructions that write the weight value and forces the
written register to 0 (locks weight at zero).
Params:
weight_write_offsets: iterable of relative offsets (RVA) from Endless.exe base
e.g. [0xFAF26, 0xFA5AF]
"""
import frida, threading, time
# Attach once for this feature (kept separate from your other sessions)
session = frida.attach("Endless.exe")
# Build the Frida script (module-safe, 32/64-bit friendly)
js = f"""
(function() {{
var mod = null;
try {{
mod = Process.getModuleByName("Endless.exe");
}} catch (e) {{
var mods = Process.enumerateModules();
mod = mods.length ? mods[0] : null;
}}
if (!mod) {{
throw new Error("Could not resolve Endless.exe module.");
}}
var base = mod.base;
// Offsets provided by Python
var OFFS = [{", ".join("ptr(0x%X)" % off for off in weight_write_offsets)}];
OFFS.forEach(function(rel) {{
var addr = base.add(rel);
try {{
Interceptor.attach(addr, {{
onEnter: function (args) {{
// Force the destination register/value to zero.
// If this instruction writes from EAX/RAX (common pattern),
// zeroing it here will clamp the write to 0.
if (this.context.eax !== undefined) {{
this.context.eax = 0;
}} else if (this.context.rax !== undefined) {{
this.context.rax = ptr(0);
}}
}}
}});
}} catch (e) {{
send({{type: "weight-lock-hook-error", address: addr.toString(), error: e.toString()}});
}}
}});
send({{type: "weight-lock-ready", count: OFFS.length}});
}})();
""".strip()
script = session.create_script(js)
def _on_message(message, data):
# Bubble up meaningful errors to your console
if message.get("type") == "send":
payload = message.get("payload", {})
if payload.get("type") == "weight-lock-ready":
print(f"[frida] Weight lock enabled on {payload.get('count')} addresses.")
elif payload.get("type") == "weight-lock-hook-error":
print(f"[frida] Hook failed @ {payload.get('address')}: {payload.get('error')}")
elif message.get("type") == "error":
print("[frida] Script error:", message)
script.on("message", _on_message)
script.load()
print("[frida] Weight lock hooks installed (listening).")
# Keep the session alive in this thread
# (Your program stays alive anyway; no busy loop needed.)
class PlayerDataManager:
def __init__(self):
self.data = {
"x": 0,
"y": 0,
"direction": 0
}
def update(self, x, y, direction):
self.data["x"] = x
self.data["y"] = y
self.data["direction"] = direction
def get_data(self):
return self.data
class AddressManager:
"""
Tracks known NPC addresses; now includes per-NPC protection windows.
Pulled/trimmed from your v5 version.
"""
def __init__(self):
self.addresses = {}
self._lock = threading.Lock()
self._removal_history = []
self._history_max = 50
self._protection_default = 8 # seconds
self.ignore_protection = False
def set_ignore_protection(self, flag: bool):
self.ignore_protection = bool(flag)
def is_protected(self, addr_hex: str) -> bool:
"""Respect the global ignore flag; if True, nothing is protected."""
if self.ignore_protection:
return False
st = self.addresses.get(addr_hex)
if not st:
return False
pu = st.get("protected_until")
now = time.time()
if pu and now < pu:
return True
# If protection just ended, start quarantine and keep filtering briefly
if pu and now >= pu:
st["protected_until"] = None
st["protected_cleared_at"] = now
# Quarantine window
pc = st.get("protected_cleared_at")
if pc and (now - pc) < POST_PROTECT_GRACE_S:
return True
return False
def add_address(self, address):
address1 = int(address, 16)
address2 = address1 + 2
address1_hex = hex(address1).upper()
address2_hex = hex(address2).upper()
with self._lock:
if address1_hex not in self.addresses:
self.addresses[address1_hex] = {
"paired_address": address2_hex,
"last_x": None,
"last_y": None,
"last_moved": time.time(),
"is_dead_counter": 0,
"last_is_dead_value": None,
"last_npc_id": None,
"last_unique_id": None,
"got_hit": None,
"protected_until": None,
"read_fail_count": 0,
"protected_until": None,
"protected_cleared_at": None,
}
return True
return False
def _log_removal(self, addr_hex: str, reason: str, meta: dict | None, last_state: dict | None):
entry = {
"ts": time.time(),
"address": addr_hex,
"reason": reason,
"meta": meta or {},
"last_state": last_state or {},
}
self._removal_history.append(entry)
if len(self._removal_history) > self._history_max:
self._removal_history = self._removal_history[-self._history_max:]
# Skip noisy protection lines unless debugging
if reason.startswith("protected:") and not DEBUG_PROTECTED:
return
ts = time.strftime("%H:%M:%S", time.localtime(entry["ts"]))
m = entry["meta"] or {}
def _fmt_float(val, default="?"):
# Robust: returns a string; uses one decimal when numeric, else raw/default
try:
return f"{float(val):.1f}"
except Exception:
return str(val) if val is not None else default
# Build a friendly reason string safely
if reason == "exp_kill":
friendly = f"EXP tick suggests kill (+{m.get('delta_exp','?')})."
elif reason == "stale":
friendly = f"No movement for {m.get('stale_seconds','?')}s."
elif reason == "stale_movement":
friendly = f"Stationary for {_fmt_float(m.get('idle_secs'))}s."
elif reason == "oob":
friendly = f"Out of bounds x={m.get('x')} y={m.get('y')}."
elif reason == "read_error":
friendly = f"Read error: {m.get('error','?')}."
elif reason == "read_fail":
friendly = f"{m.get('consecutive_failures', '?')} consecutive read failures."
else:
friendly = "No details."
print(f"[{ts}] [manager] Removed NPC {addr_hex} reason={reason} info={friendly}")
# ---- New protection API (from v5) ----
def mark_protected(self, addr_hex: str, seconds: int | None = None, reason: str = "got_hit", meta: dict | None = None):
secs = seconds if seconds is not None else self._protection_default
st = self.addresses.get(addr_hex)
if not st:
return False
st["protected_until"] = time.time() + max(1, secs)
st["protected_cleared_at"] = None
self._log_removal(addr_hex, f"protected:{reason}", meta or {}, dict(st))
return True
def protection_seconds_left(self, addr_hex: str) -> int:
st = self.addresses.get(addr_hex)
if not st or not st.get("protected_until"):
return 0
return max(0, int(st["protected_until"] - time.time()))
def remove_address(self, address, reason: str = "unspecified", meta: dict | None = None):
address1 = int(address, 16)
address1_hex = hex(address1).upper()
with self._lock:
if address1_hex in self.addresses:
last_state = dict(self.addresses[address1_hex])
del self.addresses[address1_hex]
self._log_removal(address1_hex, reason, meta, last_state)
return True
return False
def update_address_movement(self, address, x, y):
with self._lock:
state = self.addresses.get(address)
if state:
now = time.time()
if x != state["last_x"] or y != state["last_y"]:
state["last_moved"] = now
state["last_x"] = x
state["last_y"] = y
def remove_stale_addresses(self, max_stale=None):
if max_stale is None:
max_stale = STALE_NPC_SECONDS
now = time.time()
to_remove = []
with self._lock:
for addr, data in list(self.addresses.items()):
if data["last_moved"] is not None and now - data["last_moved"] > max_stale:
to_remove.append(addr)
for addr in to_remove:
last_state = dict(self.addresses[addr])
del self.addresses[addr]
self._log_removal(addr, "stale", {"stale_seconds": max_stale}, last_state)
def list_addresses(self):
with self._lock:
return [
{"address": addr, "paired": data["paired_address"], "got_hit": data["got_hit"]}
for addr, data in self.addresses.items()
]
def recent_removals(self, n: int = 10):
return self._removal_history[-n:]
manager = AddressManager()
player_data_manager = PlayerDataManager()
map_data = []
map_data_lock = threading.Lock()
class PlayerDataPopup:
def __init__(self, player_data_manager):
self.player_data_manager = player_data_manager
self.root = tk.Tk()
self.root.title("Player Data")
self.labels = {}
self.protect_var = tk.BooleanVar(value=False) # <--- NEW: default unchecked (protection enabled)
self.create_widgets()
self.create_styles()
self.update_ui()
def create_widgets(self):
self.frame = ttk.Frame(self.root, padding="10")
self.frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Existing labels...
for idx, text in enumerate(["X", "Y", "Direction"], start=2):
ttk.Label(self.frame, text=text).grid(row=idx, column=0, sticky=tk.W)
value_label = ttk.Label(self.frame, text="0")
value_label.grid(row=idx, column=1, sticky=tk.E)
self.labels[text] = value_label
# Map canvas
self.canvas = tk.Canvas(self.frame, width=200, height=200, bg="white")
self.canvas.grid(row=0, column=2, rowspan=6, padx=10)
# --- NEW: checkbox row (put it neatly under the stats) ---
ttk.Checkbutton(
self.frame,
text="Disable protected NPCs (boss mode)",
variable=self.protect_var,
command=self._on_toggle_protection
).grid(row=6, column=0, columnspan=2, sticky=(tk.W), pady=(8, 0))
# Small status hint (optional)
self.status_label = ttk.Label(self.frame, text="Protected NPCs: ENABLED")
self.status_label.grid(row=7, column=0, columnspan=2, sticky=tk.W)
# --- Hold-at-range (lock) toggle ---
self.hold_lock_var = tk.BooleanVar(value=HOLD_AT_RANGE_LOCK)
ttk.Checkbutton(
self.frame,
text="Hold at range (no retreat)",
variable=self.hold_lock_var,
command=self._on_hold_lock_toggle
).grid(row=8, column=0, columnspan=2, sticky=tk.W, pady=(6, 0))
# --- Flank range control ---
self.flank_var = tk.IntVar(value=FLANK_RANGE)
ttk.Label(self.frame, text="Flank Range").grid(row=9, column=0, sticky=tk.W, pady=(10, 0))
self.flank_spin = tk.Spinbox(
self.frame, from_=1, to=8, width=5,
textvariable=self.flank_var,
command=self._on_flank_change,
justify="center"
)
self.flank_spin.grid(row=9, column=1, sticky=tk.W, pady=(10, 0))
self.flank_spin.bind("<Return>", lambda e: self._on_flank_change())
self.flank_spin.bind("<FocusOut>", lambda e: self._on_flank_change())
def _on_toggle_protection(self):
# When checked, IGNORE protection (i.e., don't filter or postpone targets that got hit)
manager.set_ignore_protection(self.protect_var.get())
self.status_label.config(
text="Protected NPCs: DISABLED (boss mode)" if self.protect_var.get()
else "Protected NPCs: ENABLED"
)
def create_styles(self):
style = ttk.Style(self.root)
style.theme_use('default')
style.configure("red.Horizontal.TProgressbar", troughcolor='white', background='red')
style.configure("blue.Horizontal.TProgressbar", troughcolor='white', background='blue')
def update_ui(self):
data = self.player_data_manager.get_data()
self.labels["X"].config(text=data["x"])
self.labels["Y"].config(text=data["y"])
self.labels["Direction"].config(text=data["direction"])
self.draw_map()
self.root.after(100, self.update_ui)
def draw_map(self):
# Clear previous drawings.
self.canvas.delete("all")
# Set canvas and grid parameters.
canvas_size = 200
max_x = 20
max_y = 20
cell_width = canvas_size / max_x
cell_height = canvas_size / max_y
# Draw a gray background covering the entire canvas.
self.canvas.create_rectangle(0, 0, canvas_size, canvas_size, fill="gray", outline="")
# Draw vertical grid lines.
for i in range(max_x + 1):
x = i * cell_width
self.canvas.create_line(x, 0, x, canvas_size, fill="black")
# Draw horizontal grid lines.
for j in range(max_y + 1):
y = j * cell_height
self.canvas.create_line(0, y, canvas_size, y, fill="black")
# Get player data.
data = self.player_data_manager.get_data()
player_x = data["x"]
player_y = data["y"]
# Define the center of the canvas.
center_x = canvas_size / 2
center_y = canvas_size / 2
player_radius = 5
# Draw the player at the center of the canvas.
self.canvas.create_oval(center_x - player_radius, center_y - player_radius,
center_x + player_radius, center_y + player_radius,
fill="orange", outline="black")
# Draw NPC markers.
for item in map_data:
if item["type"] == "npc":
npc_x = item["X"]
npc_y = item["Y"]
# Map world coordinates to canvas positions relative to the player.
canvas_x = center_x + (npc_x - player_x) * cell_width
canvas_y = center_y + (npc_y - player_y) * cell_height
self.canvas.create_oval(canvas_x - 3, canvas_y - 3,
canvas_x + 3, canvas_y + 3,
fill="red", outline="black")
def _on_flank_change(self):
"""Validate and push GUI value to the global FLANK_RANGE."""
global FLANK_RANGE
try:
val = int(self.flank_var.get())
except Exception:
# revert to current global if invalid
self.flank_var.set(FLANK_RANGE)
return
# clamp to a sane range
if val < 1: val = 1
if val > 8: val = 8
# reflect any clamping in the UI
if val != self.flank_var.get():
self.flank_var.set(val)
FLANK_RANGE = val
# persist (optional)
cfg = load_config()
cfg["FLANK_RANGE"] = FLANK_RANGE
save_config(cfg)
def _on_hold_lock_toggle(self):
global HOLD_AT_RANGE_LOCK
HOLD_AT_RANGE_LOCK = bool(self.hold_lock_var.get())
cfg = load_config()
cfg["HOLD_AT_RANGE_LOCK"] = HOLD_AT_RANGE_LOCK
save_config(cfg)
def run(self):
self.root.mainloop()
def check_player_data(x_address, y_address, directional_address):
global pm
initialize_pymem()
prev_dir = 0 # keep last good direction so a bad read doesn't stall map_data
try:
while True:
# --- read X/Y robustly ---
try:
x = pm.read_short(x_address)
y = pm.read_short(y_address)
except Exception as e:
print(f"[player] XY read failed: {e}")
time.sleep(0.05)
continue # we can't build a player row without XY
# --- read direction *best-effort* ---
try:
direction = pm.read_bytes(directional_address, 1)[0]
prev_dir = direction
except Exception as e:
direction = prev_dir # fall back; do NOT skip publishing the player row
# (optional) print sparingly:
# print(f"[player] direction read failed (using {prev_dir}): {e}")
# --- read X/Y robustly ---
try:
x = pm.read_short(x_address)
y = pm.read_short(y_address)
except Exception as e:
...
# --- read direction best-effort ---
try:
direction = pm.read_bytes(directional_address, 1)[0]
prev_dir = direction
except Exception:
direction = prev_dir
# ✅ add this so the GUI sees live player coords
player_data_manager.update(x, y, direction)
# seed the next snapshot with the player, no matter what
temp_map_data = [{
"type": "player",
"X": x,
"Y": y,
"direction": direction
}]
# --- NPCs are best-effort; errors here shouldn't drop the player row ---
for addr, data in list(manager.addresses.items()):
address_x = int(addr, 16)
address_y = int(data["paired_address"], 16)
try:
value_x = pm.read_short(address_x)
value_y = pm.read_short(address_y)
manager.update_address_movement(addr, value_x, value_y)
# oob cull
if value_x < 0 or value_y < 0 or value_x > 100 or value_y > 100:
manager.remove_address(addr, reason="out_of_bounds",
meta={"x": value_x, "y": value_y})
continue
got_hit = pm.read_int(address_x + 0x1D0)
st = manager.addresses.get(addr)
if st is not None:
prev_gh = st.get("got_hit") or 0
st["got_hit"] = got_hit
if got_hit > prev_gh:
my_target = (addr == current_target_npc)
# Am I plausibly the hitter on THIS address?
self_active = my_target and (
is_attacking() or
recently_attacking(addr, window=ATTACK_RECENCY_S + PRE_HIT_GRACE_S)
)
# For our current target, push out an eligibility timestamp whenever we're hitting.
now_s = time.time()
if my_target and self_active:
# stash per-NPC without new globals
st["protect_eligible_at"] = now_s + (ATTACK_RECENCY_S + PRE_HIT_GRACE_S)
if not my_target:
# Non-targets: protect instantly (unchanged)
manager.mark_protected(
addr, seconds=8, reason="got_hit",
meta={"prev": prev_gh, "now": got_hit}
)
else:
# Current target: only protect if we're no longer the hitter AND cooldown passed
eligible_at = st.get("protect_eligible_at", 0.0)
if (not self_active) and (now_s >= eligible_at):
manager.mark_protected(
addr, seconds=8, reason="got_hit",
meta={"prev": prev_gh, "now": got_hit, "elig_at": eligible_at, "now_s": now_s}
)
# Keep allowing your own target even if protected, so you can keep fighting it
if manager.is_protected(addr) and not (
addr == current_target_npc and (
is_attacking() or recently_attacking(addr, window=ATTACK_RECENCY_S)
)
):
continue
temp_map_data.append({
"type": "npc",
"X": value_x,
"Y": value_y,
"address_x": addr,
"address_y": data["paired_address"]
})
except Exception:
# Ignore per-NPC failures; keep the rest flowing
continue
# atomic swap for UI + combat thread
with map_data_lock:
map_data.clear()
map_data.extend(temp_map_data)
time.sleep(0.1)
except Exception as e:
print(f"Failed to initialize memory reading: {e}")
def on_message(message, data):
if message['type'] == 'send':
payload = message['payload']
action = payload.get('action')
address = payload.get('address')
if action == 'add' and address is not None:
manager.add_address(address)
def start_frida(npc_address):
print("Npc Started")
frida_script = f"""
Interceptor.attach(Module.findBaseAddress("Endless.exe").add({npc_address}), {{
onEnter: function(args) {{
var eax = this.context.eax.toInt32();
var offset = {varOffset};
var address = eax + offset;
var addressHex = '0x' + address.toString(16).toUpperCase();
send({{action: 'add', address: addressHex}});
}}
}});
"""
session = frida.attach("Endless.exe")
script = session.create_script(frida_script)
script.on('message', on_message)
script.load()
def check_values():
global pm, combat_baseline_exp, current_target_npc, pickup_points
initialize_pymem()
if combat_baseline_exp is None:
try:
combat_baseline_exp = pm.read_int(totalExp)
print(f"Combat baseline EXP initialized: {combat_baseline_exp}")
except Exception as e:
print(f"Error initializing baseline EXP: {e}")
while True:
try:
current_exp = pm.read_int(totalExp)
if current_exp > combat_baseline_exp:
delta = current_exp - combat_baseline_exp
print(f"EXP increased from {combat_baseline_exp} to {current_exp}.")
if current_target_npc is not None:
manager.remove_address(
current_target_npc,
reason="exp_kill",
meta={"from": combat_baseline_exp, "to": current_exp, "delta_exp": delta}
)
combat_baseline_exp = current_exp
# Build reasons while scanning
removals = []
current_time = time.time()
for x in list(manager.addresses.keys()):
data = manager.addresses[x]
address_x = int(x, 16)
address_y = int(data["paired_address"], 16)
try:
value_x = pm.read_short(address_x)
value_y = pm.read_short(address_y)
last_x = data.get("last_x")
last_y = data.get("last_y")
last_moved = data.get("last_moved")
if value_x != last_x or value_y != last_y:
manager.addresses[x]["last_x"] = value_x
manager.addresses[x]["last_y"] = value_y
manager.addresses[x]["last_moved"] = current_time
else:
idle = current_time - last_moved if last_moved else 9999
if idle > STALE_NPC_SECONDS:
removals.append((x, "stale_movement", {"idle_secs": idle}))