-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshift3.py
More file actions
1646 lines (1418 loc) · 63 KB
/
Copy pathshift3.py
File metadata and controls
1646 lines (1418 loc) · 63 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 streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from collections import defaultdict
import random
import json
import zipfile
import io
import math
import time
from copy import deepcopy
from dataclasses import dataclass
from typing import List, Tuple, Optional, Dict
import pandas as pd
# ============================================================================
# Page Config
# ============================================================================
st.set_page_config(
page_title="Shift-3 Arena",
layout="wide",
initial_sidebar_state="expanded",
page_icon="⛩️"
)
st.title("⟷ Shift-3 Arena")
st.markdown("""
A dynamic, moving-board game on a **5-square row** with sliding pieces.
The board never stops moving — master the slide, win the row.
**AI Architecture:**
- 🌳 **MCTS + PUCT** — Monte Carlo Tree Search with AlphaZero's UCB formula
- 🧠 **Negamax + Alpha-Beta** — Full adversarial search with iterative deepening
- 🎯 **Sliding Threat Evaluator** — Pattern-based lookahead for surround and adjacency wins
- 🔄 **Self-Play Reinforcement** — Policy distillation from MCTS visit counts
- 📊 **Q-Learning** — Tabular state-action value estimates updated per game
- 🔬 **Loop Detection** — Handles board cycling via repetition detection
""")
st.markdown("""
<style>
body { background-color: #0e1117; }
.stApp { background-color: #0e1117; }
.stButton>button {
background: linear-gradient(90deg, #0a1a0a, #112211);
color: #ccffcc; border: 1px solid #224422; border-radius: 8px; transition: all 0.2s;
}
.stButton>button:hover { border-color: #44FF44; color: #AAFFAA; }
</style>
""", unsafe_allow_html=True)
# ============================================================================
# Shift-3 Game Logic
# ============================================================================
PLACE_ACTION = 'place'
SLIDE_ACTION = 'slide'
SLIDE_LEFT = -1
SLIDE_RIGHT = +1
@dataclass
class S3Action:
action_type: str # PLACE_ACTION or SLIDE_ACTION
position: int # board index 0-4
direction: int # 0 if place, -1/+1 if slide
player: int
def to_key(self) -> str:
return f"{self.action_type[0]}{self.position}{self.direction}{self.player}"
def __hash__(self):
return hash((self.action_type, self.position, self.direction, self.player))
def __eq__(self, other):
return (self.action_type == other.action_type and
self.position == other.position and
self.direction == other.direction and
self.player == other.player)
def description(self) -> str:
if self.action_type == PLACE_ACTION:
return f"PLACE at [{self.position}]"
dir_str = "LEFT" if self.direction == SLIDE_LEFT else "RIGHT"
return f"SLIDE [{self.position}] → {dir_str}"
class Shift3Game:
"""
Shift-3: 5-square row.
Each player has 2 pieces in hand initially; 0 pre-placed.
Turn: PLACE from hand onto empty square, OR SLIDE own piece one step into empty square.
Win: [Your, Opp, Your] in 3 consecutive squares (surround).
Draw: same position repeated 3 times, or MAX_MOVES reached.
"""
BOARD_SIZE = 5
PIECES_PER_PLAYER = 2
MAX_MOVES = 120
def __init__(self):
self.reset()
def reset(self):
self.board = [0] * self.BOARD_SIZE # 0=empty, 1=P1, 2=P2
self.current_player = 1
self.game_over = False
self.winner = None
self.hand: Dict[int, int] = {1: self.PIECES_PER_PLAYER,
2: self.PIECES_PER_PLAYER}
self.move_history: List[S3Action] = []
self.move_count = 0
self.event_log: List[str] = []
# KEY FIX: always defaultdict so += never raises KeyError
self.seen_states: defaultdict = defaultdict(int)
self.win_cells: Optional[List[int]] = None
return self.get_state()
def get_state(self) -> tuple:
return tuple(self.board) + (self.current_player,
self.hand[1], self.hand[2])
def get_state_key(self) -> str:
return (''.join(map(str, self.board)) +
str(self.current_player) +
str(self.hand[1]) +
str(self.hand[2]))
def copy(self) -> 'Shift3Game':
g = Shift3Game()
g.board = self.board[:]
g.current_player = self.current_player
g.game_over = self.game_over
g.winner = self.winner
g.hand = {1: self.hand[1], 2: self.hand[2]}
g.move_history = self.move_history[:]
g.move_count = self.move_count
g.event_log = self.event_log[:]
# KEY FIX: copy into a new defaultdict(int) — NOT a plain dict
g.seen_states = defaultdict(int, self.seen_states)
g.win_cells = self.win_cells[:] if self.win_cells else None
return g
def get_valid_actions(self) -> List[S3Action]:
if self.game_over:
return []
p = self.current_player
actions: List[S3Action] = []
# PLACE from hand
if self.hand[p] > 0:
for pos in range(self.BOARD_SIZE):
if self.board[pos] == 0:
actions.append(S3Action(PLACE_ACTION, pos, 0, p))
# SLIDE own piece one step into empty neighbour
for pos in range(self.BOARD_SIZE):
if self.board[pos] == p:
for direction in (SLIDE_LEFT, SLIDE_RIGHT):
dest = pos + direction
if 0 <= dest < self.BOARD_SIZE and self.board[dest] == 0:
actions.append(S3Action(SLIDE_ACTION, pos, direction, p))
return actions
def make_action(self, action: S3Action) -> Tuple[tuple, float, bool]:
if self.game_over:
return self.get_state(), 0.0, True
p = self.current_player
opp = 3 - p
reward = 0.0
if action.action_type == PLACE_ACTION:
if self.hand[p] <= 0 or self.board[action.position] != 0:
return self.get_state(), -1.0, False
self.board[action.position] = p
self.hand[p] -= 1
reward = 0.3
elif action.action_type == SLIDE_ACTION:
dest = action.position + action.direction
if (self.board[action.position] != p or
dest < 0 or dest >= self.BOARD_SIZE or
self.board[dest] != 0):
return self.get_state(), -1.0, False
self.board[action.position] = 0
self.board[dest] = p
reward = 0.5
self.move_history.append(action)
self.move_count += 1
# Win check
won, win_type, cells = self._check_win(p)
if won:
self.game_over = True
self.winner = p
self.win_cells = cells
reward = 100.0
self.event_log.append(f"P{p} wins via {win_type}!")
else:
# Repetition / draw detection — defaultdict handles missing keys safely
state_key = self.get_state_key()
self.seen_states[state_key] += 1
if self.seen_states[state_key] >= 3:
self.game_over = True
self.winner = None
reward = 0.0
self.event_log.append("Draw: position repeated 3 times.")
elif self.move_count >= self.MAX_MOVES:
self.game_over = True
self.winner = None
reward = 0.0
self.event_log.append("Draw: max moves reached.")
else:
self.current_player = opp
return self.get_state(), reward, self.game_over
def _check_win(self, player: int) -> Tuple[bool, str, Optional[List[int]]]:
opp = 3 - player
for i in range(self.BOARD_SIZE - 2):
if (self.board[i] == player and
self.board[i+1] == opp and
self.board[i+2] == player):
return True, f"Surround [{i},{i+1},{i+2}]", [i, i+1, i+2]
# Triple (safety — shouldn't happen with 2 pieces, but guard it)
for i in range(self.BOARD_SIZE - 2):
if all(self.board[i+j] == player for j in range(3)):
return True, f"Triple [{i},{i+1},{i+2}]", [i, i+1, i+2]
return False, "", None
def check_win_for(self, player: int) -> bool:
won, _, _ = self._check_win(player)
return won
def get_piece_positions(self, player: int) -> List[int]:
return [i for i in range(self.BOARD_SIZE) if self.board[i] == player]
# ------------------------------------------------------------------
# Heuristic evaluation
# ------------------------------------------------------------------
def evaluate_position(self, player: int) -> float:
if self.winner == player:
return 100000.0
if self.winner is not None and self.winner != player:
return -100000.0
opp = 3 - player
score = 0.0
my_pos = self.get_piece_positions(player)
op_pos = self.get_piece_positions(opp)
# Surround potential for me
if len(my_pos) == 2:
p1, p2 = sorted(my_pos)
gap = p2 - p1
if gap == 2:
mid = (p1 + p2) // 2
if self.board[mid] == opp:
score += 2000 # Opponent is sandwiched — immediate win possible
elif self.board[mid] == 0:
score += 400
elif gap == 3:
score += 150
elif gap == 1:
score += 80
# Opponent surround threat
if len(op_pos) == 2:
p1, p2 = sorted(op_pos)
gap = p2 - p1
if gap == 2:
mid = (p1 + p2) // 2
if self.board[mid] == player:
score -= 3000 # I am sandwiched — imminent loss
elif self.board[mid] == 0:
score -= 500
elif gap == 3:
score -= 200
elif gap == 1:
score -= 100
# Center preference
center_bonus = {0: 10, 1: 20, 2: 30, 3: 20, 4: 10}
for pos in my_pos:
score += center_bonus.get(pos, 10)
for pos in op_pos:
score -= center_bonus.get(pos, 10)
# Mobility — safe: save/restore current_player around get_valid_actions
saved_cp = self.current_player
self.current_player = player
my_moves = len(self.get_valid_actions())
self.current_player = opp
op_moves = len(self.get_valid_actions())
self.current_player = saved_cp # always restored
score += (my_moves - op_moves) * 25
# Hand pieces left
score += self.hand[player] * 20
score -= self.hand[opp] * 20
# Piece-to-opponent distance: opponent sandwiched between my pieces
if len(my_pos) == 2 and len(op_pos) >= 1:
p1, p2 = sorted(my_pos)
for op in op_pos:
if p1 < op < p2:
score += 300
gap_to_surround = (p2 - p1) - 2
score += max(0, 300 - gap_to_surround * 100)
# Threat lookahead (uses copy so no mutation)
my_threats = self._count_surround_threats(player)
op_threats = self._count_surround_threats(opp)
score += my_threats * 500
score -= op_threats * 500
# Edge penalty
edge_penalty = {0: -15, 4: -15, 1: -5, 3: -5, 2: 0}
for pos in my_pos:
score += edge_penalty.get(pos, 0)
return score
def _count_surround_threats(self, player: int) -> int:
"""
Count legal actions for `player` that immediately produce a win.
Uses a fresh copy each time — no mutation of self.
"""
threats = 0
# Temporarily set current_player so get_valid_actions returns correct set
saved_cp = self.current_player
self.current_player = player
candidates = self.get_valid_actions()
self.current_player = saved_cp
for action in candidates:
sim = self.copy()
sim.current_player = player
sim.make_action(action)
if sim.winner == player:
threats += 1
return threats
def get_board_info(self) -> Dict:
info = {}
for p in [1, 2]:
info[f'p{p}_hand'] = self.hand[p]
info[f'p{p}_placed'] = self.PIECES_PER_PLAYER - self.hand[p]
info[f'p{p}_pos'] = self.get_piece_positions(p)
info['empty'] = [i for i in range(self.BOARD_SIZE) if self.board[i] == 0]
info['move_count'] = self.move_count
info['seen_max'] = max(self.seen_states.values()) if self.seen_states else 0
return info
def get_action_hints(self) -> Dict[str, str]:
hints = {}
p = self.current_player
for action in self.get_valid_actions():
key = action.to_key()
sim = self.copy()
sim.make_action(action)
if sim.winner == p:
hints[key] = "⚡ WIN!"
continue
opp = 3 - p
opp_threats = 0
for opp_act in sim.get_valid_actions():
sim3 = sim.copy()
sim3.make_action(opp_act)
if sim3.winner == opp:
opp_threats += 1
if opp_threats > 0:
hints[key] = "⚠️ Risky"
elif action.action_type == SLIDE_ACTION:
hints[key] = "↔️ Slide"
else:
hints[key] = "📍 Place"
return hints
# ============================================================================
# MCTS Node
# ============================================================================
class S3MCTSNode:
def __init__(self, game: Shift3Game, parent=None,
action: Optional[S3Action] = None, prior: float = 1.0):
self.game = game
self.parent = parent
self.action = action
self.prior = prior
self.children: Dict[str, 'S3MCTSNode'] = {}
self.visit_count = 0
self.value_sum = 0.0
self.is_expanded = False
@property
def value(self) -> float:
return self.value_sum / max(1, self.visit_count)
def ucb_score(self, parent_visits: int, c_puct: float = 1.5) -> float:
q = self.value
u = c_puct * self.prior * math.sqrt(parent_visits) / (1 + self.visit_count)
return q + u
def select_child(self, c_puct: float = 1.5) -> 'S3MCTSNode':
return max(self.children.values(),
key=lambda c: c.ucb_score(self.visit_count, c_puct))
def expand(self, policy_priors: Dict[str, float]):
actions = self.game.get_valid_actions()
if not actions:
return
total = sum(policy_priors.values()) or len(actions)
for act in actions:
key = act.to_key()
child_game = self.game.copy()
child_game.make_action(act)
prior = policy_priors.get(key, 1.0) / total
self.children[key] = S3MCTSNode(child_game, parent=self,
action=act, prior=prior)
self.is_expanded = True
def backup(self, value: float):
self.visit_count += 1
self.value_sum += value
if self.parent:
self.parent.backup(-value)
# ============================================================================
# AlphaZero-Inspired Shift-3 Agent
# ============================================================================
class Shift3Agent:
"""
Hybrid agent: MCTS (PUCT) + Negamax/Alpha-Beta + Q-Learning + Policy Table.
Handles mixed PLACE/SLIDE action space with loop-detection awareness.
"""
def __init__(self, player_id: int, lr: float = 0.3, gamma: float = 0.97,
epsilon: float = 1.0, mcts_sims: int = 20, minimax_depth: int = 2):
self.player_id = player_id
self.lr = lr
self.gamma = gamma
self.epsilon = epsilon
self.epsilon_decay = 0.97
self.epsilon_min = 0.02
self.mcts_sims = mcts_sims
self.minimax_depth = minimax_depth
self.c_puct = 1.5
self.temperature = 1.0
self.q_table: Dict[str, Dict[str, float]] = \
defaultdict(lambda: defaultdict(float))
self.policy_table: Dict[str, Dict[str, float]] = \
defaultdict(lambda: defaultdict(float))
self.visit_table: Dict[str, int] = defaultdict(int)
self.wins = 0
self.losses = 0
self.draws = 0
self.total_moves = 0
self.surround_wins = 0
# ------------------------------------------------------------------
def get_policy_priors(self, game: Shift3Game) -> Dict[str, float]:
state_key = game.get_state_key()
actions = game.get_valid_actions()
priors: Dict[str, float] = {}
for act in actions:
key = act.to_key()
learned = self.policy_table[state_key].get(key, 0.0)
q_val = self.q_table[state_key].get(key, 0.0)
prior = 1.0 + max(0.0, learned) + max(0.0, q_val) * 0.5
# Immediate win
sim = game.copy()
sim.make_action(act)
if sim.winner == game.current_player:
priors[key] = prior + 10000.0
continue
# Block opponent's immediate win (check from current game, not post-move)
opp = 3 - game.current_player
opp_chk = game.copy()
opp_chk.current_player = opp
for opp_act in opp_chk.get_valid_actions():
s = opp_chk.copy()
s.make_action(opp_act)
if s.winner == opp:
prior += 600.0
# Slide is generally richer tactically
if act.action_type == SLIDE_ACTION:
prior += 40.0
# Discourage loops
sim_key = sim.get_state_key()
repeat_count = game.seen_states.get(sim_key, 0)
if repeat_count >= 1:
prior *= max(0.1, 1.0 - repeat_count * 0.3)
# Center value
center_vals = {0: 10, 1: 20, 2: 40, 3: 20, 4: 10}
dest = act.position + act.direction if act.action_type == SLIDE_ACTION \
else act.position
prior += center_vals.get(dest, 10)
# Closing-in bonus for slide
my_pos = game.get_piece_positions(game.current_player)
if len(my_pos) == 2 and act.action_type == SLIDE_ACTION:
p1, p2 = sorted(my_pos)
old_gap = p2 - p1
remaining = [p for p in my_pos if p != act.position]
new_poss = remaining + [dest]
if len(new_poss) == 2:
np1, np2 = sorted(new_poss)
new_gap = np2 - np1
if new_gap < old_gap:
prior += 80.0
# Surround trap: I'll sandwich opponent
if new_gap == 2:
mid = (np1 + np2) // 2
if game.board[mid] == opp:
prior += 500.0
priors[key] = max(0.01, prior)
return priors
# ------------------------------------------------------------------
def mcts_search(self, game: Shift3Game) -> S3MCTSNode:
root = S3MCTSNode(game.copy())
for _ in range(self.mcts_sims):
node = root
sim_game = game.copy()
while node.is_expanded and node.children and not sim_game.game_over:
node = node.select_child(self.c_puct)
sim_game.make_action(node.action)
if not sim_game.game_over:
priors = self.get_policy_priors(sim_game)
node.expand(priors)
value = self._evaluate_leaf(sim_game)
node.backup(value)
return root
def _evaluate_leaf(self, game: Shift3Game) -> float:
if game.game_over:
if game.winner == self.player_id:
return 1.0
elif game.winner is not None:
return -1.0
return 0.0
score = self._negamax(game, self.minimax_depth, -float('inf'), float('inf'),
game.current_player == self.player_id)
return math.tanh(score / 1000.0)
def _negamax(self, game: Shift3Game, depth: int,
alpha: float, beta: float, maximizing: bool) -> float:
if depth == 0 or game.game_over:
return game.evaluate_position(self.player_id)
actions = game.get_valid_actions()
if not actions:
return game.evaluate_position(self.player_id)
# Move ordering
scored = []
for act in actions:
sim = game.copy()
sim.make_action(act)
scored.append((act, sim.evaluate_position(self.player_id)))
scored.sort(key=lambda x: x[1], reverse=maximizing)
if maximizing:
best = -float('inf')
for act, _ in scored:
sim = game.copy()
sim.make_action(act)
val = self._negamax(sim, depth-1, alpha, beta, False)
best = max(best, val)
alpha = max(alpha, val)
if beta <= alpha:
break
return best
else:
best = float('inf')
for act, _ in scored:
sim = game.copy()
sim.make_action(act)
val = self._negamax(sim, depth-1, alpha, beta, True)
best = min(best, val)
beta = min(beta, val)
if beta <= alpha:
break
return best
# ------------------------------------------------------------------
def choose_action(self, game: Shift3Game,
training: bool = True) -> Optional[S3Action]:
actions = game.get_valid_actions()
if not actions:
return None
# Immediate win
for act in actions:
sim = game.copy()
sim.make_action(act)
if sim.winner == self.player_id:
self.total_moves += 1
return act
# Block opponent's immediate win
opp = 3 - self.player_id
opp_chk = game.copy()
opp_chk.current_player = opp
opp_can_win = False
for opp_act in opp_chk.get_valid_actions():
s = opp_chk.copy()
s.make_action(opp_act)
if s.winner == opp:
opp_can_win = True
break
if opp_can_win:
for block_act in actions:
sim = game.copy()
sim.make_action(block_act)
opp_still_wins = False
for opp_act2 in sim.get_valid_actions():
s2 = sim.copy()
s2.make_action(opp_act2)
if s2.winner == opp:
opp_still_wins = True
break
if not opp_still_wins:
self.total_moves += 1
return block_act
# Epsilon-greedy exploration
if training and random.random() < self.epsilon:
self.total_moves += 1
return random.choice(actions)
# MCTS
root = self.mcts_search(game)
if not root.children:
self.total_moves += 1
return random.choice(actions)
if training and self.temperature > 0.1:
visits = {key: c.visit_count for key, c in root.children.items()}
total = sum(visits.values())
if total > 0:
keys = list(visits.keys())
probs = [visits[k] / total for k in keys]
chosen_key = random.choices(keys, weights=probs)[0]
chosen = root.children[chosen_key].action
else:
chosen = random.choice(actions)
else:
best_key = max(root.children.items(),
key=lambda x: x[1].visit_count)[0]
chosen = root.children[best_key].action
# Update policy table
state_key = game.get_state_key()
total_v = sum(c.visit_count for c in root.children.values())
for key, child in root.children.items():
self.policy_table[state_key][key] = \
child.visit_count / max(1, total_v)
self.total_moves += 1
return chosen
# ------------------------------------------------------------------
def update_from_game(self, history: List[Tuple[str, str, int]],
result: Optional[int]):
for state_key, action_key, player in reversed(history):
if player != self.player_id:
continue
if result == self.player_id:
reward = 1.0
elif result is None:
reward = 0.0
else:
reward = -1.0
old_q = self.q_table[state_key][action_key]
self.q_table[state_key][action_key] = old_q + self.lr * (reward - old_q)
old_p = self.policy_table[state_key][action_key]
self.policy_table[state_key][action_key] = \
old_p + self.lr * (reward - old_p)
self.visit_table[state_key] += 1
def decay_epsilon(self):
self.epsilon = max(self.epsilon_min, self.epsilon * self.epsilon_decay)
self.temperature = max(0.1, self.temperature * 0.99)
def reset_stats(self):
self.wins = 0
self.losses = 0
self.draws = 0
self.total_moves = 0
self.surround_wins = 0
def get_stats(self) -> Dict:
total = self.wins + self.losses + self.draws
return {
'wins': self.wins, 'losses': self.losses, 'draws': self.draws,
'total': total,
'win_rate': self.wins / max(1, total),
'policies': len(self.policy_table),
'q_states': len(self.q_table),
'epsilon': self.epsilon,
'temperature': self.temperature,
'total_moves': self.total_moves,
'surround_wins': self.surround_wins,
}
# ============================================================================
# Self-Play Training
# ============================================================================
def play_s3_game(agent1: Shift3Agent, agent2: Shift3Agent,
training: bool = True) -> Optional[int]:
game = Shift3Game()
history: List[Tuple[str, str, int]] = []
agents = {1: agent1, 2: agent2}
while not game.game_over:
current = game.current_player
agent = agents[current]
state_key = game.get_state_key()
action = agent.choose_action(game, training)
if action is None:
break
history.append((state_key, action.to_key(), current))
game.make_action(action)
result = game.winner
if training:
agent1.update_from_game(history, result)
agent2.update_from_game(history, result)
if result == 1:
agent1.wins += 1
agent2.losses += 1
elif result == 2:
agent2.wins += 1
agent1.losses += 1
else:
agent1.draws += 1
agent2.draws += 1
return result
# ============================================================================
# Visualization
# ============================================================================
CELL_POS_LABELS = {0: "A", 1: "B", 2: "C", 3: "D", 4: "E"}
def draw_shift3_board(board: List[int], hand: Dict[int, int],
title: str = "Shift-3",
last_action: Optional[S3Action] = None,
win_cells: Optional[List[int]] = None,
move_count: int = 0) -> plt.Figure:
fig, ax = plt.subplots(figsize=(11, 4))
fig.patch.set_facecolor('#0e1117')
ax.set_facecolor('#0e1117')
cell_w = 1.8
cell_h = 1.6
gap = 0.15
colors_map = {0: '#111122', 1: '#1a0505', 2: '#050515'}
piece_colors = {1: '#DC143C', 2: '#1E90FF'}
edge_colors = {0: '#333344', 1: '#8B0000', 2: '#000080'}
for idx in range(5):
x = idx * (cell_w + gap)
cell_val = board[idx]
face = colors_map[cell_val]
edge = edge_colors[cell_val]
lw = 1.5
is_dest = last_action and (
(last_action.action_type == PLACE_ACTION and
last_action.position == idx) or
(last_action.action_type == SLIDE_ACTION and
(last_action.position + last_action.direction) == idx)
)
is_origin = (last_action and
last_action.action_type == SLIDE_ACTION and
last_action.position == idx)
if win_cells and idx in win_cells:
face = '#0a1a00'; edge = '#00FF44'; lw = 4
elif is_dest:
edge = '#FFFFFF'; lw = 3
elif is_origin:
face = '#222222'; edge = '#666666'
rect = plt.Rectangle((x, 0.0), cell_w, cell_h,
facecolor=face, edgecolor=edge, linewidth=lw)
ax.add_patch(rect)
# Square label
ax.text(x + cell_w/2, 0.15,
f"{CELL_POS_LABELS[idx]}[{idx}]",
ha='center', va='bottom', fontsize=9, color='#555577')
# Piece
if cell_val != 0:
ax.text(x + cell_w/2, cell_h/2 + 0.1, '●',
ha='center', va='center', fontsize=44,
color=piece_colors[cell_val], fontweight='bold', zorder=4)
# Win star
if win_cells and idx in win_cells:
ax.text(x + cell_w/2, cell_h - 0.2, '★',
ha='center', va='center', fontsize=16,
color='#FFFF00', zorder=5)
# Action arrow
if is_dest and last_action.action_type == SLIDE_ACTION:
sym = '←' if last_action.direction == -1 else '→'
ax.text(x + cell_w/2, 0.05, sym,
ha='center', va='bottom', fontsize=14,
color='#FFCC00', zorder=5)
elif is_dest and last_action.action_type == PLACE_ACTION:
ax.text(x + cell_w/2, 0.05, '↓',
ha='center', va='bottom', fontsize=14,
color='#CCFFCC', zorder=5)
# Connectors
for idx in range(4):
x1 = idx * (cell_w + gap) + cell_w
x2 = x1 + gap
ax.annotate("", xy=(x2, cell_h/2), xytext=(x1, cell_h/2),
arrowprops=dict(arrowstyle="<->", color='#444466', lw=1.5))
ax.set_xlim(-0.2, 5 * (cell_w + gap) + 0.4)
ax.set_ylim(-0.6, cell_h + 0.8)
ax.set_aspect('equal')
ax.axis('off')
ax.set_title(title, fontsize=14, color='#CCFFCC', fontweight='bold', pad=12)
h1_str = "🔴 " * hand[1] + "○ " * (Shift3Game.PIECES_PER_PLAYER - hand[1])
h2_str = "🔵 " * hand[2] + "○ " * (Shift3Game.PIECES_PER_PLAYER - hand[2])
ax.text(0, -0.4, f"P1 Hand: {h1_str}", fontsize=10, color='#FF9999')
ax.text(5*(cell_w+gap)*0.5, -0.4, f"P2 Hand: {h2_str}",
fontsize=10, color='#9999FF')
ax.text(5*(cell_w+gap)-0.3, -0.4, f"Move #{move_count}",
fontsize=9, color='#888888', ha='right')
p1_patch = mpatches.Patch(color='#DC143C', label='Player 1 (Red)')
p2_patch = mpatches.Patch(color='#1E90FF', label='Player 2 (Blue)')
ax.legend(handles=[p1_patch, p2_patch], loc='upper right',
facecolor='#0e1117', edgecolor='#334455',
labelcolor='white', fontsize=9)
return fig
def draw_board_heatmap(game: Shift3Game, player: int) -> plt.Figure:
fig, axes = plt.subplots(1, 2, figsize=(12, 3))
fig.patch.set_facecolor('#0e1117')
for p, ax in zip([1, 2], axes):
ax.set_facecolor('#0e1117')
scores = []
for pos in range(game.BOARD_SIZE):
if game.board[pos] == 0:
sim = game.copy()
sim.board[pos] = p
s = sim.evaluate_position(p)
sim.board[pos] = 0
scores.append(s)
else:
scores.append(0)
arr = np.array(scores).reshape(1, -1)
ax.imshow(arr, cmap='RdYlGn', aspect='auto',
vmin=min(scores)-1, vmax=max(scores)+1)
for i, s in enumerate(scores):
ax.text(i, 0, f"{s:.0f}", ha='center', va='center',
fontsize=9, color='black', fontweight='bold')
ax.set_xticks(range(game.BOARD_SIZE))
ax.set_xticklabels(
[f"{CELL_POS_LABELS[i]}[{i}]" for i in range(game.BOARD_SIZE)],
color='#AAAACC')
ax.set_yticks([])
pcolor = '#DC143C' if p == 1 else '#1E90FF'
ax.set_title(f"P{p} Cell Value Heatmap", color=pcolor, fontweight='bold')
for spine in ax.spines.values():
spine.set_edgecolor('#334455')
fig.suptitle("⟷ Cell Evaluation Heatmap", color='#CCFFCC',
fontsize=13, fontweight='bold')
plt.tight_layout()
return fig
def draw_action_history(move_history: List[S3Action]) -> plt.Figure:
fig, ax = plt.subplots(figsize=(10, 3))
fig.patch.set_facecolor('#0e1117')
ax.set_facecolor('#1a2a1a')
for spine in ax.spines.values():
spine.set_edgecolor('#334455')
ax.tick_params(colors='#AACCAA')
turns = list(range(1, len(move_history)+1))
slide_t = [t for t, a in zip(turns, move_history)
if a.action_type == SLIDE_ACTION]
place_t = [t for t, a in zip(turns, move_history)
if a.action_type == PLACE_ACTION]
p1_t = [t for t, a in zip(turns, move_history) if a.player == 1]
p2_t = [t for t, a in zip(turns, move_history) if a.player == 2]
ax.scatter(slide_t, [1.2]*len(slide_t), marker='<',
color='#FFD700', s=120, label='SLIDE', zorder=3)
ax.scatter(place_t, [0.8]*len(place_t), marker='^',
color='#AAFFAA', s=120, label='PLACE', zorder=3)
for t in p1_t:
ax.axvline(x=t, color='#DC143C', alpha=0.25, linewidth=2)
for t in p2_t:
ax.axvline(x=t, color='#1E90FF', alpha=0.25, linewidth=2)
for t, a in zip(turns, move_history):
dest = a.position + a.direction if a.action_type == SLIDE_ACTION \
else a.position
y = 1.2 if a.action_type == SLIDE_ACTION else 0.8
ax.text(t, y+0.18, CELL_POS_LABELS.get(dest, '?'),
ha='center', va='center', fontsize=7, color='#FFFFFF')
ax.set_xlim(0, len(move_history)+1)
ax.set_ylim(0.3, 1.7)
ax.set_yticks([0.8, 1.2])
ax.set_yticklabels(['PLACE', 'SLIDE'], color='#AACCAA', fontsize=10)
ax.set_xlabel('Turn Number', color='#AACCAA')
ax.set_title('Action Sequence (Red=P1, Blue=P2)',
color='#CCFFCC', fontweight='bold')
ax.legend(facecolor='#1a2a1a', edgecolor='#334455', labelcolor='white')
return fig
def draw_training_charts(history: Dict) -> plt.Figure:
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
fig.patch.set_facecolor('#0e1117')
for ax in axes.flat:
ax.set_facecolor('#1a2a1a')
ax.tick_params(colors='#AACCAA')
for spine in ax.spines.values():
spine.set_edgecolor('#334455')
eps = history.get('episode', [])
if not eps:
return fig
axes[0,0].plot(eps, history.get('agent1_wins',[]), color='#DC143C', lw=2, label='P1 Wins')
axes[0,0].plot(eps, history.get('agent2_wins',[]), color='#1E90FF', lw=2, label='P2 Wins')
axes[0,0].plot(eps, history.get('draws',[]), color='#888888', lw=1.5, ls='--', label='Draws')
axes[0,0].set_title('Win/Draw Distribution', color='#CCFFCC')
axes[0,0].legend(facecolor='#1a2a1a', edgecolor='#334455', labelcolor='white')
axes[0,1].plot(eps, history.get('agent1_epsilon',[]), color='#FF6B6B', lw=2, label='P1 ε')
axes[0,1].plot(eps, history.get('agent2_epsilon',[]), color='#66B3FF', lw=2, label='P2 ε')
axes[0,1].set_title('Exploration Rate (ε)', color='#CCFFCC')
axes[0,1].legend(facecolor='#1a2a1a', edgecolor='#334455', labelcolor='white')
axes[1,0].plot(eps, history.get('agent1_policies',[]), color='#FF6B6B', lw=2, label='P1')
axes[1,0].plot(eps, history.get('agent2_policies',[]), color='#66B3FF', lw=2, label='P2')
axes[1,0].set_title('Policy Table Size', color='#CCFFCC')
axes[1,0].legend(facecolor='#1a2a1a', edgecolor='#334455', labelcolor='white')
a1w = history.get('agent1_wins',[0])
a2w = history.get('agent2_wins',[0])
dr = history.get('draws',[0])
totals = [max(1, a+b+d) for a,b,d in zip(a1w, a2w, dr)]
axes[1,1].plot(eps, [w/t for w,t in zip(a1w, totals)],
color='#DC143C', lw=2, label='P1 WR')
axes[1,1].plot(eps, [w/t for w,t in zip(a2w, totals)],
color='#1E90FF', lw=2, label='P2 WR')
axes[1,1].set_ylim(0, 1)
axes[1,1].set_title('Win Rate Over Time', color='#CCFFCC')
axes[1,1].legend(facecolor='#1a2a1a', edgecolor='#334455', labelcolor='white')
fig.suptitle('⟷ Shift-3 Training Analytics', fontsize=15,
color='#CCFFCC', fontweight='bold')
plt.tight_layout()
return fig
# ============================================================================