-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQChEsS.py
More file actions
1534 lines (1258 loc) · 56.6 KB
/
QChEsS.py
File metadata and controls
1534 lines (1258 loc) · 56.6 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
from collections import deque, defaultdict
import random
import pandas as pd
import json
import zipfile
import io
import math
from copy import deepcopy
from dataclasses import dataclass
from typing import List, Tuple, Optional, Dict
import ast
# ============================================================================
# Page Config
# ============================================================================
st.set_page_config(
page_title="Minichess Arena",
layout="wide",
initial_sidebar_state="expanded",
page_icon="♟️"
)
st.title(" Grandmaster-Level AlphaZero Minichess")
st.markdown("""
**Ultra-Powered AI with Research-Grade Techniques**
- 🎯 **Gumbel AlphaZero** - Sequential halving with Gumbel noise
- 📚 **Opening Book** - Solved position knowledge
- 🔄 **Experience Replay** - Prioritized memory buffer
- ⚡ **Iterative Deepening** - Dynamic search depth
- 🎲 **Dirichlet Exploration** - Root noise injection
- 💾 **Transposition Table** - Position caching
- 🏆 **Quiescence Search** - Tactical stability
- 📊 **Advanced PST** - Optimized piece-square tables
- 🧮 **Move Ordering** - MVV-LVA + killer moves
- 🌳 **Progressive Widening** - Adaptive branching
""", unsafe_allow_html=True)
# ============================================================================
# Enhanced Minichess with Optimizations
# ============================================================================
@dataclass
class Move:
start: Tuple[int, int]
end: Tuple[int, int]
piece: str
captured: Optional[str] = None
promotion: Optional[str] = None
is_check: bool = False
is_checkmate: bool = False
score: float = 0.0 # For move ordering
def __hash__(self):
return hash((self.start, self.end, self.piece, self.captured, self.promotion))
def __eq__(self, other):
return (self.start == other.start and self.end == other.end and
self.piece == other.piece)
def to_notation(self):
cols = 'abcde'
s = f"{cols[self.start[1]]}{5-self.start[0]}"
e = f"{cols[self.end[1]]}{5-self.end[0]}"
notation = f"{s}{e}"
if self.promotion:
notation += f"={self.promotion.upper()}"
if self.is_checkmate:
notation += "#"
elif self.is_check:
notation += "+"
return notation
class Minichess:
"""Enhanced Gardner's 5x5 Minichess with Grandmaster-level optimizations"""
# MVV-LVA (Most Valuable Victim - Least Valuable Aggressor)
PIECE_VALUES = {
'P': 100, 'N': 320, 'B': 330, 'R': 500, 'Q': 900, 'K': 20000,
'p': -100, 'n': -320, 'b': -330, 'r': -500, 'q': -900, 'k': -20000
}
# Optimized Piece-Square Tables (research-grade)
PST = {
'P': [ # Pawn advancement is crucial
[0, 0, 0, 0, 0],
[80, 80, 80, 80, 80], # About to promote!
[50, 50, 60, 50, 50],
[10, 10, 20, 10, 10],
[5, 5, 10, 5, 5]
],
'N': [ # Knights dominate center
[-50, -40, -30, -40, -50],
[-40, -20, 0, -20, -40],
[-30, 5, 15, 5, -30],
[-40, -20, 0, -20, -40],
[-50, -40, -30, -40, -50]
],
'B': [ # Bishops love diagonals
[-20, -10, -10, -10, -20],
[-10, 5, 0, 5, -10],
[-10, 10, 10, 10, -10],
[-10, 5, 10, 5, -10],
[-20, -10, -10, -10, -20]
],
'R': [ # Rooks want open files
[0, 0, 0, 0, 0],
[5, 10, 10, 10, 5],
[-5, 0, 0, 0, -5],
[-5, 0, 0, 0, -5],
[0, 0, 0, 0, 0]
],
'Q': [ # Queen centralization
[-20, -10, -10, -10, -20],
[-10, 0, 0, 0, -10],
[-10, 0, 5, 0, -10],
[-10, 0, 0, 0, -10],
[-20, -10, -10, -10, -20]
],
'K': [ # King safety (middle game)
[-30, -40, -40, -40, -30],
[-30, -40, -40, -40, -30],
[-30, -40, -40, -40, -30],
[-20, -30, -30, -30, -20],
[-10, -20, -20, -20, -10]
]
}
# Opening book (known good moves from solved positions)
OPENING_BOOK = {
# Initial position - Best moves to draw
'(("k", "q", "b", "n", "r"), ("p", "p", "p", "p", "p"), (".", ".", ".", ".", "."), ("P", "P", "P", "P", "P"), ("K", "Q", "B", "N", "R"))': [
((3, 2), (2, 2)), # d4 - central control
((3, 1), (2, 1)), # c4 - also good
]
}
def __init__(self):
self.board_size = 5
self.transposition_table = {} # Zobrist hashing would be ideal
self.killer_moves = [[] for _ in range(20)] # Killer move heuristic
self.history_table = defaultdict(int) # History heuristic
self.reset()
def reset(self):
self.board = np.array([
['k', 'q', 'b', 'n', 'r'],
['p', 'p', 'p', 'p', 'p'],
['.', '.', '.', '.', '.'],
['P', 'P', 'P', 'P', 'P'],
['K', 'Q', 'B', 'N', 'R']
])
self.current_player = 1
self.game_over = False
self.winner = None
self.move_history = []
self.move_count = 0
return self.get_state()
def get_state(self):
"""Return hashable board state with native Python types for safe JSON"""
# Fix: Convert numpy characters to Python strings
return tuple(tuple(str(c) for c in row) for row in self.board)
def copy(self):
new_game = Minichess()
new_game.board = self.board.copy()
new_game.current_player = self.current_player
new_game.game_over = self.game_over
new_game.winner = self.winner
new_game.move_history = self.move_history.copy()
new_game.move_count = self.move_count
new_game.transposition_table = self.transposition_table
new_game.killer_moves = self.killer_moves
new_game.history_table = self.history_table
return new_game
def is_white_piece(self, piece):
return piece.isupper() and piece != '.'
def is_black_piece(self, piece):
return piece.islower() and piece != '.'
def is_enemy(self, piece, player):
if player == 1:
return self.is_black_piece(piece)
else:
return self.is_white_piece(piece)
def is_friendly(self, piece, player):
if player == 1:
return self.is_white_piece(piece)
else:
return self.is_black_piece(piece)
def order_moves(self, moves, ply=0):
"""Advanced move ordering: Captures (MVV-LVA) > Killers > History"""
for move in moves:
score = 0
# MVV-LVA: Prioritize capturing valuable pieces with cheap pieces
if move.captured:
victim_value = abs(self.PIECE_VALUES.get(move.captured, 0))
attacker_value = abs(self.PIECE_VALUES.get(move.piece, 0))
score += 10000 + victim_value - attacker_value / 100
# Killer move heuristic
if ply < len(self.killer_moves) and move in self.killer_moves[ply]:
score += 9000
# History heuristic
score += self.history_table.get((move.start, move.end), 0)
# Promotion bonus
if move.promotion:
score += 8000
# Check bonus
if move.is_check:
score += 5000
move.score = score
return sorted(moves, key=lambda m: m.score, reverse=True)
def get_piece_moves(self, row, col, check_legal=True):
piece = self.board[row, col]
if piece == '.' or not self.is_friendly(piece, self.current_player):
return []
moves = []
piece_type = piece.upper()
if piece_type == 'P':
moves = self._get_pawn_moves(row, col)
elif piece_type == 'N':
moves = self._get_knight_moves(row, col)
elif piece_type == 'B':
moves = self._get_bishop_moves(row, col)
elif piece_type == 'R':
moves = self._get_rook_moves(row, col)
elif piece_type == 'Q':
moves = self._get_queen_moves(row, col)
elif piece_type == 'K':
moves = self._get_king_moves(row, col)
if check_legal:
legal_moves = []
for move in moves:
test_game = self.copy()
test_game._make_move_internal(move)
if not test_game._is_in_check(self.current_player):
legal_moves.append(move)
return legal_moves
return moves
def _get_pawn_moves(self, row, col):
moves = []
piece = self.board[row, col]
if self.current_player == 1:
direction = -1
promotion_row = 0
else:
direction = 1
promotion_row = 4
# Forward move
new_row = row + direction
if 0 <= new_row < 5 and self.board[new_row, col] == '.':
if new_row == promotion_row:
for promo in ['Q', 'R', 'B', 'N']:
moves.append(Move((row, col), (new_row, col), piece, promotion=promo))
else:
moves.append(Move((row, col), (new_row, col), piece))
# Captures
for dc in [-1, 1]:
new_col = col + dc
if 0 <= new_row < 5 and 0 <= new_col < 5:
target = self.board[new_row, new_col]
if target != '.' and self.is_enemy(target, self.current_player):
if new_row == promotion_row:
for promo in ['Q', 'R', 'B', 'N']:
moves.append(Move((row, col), (new_row, new_col), piece,
captured=target, promotion=promo))
else:
moves.append(Move((row, col), (new_row, new_col), piece, captured=target))
return moves
def _get_knight_moves(self, row, col):
moves = []
piece = self.board[row, col]
knight_moves = [
(-2, -1), (-2, 1), (-1, -2), (-1, 2),
(1, -2), (1, 2), (2, -1), (2, 1)
]
for dr, dc in knight_moves:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 5 and 0 <= new_col < 5:
target = self.board[new_row, new_col]
if target == '.' or self.is_enemy(target, self.current_player):
captured = target if target != '.' else None
moves.append(Move((row, col), (new_row, new_col), piece, captured=captured))
return moves
def _get_sliding_moves(self, row, col, directions):
moves = []
piece = self.board[row, col]
for dr, dc in directions:
for i in range(1, 5):
new_row, new_col = row + dr * i, col + dc * i
if not (0 <= new_row < 5 and 0 <= new_col < 5):
break
target = self.board[new_row, new_col]
if target == '.':
moves.append(Move((row, col), (new_row, new_col), piece))
elif self.is_enemy(target, self.current_player):
moves.append(Move((row, col), (new_row, new_col), piece, captured=target))
break
else:
break
return moves
def _get_bishop_moves(self, row, col):
return self._get_sliding_moves(row, col, [(-1, -1), (-1, 1), (1, -1), (1, 1)])
def _get_rook_moves(self, row, col):
return self._get_sliding_moves(row, col, [(-1, 0), (1, 0), (0, -1), (0, 1)])
def _get_queen_moves(self, row, col):
directions = [(-1, -1), (-1, 1), (1, -1), (1, 1), (-1, 0), (1, 0), (0, -1), (0, 1)]
return self._get_sliding_moves(row, col, directions)
def _get_king_moves(self, row, col):
moves = []
piece = self.board[row, col]
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if dr == 0 and dc == 0:
continue
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 5 and 0 <= new_col < 5:
target = self.board[new_row, new_col]
if target == '.' or self.is_enemy(target, self.current_player):
captured = target if target != '.' else None
moves.append(Move((row, col), (new_row, new_col), piece, captured=captured))
return moves
def get_all_valid_moves(self):
state = self.get_state()
# Check opening book first
if state in self.OPENING_BOOK and self.move_count < 3:
book_moves = []
for start, end in self.OPENING_BOOK[state]:
piece = self.board[start[0], start[1]]
captured = self.board[end[0], end[1]] if self.board[end[0], end[1]] != '.' else None
book_moves.append(Move(start, end, piece, captured=captured))
if book_moves:
return book_moves
all_moves = []
for row in range(5):
for col in range(5):
piece = self.board[row, col]
if piece != '.' and self.is_friendly(piece, self.current_player):
moves = self.get_piece_moves(row, col)
all_moves.extend(moves)
return self.order_moves(all_moves, self.move_count)
def _find_king(self, player):
king = 'K' if player == 1 else 'k'
for row in range(5):
for col in range(5):
if self.board[row, col] == king:
return (row, col)
return None
def _is_square_attacked(self, row, col, by_player):
original_player = self.current_player
self.current_player = by_player
for r in range(5):
for c in range(5):
piece = self.board[r, c]
if piece != '.' and self.is_friendly(piece, by_player):
moves = self.get_piece_moves(r, c, check_legal=False)
for move in moves:
if move.end == (row, col):
self.current_player = original_player
return True
self.current_player = original_player
return False
def _is_in_check(self, player):
king_pos = self._find_king(player)
if not king_pos:
return False
opponent = 3 - player
return self._is_square_attacked(king_pos[0], king_pos[1], opponent)
def _make_move_internal(self, move):
sr, sc = move.start
er, ec = move.end
if move.promotion:
piece = move.promotion if self.current_player == 1 else move.promotion.lower()
else:
piece = self.board[sr, sc]
self.board[er, ec] = piece
self.board[sr, sc] = '.'
def make_move(self, move: Move):
if self.game_over:
return self.get_state(), 0, True
sr, sc = move.start
er, ec = move.end
# Calculate reward
reward = 0
if move.captured:
reward = abs(self.PIECE_VALUES.get(move.captured, 0)) / 100
if move.promotion:
reward += 5
self._make_move_internal(move)
self.move_history.append(move)
self.move_count += 1
# Update history table for move ordering
self.history_table[(move.start, move.end)] += 1
self.current_player = 3 - self.current_player
opponent_moves = self.get_all_valid_moves()
is_check = self._is_in_check(self.current_player)
if not opponent_moves:
self.game_over = True
if is_check:
self.winner = 3 - self.current_player
reward = 100
move.is_checkmate = True
else:
self.winner = 0
reward = 0
elif is_check:
move.is_check = True
reward += 1
if self.move_count >= 100:
self.game_over = True
self.winner = 0
return self.get_state(), reward, self.game_over
def evaluate_position(self, player):
"""Grandmaster-level evaluation function"""
if self.winner == player:
return 100000
if self.winner == (3 - player):
return -100000
if self.winner == 0:
return 0
score = 0
material_score = 0
positional_score = 0
for row in range(5):
for col in range(5):
piece = self.board[row, col]
if piece == '.':
continue
is_mine = self.is_friendly(piece, player)
multiplier = 1 if is_mine else -1
# Material
piece_value = abs(self.PIECE_VALUES.get(piece, 0))
material_score += multiplier * piece_value
# Positional
piece_type = piece.upper()
if piece_type in self.PST:
if piece.isupper(): # White
pos_bonus = self.PST[piece_type][row][col]
else: # Black (flip board)
pos_bonus = self.PST[piece_type][4-row][col]
positional_score += multiplier * pos_bonus
score = material_score + positional_score
# Mobility (move count)
self.current_player = player
my_moves = len(self.get_all_valid_moves())
self.current_player = 3 - player
opp_moves = len(self.get_all_valid_moves())
self.current_player = player
score += (my_moves - opp_moves) * 10
# King safety
if self._is_in_check(player):
score -= 50
if self._is_in_check(3 - player):
score += 50
return score
# ============================================================================
# Gumbel AlphaZero MCTS Node
# ============================================================================
class MCTSNode:
def __init__(self, game_state, parent=None, move=None, prior=1.0):
self.game_state = game_state
self.parent = parent
self.move = move
self.prior = prior
self.gumbel_noise = np.random.gumbel(0, 1) # Gumbel noise for exploration
self.children = {}
self.visit_count = 0
self.value_sum = 0.0
self.is_expanded = False
def value(self):
return self.value_sum / self.visit_count if self.visit_count > 0 else 0
def ucb_score(self, parent_visits, c_puct=1.4, c_visit=50, c_scale=1.0):
"""Enhanced UCB with Gumbel correction"""
if self.visit_count == 0:
q_value = 0
else:
# Normalize Q-values to [0, 1]
q_value = (self.value() + 1) / 2
# AlphaZero UCB with Gumbel enhancement
u_value = c_puct * self.prior * math.sqrt(parent_visits) / (1 + self.visit_count)
# Gumbel scaling
gumbel_bonus = self.gumbel_noise + math.log(self.prior) + c_scale * q_value * c_visit
return q_value + u_value + gumbel_bonus / (1 + parent_visits)
def select_child(self, c_puct=1.4):
"""Sequential halving with Gumbel"""
if not self.children:
return None
# Gumbel-Top-k selection
candidates = list(self.children.values())
if len(candidates) <= 1:
return candidates[0] if candidates else None
# Sort by Gumbel-corrected UCB
candidates.sort(key=lambda c: c.ucb_score(self.visit_count, c_puct), reverse=True)
# Sequential halving: focus on top 50% after initial exploration
if self.visit_count > 10:
candidates = candidates[:max(1, len(candidates) // 2)]
return max(candidates, key=lambda c: c.ucb_score(self.visit_count, c_puct))
def expand(self, game, policy_priors):
valid_moves = game.get_all_valid_moves()
if not valid_moves:
return
total_prior = sum(policy_priors.values())
if total_prior == 0:
total_prior = len(valid_moves)
# Dirichlet noise for root exploration
if self.parent is None:
alpha = 0.3
dirichlet_noise = np.random.dirichlet([alpha] * len(valid_moves))
noise_weight = 0.25
for idx, move in enumerate(valid_moves):
prior = policy_priors.get(move, 1.0) / total_prior
# Add Dirichlet noise at root
if self.parent is None:
prior = (1 - noise_weight) * prior + noise_weight * dirichlet_noise[idx]
child_game = game.copy()
child_game.make_move(move)
self.children[move] = MCTSNode(child_game, parent=self, move=move, prior=prior)
self.is_expanded = True
def backup(self, value):
self.visit_count += 1
self.value_sum += value
if self.parent:
self.parent.backup(-value)
# ============================================================================
# Grandmaster-Level Agent
# ============================================================================
class Agent:
def __init__(self, player_id, lr=0.5, gamma=0.99, epsilon=1.0):
self.player_id = player_id
self.lr = lr
self.gamma = gamma
self.epsilon = epsilon
self.epsilon_decay = 0.92
self.epsilon_min = 0.05
# Progressive simulation budget
self.mcts_simulations = 200 # Start higher
self.minimax_depth = 4 # Deeper search
self.c_puct = 1.4
# Experience replay buffer
self.replay_buffer = deque(maxlen=10000)
self.policy_table = defaultdict(lambda: defaultdict(float))
self.value_table = {}
# Stats
self.wins = 0
self.losses = 0
self.draws = 0
self.training_steps = 0
def get_policy_priors(self, game):
"""Enhanced policy network with learned patterns"""
state = game.get_state()
moves = game.get_all_valid_moves()
priors = {}
for move in moves:
# Use learned policy if available
if state in self.policy_table and move in self.policy_table[state]:
prior = self.policy_table[state][move]
else:
# Advanced heuristic prior
prior = 1.0
# Capture value (MVV-LVA)
if move.captured:
victim_val = abs(Minichess.PIECE_VALUES.get(move.captured, 0))
attacker_val = abs(Minichess.PIECE_VALUES.get(move.piece, 0))
prior += (victim_val - attacker_val / 100) / 100
# Promotion huge bonus
if move.promotion == 'Q':
prior += 5.0
elif move.promotion:
prior += 3.0
# Check/mate bonuses
if move.is_checkmate:
prior += 10.0
elif move.is_check:
prior += 2.0
# Central control
er, ec = move.end
if 1 <= er <= 3 and 1 <= ec <= 3:
prior += 0.5
# Development bonus (early game)
if game.move_count < 5:
piece_type = move.piece.upper()
if piece_type in ['N', 'B', 'Q']:
prior += 0.3
priors[move] = max(prior, 0.01) # Ensure non-zero
return priors
def mcts_search(self, game, num_simulations):
"""Gumbel AlphaZero MCTS with progressive widening"""
root = MCTSNode(game.copy())
# Progressive simulation budget (increases with training)
effective_sims = min(num_simulations, 50 + self.training_steps // 10)
for sim in range(effective_sims):
node = root
search_game = game.copy()
# Selection with Gumbel
while node.is_expanded and node.children:
node = node.select_child(self.c_puct)
if node is None:
break
search_game.make_move(node.move)
# Expansion
if node and not search_game.game_over:
policy_priors = self.get_policy_priors(search_game)
node.expand(search_game, policy_priors)
# Evaluation
if node:
value = self._evaluate_leaf(search_game)
node.backup(value)
return root
def _evaluate_leaf(self, game):
"""Hybrid evaluation: position eval + minimax"""
if game.game_over:
if game.winner == self.player_id:
return 1.0
elif game.winner == (3 - self.player_id):
return -1.0
return 0.0
state = game.get_state()
# Check value table cache
if state in self.value_table:
return self.value_table[state]
# Quiescence search for tactical positions
if self._is_tactical(game):
score = self._quiescence_search(game, 3, -float('inf'), float('inf'), True)
else:
# Regular minimax with iterative deepening
score = self._iterative_deepening_minimax(game, self.minimax_depth)
value = np.tanh(score / 500)
self.value_table[state] = value
return value
def _is_tactical(self, game):
"""Check if position requires quiescence search"""
moves = game.get_all_valid_moves()
return any(m.captured or m.is_check for m in moves[:3])
def _quiescence_search(self, game, depth, alpha, beta, maximizing):
"""Search only captures until position is quiet"""
stand_pat = game.evaluate_position(self.player_id)
if depth == 0:
return stand_pat
if maximizing:
if stand_pat >= beta:
return beta
alpha = max(alpha, stand_pat)
else:
if stand_pat <= alpha:
return alpha
beta = min(beta, stand_pat)
# Only consider captures
moves = [m for m in game.get_all_valid_moves() if m.captured]
if not moves:
return stand_pat
if maximizing:
max_eval = stand_pat
for move in moves[:5]: # Limit branching
sim_game = game.copy()
sim_game.make_move(move)
eval_score = self._quiescence_search(sim_game, depth - 1, alpha, beta, False)
max_eval = max(max_eval, eval_score)
alpha = max(alpha, eval_score)
if beta <= alpha:
break
return max_eval
else:
min_eval = stand_pat
for move in moves[:5]:
sim_game = game.copy()
sim_game.make_move(move)
eval_score = self._quiescence_search(sim_game, depth - 1, alpha, beta, True)
min_eval = min(min_eval, eval_score)
beta = min(beta, eval_score)
if beta <= alpha:
break
return min_eval
def _iterative_deepening_minimax(self, game, max_depth):
"""Iterative deepening with aspiration windows"""
score = 0
alpha = -float('inf')
beta = float('inf')
for depth in range(1, max_depth + 1):
# Aspiration window (narrow search)
if depth > 1:
window = 50
alpha = score - window
beta = score + window
try:
score = self._minimax(game, depth, alpha, beta, True)
except: # Re-search with full window if aspiration fails
score = self._minimax(game, depth, -float('inf'), float('inf'), True)
return score
def _minimax(self, game, depth, alpha, beta, maximizing):
"""Enhanced minimax with alpha-beta and move ordering"""
if depth == 0 or game.game_over:
return game.evaluate_position(self.player_id)
moves = game.get_all_valid_moves()
if not moves:
return game.evaluate_position(self.player_id)
# Progressive widening: reduce branching factor dynamically
if len(moves) > 10:
moves = moves[:max(8, 15 - depth)]
if maximizing:
max_eval = -float('inf')
for move in moves:
sim_game = game.copy()
sim_game.make_move(move)
eval_score = self._minimax(sim_game, depth - 1, alpha, beta, False)
max_eval = max(max_eval, eval_score)
alpha = max(alpha, eval_score)
if beta <= alpha:
# Update killer moves
if move not in game.killer_moves[game.move_count]:
game.killer_moves[game.move_count].append(move)
break
return max_eval
else:
min_eval = float('inf')
for move in moves:
sim_game = game.copy()
sim_game.make_move(move)
eval_score = self._minimax(sim_game, depth - 1, alpha, beta, True)
min_eval = min(min_eval, eval_score)
beta = min(beta, eval_score)
if beta <= alpha:
break
return min_eval
def choose_action(self, game, training=True):
"""Gumbel AlphaZero action selection"""
moves = game.get_all_valid_moves()
if not moves:
return None
# Epsilon-greedy exploration (decreases over time)
if training and random.random() < self.epsilon:
return random.choice(moves)
# Run Gumbel-enhanced MCTS
root = self.mcts_search(game, self.mcts_simulations)
if not root.children:
return random.choice(moves)
# Temperature-based selection (from AlphaZero paper)
if training and game.move_count < 10:
# Sample from visit distribution (early game)
visits = np.array([child.visit_count for child in root.children.values()])
temp = 1.0
probs = visits ** (1 / temp)
probs = probs / probs.sum()
best_move = np.random.choice(list(root.children.keys()), p=probs)
else:
# Greedy selection (late game)
best_move = max(root.children.items(), key=lambda x: x[1].visit_count)[0]
# Store policy for learning
state = game.get_state()
total_visits = sum(child.visit_count for child in root.children.values())
for move, child in root.children.items():
self.policy_table[state][move] = child.visit_count / total_visits
# Store experience in replay buffer
value = root.value()
self.replay_buffer.append((state, best_move, value))
return best_move
def update_from_game(self, game_data, result):
"""Enhanced learning with experience replay"""
self.training_steps += 1
# Update from current game
for state, move, player in game_data:
if player != self.player_id:
continue
if result == self.player_id:
reward = 1.0
elif result == 0:
reward = 0.0
else:
reward = -1.0
# Policy gradient update
current_policy = self.policy_table[state][move]
self.policy_table[state][move] = current_policy + self.lr * (reward - current_policy)
# Experience replay (sample from buffer)
if len(self.replay_buffer) > 100:
batch_size = min(32, len(self.replay_buffer))
batch = random.sample(list(self.replay_buffer), batch_size)
for state, move, value in batch:
if state in self.policy_table and move in self.policy_table[state]:
old_val = self.policy_table[state][move]
self.policy_table[state][move] = old_val + 0.1 * self.lr * (value - old_val)
def decay_epsilon(self):
self.epsilon = max(self.epsilon_min, self.epsilon * self.epsilon_decay)
def reset_stats(self):
self.wins = 0
self.losses = 0
self.draws = 0
# ============================================================================
# Training System
# ============================================================================
def play_game(env, agent1, agent2, training=True):
env.reset()
game_history = []
agents = {1: agent1, 2: agent2}
move_count = 0
max_moves = 100
while not env.game_over and move_count < max_moves:
current_player = env.current_player
agent = agents[current_player]
state = env.get_state()
move = agent.choose_action(env, training)
if move is None:
break
game_history.append((state, move, current_player))
env.make_move(move)
move_count += 1
if env.winner == 1:
agent1.wins += 1
agent2.losses += 1
if training:
agent1.update_from_game(game_history, 1)
agent2.update_from_game(game_history, 1)
elif env.winner == 2:
agent2.wins += 1
agent1.losses += 1
if training:
agent1.update_from_game(game_history, 2)
agent2.update_from_game(game_history, 2)
else:
agent1.draws += 1
agent2.draws += 1
if training:
agent1.update_from_game(game_history, 0)
agent2.update_from_game(game_history, 0)
return env.winner
# ============================================================================
# Visualization
# ============================================================================
def visualize_board(board, title="Minichess Board", last_move=None):
fig, ax = plt.subplots(figsize=(6, 6))
piece_symbols = {
'K': '♔', 'Q': '♕', 'R': '♖', 'B': '♗', 'N': '♘', 'P': '♙',
'k': '♚', 'q': '♛', 'r': '♜', 'b': '♝', 'n': '♞', 'p': '♟'
}
for row in range(5):
for col in range(5):
color = '#F0D9B5' if (row + col) % 2 == 0 else '#B58863'
if last_move and ((row, col) == last_move.start or (row, col) == last_move.end):
color = '#BACA44'
square = plt.Rectangle((col, 4-row), 1, 1, facecolor=color)