-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfishing_bot.py
More file actions
1606 lines (1440 loc) · 62 KB
/
fishing_bot.py
File metadata and controls
1606 lines (1440 loc) · 62 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
import argparse
import json
import math
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional, Tuple
import cv2
import keyboard
import mss
import numpy as np
import pydirectinput
@dataclass
class Config:
capture_region: dict
fish_hsv_low: Tuple[int, int, int]
fish_hsv_high: Tuple[int, int, int]
line_hsv_low: Tuple[int, int, int]
line_hsv_high: Tuple[int, int, int]
bar_hsv_low: Tuple[int, int, int]
bar_hsv_high: Tuple[int, int, int]
left_key: str
right_key: str
ui_language: str
input_backend: str
auto_action_enabled: bool
auto_action_key: str
auto_action_interval_sec: float
auto_action_hold_sec: float
auto_action_idle_grace_sec: float
prompt_detection_enabled: bool
prompt_region: Optional[dict]
prompt_detect_interval_sec: float
prompt_cooldown_sec: float
auto_click_enabled: bool
auto_click_interval_sec: float
auto_click_position: Optional[dict]
recovery_escape_enabled: bool
recovery_no_line_timeout_sec: float
recovery_escape_cooldown_sec: float
recovery_click_before_escape: bool
recovery_click_attempts: int
use_template_matching: bool
fish_template_path: str
template_match_threshold: float
hold_control_enabled: bool
fine_control_zone_px: int
fine_tap_sec: float
fine_tap_cooldown_sec: float
gui_start_delay_sec: float
dead_zone_px: int
edge_margin_px: int
min_blob_area: int
min_col_pixels: int
max_x_jump: int
max_lost_frames: int
mask_open_kernel: int
mask_close_kernel: int
enable_clahe: bool
target_fps: int
log_every_n_frames: int
test_image_path: str
debug_window_scale: float
fullscreen_debug: bool
debug_show_full_monitor: bool
dry_run_default: bool
show_mask_windows: bool
def save_config(path: Path, config: Config) -> None:
raw = {
"capture_region": config.capture_region,
"fish_hsv_low": list(config.fish_hsv_low),
"fish_hsv_high": list(config.fish_hsv_high),
"line_hsv_low": list(config.line_hsv_low),
"line_hsv_high": list(config.line_hsv_high),
"bar_hsv_low": list(config.bar_hsv_low),
"bar_hsv_high": list(config.bar_hsv_high),
"left_key": config.left_key,
"right_key": config.right_key,
"ui_language": config.ui_language,
"input_backend": config.input_backend,
"auto_action_enabled": config.auto_action_enabled,
"auto_action_key": config.auto_action_key,
"auto_action_interval_sec": config.auto_action_interval_sec,
"auto_action_hold_sec": config.auto_action_hold_sec,
"auto_action_idle_grace_sec": config.auto_action_idle_grace_sec,
"prompt_detection_enabled": config.prompt_detection_enabled,
"prompt_region": config.prompt_region,
"prompt_detect_interval_sec": config.prompt_detect_interval_sec,
"prompt_cooldown_sec": config.prompt_cooldown_sec,
"auto_click_enabled": config.auto_click_enabled,
"auto_click_interval_sec": config.auto_click_interval_sec,
"auto_click_position": config.auto_click_position,
"recovery_escape_enabled": config.recovery_escape_enabled,
"recovery_no_line_timeout_sec": config.recovery_no_line_timeout_sec,
"recovery_escape_cooldown_sec": config.recovery_escape_cooldown_sec,
"recovery_click_before_escape": config.recovery_click_before_escape,
"recovery_click_attempts": config.recovery_click_attempts,
"use_template_matching": config.use_template_matching,
"fish_template_path": config.fish_template_path,
"template_match_threshold": config.template_match_threshold,
"hold_control_enabled": config.hold_control_enabled,
"fine_control_zone_px": config.fine_control_zone_px,
"fine_tap_sec": config.fine_tap_sec,
"fine_tap_cooldown_sec": config.fine_tap_cooldown_sec,
"gui_start_delay_sec": config.gui_start_delay_sec,
"dead_zone_px": config.dead_zone_px,
"edge_margin_px": config.edge_margin_px,
"min_blob_area": config.min_blob_area,
"min_col_pixels": config.min_col_pixels,
"max_x_jump": config.max_x_jump,
"max_lost_frames": config.max_lost_frames,
"mask_open_kernel": config.mask_open_kernel,
"mask_close_kernel": config.mask_close_kernel,
"enable_clahe": config.enable_clahe,
"target_fps": config.target_fps,
"log_every_n_frames": config.log_every_n_frames,
"test_image_path": config.test_image_path,
"debug_window_scale": config.debug_window_scale,
"fullscreen_debug": config.fullscreen_debug,
"debug_show_full_monitor": config.debug_show_full_monitor,
"dry_run_default": config.dry_run_default,
"show_mask_windows": config.show_mask_windows,
}
path.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")
def load_config(path: Path) -> Config:
raw = json.loads(path.read_text(encoding="utf-8"))
return Config(
capture_region=raw["capture_region"],
fish_hsv_low=tuple(raw["fish_hsv_low"]),
fish_hsv_high=tuple(raw["fish_hsv_high"]),
line_hsv_low=tuple(raw["line_hsv_low"]),
line_hsv_high=tuple(raw["line_hsv_high"]),
bar_hsv_low=tuple(raw["bar_hsv_low"]),
bar_hsv_high=tuple(raw["bar_hsv_high"]),
left_key=raw.get("left_key", "a"),
right_key=raw.get("right_key", "d"),
ui_language=str(raw.get("ui_language", "ru")),
input_backend=str(raw.get("input_backend", "pydirectinput")),
auto_action_enabled=bool(raw.get("auto_action_enabled", True)),
auto_action_key=str(raw.get("auto_action_key", "f")),
auto_action_interval_sec=float(raw.get("auto_action_interval_sec", 0.6)),
auto_action_hold_sec=float(raw.get("auto_action_hold_sec", 0.05)),
auto_action_idle_grace_sec=float(raw.get("auto_action_idle_grace_sec", 0.7)),
prompt_detection_enabled=bool(raw.get("prompt_detection_enabled", True)),
prompt_region=raw.get("prompt_region"),
prompt_detect_interval_sec=float(raw.get("prompt_detect_interval_sec", 0.08)),
prompt_cooldown_sec=float(raw.get("prompt_cooldown_sec", 0.35)),
auto_click_enabled=bool(raw.get("auto_click_enabled", True)),
auto_click_interval_sec=float(raw.get("auto_click_interval_sec", 0.6)),
auto_click_position=raw.get("auto_click_position"),
recovery_escape_enabled=bool(raw.get("recovery_escape_enabled", True)),
recovery_no_line_timeout_sec=float(raw.get("recovery_no_line_timeout_sec", 3.0)),
recovery_escape_cooldown_sec=float(raw.get("recovery_escape_cooldown_sec", 10.0)),
recovery_click_before_escape=bool(raw.get("recovery_click_before_escape", True)),
recovery_click_attempts=int(raw.get("recovery_click_attempts", 2)),
use_template_matching=bool(raw.get("use_template_matching", True)),
fish_template_path=str(raw.get("fish_template_path", "fish_reference.png")),
template_match_threshold=float(raw.get("template_match_threshold", 0.62)),
hold_control_enabled=bool(raw.get("hold_control_enabled", True)),
fine_control_zone_px=int(raw.get("fine_control_zone_px", 22)),
fine_tap_sec=float(raw.get("fine_tap_sec", 0.012)),
fine_tap_cooldown_sec=float(raw.get("fine_tap_cooldown_sec", 0.015)),
gui_start_delay_sec=float(raw.get("gui_start_delay_sec", 3.0)),
dead_zone_px=int(raw.get("dead_zone_px", 6)),
edge_margin_px=int(raw.get("edge_margin_px", 8)),
min_blob_area=int(raw.get("min_blob_area", 35)),
min_col_pixels=int(raw.get("min_col_pixels", 2)),
max_x_jump=int(raw.get("max_x_jump", 35)),
max_lost_frames=int(raw.get("max_lost_frames", 6)),
mask_open_kernel=int(raw.get("mask_open_kernel", 3)),
mask_close_kernel=int(raw.get("mask_close_kernel", 5)),
enable_clahe=bool(raw.get("enable_clahe", True)),
target_fps=int(raw.get("target_fps", 30)),
log_every_n_frames=int(raw.get("log_every_n_frames", 1)),
test_image_path=str(raw.get("test_image_path", "")),
debug_window_scale=float(raw.get("debug_window_scale", 1.0)),
fullscreen_debug=bool(raw.get("fullscreen_debug", True)),
debug_show_full_monitor=bool(raw.get("debug_show_full_monitor", True)),
dry_run_default=bool(raw.get("dry_run_default", False)),
show_mask_windows=bool(raw.get("show_mask_windows", False)),
)
def resolve_config_path() -> Path:
# 打包后统一使用 exe 同目录配置;源码运行使用脚本同目录配置。
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().with_name("fishing_config.json")
return Path(__file__).resolve().with_name("fishing_config.json")
def resolve_asset_path(config_path: Path, raw_path: str) -> Path:
path = Path(raw_path)
if path.is_absolute():
return path
return config_path.resolve().parent / path
def enhance_hsv(hsv: np.ndarray, enable_clahe: bool) -> np.ndarray:
if not enable_clahe:
return hsv
h, s, v = cv2.split(hsv)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
v = clahe.apply(v)
return cv2.merge((h, s, v))
def make_mask(
hsv: np.ndarray,
low: Tuple[int, int, int],
high: Tuple[int, int, int],
open_kernel_size: int,
close_kernel_size: int,
) -> np.ndarray:
mask = cv2.inRange(hsv, np.array(low, dtype=np.uint8), np.array(high, dtype=np.uint8))
open_kernel_size = max(1, open_kernel_size | 1)
close_kernel_size = max(1, close_kernel_size | 1)
open_kernel = np.ones((open_kernel_size, open_kernel_size), np.uint8)
close_kernel = np.ones((close_kernel_size, close_kernel_size), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, open_kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel)
return mask
def make_relaxed_range(
low: Tuple[int, int, int],
high: Tuple[int, int, int],
h_pad: int = 10,
sv_pad_low: int = 25,
sv_pad_high: int = 10,
) -> Tuple[Tuple[int, int, int], Tuple[int, int, int]]:
low_h = max(0, int(low[0]) - h_pad)
low_s = max(0, int(low[1]) - sv_pad_low)
low_v = max(0, int(low[2]) - sv_pad_low)
high_h = min(179, int(high[0]) + h_pad)
high_s = min(255, int(high[1]) + sv_pad_high)
high_v = min(255, int(high[2]) + sv_pad_high)
return (low_h, low_s, low_v), (high_h, high_s, high_v)
def yellow_line_candidate_mask(bgr: np.ndarray, hsv: np.ndarray, tolerance: int = 10) -> np.ndarray:
tolerance = max(1, int(tolerance))
b = bgr[:, :, 0].astype(np.int16)
g = bgr[:, :, 1].astype(np.int16)
r = bgr[:, :, 2].astype(np.int16)
h = hsv[:, :, 0].astype(np.int16)
s = hsv[:, :, 1].astype(np.int16)
v = hsv[:, :, 2].astype(np.int16)
r_min = max(125, 190 - tolerance * 4)
g_min = max(90, 145 - tolerance * 3)
rb_min = max(8, 36 - tolerance)
gb_min = max(0, 18 - tolerance)
h_low = max(0, 16 - tolerance)
h_high = min(60, 38 + tolerance)
s_min = max(20, 115 - tolerance * 5)
v_min = max(90, 160 - tolerance * 4)
warm_rgb = (r >= r_min) & (g >= g_min) & (r >= b + rb_min) & (g >= b + gb_min)
warm_hsv = (h >= h_low) & (h <= h_high) & (s >= s_min) & (v >= v_min)
pale_core = (
(r >= max(200, 245 - tolerance * 3))
& (g >= max(170, 215 - tolerance * 3))
& (b <= min(245, 205 + tolerance * 3))
& (r >= b + max(5, 25 - tolerance))
& (g >= b + max(0, 12 - tolerance))
)
orange_glow = (
(r >= max(145, 185 - tolerance * 3))
& (g >= max(70, 105 - tolerance * 2))
& (r >= g + max(8, 28 - tolerance))
& (r >= b + max(35, 70 - tolerance * 2))
)
mask = ((warm_rgb & warm_hsv) | pale_core | orange_glow).astype(np.uint8) * 255
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((3, 2), np.uint8))
return mask
def vertical_line_component_mask(
mask: np.ndarray,
min_area: int,
bgr: Optional[np.ndarray] = None,
preferred_x: Optional[int] = None,
edge_margin: Optional[int] = None,
) -> np.ndarray:
frame_height, frame_width = mask.shape[:2]
col_counts = np.count_nonzero(mask, axis=0)
min_col_pixels = max(3, min(frame_height - 1, frame_height // 4))
active_cols = np.where(col_counts >= min_col_pixels)[0]
result = np.zeros_like(mask)
if active_cols.size == 0:
return result
if preferred_x is not None:
preferred_window = max(28, frame_width // 14)
preferred_left = max(0, int(preferred_x) - preferred_window)
preferred_right = min(frame_width - 1, int(preferred_x) + preferred_window)
preferred_cols = active_cols[(active_cols >= preferred_left) & (active_cols <= preferred_right)]
if preferred_cols.size:
active_cols = preferred_cols
if edge_margin is None:
edge_margin = min(max(6, frame_height // 2), max(0, frame_width // 25))
edge_margin = max(0, int(edge_margin))
max_width = max(8, min(22, frame_height))
best = None
best_score = 0.0
edge_best = None
edge_best_score = 0.0
start = int(active_cols[0])
prev = int(active_cols[0])
spans = []
for col in active_cols[1:]:
col = int(col)
if col <= prev + 2:
prev = col
continue
spans.append((start, prev))
start = col
prev = col
spans.append((start, prev))
for start, end in spans:
width = end - start + 1
if width > max_width:
continue
x1 = max(0, start - 2)
x2 = min(frame_width, end + 3)
component = mask[:, x1:x2]
ys, xs = np.where(component > 0)
if xs.size < max(5, min_area // 8):
continue
height = int(ys.max() - ys.min() + 1)
comp_width = int(xs.max() - xs.min() + 1)
if height < max(6, frame_height // 4):
continue
if comp_width > max_width:
continue
full_height_width_limit = max(14, int(frame_height * 0.8))
if height >= frame_height - 1 and comp_width > full_height_width_limit:
continue
area = int(xs.size)
center = x1 + int(round(float(xs.mean())))
score = area * (height / max(1, comp_width)) * min(2.0, height / max(1, frame_height * 0.45))
if bgr is not None:
roi = bgr[:, x1:x2]
pixels = roi[component > 0].astype(np.int16)
if pixels.size:
blue = pixels[:, 0]
green = pixels[:, 1]
red = pixels[:, 2]
brightness = float(np.mean(np.maximum.reduce((red, green, blue))))
yellow_warmth = float(np.mean(np.minimum(red, green) - blue))
red_only = float(np.mean(red - green))
score *= max(0.25, 1.0 + yellow_warmth / 42.0 + (brightness - 150.0) / 220.0)
if red_only > 45.0:
score *= 0.35
if preferred_x is not None:
distance = abs(center - int(preferred_x))
score *= 1.0 / (1.0 + distance / max(18.0, frame_width * 0.04))
is_edge = center < edge_margin or center > frame_width - 1 - edge_margin
if is_edge:
if score > edge_best_score:
edge_best_score = score
edge_best = (x1, x2)
continue
if score > best_score:
best_score = score
best = (x1, x2)
if best is None:
best = edge_best
if best is None:
return result
x1, x2 = best
result[:, x1:x2] = mask[:, x1:x2]
result = cv2.morphologyEx(result, cv2.MORPH_CLOSE, np.ones((2, 2), np.uint8))
return result
def yellow_line_component_mask(
bgr: np.ndarray,
hsv: np.ndarray,
tolerance: int = 10,
min_area: int = 35,
preferred_x: Optional[int] = None,
edge_margin: Optional[int] = None,
) -> np.ndarray:
raw_mask = yellow_line_candidate_mask(bgr, hsv, tolerance=tolerance)
return vertical_line_component_mask(
raw_mask,
min_area=min_area,
bgr=bgr,
preferred_x=preferred_x,
edge_margin=edge_margin,
)
def vertical_line_center_x_from_mask(
mask: np.ndarray,
min_area: int,
bgr: Optional[np.ndarray] = None,
preferred_x: Optional[int] = None,
edge_margin: Optional[int] = None,
) -> Optional[int]:
filtered = vertical_line_component_mask(
mask,
min_area=min_area,
bgr=bgr,
preferred_x=preferred_x,
edge_margin=edge_margin,
)
if np.count_nonzero(filtered):
mask = filtered
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
best = None
best_score = 0.0
frame_height = mask.shape[0]
for contour in contours:
area = cv2.contourArea(contour)
if area < max(4, min_area // 10):
continue
x, _y, w, h = cv2.boundingRect(contour)
if h < max(5, frame_height // 4):
continue
if w > max(18, frame_height):
continue
full_height_width_limit = max(14, int(frame_height * 0.8))
if h >= frame_height - 1 and w > full_height_width_limit:
continue
score = area * (h / max(1, w)) * min(2.0, h / max(1, frame_height * 0.45))
if score > best_score:
best_score = score
best = x + w // 2
return best
def largest_blob_center_x(mask: np.ndarray, min_area: int) -> Optional[int]:
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
best = None
best_area = 0.0
for contour in contours:
area = cv2.contourArea(contour)
if area < min_area or area <= best_area:
continue
x, y, w, h = cv2.boundingRect(contour)
best = x + w // 2
best_area = area
return best
def tracked_blob_center_x(
mask: np.ndarray,
min_area: int,
prev_x: Optional[int],
max_x_jump: int,
min_width: int = 0,
) -> Optional[int]:
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
candidates = []
for contour in contours:
area = cv2.contourArea(contour)
if area < min_area:
continue
x, y, w, h = cv2.boundingRect(contour)
if w < min_width:
continue
cx = x + w // 2
candidates.append((cx, area))
if not candidates:
return None
if prev_x is None:
return int(max(candidates, key=lambda item: item[1])[0])
near = [item for item in candidates if abs(item[0] - prev_x) <= max_x_jump]
if near:
return int(max(near, key=lambda item: item[1])[0])
return int(max(candidates, key=lambda item: item[1])[0])
def dominant_span(mask: np.ndarray, min_area: int) -> Optional[Tuple[int, int]]:
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
best = None
best_area = 0.0
for contour in contours:
area = cv2.contourArea(contour)
if area < min_area or area <= best_area:
continue
x, y, w, h = cv2.boundingRect(contour)
best = (x, x + w)
best_area = area
return best
def center_x_by_projection(mask: np.ndarray, min_col_pixels: int = 2) -> Optional[int]:
col_counts = np.count_nonzero(mask, axis=0)
active = np.where(col_counts >= min_col_pixels)[0]
if active.size == 0:
return None
return int(active.mean())
def longest_span_from_counts(counts: np.ndarray, min_col_pixels: int, min_width: int = 2) -> Optional[Tuple[int, int]]:
active = np.where(counts >= min_col_pixels)[0]
if active.size == 0:
return None
best = None
start = int(active[0])
prev = int(active[0])
for idx in active[1:]:
idx = int(idx)
if idx == prev + 1:
prev = idx
continue
if prev - start + 1 >= min_width:
if best is None or (prev - start) > (best[1] - best[0]):
best = (start, prev)
start = idx
prev = idx
if prev - start + 1 >= min_width:
if best is None or (prev - start) > (best[1] - best[0]):
best = (start, prev)
return best
def peak_x_from_counts(
counts: np.ndarray, min_col_pixels: int, prev_x: Optional[int], max_x_jump: int
) -> Optional[int]:
candidates = np.where(counts >= min_col_pixels)[0]
if candidates.size == 0:
return None
if prev_x is None:
return int(candidates[np.argmax(counts[candidates])])
nearby = [int(x) for x in candidates if abs(int(x) - prev_x) <= max_x_jump]
if nearby:
return int(max(nearby, key=lambda x: int(counts[x])))
return int(candidates[np.argmax(counts[candidates])])
def span_by_projection(mask: np.ndarray, min_col_pixels: int = 2) -> Optional[Tuple[int, int]]:
col_counts = np.count_nonzero(mask, axis=0)
active = np.where(col_counts >= min_col_pixels)[0]
if active.size == 0:
return None
return int(active[0]), int(active[-1])
def motion_center_x(prev_gray: Optional[np.ndarray], gray: np.ndarray, min_col_pixels: int) -> Optional[int]:
if prev_gray is None:
return None
diff = cv2.absdiff(gray, prev_gray)
_, motion = cv2.threshold(diff, 18, 255, cv2.THRESH_BINARY)
motion = cv2.medianBlur(motion, 3)
return center_x_by_projection(motion, min_col_pixels=max(2, min_col_pixels))
def load_template_image(config_path: Path, raw_path: str) -> Optional[np.ndarray]:
if not raw_path:
return None
path = resolve_asset_path(config_path, raw_path)
if not path.exists():
return None
image = cv2.imread(str(path), cv2.IMREAD_COLOR)
if image is None or image.shape[0] < 3 or image.shape[1] < 3:
return None
return image
def template_center_x(
bgr: np.ndarray,
template: Optional[np.ndarray],
threshold: float,
) -> Optional[Tuple[int, float]]:
if template is None:
return None
th, tw = template.shape[:2]
fh, fw = bgr.shape[:2]
if th > fh or tw > fw:
return None
frame_gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
if float(np.std(template_gray)) < 3.0:
return None
clahe = cv2.createCLAHE(clipLimit=2.5, tileGridSize=(4, 4))
frame_eq = clahe.apply(frame_gray)
template_eq = clahe.apply(template_gray)
frame_edge = cv2.Canny(frame_eq, 45, 130)
template_edge = cv2.Canny(template_eq, 45, 130)
candidates = []
for frame_variant, template_variant, weight in (
(frame_gray, template_gray, 1.00),
(frame_eq, template_eq, 1.05),
(frame_edge, template_edge, 0.92),
):
if float(np.std(template_variant)) < 3.0:
continue
result = cv2.matchTemplate(frame_variant, template_variant, cv2.TM_CCOEFF_NORMED)
_, score, _, location = cv2.minMaxLoc(result)
candidates.append((float(score) * weight, location))
if not candidates:
return None
score, location = max(candidates, key=lambda item: item[0])
if score < threshold:
return None
return int(location[0] + tw // 2), float(score)
def turquoise_indicator_center_x(
hsv: np.ndarray,
min_area: int,
low: Tuple[int, int, int],
high: Tuple[int, int, int],
) -> Optional[int]:
mask = cv2.inRange(hsv, np.array(low, dtype=np.uint8), np.array(high, dtype=np.uint8))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 5), np.uint8))
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
best = None
best_score = 0.0
for contour in contours:
area = cv2.contourArea(contour)
if area < max(min_area, 80):
continue
x, _y, w, h = cv2.boundingRect(contour)
if w < 30 or h < 5:
continue
aspect = w / max(1, h)
if aspect < 2.0:
continue
score = area * min(6.0, aspect)
if score > best_score:
best_score = score
best = x + w // 2
return best
def yellow_line_center_x(hsv: np.ndarray, min_area: int, bgr: Optional[np.ndarray] = None) -> Optional[int]:
if bgr is not None:
mask = yellow_line_component_mask(bgr, hsv, tolerance=12, min_area=min_area)
else:
mask = cv2.inRange(hsv, np.array((14, 55, 105), dtype=np.uint8), np.array((48, 255, 255), dtype=np.uint8))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8))
mask = vertical_line_component_mask(mask, min_area=min_area)
return vertical_line_center_x_from_mask(mask, min_area)
def detect_action_prompt(bgr: np.ndarray) -> Optional[Tuple[int, int]]:
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
dark_mask = cv2.inRange(hsv, np.array((0, 0, 8), dtype=np.uint8), np.array((179, 120, 95), dtype=np.uint8))
dark_mask = cv2.morphologyEx(dark_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
dark_mask = cv2.morphologyEx(dark_mask, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
contours, _ = cv2.findContours(dark_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
best_score = 0.0
best_center = None
for contour in contours:
area = cv2.contourArea(contour)
if area < 120 or area > 2600:
continue
x, y, w, h = cv2.boundingRect(contour)
if w < 16 or h < 16 or w > 72 or h > 72:
continue
aspect = w / max(1, h)
if aspect < 0.65 or aspect > 1.35:
continue
perimeter = cv2.arcLength(contour, True)
if perimeter <= 0:
continue
circularity = 4.0 * math.pi * area / (perimeter * perimeter)
if circularity < 0.45:
continue
roi_gray = gray[y : y + h, x : x + w]
roi_hsv = hsv[y : y + h, x : x + w]
bright_mask = cv2.inRange(
roi_hsv,
np.array((0, 0, 120), dtype=np.uint8),
np.array((179, 95, 255), dtype=np.uint8),
)
bright_mask = cv2.bitwise_or(bright_mask, cv2.inRange(roi_gray, 135, 255))
bright_pixels = int(np.count_nonzero(bright_mask))
bright_ratio = bright_pixels / max(1, w * h)
if bright_pixels < 8 or bright_ratio > 0.35:
continue
score = circularity * area * min(1.0, bright_pixels / 55.0)
if score > best_score:
best_score = score
best_center = (x + w // 2, y + h // 2)
return best_center
def key_down(key: str, backend: str) -> None:
backend = (backend or "pydirectinput").lower()
if backend in ("pydirectinput", "auto"):
try:
pydirectinput.keyDown(key)
except Exception:
if backend != "auto":
raise
if backend in ("keyboard", "auto"):
try:
keyboard.press(key)
except Exception:
if backend != "auto":
raise
def key_up(key: str, backend: str) -> None:
backend = (backend or "pydirectinput").lower()
if backend in ("keyboard", "auto"):
try:
keyboard.release(key)
except Exception:
if backend != "auto":
raise
if backend in ("pydirectinput", "auto"):
try:
pydirectinput.keyUp(key)
except Exception:
if backend != "auto":
raise
def release_keys(left_key: str, right_key: str, backend: str = "pydirectinput") -> None:
key_up(left_key, backend)
key_up(right_key, backend)
def tap(key: str, duration: float, backend: str = "pydirectinput") -> None:
key_down(key, backend)
time.sleep(duration)
key_up(key, backend)
def click_at(x: int, y: int) -> None:
pydirectinput.moveTo(int(x), int(y))
pydirectinput.click()
def default_action_click_point(monitor: dict) -> Tuple[int, int]:
return (
int(monitor["left"] + monitor["width"] * 0.925),
int(monitor["top"] + monitor["height"] * 0.91),
)
def default_recovery_click_point(monitor: dict) -> Tuple[int, int]:
return (
int(monitor["left"] + monitor["width"] * 0.25),
int(monitor["top"] + monitor["height"] * 0.78),
)
def default_prompt_scan_region(monitor: dict) -> dict:
width = int(monitor["width"] * 0.42)
height = int(monitor["height"] * 0.42)
return {
"left": int(monitor["left"] + monitor["width"] - width),
"top": int(monitor["top"] + monitor["height"] - height),
"width": width,
"height": height,
}
def resolve_auto_click_point(
config: Config,
monitor: dict,
last_prompt_point: Optional[Tuple[int, int]],
) -> Tuple[int, int]:
if config.auto_click_position is not None:
return int(config.auto_click_position["x"]), int(config.auto_click_position["y"])
if last_prompt_point is not None:
return last_prompt_point
if config.prompt_region is not None:
return (
int(config.prompt_region["left"] + config.prompt_region["width"] / 2),
int(config.prompt_region["top"] + config.prompt_region["height"] / 2),
)
return default_action_click_point(monitor)
def is_stop_requested(stop_event: Optional[object]) -> bool:
return bool(stop_event is not None and getattr(stop_event, "is_set")())
def select_capture_region(sct: mss.MSS, fallback_region: dict) -> Optional[dict]:
monitor = sct.monitors[1]
shot = sct.grab(monitor)
frame = np.array(shot)
bgr = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
preview = bgr.copy()
fr = fallback_region
l = int(fr["left"] - monitor["left"])
t = int(fr["top"] - monitor["top"])
w = int(fr["width"])
h = int(fr["height"])
cv2.rectangle(preview, (l, t), (l + w, t + h), (0, 255, 255), 2)
cv2.putText(
preview,
"Select ROI and press ENTER / SPACE, or C to cancel",
(20, 40),
cv2.FONT_HERSHEY_SIMPLEX,
0.8,
(0, 255, 255),
2,
)
roi = cv2.selectROI("Select Fishing Region", preview, showCrosshair=True, fromCenter=False)
cv2.destroyWindow("Select Fishing Region")
x, y, rw, rh = [int(v) for v in roi]
if rw <= 0 or rh <= 0:
return None
return {
"left": monitor["left"] + x,
"top": monitor["top"] + y,
"width": rw,
"height": rh,
}
STRIP_MIN_HEIGHT = 12
STRIP_MAX_HEIGHT = 48
def _clamp(value: int, minimum: int, maximum: int) -> int:
return max(minimum, min(value, maximum))
def normalize_capture_strip_selection(
monitor: dict,
fallback_region: dict,
start: Tuple[int, int],
end: Tuple[int, int],
strip_height: Optional[int] = None,
) -> Optional[dict]:
mon_left = int(monitor["left"])
mon_top = int(monitor["top"])
mon_width = int(monitor["width"])
mon_height = int(monitor["height"])
x1, y1 = start
x2, y2 = end
left = _clamp(min(x1, x2), 0, max(0, mon_width - 2))
right = _clamp(max(x1, x2), 0, mon_width)
width = right - left
if width < 8:
return None
fallback_height = int(fallback_region.get("height", 24))
drag_height = abs(y2 - y1)
if strip_height is None:
wanted_height = drag_height if drag_height >= 6 else fallback_height
else:
wanted_height = strip_height
height = _clamp(int(wanted_height), STRIP_MIN_HEIGHT, min(STRIP_MAX_HEIGHT, mon_height))
center_y = _clamp(int(round((y1 + y2) / 2)), 0, max(0, mon_height - 1))
top = _clamp(center_y - height // 2, 0, max(0, mon_height - height))
return {
"left": mon_left + left,
"top": mon_top + top,
"width": width,
"height": height,
}
class LiveStripSelector:
def __init__(self, monitor: dict, fallback_region: dict) -> None:
fallback_height = int(fallback_region.get("height", 24))
self.strip_height = _clamp(fallback_height, STRIP_MIN_HEIGHT, STRIP_MAX_HEIGHT)
self.monitor = monitor
self.fallback_region = fallback_region
self.dragging = False
self.start: Optional[Tuple[int, int]] = None
self.end: Optional[Tuple[int, int]] = None
def on_mouse(self, event: int, x: int, y: int, flags: int, _param: object) -> None:
if event == cv2.EVENT_LBUTTONDOWN:
self.dragging = True
self.start = (x, y)
self.end = (x, y)
elif event == cv2.EVENT_MOUSEMOVE and self.dragging:
self.end = (x, y)
if self.start is not None:
drag_height = abs(y - self.start[1])
if drag_height >= 6:
self.strip_height = _clamp(drag_height, STRIP_MIN_HEIGHT, STRIP_MAX_HEIGHT)
elif event == cv2.EVENT_LBUTTONUP and self.dragging:
self.dragging = False
self.end = (x, y)
if self.start is not None:
drag_height = abs(y - self.start[1])
if drag_height >= 6:
self.strip_height = _clamp(drag_height, STRIP_MIN_HEIGHT, STRIP_MAX_HEIGHT)
elif event == cv2.EVENT_MOUSEWHEEL:
step = 2 if flags > 0 else -2
self.strip_height = _clamp(self.strip_height + step, STRIP_MIN_HEIGHT, STRIP_MAX_HEIGHT)
def current_region(self) -> Optional[dict]:
if self.start is None or self.end is None:
return None
return normalize_capture_strip_selection(
self.monitor,
self.fallback_region,
self.start,
self.end,
self.strip_height,
)
def _relative_region_rect(monitor: dict, region: dict) -> Tuple[int, int, int, int]:
mon_width = int(monitor["width"])
mon_height = int(monitor["height"])
left = _clamp(int(region["left"] - monitor["left"]), 0, max(0, mon_width - 1))
top = _clamp(int(region["top"] - monitor["top"]), 0, max(0, mon_height - 1))
right = _clamp(left + int(region["width"]), 0, mon_width)
bottom = _clamp(top + int(region["height"]), 0, mon_height)
return left, top, right, bottom
def select_capture_strip(sct: mss.MSS, fallback_region: dict) -> Optional[dict]:
monitor = sct.monitors[1]
selector = LiveStripSelector(monitor, fallback_region)
window_name = "Select Fishing Strip"
shot = sct.grab(monitor)
frame = np.array(shot)
base_bgr = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
cv2.resizeWindow(window_name, int(monitor["width"]), int(monitor["height"]))
cv2.moveWindow(window_name, int(monitor["left"]), int(monitor["top"]))
cv2.setMouseCallback(window_name, selector.on_mouse)
try:
while True:
view = base_bgr.copy()
fl, ft, fr, fb = _relative_region_rect(monitor, fallback_region)
cv2.rectangle(view, (fl, ft), (fr, fb), (120, 120, 120), 2)
cv2.putText(
view,
"Drag along the minigame bar | Mouse wheel: height | ENTER/SPACE confirm | C/ESC cancel",
(20, 40),
cv2.FONT_HERSHEY_SIMPLEX,
0.75,
(0, 255, 255),
2,
)
region = selector.current_region()
if region is not None:
l, t, r, b = _relative_region_rect(monitor, region)
overlay = view.copy()
cv2.rectangle(overlay, (l, t), (r, b), (0, 255, 255), thickness=cv2.FILLED)
cv2.addWeighted(overlay, 0.22, view, 0.78, 0, view)
cv2.rectangle(view, (l, t), (r, b), (0, 255, 255), 2)
cv2.line(view, (l, (t + b) // 2), (r, (t + b) // 2), (0, 255, 255), 1)
cv2.putText(
view,
f"STRIP: left={region['left']} top={region['top']} width={region['width']} height={region['height']}",
(20, 72),
cv2.FONT_HERSHEY_SIMPLEX,
0.65,
(0, 255, 255),
2,
)
else:
cv2.putText(
view,
f"Current height: {selector.strip_height}px",
(20, 72),
cv2.FONT_HERSHEY_SIMPLEX,
0.65,
(0, 255, 255),
2,
)