-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexplorer_main.py
More file actions
1629 lines (1308 loc) · 59.2 KB
/
explorer_main.py
File metadata and controls
1629 lines (1308 loc) · 59.2 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 copy
import json
import math
import random
import time
from array import array
from collections import defaultdict
from enum import Enum
from dataclasses import dataclass
from scipy import stats
import torch
import torch.nn.functional as F
from kivy.config import Config
Config.set('input', 'mouse', 'mouse,disable_multitouch')
from kivy.app import App
from kivy.clock import Clock
from kivy.core.text import Label as CoreLabel
from kivy.core.text.markup import MarkupLabel
from kivy.core.window import Window
from kivy.graphics import Color, Ellipse, Line, Rectangle, RoundedRectangle
from kivy.properties import NumericProperty, StringProperty, ListProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.widget import Widget
from kivy_garden.graph import Graph, MeshLinePlot
from model import InferenceGraph, Net
from saiblo.game import ConnectFour
from plyer import filechooser
Window.size = (1400, 800)
@dataclass
class Configuration:
"""Application configuration settings."""
model_path: str = './weights/b3c128nbt_2025-08-18_19-22-00/katac4_b3c128nbt_30000.pth'
use_gpu: bool = True
n_playout: int = 1000
c_puct: float = 1.1
c_fpu: float = 0.2
player_names: dict = None
color_bg: tuple = (0.08, 0.09, 0.11, 1) # Midnight Blue-Black
color_board: tuple = (0.13, 0.15, 0.18, 1) # Dark Slate
color_grid: tuple = (0.25, 0.28, 0.32, 1) # Soft Steel
color_p1: tuple = (0.95, 0.75, 0.25, 1) # Soft Gold
color_p2: tuple = (0.55, 0.35, 0.9, 1) # Vibrant Indigo
color_forbidden: tuple = (0.85, 0.25, 0.25, 1) # Soft Red
color_highlight: tuple = (1, 1, 1, 0.1)
color_lcb: tuple = (0, 0.9, 0.9, 1) # Cyan
def __post_init__(self):
if self.player_names is None:
self.player_names = {1: "Orange", -1: "Purple"}
config = Configuration()
class GameMode(str, Enum):
PLAY = 'play'
ANALYSIS = 'analysis'
def win_rate_for_player(q_value: float, player_to_move: int, perspective_player: int) -> float:
"""Convert a Q-value into a win probability for the given perspective player."""
q_value *= player_to_move * perspective_player
return 0.5 * (q_value + 1.0)
def orange_win_rate(q_value: float, player_to_move: int) -> float:
"""Specialized helper that reports Orange's (player=1) win probability."""
return win_rate_for_player(q_value, player_to_move, perspective_player=1)
def compute_board_geometry(widget, rows, cols, padding=0.9):
if widget.height == 0: return 0, 0, 0, 0, 0
board_aspect = cols / rows
screen_aspect = widget.width / widget.height
if screen_aspect > board_aspect:
h = widget.height * padding
w = h * board_aspect
else:
w = widget.width * padding
h = w / board_aspect
off_x = widget.x + (widget.width - w) / 2
off_y = widget.y + (widget.height - h) / 2
cell_size = w / cols
return off_x, off_y, w, h, cell_size
def draw_piece(cx, cy, size, color):
r, g, b, a = color
Color(0, 0, 0, 0.4)
Ellipse(pos=(cx + size*0.05, cy - size*0.05), size=(size, size))
Color(r*0.8, g*0.8, b*0.8, a)
Ellipse(pos=(cx, cy), size=(size, size))
Color(r, g, b, a)
Ellipse(pos=(cx + size*0.05, cy + size*0.1), size=(size*0.9, size*0.9))
Color(1, 1, 1, 0.3)
Ellipse(pos=(cx + size*0.25, cy + size*0.55), size=(size*0.3, size*0.2))
def draw_board_grid_and_pieces(rows, cols, off_x, off_y, cs, forbidden_point=None, board=None):
for r in range(rows):
for c in range(cols):
cx = off_x + c * cs
cy = off_y + r * cs
Color(*config.color_grid)
Line(rectangle=(cx, cy, cs, cs), width=1)
val = 0
if board is not None:
val = board[r, c]
is_forbidden = (forbidden_point is not None and (r, c) == forbidden_point)
if val == 1:
padding = cs * 0.1
sz = cs - 2*padding
draw_piece(cx + padding, cy + padding, sz, config.color_p1)
elif val == -1:
padding = cs * 0.1
sz = cs - 2*padding
draw_piece(cx + padding, cy + padding, sz, config.color_p2)
elif is_forbidden:
Color(*config.color_forbidden)
m = cs * 0.25
Line(points=[cx+m, cy+m, cx+cs-m, cy+cs-m], width=2)
Line(points=[cx+m, cy+cs-m, cx+cs-m, cy+m], width=2)
class RoundedShapeMixin:
def update_shape(self, bg_color_normal, bg_color_down, radius=[6]):
self.canvas.before.clear()
with self.canvas.before:
if self.state == 'down':
c = bg_color_down or (bg_color_normal[0]*0.7, bg_color_normal[1]*0.7, bg_color_normal[2]*0.7, bg_color_normal[3])
Color(*c)
else:
Color(*bg_color_normal)
RoundedRectangle(pos=self.pos, size=self.size, radius=radius)
class RoundedButton(Button, RoundedShapeMixin):
def __init__(self, **kwargs):
self.bg_color = kwargs.pop('bg_color', (0.25, 0.3, 0.35, 1))
super().__init__(**kwargs)
self.background_color = (0, 0, 0, 0)
self.bind(pos=self.redraw, size=self.redraw, state=self.redraw)
def redraw(self, *args):
self.update_shape(self.bg_color, None)
class RoundedToggleButton(ToggleButton, RoundedShapeMixin):
def __init__(self, **kwargs):
self.bg_normal = kwargs.pop('bg_normal', (0.2, 0.22, 0.25, 1))
self.bg_down = kwargs.pop('bg_down', (0.2, 0.6, 0.8, 1))
super().__init__(**kwargs)
self.background_color = (0, 0, 0, 0)
self.bind(pos=self.redraw, size=self.redraw, state=self.redraw)
def redraw(self, *args):
self.update_shape(self.bg_normal, self.bg_down)
# --- Inference Helper ---
class CPUInference:
def __init__(self, net, height, width):
dummy_input = torch.empty(1, 6, height, width, device='cpu', dtype=torch.float32)
net = torch.jit.trace(net.to('cpu'), dummy_input)
self.net = torch.jit.freeze(net)
def policy_value_fn(self, game):
with torch.inference_mode():
state_tensor = torch.FloatTensor(game.state()).unsqueeze(0)
(policy_logits,), value_logits = self.net(state_tensor)
value_probs = F.softmax(value_logits.squeeze(0), dim=0)
policy_logits = policy_logits.squeeze(0)
sensible_moves = game.sensible_moves()
relevant_logits = policy_logits[game.top[sensible_moves], sensible_moves]
policy = F.softmax(relevant_logits, dim=0).numpy()
win_rate, loss_rate, _ = value_probs.tolist()
value = win_rate - loss_rate
return sensible_moves, policy, value
def load_model(path):
state_dict = torch.load(path, map_location='cpu', weights_only=True)
if 'policy_head.conv2.conv.weight' in state_dict:
state_dict['policy_head.conv2.conv.weight'] = \
state_dict['policy_head.conv2.conv.weight'][0:1]
net = Net(c_policy=1)
net.load_state_dict(state_dict)
return net
class LazyZTable:
def __init__(self, size=1000, p=1e-5):
self._size = size
self._p = p
self._cache = {}
def __getitem__(self, idx):
if val := self._cache.get(idx):
return val
val = stats.t.isf(self._p, idx + 1)
self._cache[idx] = val
return val
def __len__(self):
return self._size
# --- Core MCGS Logic ---
class TreeNode:
__slots__ = ('children', 'edge_N', 'edge_P', 'N', 'Q', 'avg_Q2', 'U')
def __init__(self):
self.children = [] # List[TreeNode | None]
self.edge_N = array('I') # Array of unsigned int
self.edge_P = array('f') # Array of float
self.N = 0
self.Q = 0.0
self.avg_Q2 = 0.0
self.U = 0.0
def is_expanded(self):
return len(self.children) > 0
def expand(self, policy_fn, state):
acts, probs, value = policy_fn(state)
width = state.width
self.children = [None] * width
zeros = b'\x00' * 4 * width
self.edge_N = array('I', zeros)
self.edge_P = array('f', zeros)
for a, p in zip(acts, probs):
if a < width:
self.edge_P[a] = float(p)
self.Q = self.U = value
def select(self, c_puct, c_fpu):
best_action = -1
best_uct = -float('inf')
# Sum edge_P where edge_N > 0 for FPU calculation
p_explored = 0.0
for i in range(len(self.children)):
if self.edge_N[i] > 0:
p_explored += self.edge_P[i]
fpu_penalty = c_fpu * math.sqrt(p_explored)
if self.N > 2:
k = 4 * math.sqrt(self.var) / self.N
k = min(max(k, 0.5), 1.4)
child_N_sum = sum(self.edge_N)
alpha = 1.0 / (1 + math.sqrt(child_N_sum / 10000.0))
c_puct *= (alpha * k + (1.0 - alpha))
sqrt_N = math.sqrt(self.N)
for i in range(len(self.children)):
if self.edge_P[i] <= 1e-8:
continue
child = self.children[i]
n_edge = self.edge_N[i]
edge_Q = self.Q - fpu_penalty if child is None else -child.Q
uct = edge_Q + c_puct * self.edge_P[i] * sqrt_N / (1 + n_edge)
if uct > best_uct:
best_uct = uct
best_action = i
return best_action, self.children[best_action], self.edge_N[best_action]
def update(self):
# Terminal/Leaf Node: Q is static U (no children to average)
if not self.children:
self.Q = self.U
self.avg_Q2 = self.U ** 2
return
sum_q = 0.0
sum_q2 = 0.0
for i in range(len(self.children)):
n = self.edge_N[i]
if n > 0:
if child := self.children[i]:
sum_q += child.Q * n
sum_q2 += child.avg_Q2 * n
self.Q = (self.U - sum_q) / self.N
self.avg_Q2 = (self.U * self.U + sum_q2) / self.N
@property
def var(self):
return max(0.0, self.avg_Q2 - self.Q ** 2)
class MCGS:
__slots__ = ('c_puct', 'c_fpu', 'policy', 'root', 'nodes_by_hash', 'z_table')
def __init__(self, policy_value_fn, z_table, c_puct=1.0, c_fpu=0.2):
self.c_puct = c_puct
self.c_fpu = c_fpu
self.policy = policy_value_fn
self.root = None
self.nodes_by_hash = defaultdict(TreeNode)
self.z_table = z_table
def playout(self, state):
state = copy.deepcopy(state)
if self.root is None:
self.root = self.nodes_by_hash[state.hash]
node = self.root
path = []
# Descent
while node.is_expanded():
path.append(node)
# Use c_fpu=0 at root for exploration, regular c_fpu elsewhere
eff_fpu = 0.0 if node is self.root else self.c_fpu
action, child, edge_N = node.select(self.c_puct, eff_fpu)
state.step(action)
if child is None:
child = self.nodes_by_hash[state.hash]
node.children[action] = child
node.edge_N[action] += 1
node = child
# Leaf Evaluation
if state.is_terminal():
node.Q = node.U = -1.0 if state.winner else 0.0
else:
node.expand(self.policy, state)
node.avg_Q2 = node.Q ** 2
node.N += 1
# Backprop
for node in reversed(path):
node.N += 1
node.update()
def reroot(self, state):
self.root = self.nodes_by_hash[state.hash]
def get_best_move(self):
# LCB Selection logic
root_node = self.root
if not root_node: return None
N_min = max(math.ceil(0.1 * root_node.N), 2)
cands = []
for act in range(len(root_node.children)):
child = root_node.children[act]
# Must check if child exists and meets threshold
if child and child.N >= N_min:
cands.append((act, child))
if not cands:
# Fallback to Max Visits
max_visits = -1
best_action = None
for act in range(len(root_node.children)):
edge_N = root_node.edge_N[act]
if edge_N > max_visits:
max_visits = edge_N
best_action = act
return best_action
else:
# LCB Metric
def lcb(item):
_, child = item
var = child.var * (child.N / (child.N - 1)) if child.N > 1 else child.var
idx = max(0, min(child.N, len(self.z_table)) - 1)
t_val = self.z_table[idx]
return -child.Q - t_val * math.sqrt(var) / child.N
best_action, _ = max(cands, key=lcb)
return best_action
# --- Session State ---
class GameSession:
"""Encapsulate match state, inference objects, and navigation logic."""
def __init__(self, config: Configuration):
self.config = config
device_type = 'cuda' if self.config.use_gpu and torch.cuda.is_available() else 'cpu'
self.device = torch.device(device_type)
if device_type == 'cpu':
torch.set_num_threads(4)
self.net = load_model(self.config.model_path).to(self.device)
self.net.eval()
self.z_table = LazyZTable(p=1e-5)
self.history = []
self.win_history = []
self.cursor = 0
self.mcgs = None
self._graph = None
self.start_new_game()
@property
def current_game(self):
return self.history[self.cursor] if 0 <= self.cursor < len(self.history) else None
def start_new_game(self, height=None, width=None, forbidden_point=None):
game = ConnectFour(height=height, width=width, forbidden_point=forbidden_point)
self.history = [game]
self.win_history = [(0, 0.5)]
self.cursor = 0
self._init_mcgs(game)
def apply_move(self, col):
current = self.current_game
if current is None or current.is_terminal():
return None
if self.cursor < len(self.history) - 1:
self.history = self.history[:self.cursor + 1]
self.win_history = self.win_history[:self.cursor + 1]
next_game = copy.deepcopy(self.history[-1])
next_game.step(col)
self.history.append(next_game)
self.cursor = len(self.history) - 1
self.win_history.append((self.cursor, 0.5))
self.mcgs.reroot(next_game)
return next_game
def navigate(self, idx):
if not (0 <= idx < len(self.history)):
return False
self.cursor = idx
self.mcgs.reroot(self.history[idx])
return True
def load_rounds(self, height, width, forbidden_point, rounds):
base_game = ConnectFour(height=height, width=width, forbidden_point=forbidden_point)
self.history = [base_game]
self.win_history = [(0, 0.5)]
current = base_game
for idx, move in enumerate(rounds, start=1):
next_game = copy.deepcopy(current)
next_game.step(move)
self.history.append(next_game)
self.win_history.append((idx, 0.5))
current = next_game
self.cursor = len(self.history) - 1
self._init_mcgs(base_game)
# Prime evaluations for each node in history
for idx, game in enumerate(self.history):
self.mcgs.reroot(game)
self.mcgs.playout(game)
if self.mcgs.root and self.mcgs.root.N > 0:
q = self.mcgs.root.Q
wr = orange_win_rate(q, game.player)
self.win_history[idx] = (idx, wr)
self.mcgs.reroot(self.current_game)
def ensure_win_history_length(self, idx):
while len(self.win_history) <= idx:
self.win_history.append((len(self.win_history), 0.5))
def set_winrate(self, idx, value):
self.ensure_win_history_length(idx)
self.win_history[idx] = (idx, value)
def _init_mcgs(self, game):
policy_fn = self._build_policy_fn(game)
self.mcgs = MCGS(policy_fn, self.z_table, c_puct=self.config.c_puct, c_fpu=self.config.c_fpu)
self.mcgs.reroot(game)
def _build_policy_fn(self, game):
if self.device.type == 'cuda':
try:
self._graph = InferenceGraph(self.net, self.device, game.height, game.width)
return self._graph.policy_value_fn
except Exception:
self._graph = None
cpu = CPUInference(self.net, game.height, game.width)
return cpu.policy_value_fn
# --- UI Components ---
class PreviewBoardWidget(Widget):
rows = NumericProperty(10)
cols = NumericProperty(9)
forbidden_x = NumericProperty(4)
forbidden_y = NumericProperty(5) # User Row (0=Top)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.bind(pos=self.update_canvas, size=self.update_canvas)
self.bind(rows=self.update_canvas, cols=self.update_canvas)
self.bind(forbidden_x=self.update_canvas, forbidden_y=self.update_canvas)
def on_touch_down(self, touch):
if 'button' in touch.profile and touch.button != 'left':
return False
if not self.collide_point(*touch.pos): return False
off_x, off_y, w, h, cs = compute_board_geometry(self, self.rows, self.cols, 0.95)
if not (off_x <= touch.x <= off_x + w and off_y <= touch.y <= off_y + h):
return False
col = int((touch.x - off_x) / cs)
row_engine = int((touch.y - off_y) / cs)
col = max(0, min(col, self.cols - 1))
row = max(0, min(row_engine, self.rows - 1))
row = self.rows - 1 - row
self.forbidden_x = col
self.forbidden_y = row
return True
def update_canvas(self, *args):
self.canvas.clear()
off_x, off_y, w, h, cs = compute_board_geometry(self, self.rows, self.cols, 0.95)
with self.canvas:
Color(*config.color_board)
RoundedRectangle(pos=(off_x, off_y), size=(w, h), radius=[4])
forbidden_r = (self.rows - 1) - self.forbidden_y
draw_board_grid_and_pieces(self.rows, self.cols, off_x, off_y, cs,
forbidden_point=(forbidden_r, self.forbidden_x))
class Card(BoxLayout):
def __init__(self, **kwargs):
self.bg_color = kwargs.pop('bg_color', (0.13, 0.15, 0.18, 1))
self.radius = kwargs.pop('radius', [10])
if 'padding' not in kwargs: kwargs['padding'] = 15
if 'spacing' not in kwargs: kwargs['spacing'] = 10
super().__init__(**kwargs)
self.bind(pos=self.update_bg, size=self.update_bg)
def update_bg(self, *args):
self.canvas.before.clear()
with self.canvas.before:
Color(*self.bg_color)
RoundedRectangle(pos=self.pos, size=self.size, radius=self.radius)
class SpinBox(BoxLayout):
text = StringProperty('')
values = ListProperty([])
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.orientation = 'horizontal'
self.spacing = 5
self.btn_down = RoundedButton(text='<', bg_color=(0.25, 0.28, 0.32, 1),
size_hint_x=None, width=35,
font_size='14sp', font_name='Roboto-Bold')
self.btn_down.bind(on_release=self.decrement)
self.add_widget(self.btn_down)
self.label = Label(text=self.text, font_size='16sp', color=(0.9, 0.9, 0.9, 1))
self.label.bind(pos=self.update_rect, size=self.update_rect)
self.add_widget(self.label)
self.btn_up = RoundedButton(text='>', bg_color=(0.25, 0.28, 0.32, 1),
size_hint_x=None, width=35,
font_size='14sp', font_name='Roboto-Bold')
self.btn_up.bind(on_release=self.increment)
self.add_widget(self.btn_up)
self.bind(text=self.on_text_changed)
self.bind(values=self.on_values_changed)
def update_rect(self, *args):
self.label.canvas.before.clear()
with self.label.canvas.before:
Color(0.15, 0.17, 0.20, 1)
RoundedRectangle(pos=self.label.pos, size=self.label.size, radius=[4])
def on_text_changed(self, *args):
self.label.text = self.text
def on_values_changed(self, *args):
if self.values and self.text not in self.values:
self.text = self.values[0]
def increment(self, *args):
idx = self.values.index(self.text)
self.text = self.values[(idx + 1) % len(self.values)]
def decrement(self, *args):
idx = self.values.index(self.text)
self.text = self.values[(idx - 1) % len(self.values)]
class OptionSelector(BoxLayout):
text = StringProperty('')
def __init__(self, values=(), **kwargs):
super().__init__(**kwargs)
self.orientation = 'horizontal'
self.spacing = 5
self._buttons = {}
group_name = f"opt_{id(self)}"
for val in values:
val_str = str(val)
state = 'down' if val_str == self.text else 'normal'
btn = RoundedToggleButton(text=val_str, group=group_name,
allow_no_selection=False, state=state)
btn.bind(state=self.on_btn_state)
self.add_widget(btn)
self._buttons[val_str] = btn
self.bind(text=self.on_text_change)
def on_text_change(self, instance, value):
for val_str, btn in self._buttons.items():
btn.state = 'down' if val_str == value else 'normal'
def on_btn_state(self, instance, value):
if value == 'down':
self.text = instance.text
class NewGamePopup(Popup):
def __init__(self, on_confirm, initial_cfg=None, **kwargs):
super().__init__(**kwargs)
self.on_confirm = on_confirm
self.title = "New Game Configuration"
self.title_size = '22sp'
self.title_font = 'Roboto-Bold'
self.separator_height = 0
self.size_hint = (0.75, 0.75)
self.background_color = (0.05, 0.06, 0.08, 0.95)
init_w = '9'
init_h = '10'
init_fx = '4'
init_fy = '5'
if initial_cfg:
h, w, (fr, fc) = initial_cfg
init_w = str(w)
init_h = str(h)
init_fx = str(fc)
# user y = (h - 1) - engine_r
init_fy = str((h - 1) - fr)
root = BoxLayout(orientation='vertical', spacing=30, padding=25)
content = BoxLayout(orientation='horizontal', spacing=30)
controls = BoxLayout(orientation='vertical', spacing=30, size_hint_x=None, width=360)
def make_label(text, hint_x):
l = Label(text=text, color=(0.7,0.7,0.7,1), size_hint_x=hint_x, halign='center', valign='middle')
l.bind(size=lambda s, _: setattr(s, 'text_size', (s.width-10, s.height)))
return l
dim_card = Card(orientation='vertical', size_hint_y=None, height=280, padding=20, spacing=10)
dim_title = Label(text="Board Size", bold=True, font_size='16sp',
size_hint_y=None, height=30, halign='center', valign='middle')
dim_title.bind(size=lambda s, _: setattr(s, 'text_size', (s.width, s.height)))
dim_card.add_widget(dim_title)
dim_card.add_widget(Widget(size_hint_y=None, height=4))
w_box = BoxLayout(spacing=10)
w_box.add_widget(make_label("Width", 0.25))
self.width_input = OptionSelector(text=init_w, values=('9', '10', '11', '12'), size_hint_x=0.75)
w_box.add_widget(self.width_input)
dim_card.add_widget(w_box)
h_box = BoxLayout(spacing=10)
h_box.add_widget(make_label("Height", 0.25))
self.height_input = OptionSelector(text=init_h, values=('9', '10', '11', '12'), size_hint_x=0.75)
h_box.add_widget(self.height_input)
dim_card.add_widget(h_box)
dim_card.add_widget(Label(text="The model only supports these board sizes.",
color=(0.5, 0.5, 0.5, 1), font_size='11sp', halign='center'))
rand_dim_btn = RoundedButton(text="Random Size", size_hint_y=None, height=40, bg_color=(0.3, 0.3, 0.35, 1))
rand_dim_btn.bind(on_release=self.randomize_dims)
dim_card.add_widget(rand_dim_btn)
controls.add_widget(dim_card)
fp_card = Card(orientation='vertical', size_hint_y=None, height=280, padding=20, spacing=10)
fp_title = Label(text="Forbidden Point", bold=True, font_size='16sp',
size_hint_y=None, height=30, halign='center', valign='middle')
fp_title.bind(size=lambda s, _: setattr(s, 'text_size', (s.width, s.height)))
fp_card.add_widget(fp_title)
fp_card.add_widget(Widget(size_hint_y=None, height=4))
fpx_box = BoxLayout(spacing=10)
fpx_box.add_widget(make_label("Column (X)", 0.45))
self.fp_x = SpinBox(text=init_fx, values=['0'], size_hint_x=0.55)
fpx_box.add_widget(self.fp_x)
fp_card.add_widget(fpx_box)
fpy_box = BoxLayout(spacing=10)
fpy_box.add_widget(make_label("Row (Y)", 0.45))
self.fp_y = SpinBox(text=init_fy, values=['0'], size_hint_x=0.55)
fpy_box.add_widget(self.fp_y)
fp_card.add_widget(fpy_box)
fp_card.add_widget(Label(text="Topleft is (0,0). Click preview to set.",
color=(0.5, 0.5, 0.5, 1), font_size='12sp', halign='center'))
rand_fp_btn = RoundedButton(text="Random Point", size_hint_y=None, height=40, bg_color=(0.3, 0.3, 0.35, 1))
rand_fp_btn.bind(on_release=self.randomize_fp)
fp_card.add_widget(rand_fp_btn)
controls.add_widget(fp_card)
controls.add_widget(Widget()) # Vertical Spacer
content.add_widget(controls)
preview_container = Card(bg_color=(0.1, 0.11, 0.13, 1), radius=[12])
self.preview = PreviewBoardWidget()
self.preview.cols = int(init_w)
self.preview.rows = int(init_h)
self.preview.forbidden_x = int(init_fx)
self.preview.forbidden_y = int(init_fy)
preview_container.add_widget(self.preview)
content.add_widget(preview_container)
root.add_widget(content)
btn_box = BoxLayout(orientation='horizontal', spacing=20, size_hint_y=None, height=55)
btn_box.add_widget(Widget()) # Left spacer to push buttons right
cancel_btn = RoundedButton(text="Cancel", bg_color=(0.25, 0.25, 0.25, 1), size_hint_x=None, width=120)
cancel_btn.bind(on_release=self.dismiss)
start_btn = RoundedButton(text="Start Game", bg_color=(0.2, 0.65, 0.35, 1), size_hint_x=None, width=160, font_size='16sp', bold=True)
start_btn.bind(on_release=self.confirm)
btn_box.add_widget(cancel_btn)
btn_box.add_widget(start_btn)
root.add_widget(btn_box)
self.content = root
# Bindings
self.width_input.bind(text=self.on_dim_change)
self.height_input.bind(text=self.on_dim_change)
self.fp_x.bind(text=self.on_fp_spinner_change)
self.fp_y.bind(text=self.on_fp_spinner_change)
self.preview.bind(forbidden_x=self.on_preview_fp_change)
self.preview.bind(forbidden_y=self.on_preview_fp_change)
# Init state
Clock.schedule_once(self.on_dim_change, 0)
def randomize_dims(self, instance):
vals = ['9', '10', '11', '12']
self.width_input.text = random.choice(vals)
self.height_input.text = random.choice(vals)
def randomize_fp(self, instance):
w = int(self.width_input.text)
h = int(self.height_input.text)
self.fp_x.text = str(random.randrange(w))
self.fp_y.text = str(random.randrange(h))
def on_dim_change(self, *args):
w = int(self.width_input.text)
h = int(self.height_input.text)
self.preview.cols = w
self.preview.rows = h
# Update Spinner ranges
self.fp_x.values = list(map(str, range(w)))
self.fp_y.values = list(map(str, range(h)))
# Clamp preview FP if out of bounds
self.preview.forbidden_x = min(self.preview.forbidden_x, w - 1)
self.preview.forbidden_y = min(self.preview.forbidden_y, h - 1)
self.fp_x.text = str(self.preview.forbidden_x)
self.fp_y.text = str(self.preview.forbidden_y)
def on_fp_spinner_change(self, *args):
x = int(self.fp_x.text)
y = int(self.fp_y.text)
self.preview.forbidden_x, self.preview.forbidden_y = x, y
def on_preview_fp_change(self, *args):
self.fp_x.text, self.fp_y.text = str(self.preview.forbidden_x), str(self.preview.forbidden_y)
def confirm(self, instance):
w = int(self.width_input.text)
h = int(self.height_input.text)
fx = min(w - 1, int(self.fp_x.text))
fy = min(h - 1, int(self.fp_y.text))
fy = h - 1 - fy
self.dismiss()
self.on_confirm(h, w, (fy, fx))
def find_winning_line(game):
if not game.winner: return []
h, w = game.height, game.width
board = game.board
p = game.winner
for r in range(h):
for c in range(w):
if board[r, c] == p:
for dr, dc in [(0,1), (1,0), (1,1), (1,-1)]:
if 0 <= r + 3*dr < h and 0 <= c + 3*dc < w:
if all(board[r+i*dr, c+i*dc] == p for i in range(1, 4)):
return [(r+i*dr, c+i*dc) for i in range(4)]
return []
class MiniBoardWidget(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.game_snapshot = None
self.pv_moves = []
self.winning_line = []
self.pv_info = None
self.bind(pos=self.update_canvas, size=self.update_canvas)
def update(self, game, pv_moves, winning_line=None, pv_info=None):
self.game_snapshot = game
self.pv_moves = pv_moves
self.winning_line = winning_line
self.pv_info = pv_info
self.update_canvas()
def update_canvas(self, *args):
self.canvas.clear()
if not self.game_snapshot:
return
game = self.game_snapshot
# Draw Background
with self.canvas:
Color(0, 0, 0, 0.3)
RoundedRectangle(pos=self.pos, size=self.size, radius=[8])
off_x, off_y, w, h, cs = compute_board_geometry(self, game.height, game.width, 0.9)
with self.canvas:
Color(*config.color_board)
RoundedRectangle(pos=(off_x, off_y), size=(w, h), radius=[4])
draw_board_grid_and_pieces(game.height, game.width, off_x, off_y, cs,
forbidden_point=game.forbidden_point,
board=game.board)
# Draw PV Moves
if self.pv_moves:
for i, (r, c, p) in enumerate(self.pv_moves):
cx = off_x + c * cs
cy = off_y + r * cs
padding = cs * 0.1
sz = cs - 2*padding
if p == 1:
draw_piece(cx + padding, cy + padding, sz, config.color_p1)
else:
draw_piece(cx + padding, cy + padding, sz, config.color_p2)
label = CoreLabel(text=str(i+1), font_size=cs*0.5, halign='center', valign='middle')
label.refresh()
if label.texture:
t = label.texture
Color(0, 0, 0, 0.8)
Rectangle(texture=t, pos=(cx + (cs - t.size[0])/2, cy + (cs - t.size[1])/2), size=t.size)
# Draw Winning Line
if self.winning_line:
Color(0.2, 1, 0.2, 0.9)
pts = []
for r, c in self.winning_line:
cx = off_x + c * cs + cs/2
cy = off_y + r * cs + cs/2
pts.extend([cx, cy])
Line(points=pts, width=3, cap='round', joint='round')
# Title
lbl_title = CoreLabel(text="Principal Variation", font_size=14, color=(0.7, 0.7, 0.8, 1))
lbl_title.refresh()
if lbl_title.texture:
Color(1, 1, 1, 1)
Rectangle(texture=lbl_title.texture, pos=(self.x + 10, self.top - 25), size=lbl_title.texture.size)
if self.pv_info:
v, wr = self.pv_info
v_str = f"{v/1000:.1f}k" if v >= 1000 else str(v)
info_text = f"N={v_str} / {wr*100:.1f}%"
lbl_info = CoreLabel(text=info_text, font_size=14, color=(0.7, 0.7, 0.8, 1))
lbl_info.refresh()
if lbl_info.texture:
Color(1, 1, 1, 1)
# Align right with 10px padding
rx = self.x + self.width - lbl_info.texture.size[0] - 10
Rectangle(texture=lbl_info.texture, pos=(rx, self.top - 25), size=lbl_info.texture.size)
class BoardWidget(Widget):
mouse_col = NumericProperty(-1)
mouse_row = NumericProperty(-1)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.bind(pos=self.update_canvas, size=self.update_canvas)
Window.bind(mouse_pos=self.on_mouse_move)
def get_game(self):
return App.get_running_app().get_current_game()
def on_mouse_move(self, window, pos):
app = App.get_running_app()
if app.dialog_open:
if self.mouse_col != -1:
self.mouse_col = self.mouse_row = -1
self.update_canvas()
return
game = self.get_game()
if not game or not self.collide_point(*pos):
if self.mouse_col != -1:
self.mouse_col = self.mouse_row = -1
self.update_canvas()
return
off_x, off_y, w, h, cs = compute_board_geometry(self, game.height, game.width, 0.9)
inside_board = off_x <= pos[0] <= off_x + w and off_y <= pos[1] <= off_y + h
if not inside_board:
if self.mouse_col != -1:
self.mouse_col = self.mouse_row = -1
self.update_canvas()
return
col = int((pos[0] - off_x) // cs)
row = int((pos[1] - off_y) // cs)
self.mouse_col = col if 0 <= col < game.width and game.top[col] < game.height else -1
self.mouse_row = row if 0 <= row < game.height else -1
self.update_canvas()
def on_touch_down(self, touch):
app = App.get_running_app()
if app.dialog_open or ('button' in touch.profile and touch.button != 'left'):
return super().on_touch_down(touch)
game = self.get_game()
if not game or not self.collide_point(*touch.pos):
return super().on_touch_down(touch)
col = self.mouse_col
if (
col != -1
and game.top[col] < game.height
and not game.is_terminal()
and (not app.is_mode(GameMode.PLAY) or game.player == 1)
):
app.make_move(col)
return True
def update_canvas(self, *args):
self.canvas.clear()
game = self.get_game()
if not game: return
offset_x, offset_y, w, h, cell_size = compute_board_geometry(self, game.height, game.width, 0.9)
app = App.get_running_app()
mcgs = app.session.mcgs
if not mcgs: