-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxiangqi_bot.py
More file actions
2187 lines (1919 loc) · 87.7 KB
/
Copy pathxiangqi_bot.py
File metadata and controls
2187 lines (1919 loc) · 87.7 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
#!/usr/bin/env python3
"""
Xiangqi Bot - Auto-play 天天象棋 using Pikafish engine.
Usage:
1. Open 天天象棋 in WeChat, start a game (initial position)
2. python3 /tmp/xiangqi_bot.py
3. Follow the calibration prompts (move mouse to 2 corners)
4. Bot auto-plays! Ctrl+C to stop.
"""
import subprocess
import sys
import time
import os
import numpy as np
import cv2
import pyautogui
import Quartz
pyautogui.FAILSAFE = True # Move mouse to corner to abort
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PIKAFISH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pikafish")
PIKAFISH_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIR = os.path.join(_SCRIPT_DIR, "templates")
SCREENSHOT_PATH = os.path.join(_SCRIPT_DIR, "screen.png")
CALIB_PATH = os.path.join(_SCRIPT_DIR, "calib.json")
MOVE_TIME_MS = 500 # Fast for real games with time pressure
SEARCH_DEPTH = 0 # 0 = unlimited (use movetime), >0 = limit search depth
# Initial board layouts (screen space)
INIT_RED = [
['r','n','b','a','k','a','b','n','r'],
[None]*9,
[None,'c',None,None,None,None,None,'c',None],
['p',None,'p',None,'p',None,'p',None,'p'],
[None]*9, [None]*9,
['P',None,'P',None,'P',None,'P',None,'P'],
[None,'C',None,None,None,None,None,'C',None],
[None]*9,
['R','N','B','A','K','A','B','N','R'],
]
INIT_BLACK = [
['R','N','B','A','K','A','B','N','R'],
[None]*9,
[None,'C',None,None,None,None,None,'C',None],
['P',None,'P',None,'P',None,'P',None,'P'],
[None]*9, [None]*9,
['p',None,'p',None,'p',None,'p',None,'p'],
[None,'c',None,None,None,None,None,'c',None],
[None]*9,
['r','n','b','a','k','a','b','n','r'],
]
class Bot:
def __init__(self):
self.cols_logical = [] # 9 x-coords in logical screen space
self.rows_logical = [] # 10 y-coords in logical screen space
self.cell_w = 0
self.cell_h = 0
self.templates = {}
self.patch_size = 0
self.playing_red = True
self.retina_scale = 2.0
self.win_id = None
self.win_x = 0
self.win_y = 0
self.cnn = None # CNN classifier (loaded on demand)
self.stop_flag = False # Set to True to stop the bot
# --- Window & Screenshot ---
def find_window(self):
import Quartz
windows = Quartz.CGWindowListCopyWindowInfo(
Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)
for w in windows:
if 'WeChat' in w.get('kCGWindowOwnerName', '') and \
'天天象棋' in w.get('kCGWindowName', ''):
self.win_id = w['kCGWindowNumber']
b = w['kCGWindowBounds']
self.win_x, self.win_y = int(b['X']), int(b['Y'])
lw = int(b['Width'])
print(f" Window: id={self.win_id} pos=({self.win_x},{self.win_y}) "
f"size={lw}x{int(b['Height'])}")
return
raise RuntimeError("天天象棋 window not found!")
def screenshot_for_processing(self):
"""Capture window, return image. Uses unique filename each time."""
self._ss_counter = getattr(self, '_ss_counter', 0) + 1
path = os.path.join(_SCRIPT_DIR, f"ss_{self._ss_counter % 3}.png")
subprocess.run(['screencapture', '-x', '-o', '-l', str(self.win_id),
path], capture_output=True, check=True)
full = cv2.imread(path)
if full is None:
raise RuntimeError("Screenshot failed!")
# Determine retina scale from window capture
import Quartz
windows = Quartz.CGWindowListCopyWindowInfo(
Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)
for w in windows:
if w.get('kCGWindowNumber') == self.win_id:
lw = int(w['kCGWindowBounds']['Width'])
self.retina_scale = full.shape[1] / lw
break
return full
def logical_to_pixel(self, lx, ly):
"""Convert logical screen coords to full-res pixel coords in window capture."""
# Logical coords are absolute screen coords
# Window capture starts at (win_x, win_y) in logical space
px = (lx - self.win_x) * self.retina_scale
py = (ly - self.win_y) * self.retina_scale
return int(px), int(py)
# --- Calibration ---
def auto_calibrate(self, img):
"""Auto-detect board grid using CNN. Start from default ratios, fine-tune with grid search."""
if not self.load_cnn():
print(" Auto-calibrate: CNN not available")
return False
import json
win_w = self._get_window_width()
win_h = self._get_window_height()
# Default ratios from known 天天象棋 layout
DEFAULT_RX1, DEFAULT_RY1 = 0.2985, 0.1344
DEFAULT_RX2, DEFAULT_RY2 = 0.7027, 0.9052
def try_grid(rx1, ry1, rx2, ry2):
"""Try a grid configuration, return (total_confidence, non_empty_count)."""
x1 = self.win_x + rx1 * win_w
y1 = self.win_y + ry1 * win_h
x2 = self.win_x + rx2 * win_w
y2 = self.win_y + ry2 * win_h
cw = (x2 - x1) / 8.0
ch = (y2 - y1) / 9.0
cols = [x1 + i * cw for i in range(9)]
rows = [y1 + j * ch for j in range(10)]
# Suppress FEN validation output during grid search
import io
old_stdout = sys.stdout
sys.stdout = io.StringIO()
try:
board = self.cnn.parse_board(
img, cols, rows, self.retina_scale,
self.win_x, self.win_y, cw, ch)
finally:
sys.stdout = old_stdout
# Score: sum of max confidence for non-empty cells
total_conf = 0.0
n_pieces = 0
for r in range(10):
for c in range(9):
if self.cnn._cell_probs[r][c] is not None:
conf = float(self.cnn._cell_probs[r][c].max())
if board[r][c] is not None:
total_conf += conf
n_pieces += 1
return total_conf, n_pieces
# First try default ratios
best_score, best_n = try_grid(DEFAULT_RX1, DEFAULT_RY1, DEFAULT_RX2, DEFAULT_RY2)
best_params = (DEFAULT_RX1, DEFAULT_RY1, DEFAULT_RX2, DEFAULT_RY2)
# Fine-tune: grid search around default with small offsets
STEP = 0.005 # ~0.5% of window size
for dx in [-STEP, 0, STEP]:
for dy in [-STEP, 0, STEP]:
for ds in [-STEP, 0, STEP]: # scale adjustment
if dx == 0 and dy == 0 and ds == 0:
continue
rx1 = DEFAULT_RX1 + dx
ry1 = DEFAULT_RY1 + dy
rx2 = DEFAULT_RX2 + dx + ds
ry2 = DEFAULT_RY2 + dy + ds
score, n = try_grid(rx1, ry1, rx2, ry2)
if score > best_score:
best_score = score
best_n = n
best_params = (rx1, ry1, rx2, ry2)
rx1, ry1, rx2, ry2 = best_params
x1 = self.win_x + rx1 * win_w
y1 = self.win_y + ry1 * win_h
x2 = self.win_x + rx2 * win_w
y2 = self.win_y + ry2 * win_h
self.cell_w = (x2 - x1) / 8.0
self.cell_h = (y2 - y1) / 9.0
self.cols_logical = [x1 + i * self.cell_w for i in range(9)]
self.rows_logical = [y1 + j * self.cell_h for j in range(10)]
print(f" Auto-calibrate (CNN): {best_n} pieces, conf={best_score:.1f}, cell={self.cell_w:.1f}x{self.cell_h:.1f}")
# Save calibration
with open(CALIB_PATH, 'w') as f:
json.dump({'rx1': rx1, 'ry1': ry1, 'rx2': rx2, 'ry2': ry2}, f)
if best_n < 10:
print(" Auto-calibrate: too few pieces detected, may be inaccurate")
return False
return True
def calibrate(self):
"""Calibration: user points mouse to 2 corner pieces (countdown, no Enter needed)."""
print("\n=== CALIBRATION ===")
print("Move mouse to TOP-LEFT corner piece (leftmost piece on top rank)")
for i in range(5, 0, -1):
print(f" Capturing in {i}...", end="\r")
time.sleep(1)
x1, y1 = pyautogui.position()
print(f" Top-left: ({x1}, {y1}) ")
print("\nNow move mouse to BOTTOM-RIGHT corner piece (rightmost piece on bottom rank)")
for i in range(5, 0, -1):
print(f" Capturing in {i}...", end="\r")
time.sleep(1)
x2, y2 = pyautogui.position()
print(f" Bottom-right: ({x2}, {y2}) ")
self.cell_w = (x2 - x1) / 8.0
self.cell_h = (y2 - y1) / 9.0
self.cols_logical = [x1 + i * self.cell_w for i in range(9)]
self.rows_logical = [y1 + j * self.cell_h for j in range(10)]
print(f"\n Cell size: {self.cell_w:.1f} x {self.cell_h:.1f} logical pixels")
print(f" Grid: x=[{x1:.0f}..{x2:.0f}] y=[{y1:.0f}..{y2:.0f}]")
# Save calibration as relative to window (survives resize)
import json
win_w = self._get_window_width()
win_h = self._get_window_height()
with open(CALIB_PATH, 'w') as f:
json.dump({
'rx1': (x1 - self.win_x) / win_w,
'ry1': (y1 - self.win_y) / win_h,
'rx2': (x2 - self.win_x) / win_w,
'ry2': (y2 - self.win_y) / win_h,
}, f)
print(f" Saved to {CALIB_PATH}")
def _get_window_width(self):
windows = Quartz.CGWindowListCopyWindowInfo(
Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)
for w in windows:
if w.get('kCGWindowNumber') == self.win_id:
return int(w['kCGWindowBounds']['Width'])
return 1628 # fallback
def _get_window_height(self):
windows = Quartz.CGWindowListCopyWindowInfo(
Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)
for w in windows:
if w.get('kCGWindowNumber') == self.win_id:
return int(w['kCGWindowBounds']['Height'])
return 960 # fallback
def load_calibration(self):
"""Load calibration, auto-adapt to current window size/position."""
import json
if not os.path.exists(CALIB_PATH):
return False
try:
with open(CALIB_PATH) as f:
d = json.load(f)
# Support both relative (new) and absolute (old) formats
if 'rx1' in d:
win_w = self._get_window_width()
win_h = self._get_window_height()
x1 = self.win_x + d['rx1'] * win_w
y1 = self.win_y + d['ry1'] * win_h
x2 = self.win_x + d['rx2'] * win_w
y2 = self.win_y + d['ry2'] * win_h
else:
x1, y1, x2, y2 = d['x1'], d['y1'], d['x2'], d['y2']
if d.get('win_x') != self.win_x or d.get('win_y') != self.win_y:
dx = self.win_x - d.get('win_x', 0)
dy = self.win_y - d.get('win_y', 0)
x1 += dx; y1 += dy; x2 += dx; y2 += dy
self.cell_w = (x2 - x1) / 8.0
self.cell_h = (y2 - y1) / 9.0
self.cols_logical = [x1 + i * self.cell_w for i in range(9)]
self.rows_logical = [y1 + j * self.cell_h for j in range(10)]
print(f" Loaded calibration: cell={self.cell_w:.1f}x{self.cell_h:.1f}")
return True
except:
return False
# --- Orientation & Templates ---
def detect_orientation(self, img):
"""Check if top-row pieces are red (→ user plays BLACK)."""
ps = int(min(self.cell_w, self.cell_h) * self.retina_scale * 0.6)
red_total = 0
for ci in [0, 4, 8]:
px, py = self.logical_to_pixel(self.cols_logical[ci], self.rows_logical[0])
h, w = img.shape[:2]
patch = img[max(0,py-ps):min(h,py+ps), max(0,px-ps):min(w,px+ps)]
if patch.size == 0:
continue
hsv = cv2.cvtColor(patch, cv2.COLOR_BGR2HSV)
m1 = cv2.inRange(hsv, (0, 60, 60), (12, 255, 255))
m2 = cv2.inRange(hsv, (168, 60, 60), (180, 255, 255))
red_total += (cv2.countNonZero(m1) + cv2.countNonZero(m2)) / max(1, patch.size//3)
self.playing_red = red_total < 0.03
print(f" You play: {'RED' if self.playing_red else 'BLACK'}")
def capture_templates(self, img):
"""Capture templates from ALL initial positions (multiple per piece)."""
os.makedirs(TEMPLATE_DIR, exist_ok=True)
init = INIT_RED if self.playing_red else INIT_BLACK
ps = int(min(self.cell_w, self.cell_h) * self.retina_scale * 0.7)
self.patch_size = ps
self.templates = {} # piece -> [tmpl1, tmpl2, ...]
for r in range(10):
for c in range(9):
piece = init[r][c]
if piece is None:
continue
px, py = self.logical_to_pixel(self.cols_logical[c], self.rows_logical[r])
patch = self._extract(img, px, py, ps)
if patch is not None:
if piece not in self.templates:
self.templates[piece] = []
self.templates[piece].append(patch)
# Empty cells from many positions (including edges)
self.templates['_'] = []
for er in [1, 4, 5, 8]: # rows that are fully empty
for ec in range(9):
px, py = self.logical_to_pixel(self.cols_logical[ec], self.rows_logical[er])
ep = self._extract(img, px, py, ps)
if ep is not None:
self.templates['_'].append(ep)
total = sum(len(v) for k, v in self.templates.items() if k != '_')
print(f" Templates: {len(self.templates)} types, {total} variants")
def _extract(self, img, cx, cy, ps):
h, w = img.shape[:2]
x1, y1 = max(0, cx-ps), max(0, cy-ps)
x2, y2 = min(w, cx+ps), min(h, cy+ps)
p = img[y1:y2, x1:x2]
return p if p.shape[0] >= ps and p.shape[1] >= ps else None
# --- Color-based Piece Classifier (v2) ---
def _extract_piece_center(self, img, px, py, radius=None):
"""Extract the circular piece region centered at (px, py)."""
if radius is None:
radius = int(min(self.cell_w, self.cell_h) * self.retina_scale * 0.28)
h, w = img.shape[:2]
x1 = max(0, px - radius)
y1 = max(0, py - radius)
x2 = min(w, px + radius)
y2 = min(h, py + radius)
patch = img[y1:y2, x1:x2]
if patch.shape[0] < radius or patch.shape[1] < radius:
return None
return patch
def _find_piece_circle(self, img, px, py):
"""Detect the circular piece token using Hough circles.
Returns (cx, cy, cr) in image coordinates if found, or None.
The circle center is in ABSOLUTE image coordinates.
"""
scale = min(self.cell_w, self.cell_h) * self.retina_scale
search_r = int(scale * 0.55)
piece_r_min = int(scale * 0.22)
piece_r_max = int(scale * 0.42)
center_tol = int(scale * 0.25)
h, w = img.shape[:2]
x1 = max(0, px - search_r)
y1 = max(0, py - search_r)
x2 = min(w, px + search_r)
y2 = min(h, py + search_r)
patch = img[y1:y2, x1:x2]
if patch.shape[0] < 30 or patch.shape[1] < 30:
return None
gray = cv2.cvtColor(patch, cv2.COLOR_BGR2GRAY)
ph, pw = gray.shape[:2]
# Try multiple blur sizes and Hough sensitivity levels
for blur_k in [7, 5, 9]:
blurred = cv2.GaussianBlur(gray, (blur_k, blur_k), 2.0)
for p1, p2 in [(70, 30), (60, 25), (50, 22), (80, 35)]:
circles = cv2.HoughCircles(
blurred, cv2.HOUGH_GRADIENT, dp=1.2,
minDist=search_r,
param1=p1, param2=p2,
minRadius=piece_r_min,
maxRadius=piece_r_max
)
if circles is not None:
# Find circle closest to patch center
best_circ = None
best_dist = float('inf')
for circ in circles[0]:
cx, cy, cr = circ
dist = np.sqrt((cx - pw / 2) ** 2 + (cy - ph / 2) ** 2)
if dist < center_tol and dist < best_dist:
best_dist = dist
best_circ = circ
if best_circ is not None:
abs_cx = int(best_circ[0] + x1)
abs_cy = int(best_circ[1] + y1)
abs_cr = int(best_circ[2])
return (abs_cx, abs_cy, abs_cr)
return None
def _has_piece_v2(self, img, px, py):
"""Check if the cell at (px, py) has a piece.
Uses Hough circle detection as primary method, with a color-based
fallback that checks for the characteristic piece ring color.
"""
# Primary: Hough circle detection
circle = self._find_piece_circle(img, px, py)
if circle is not None:
return True
# Fallback: check for red/dark ring pixels in an annular region
# This catches pieces that Hough misses (edge cases, partial visibility)
scale = min(self.cell_w, self.cell_h) * self.retina_scale
outer_r = int(scale * 0.35)
inner_r = int(scale * 0.22)
h, w = img.shape[:2]
x1 = max(0, px - outer_r)
y1 = max(0, py - outer_r)
x2 = min(w, px + outer_r)
y2 = min(h, py + outer_r)
patch = img[y1:y2, x1:x2]
if patch.shape[0] < outer_r or patch.shape[1] < outer_r:
return False
ph, pw = patch.shape[:2]
pcx, pcy = pw // 2, ph // 2
# Create annular mask (ring where piece border would be)
mask_outer = np.zeros((ph, pw), dtype=np.uint8)
mask_inner = np.zeros((ph, pw), dtype=np.uint8)
cv2.circle(mask_outer, (pcx, pcy), outer_r, 255, -1)
cv2.circle(mask_inner, (pcx, pcy), inner_r, 255, -1)
ring_mask = cv2.subtract(mask_outer, mask_inner)
# Check for red ring pixels (red piece borders)
hsv = cv2.cvtColor(patch, cv2.COLOR_BGR2HSV)
red_mask1 = cv2.inRange(hsv, (0, 80, 100), (12, 255, 200))
red_mask2 = cv2.inRange(hsv, (168, 80, 100), (180, 255, 200))
red_ring = cv2.bitwise_and(cv2.bitwise_or(red_mask1, red_mask2), ring_mask)
red_count = cv2.countNonZero(red_ring)
# Check for dark ring pixels (black piece borders)
gray = cv2.cvtColor(patch, cv2.COLOR_BGR2GRAY)
dark_ring_vals = gray[ring_mask > 0]
dark_count = int(np.sum(dark_ring_vals < 100)) if len(dark_ring_vals) > 0 else 0
ring_total = max(1, cv2.countNonZero(ring_mask))
red_ratio = red_count / ring_total
dark_ratio = dark_count / ring_total
# A piece border needs both red/dark ring AND bright center (piece token is convex)
# Be strict to avoid false positives from board borders and adjacent piece edges
center_mask = np.zeros((ph, pw), dtype=np.uint8)
cv2.circle(center_mask, (pcx, pcy), int(scale * 0.10), 255, -1)
center_vals = gray[center_mask > 0]
center_brightness = float(np.mean(center_vals)) if len(center_vals) > 0 else 0
ring_brightness = float(np.mean(dark_ring_vals)) if len(dark_ring_vals) > 0 else 0
has_ring = red_ratio > 0.15 or dark_ratio > 0.25
has_bright_center = center_brightness > 140 and center_brightness > ring_brightness + 5
return has_ring and has_bright_center
def _classify_color_v2(self, img, px, py):
"""Classify a piece as RED or BLACK based on text/ring color.
Red pieces have red-colored Chinese characters and ring on a tan background.
Black pieces have dark/black characters and ring on a tan background.
Returns 'red' or 'black'.
"""
# Use the piece center for color analysis
radius = int(min(self.cell_w, self.cell_h) * self.retina_scale * 0.22)
# Try to use actual circle center if found
circle = self._find_piece_circle(img, px, py)
if circle is not None:
px, py = circle[0], circle[1]
h, w = img.shape[:2]
x1 = max(0, px - radius)
y1 = max(0, py - radius)
x2 = min(w, px + radius)
y2 = min(h, py + radius)
patch = img[y1:y2, x1:x2]
if patch.size == 0:
return 'unknown'
hsv = cv2.cvtColor(patch, cv2.COLOR_BGR2HSV)
# Create circular mask
ph, pw = patch.shape[:2]
mask = np.zeros((ph, pw), dtype=np.uint8)
cv2.circle(mask, (pw // 2, ph // 2), min(ph, pw) // 2, 255, -1)
# Count red pixels (text/ring of red pieces)
red_mask1 = cv2.inRange(hsv, (0, 70, 80), (12, 255, 255))
red_mask2 = cv2.inRange(hsv, (168, 70, 80), (180, 255, 255))
red_mask = cv2.bitwise_and(cv2.bitwise_or(red_mask1, red_mask2), mask)
red_count = cv2.countNonZero(red_mask)
# Count dark pixels (text/ring of black pieces)
gray = cv2.cvtColor(patch, cv2.COLOR_BGR2GRAY)
dark_vals = gray[mask > 0]
dark_count = int(np.sum(dark_vals < 80)) if len(dark_vals) > 0 else 0
total = max(1, cv2.countNonZero(mask))
red_ratio = red_count / total
dark_ratio = dark_count / total
if red_ratio > 0.03:
return 'red'
elif dark_ratio > 0.03:
return 'black'
else:
return 'red' if red_ratio > dark_ratio else 'black'
def _compute_feature_vector(self, img, px, py, grid_size=5):
"""Compute a structural feature vector from the character on a piece.
Uses multiple complementary features:
1. Stroke density in a grid (captures overall character shape)
2. Horizontal and vertical edge density (captures stroke orientations)
3. Multi-scale: coarse (4x4) and fine (6x6) grids
Returns a normalized feature vector.
"""
radius = int(min(self.cell_w, self.cell_h) * self.retina_scale * 0.18)
# Use actual circle center if found
circle = self._find_piece_circle(img, px, py)
if circle is not None:
px, py = circle[0], circle[1]
h, w = img.shape[:2]
x1 = max(0, px - radius)
y1 = max(0, py - radius)
x2 = min(w, px + radius)
y2 = min(h, py + radius)
patch = img[y1:y2, x1:x2]
if patch.shape[0] < radius or patch.shape[1] < radius:
return None
gray = cv2.cvtColor(patch, cv2.COLOR_BGR2GRAY).astype(np.float32)
ph, pw = gray.shape
# Create circular mask
mask = np.zeros((ph, pw), dtype=np.float32)
cv2.circle(mask, (pw // 2, ph // 2), min(ph, pw) // 2, 1.0, -1)
# Normalize brightness within mask
masked_pixels = gray[mask > 0]
if len(masked_pixels) == 0:
return None
local_mean = np.mean(masked_pixels)
local_std = np.std(masked_pixels)
if local_std < 5:
return None
# Normalized grayscale (mean-subtracted, std-normalized)
norm_gray = (gray - local_mean) / local_std
norm_gray = norm_gray * mask
# Compute edge maps for orientation features
sobel_x = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3) * mask
sobel_y = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3) * mask
features = []
# Feature set 1: normalized brightness in grid cells (captures character structure)
for gs in [4, 6]: # multi-scale
for gi in range(gs):
for gj in range(gs):
y_start = int(gi * ph / gs)
y_end = int((gi + 1) * ph / gs)
x_start = int(gj * pw / gs)
x_end = int((gj + 1) * pw / gs)
region = norm_gray[y_start:y_end, x_start:x_end]
region_mask = mask[y_start:y_end, x_start:x_end]
mask_sum = np.sum(region_mask)
if mask_sum > 0:
features.append(float(np.sum(region) / mask_sum))
else:
features.append(0.0)
# Feature set 2: horizontal vs vertical edge balance in grid cells
for gi in range(4):
for gj in range(4):
y_start = int(gi * ph / 4)
y_end = int((gi + 1) * ph / 4)
x_start = int(gj * pw / 4)
x_end = int((gj + 1) * pw / 4)
sx = np.abs(sobel_x[y_start:y_end, x_start:x_end])
sy = np.abs(sobel_y[y_start:y_end, x_start:x_end])
region_mask = mask[y_start:y_end, x_start:x_end]
mask_sum = np.sum(region_mask)
if mask_sum > 0:
# Ratio of vertical to horizontal edges
sx_sum = float(np.sum(sx * region_mask))
sy_sum = float(np.sum(sy * region_mask))
total_edge = sx_sum + sy_sum + 1e-8
features.append(sx_sum / total_edge) # horizontal dominance
else:
features.append(0.5)
vec = np.array(features, dtype=np.float32)
norm = np.linalg.norm(vec)
if norm > 1e-8:
vec = vec / norm
return vec
def _cosine_similarity(self, v1, v2):
"""Compute cosine similarity between two vectors."""
n1 = np.linalg.norm(v1)
n2 = np.linalg.norm(v2)
if n1 < 1e-8 or n2 < 1e-8:
return 0.0
return float(np.dot(v1, v2) / (n1 * n2))
def capture_feature_vectors(self, img):
"""Capture feature vectors from known piece positions in the initial layout.
This builds self.piece_features: dict mapping piece code -> list of feature vectors
and self.piece_color_map: dict mapping piece code -> 'red' or 'black'
"""
init = INIT_RED if self.playing_red else INIT_BLACK
self.piece_features = {} # piece -> [vec1, vec2, ...]
self.piece_color_map = {}
for r in range(10):
for c in range(9):
piece = init[r][c]
if piece is None:
continue
px, py = self.logical_to_pixel(self.cols_logical[c], self.rows_logical[r])
vec = self._compute_feature_vector(img, px, py)
if vec is not None:
if piece not in self.piece_features:
self.piece_features[piece] = []
self.piece_features[piece].append(vec)
# Map piece to color
if piece.isupper():
self.piece_color_map[piece] = 'red' if self.playing_red else 'black'
else:
self.piece_color_map[piece] = 'black' if self.playing_red else 'red'
total = sum(len(v) for v in self.piece_features.values())
print(f" Feature vectors: {len(self.piece_features)} types, {total} vectors")
def capture_feature_vectors_from_board(self, img, board):
"""Rebuild feature vectors from current known board state.
Uses only cells where we confidently know what piece is there.
"""
self.piece_features = {}
for r in range(10):
for c in range(9):
piece = board[r][c]
if piece is None:
continue
px, py = self.logical_to_pixel(self.cols_logical[c], self.rows_logical[r])
vec = self._compute_feature_vector(img, px, py)
if vec is not None:
if piece not in self.piece_features:
self.piece_features[piece] = []
self.piece_features[piece].append(vec)
def identify_v2(self, img, px, py):
"""Identify the piece at pixel position (px, py) using color-based classification.
Returns piece code (e.g. 'R', 'n', 'K') or None if empty.
Algorithm:
1. Check if cell has a piece (Hough circle + edge density fallback)
2. Classify red vs black via HSV analysis
3. Match character structure via stroke-density feature vector similarity
"""
# Step 1: Is there a piece here?
if not self._has_piece_v2(img, px, py):
return None
# Step 2: Red or Black?
color = self._classify_color_v2(img, px, py)
# Step 3: Match type via feature vector
vec = self._compute_feature_vector(img, px, py)
if vec is None:
return None
if not hasattr(self, 'piece_features') or not self.piece_features:
return None
# Filter candidates by color
candidates = {}
for piece, vecs in self.piece_features.items():
piece_color = self.piece_color_map.get(piece, 'unknown')
if piece_color == color or color == 'unknown':
candidates[piece] = vecs
if not candidates:
# Fall back to all pieces
candidates = self.piece_features
# Find best match by cosine similarity
best_piece = None
best_sim = -1.0
for piece, vecs in candidates.items():
for ref_vec in vecs:
sim = self._cosine_similarity(vec, ref_vec)
if sim > best_sim:
best_sim = sim
best_piece = piece
# Threshold check
if best_sim < 0.60:
return None
return best_piece
def parse_board_v2(self, img):
"""Parse the full board using identify_v2."""
board = []
for r in range(10):
row = []
for c in range(9):
px, py = self.logical_to_pixel(self.cols_logical[c], self.rows_logical[r])
p = self.identify_v2(img, px, py)
row.append(p)
board.append(row)
return board
# --- Move validation helpers ---
def _valid_destinations(self, piece, from_row, from_col, board):
"""Return set of (row, col) reachable positions for a piece.
Uses basic Chinese chess movement rules. Not a full legal move generator
(doesn't check for checks etc.) but validates piece-type movement patterns.
"""
dests = set()
is_upper = piece.isupper()
p = piece.upper()
# Determine which half of the board is "own side"
# In screen coords: rows 0-4 are top, 5-9 are bottom
# If playing red: red is bottom (5-9), black is top (0-4)
# If playing black: red is top (0-4), black is bottom (5-9)
if self.playing_red:
own_top = 5 if is_upper else 0 # uppercase=red=bottom, lower=black=top
own_bottom = 9 if is_upper else 4
enemy_top = 0 if is_upper else 5
enemy_bottom = 4 if is_upper else 9
else:
own_top = 0 if is_upper else 5
own_bottom = 4 if is_upper else 9
enemy_top = 5 if is_upper else 0
enemy_bottom = 9 if is_upper else 4
r, c = from_row, from_col
if p == 'R': # Rook: straight lines
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
while 0 <= nr <= 9 and 0 <= nc <= 8:
dests.add((nr, nc))
if board[nr][nc] is not None:
break
nr += dr
nc += dc
elif p == 'N': # Knight
for dr, dc, br, bc in [
(-2, -1, -1, 0), (-2, 1, -1, 0),
(2, -1, 1, 0), (2, 1, 1, 0),
(-1, -2, 0, -1), (-1, 2, 0, 1),
(1, -2, 0, -1), (1, 2, 0, 1)
]:
# Check blocking piece
block_r, block_c = r + br, c + bc
if 0 <= block_r <= 9 and 0 <= block_c <= 8:
if board[block_r][block_c] is not None:
continue
nr, nc = r + dr, c + dc
if 0 <= nr <= 9 and 0 <= nc <= 8:
dests.add((nr, nc))
elif p == 'B': # Bishop/Elephant: diagonal 2 steps, own half only
for dr, dc in [(-2, -2), (-2, 2), (2, -2), (2, 2)]:
# Check blocking piece at midpoint
mr, mc = r + dr // 2, c + dc // 2
if 0 <= mr <= 9 and 0 <= mc <= 8:
if board[mr][mc] is not None:
continue
nr, nc = r + dr, c + dc
if 0 <= nr <= 9 and 0 <= nc <= 8:
if own_top <= nr <= own_bottom:
dests.add((nr, nc))
elif p == 'A': # Advisor: diagonal 1 step within palace
# Palace: top 3 rows if own side is top, bottom 3 if own side is bottom
if own_top == 0:
palace_r_min, palace_r_max = 0, 2
else:
palace_r_min, palace_r_max = 7, 9
for dr, dc in [(-1, -1), (-1, 1), (1, -1), (1, 1)]:
nr, nc = r + dr, c + dc
if 3 <= nc <= 5 and palace_r_min <= nr <= palace_r_max:
dests.add((nr, nc))
elif p == 'K': # King: orthogonal 1 step within palace
if own_top == 0:
palace_r_min, palace_r_max = 0, 2
else:
palace_r_min, palace_r_max = 7, 9
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
if 3 <= nc <= 5 and palace_r_min <= nr <= palace_r_max:
dests.add((nr, nc))
# Flying general (face-to-face kings) - can capture opposing king
for dr in [1, -1]:
nr = r + dr
while 0 <= nr <= 9:
if board[nr][c] is not None:
if board[nr][c].upper() == 'K':
dests.add((nr, c))
break
nr += dr
elif p == 'C': # Cannon: straight lines, jump capture
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
jumped = False
while 0 <= nr <= 9 and 0 <= nc <= 8:
if not jumped:
if board[nr][nc] is None:
dests.add((nr, nc))
else:
jumped = True
else:
if board[nr][nc] is not None:
dests.add((nr, nc))
break
nr += dr
nc += dc
elif p == 'P': # Pawn
# Determine forward direction
if self.playing_red:
fwd = -1 if is_upper else 1
else:
fwd = 1 if is_upper else -1
nr = r + fwd
if 0 <= nr <= 9:
dests.add((nr, c))
# After crossing river, can move sideways
crossed = (r <= own_top - 1) or (r >= own_bottom + 1)
# More precise: pawn has crossed if it's in enemy half
if enemy_top <= r <= enemy_bottom:
crossed = True
if crossed:
for dc in [-1, 1]:
nc = c + dc
if 0 <= nc <= 8:
dests.add((r, nc))
return dests
def detect_move_v2(self, img_before, img_after, board_before):
"""Detect opponent's move using identify_v2 and move validation.
Algorithm:
1. Find cells that changed visually (pixel diff)
2. Use identify_v2 to classify what's at each changed cell
3. Determine source (cell that lost a piece) and dest (cell that gained/changed)
4. Validate against piece movement rules
5. Fall back to heuristics if needed
"""
board_after = [row[:] for row in board_before]
changed = []
# Step 1: Find changed cells
for r in range(10):
for c in range(9):
px, py = self.logical_to_pixel(self.cols_logical[c], self.rows_logical[r])
ps = self.patch_size
h, w = img_before.shape[:2]
x1, y1 = max(0, px - ps), max(0, py - ps)
x2, y2 = min(w, px + ps), min(h, py + ps)
p1 = img_before[y1:y2, x1:x2]
p2 = img_after[y1:y2, x1:x2]
if p1.shape != p2.shape:
continue
diff = cv2.absdiff(p1, p2)
gray_diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
change = np.count_nonzero(gray_diff > 30) / max(1, gray_diff.size)
if change > 0.03:
changed.append((r, c, change))
if not changed:
print(" detect_move_v2: no changed cells")
return board_before
# Refresh feature vectors from unchanged cells in the new image
self.capture_feature_vectors_from_board(img_after, board_before)
# Step 2: Identify what's at each changed cell now
cell_info = []
for r, c, change_amt in changed:
px, py = self.logical_to_pixel(self.cols_logical[c], self.rows_logical[r])
had_piece = board_before[r][c]
has_piece_now = self._has_piece_v2(img_after, px, py)
now_piece = self.identify_v2(img_after, px, py) if has_piece_now else None
cell_info.append({
'row': r, 'col': c,
'change': change_amt,
'had': had_piece,
'has_now': has_piece_now,
'now_piece': now_piece,
})
# Debug output
for ci in cell_info:
print(f" Changed ({ci['row']},{ci['col']}): "
f"had={ci['had']} now={ci['now_piece']} "
f"has_piece={ci['has_now']} change={ci['change']:.3f}")
# Step 3: Find source and destination
# Source: cell that had an opponent piece and now is empty or has different piece
# Destination: cell that now has a piece that wasn't there before, or has a different piece
sources = [] # Cells that lost a piece
dests = [] # Cells that gained/changed a piece
for ci in cell_info:
if ci['had'] is not None and not ci['has_now']:
sources.append(ci)
elif ci['had'] is None and ci['has_now']:
dests.append(ci)
elif ci['had'] is not None and ci['has_now']:
# Piece was here and still a piece here - could be capture destination
# or could be a highlight/selection artifact
if ci['now_piece'] is not None and ci['now_piece'] != ci['had']:
# Different piece arrived - this is a capture destination
dests.append(ci)
elif ci['change'] > 0.15:
# Large change with piece still there - might be dest of a capture
dests.append(ci)
# Handle case: exactly one source, one or zero dests
if len(sources) == 1 and len(dests) == 1:
src = sources[0]
dst = dests[0]
moving_piece = src['had']
# Step 4: Validate move
valid_dests = self._valid_destinations(
moving_piece, src['row'], src['col'], board_before)
if (dst['row'], dst['col']) in valid_dests:
board_after[src['row']][src['col']] = None
board_after[dst['row']][dst['col']] = moving_piece
print(f" Move: {moving_piece} ({src['row']},{src['col']}) → "
f"({dst['row']},{dst['col']}) [validated]")
return board_after
else:
# Move doesn't match rules for this piece type - still apply it
# but warn (could be wrong identification)
board_after[src['row']][src['col']] = None
board_after[dst['row']][dst['col']] = moving_piece
print(f" Move: {moving_piece} ({src['row']},{src['col']}) → "