-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGameState.py
More file actions
1020 lines (884 loc) · 34.8 KB
/
Copy pathGameState.py
File metadata and controls
1020 lines (884 loc) · 34.8 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
"""
Stores current state of game
Determines valid moves
Keeps a move log
"""
from __future__ import annotations
from re import S
from typing import Optional,List
import sys
import chess
from chess.pgn import ChildNode, Game
import chess.polyglot
import random
import threading
import queue
import pyttsx3
import book
from move_speech import expand_moves_for_speech
class Voce:
"""Asynchronous TTS.
Architecture: a single persistent worker thread owns the pyttsx3 engine
and consumes a queue of requests. The voice is selected ONCE by the worker
(not by the main thread). This avoids the SAPI5 apartment-threading problem
on Windows: a `setProperty('voice', ...)` executed on a COM thread
different from the one that runs `say()` is silently ignored, causing the
reading to fall back to the system default voice (e.g. Italian if that is
what the system is set to).
"""
def __init__(self, lang_prefix="en"):
self._lang_prefix = lang_prefix
self._queue: "queue.Queue[str]" = queue.Queue()
self._engine = None # created in the worker
self._voice_id = None # populated by _apply_voice
self._engine_ready = threading.Event()
self._worker_thread = threading.Thread(
target=self._worker, name="TTSWorker", daemon=True
)
self._worker_thread.start()
# We briefly wait for initialization, so the first leggi() does not
# start before the engine and voice are ready.
self._engine_ready.wait(timeout=3.0)
def _find_target_voice_id(self, voices):
"""Returns the voice.id to set, or None if no English voice was found.
Precedence order identical to `_select_voice`."""
try:
from config import config as _cfg
target = (getattr(_cfg, 'tts_voice', '') or '').strip().lower()
except Exception:
target = ''
if target:
for v in voices:
hay = ((v.name or '') + ' ' + (v.id or '')).lower()
if target in hay:
return v.id, f"config '{target}'"
name_hints = ('english', 'en-', 'en_', 'zira', 'david', 'mark', 'hazel',
'eva', 'james', 'susan')
for v in voices:
name_l = (v.name or '').lower()
if any(h in name_l for h in name_hints):
return v.id, "name-hint"
for v in voices:
try:
for lang in (v.languages or []):
if isinstance(lang, bytes):
lang = lang.decode('utf-8', errors='replace')
if self._lang_prefix in str(lang).lower():
return v.id, "lang-prefix"
except Exception:
continue
return None, None
def _apply_rate_from_config(self):
"""Sets the rate of the TTS engine.
On Windows we use the SAPI5 driver directly; on other systems we let
the pyttsx3 driver handle the property.
"""
try:
from config import config as _cfg
wpm = int(getattr(_cfg, 'tts_rate', 150) or 150)
except Exception:
wpm = 150
if sys.platform != 'win32':
try:
self._engine.setProperty('rate', wpm)
except Exception:
pass
return
# Conversion wpm -> SAPI5 rate (-10..+10). 200 wpm = 0 (Windows default).
if wpm < 100:
sapi_rate = -10
elif wpm > 350:
sapi_rate = 10
else:
sapi_rate = int(round((wpm - 200) / 15))
driver = getattr(getattr(self._engine, 'proxy', None), '_driver', None)
sapi = getattr(driver, '_tts', None)
if sapi is None:
return
try:
sapi.Rate = sapi_rate
except Exception as e:
print(f"TTS apply rate failed: {e}")
def _apply_voice(self, voice_id, source):
"""Sets the voice of the TTS engine."""
if sys.platform != 'win32':
try:
self._engine.setProperty('voice', voice_id)
self._voice_id = voice_id
return True
except Exception as e:
print(f"TTS apply voice failed: {e}")
return False
# Canonical path to SAPI5 in modern pyttsx3
driver = getattr(getattr(self._engine, 'proxy', None), '_driver', None)
sapi = getattr(driver, '_tts', None)
if sapi is None:
print("TTS: SAPI5 driver not found (unexpected pyttsx3 version)")
return False
try:
voices = sapi.GetVoices()
n = voices.Count
for i in range(n):
token = voices.Item(i)
if token.Id == voice_id:
sapi.Voice = token
self._voice_id = voice_id
# Direct verification on the COM object
actual = sapi.Voice.Id if sapi.Voice else None
return actual == voice_id
except Exception as e:
print(f"TTS apply voice failed: {e}")
return False
def _select_voice(self):
"""Chooses and applies an English voice; prints diagnostics at startup."""
try:
voices = list(self._engine.getProperty('voices'))
except Exception as e:
print(f"TTS: cannot list voices: {e}")
return
voice_id, source = self._find_target_voice_id(voices)
if voice_id is None:
print(f"TTS: no voice '{self._lang_prefix}' found, OS default")
return
ok = self._apply_voice(voice_id, source)
def _worker(self):
try:
self._engine = pyttsx3.init()
self._engine.setProperty('volume', 1.0)
self._select_voice()
self._apply_rate_from_config()
except Exception as e:
print(f"TTS init failed: {e}")
self._engine_ready.set()
return
self._engine_ready.set()
while True:
text = self._queue.get()
if text is None: # sentinel (unused today: thread is a daemon)
break
try:
# On Windows some pyttsx3 SAPI5 versions lose the setting
# between consecutive say() calls and revert to the default.
if sys.platform == 'win32' and self._voice_id is not None:
try:
driver = getattr(getattr(self._engine, 'proxy', None),
'_driver', None)
sapi = getattr(driver, '_tts', None)
if sapi is not None:
voices = sapi.GetVoices()
for i in range(voices.Count):
token = voices.Item(i)
if token.Id == self._voice_id:
sapi.Voice = token
break
except Exception:
pass
self._engine.say(text)
self._engine.runAndWait()
except Exception as e:
# Typically "run loop already started" if stop() arrives
# while say() is queued: no-op.
print(f"TTS warning: {e}")
def leggi(self, testo: str):
"""Queues a text to read; any reading in progress is interrupted.
Returns immediately (does not block)."""
if self._engine is None:
return
self._drain_queue()
self._engine_stop_safe()
testo = testo.replace("0-0-0", "long castle").replace("0-0", "castle")
self._queue.put(testo)
def stop(self):
"""Interrupts the TTS reading in progress (no-op if none is in progress)."""
self._drain_queue()
self._engine_stop_safe()
def refresh_rate(self):
"""Re-applies the rate from the current `config.tts_rate`. To be called
after an onchange of the TTS speed slider in the Setup menu."""
if self._engine is None:
return
self._apply_rate_from_config()
def _drain_queue(self):
try:
while True:
self._queue.get_nowait()
except queue.Empty:
pass
def _engine_stop_safe(self):
if self._engine is None:
return
try:
self._engine.stop()
except Exception:
pass
voce = Voce()
# --- Standard PGN annotation glyphs (NAGs) ---------------------------------
# Uses the actual Unicode symbols on screen (a few may not render if the
# move-log font lacks the glyph). The PGN file always stores the numeric NAG,
# so the canonical glyph survives save/load regardless of the font.
NAG_SYMBOL = {
1: "!", 2: "?", 3: "!!", 4: "??", 5: "!?", 6: "?!", 7: "□",
10: "=", 13: "∞", 14: "⩲", 15: "⩱", 16: "±", 17: "∓",
18: "+−", 19: "−+", 22: "⨀", 23: "⨀",
}
# Ordered (nag, label) choices shown in the annotation menu.
NAG_CHOICES = [
(1, "! good move"), (2, "? mistake"), (3, "!! brilliant move"),
(4, "?? blunder"), (5, "!? interesting move"), (6, "?! dubious move"),
(7, "□ only move"),
(10, "= equal position"), (13, "∞ unclear position"),
(14, "⩲ White slightly better"), (15, "⩱ Black slightly better"),
(16, "± White better"), (17, "∓ Black better"),
(18, "+− White winning"), (19, "−+ Black winning"),
(22, "⨀ zugzwang"),
]
class GameState:
def __init__(self):
# first char is the color, second char the piece, -- is empty
self.pgn = Game()
self.moveLog:List[Move] = []
self.header = []
self.node = self.pgn
def get_hash(self):
"""
Returns the hash of the current position
"""
if self.node is None:
return None
return chess.polyglot.zobrist_hash(self.board())
def board(self) -> chess.Board:
"""
Returns the current board
"""
if self.node is None:
return None
return self.node.board()
def setPgn(self, pgn: chess.pgn.Game):
"""
Sets the PGN game
"""
self.pgn = pgn
self.node = pgn
self.moveLog = []
self.header = []
for key, value in pgn.headers.items():
if key in ['Date','White','Black','Result']:
self.header.append(key)
self.header.append(value)
# Rebuild the move log from the PGN
# self.goToLastMove()
def leggiCommentoCorrente(self):
if self.node and self.node.comment:
voce.leggi(expand_moves_for_speech(self.node.comment))
def doNextMainMove(self)->bool:
'''
do next main move
returns:
true of there was some move to do
'''
newNode = self.node.next()
if newNode is None:
return False
self.makeChessMove(newNode.move)
return True
def is_end(self):
# Checks if this node is the last node in the current variation.
return True if self.node is None else self.node.is_end()
def checkNextMove(self, move:chess.Move)->bool:
"""
Check if the input move is the next main move in the current variation
params:
move:Move move to check
Returns:
boolean
"""
newNode:Optional[ChildNode] = self.node.next()
if newNode is None:
return False
return move == newNode.move
def getPgn(self)->chess.pgn.Game:
"""
Returns a PGN game
"""
header = self.getHeader()
# Set headers, if available
if header:
headers = dict(zip(header[::2], header[1::2]))
for key, value in headers.items():
self.pgn.headers[key] = value
return self.pgn
def to_PgnString(self) -> str:
'''Export the whole game to a PGN string (headers, variations and
comments included).'''
exporter = chess.pgn.StringExporter(headers=True, variations=True, comments=True)
return self.getPgn().accept(exporter)
def setHeader(self, header):
self.header = header
def getHeader(self):
return self.header
def setFen(self, fen:str):
'''
Sets the board as stated by the fen str, resetting move log
'''
self.pgn = chess.pgn.Game()
self.pgn.headers["FEN"] = fen
self.pgn.setup(fen)
self.pgn.variations = [] # removes all previous moves
self.node = self.pgn
self.moveLog = []
def _pgnMakeMove(self, move:Move)->bool:
'''
Make a move in the current pgn game
Args:
move:Move move to make
'''
if self.node is None:
return False
# Check whether the move is already present among the variations
for idx, child in enumerate(self.node.variations):
existing_move = child.move
if existing_move == move:
self.node = child
self.leggiCommentoCorrente()
return False
# Otherwise: create a new variation
new_node = self.node.add_variation(move) # creates and adds
self.node = new_node
return True
def getNextMoves(self)->List[chess.Move]:
'''
Get the next moves in the current variation
returns:
a list of moves
'''
if self.node is None:
return []
nextNodes:List[ChildNode] = self.node.variations
return [n.move for n in nextNodes]
def getContinuationLines(self, max_plies: int = 20) -> List[str]:
'''
The continuation of the current line as readable text: the upcoming
mainline moves from the current position, in SAN with move numbers
(e.g. ["12. Nf3 Nc6", "13. Bb5 a6", ...]). Capped at `max_plies`
half-moves so it fits the side panel. Used by the "PGN moves" panel.
'''
if self.node is None:
return []
board = self.node.board()
lines: List[str] = []
pending = "" # a White move waiting for Black's reply
n = self.node
for _ in range(max_plies):
nxt = n.next()
if nxt is None:
break
try:
san = board.san(nxt.move)
except Exception:
break
num = board.fullmove_number
if board.turn: # White to move
pending = f"{num}. {san}"
else: # Black to move
if pending:
lines.append(f"{pending} {san}")
pending = ""
else:
lines.append(f"{num}... {san}")
board.push(nxt.move)
n = nxt
if pending:
lines.append(pending)
return lines
def getNextMoveLines(self) -> List[str]:
'''
Lines for the "PGN moves" panel: the next MAIN move plus any
alternative variations available right here (only the immediate next
move of each), so that while navigating you can see a fork coming.
Main line first (with move number); the alternatives are listed
below, indented. [] at the end of the line.
'''
if self.node is None:
return []
children = self.node.variations
if not children:
return []
board = self.node.board()
num = board.fullmove_number
sep = "." if board.turn else "..." # "13." (White) / "13..." (Black)
lines: List[str] = []
for idx, child in enumerate(children):
try:
san = board.san(child.move)
except Exception:
continue
if idx == 0:
lines.append(f"{num}{sep} {san}") # next main move
else:
lines.append(f" - {san}") # alternative next move
return lines
@staticmethod
def count_leaves(node) -> int:
'''
Number of leaf nodes (terminal lines) in `node`'s subtree; a node with no
variations counts as a single leaf. Used to weight the random choice of
the next move so that every leaf line is equiprobable -- only the number
of branches matters, not their depth.
'''
if not node.variations:
return 1
return sum(GameState.count_leaves(child) for child in node.variations)
def makeNextMove(self):
'''
Play a random move among the stored variations, weighting each candidate
by the number of leaf lines below it, so that every terminal line is
equally likely to be reached (e.g. a branch with 3 leaves is chosen 3/5
of the time against a sibling with 2 leaves).
'''
if self.node is None or self.is_end():
return None
children = self.node.variations
if not children:
return None
weights = [GameState.count_leaves(child) for child in children]
node = random.choices(children, weights=weights, k=1)[0]
if node.comment:
print(node.comment)
move: Move = Move.fromChessMove(node.move, self)
self.makeMove(move)
return move
def gotoFirstMove(self) -> bool:
"""
Go to the first move in the current game
"""
if self.node is None:
return False
while self.node.parent is not None:
self.node = self.node.parent
if len(self.moveLog) > 0:
del self.moveLog[-1]
return True
def goToLastMove(self)->bool:
"""
Go to the last move in the current game
"""
if self.node is None:
return False
while self.node.variations:
node = self.node.variations[0] # Follow only the main line
move = Move.fromChessMove(node.move, self)
self.makeMove(move)
return True
def getNextMainMove(self):
'''
Get the next move in the main line
'''
if self.node is None:
return None
nextNode:ChildNode = self.node.next()
return None if nextNode is None else nextNode.move
def makeChessMove(self, move: chess.Move):
"""
Takes a chess move and executes it. Does not work for special moves
param move: chess.Move
return:
"""
if move is None:
return
self.makeMove(Move.fromChessMove(move, self))
def getMovesFromBook(self)->List[chess.polyglot.Entry]:
"""
Returns a list of moves from the book for the current position
"""
if self.node is None:
return []
return book.getMovesFromBook(self.board())
def makeMove(self, move:Move):
"""
Takes a move and executes it. Does not work for special moves
param move: Move
return:
"""
self._pgnMakeMove(move.move)
#self.pgn.board.push(move.move)
self.moveLog.append(move)
def undoMove(self):
'''
Rethreat last move
'''
if len(self.moveLog) == 0:
return
# update pgn node
self.node = self.node.parent if self.node is not None else None
#self.board.pop()
del self.moveLog[-1]
def truncateAfterCurrent(self) -> bool:
'''
Delete every move/variation that follows the current position
(the current node is kept). Returns True if something was removed.
'''
if self.node is None or not self.node.variations:
return False
self.node.variations = []
return True
def deleteCurrentVariation(self) -> bool:
'''
Remove the current move (and everything after it) from the game tree and
step back to the parent node. Returns False on the start position
(there is no move to delete).
'''
if self.node is None or self.node.parent is None:
return False
parent = self.node.parent
parent.remove_variation(self.node.move)
self.node = parent
if self.moveLog:
del self.moveLog[-1]
return True
def isInVariation(self) -> bool:
'''
True if the current node lies inside a variation (i.e. somewhere on the
path from the root a node is NOT the main/first child of its parent).
'''
n = self.node
while n is not None and n.parent is not None:
if n.parent.variations and n.parent.variations[0] is not n:
return True
n = n.parent
return False
def deleteCurrentVariationLine(self) -> bool:
'''
Delete the ENTIRE variation the current node belongs to -- back to the
point where it branched off the parent line -- and return to that branch
point. Returns False if the current node is on the main line.
'''
if self.node is None or self.node.parent is None:
return False
# Head = nearest ancestor-or-self that is a non-main child of its parent.
head = None
n = self.node
while n.parent is not None:
if n.parent.variations and n.parent.variations[0] is not n:
head = n
break
n = n.parent
if head is None:
return False # on the main line, no variation
# How many moves from head.parent down to the current node (to fix moveLog).
steps = 0
n = self.node
while n is not head.parent:
n = n.parent
steps += 1
head.parent.remove_variation(head.move)
self.node = head.parent
if steps:
del self.moveLog[max(0, len(self.moveLog) - steps):]
return True
def promoteCurrentVariation(self) -> bool:
'''
Promote the variation the current node belongs to so that it becomes the
MAIN line at the point where it branches off its enclosing line. If that
branch point is on the game's main line, the current variation becomes
the main line.
Operates ONE level (the nearest branch going up): when nested in a
sub-variation it makes the line main "within the scope of the line it is
in"; call it again to keep promoting the next level up. Only the order of
the variations is changed -- self.node, the board and moveLog are
untouched (the current position simply now lies on the main line).
Returns False if the current node is already on the main line.
'''
if self.node is None or self.node.parent is None:
return False
# Head = nearest ancestor-or-self that is a non-main child of its parent
# (same lookup as deleteCurrentVariationLine).
head = None
n = self.node
while n.parent is not None:
if n.parent.variations and n.parent.variations[0] is not n:
head = n
break
n = n.parent
if head is None:
return False # already on the main line
head.parent.promote_to_main(head)
return True
def setMoveNag(self, nag: int) -> bool:
'''
Set the (single) annotation glyph on the current move, REPLACING any
previous one -- a move's assessment is unique. A falsy nag (0/None)
just clears the annotation. No-op (returns False) on the start position,
which has no move to annotate.
'''
if self.node is None or self.node.parent is None:
return False
self.node.nags.clear()
if nag:
self.node.nags.add(nag)
return True
def clearMoveNags(self) -> bool:
'''Remove every annotation glyph from the current move.'''
if self.node is None or self.node.parent is None:
return False
self.node.nags.clear()
return True
def getMoveGlyphs(self) -> List[str]:
'''
Glyph string for EACH move in moveLog (same length, aligned by index);
'' means no annotation. Covers the whole current line (not just the last
move) so the move list can show the marks next to every move.
'''
line = []
n = self.node
while n is not None and n.parent is not None:
line.append(n)
n = n.parent
line.reverse()
glyphs = ["".join(NAG_SYMBOL[x] for x in sorted(node.nags) if x in NAG_SYMBOL)
for node in line]
while len(glyphs) < len(self.moveLog):
glyphs.append("")
return glyphs[:len(self.moveLog)]
def setMoveComment(self, text: str) -> bool:
'''
Set the text comment (PGN comment) on the current move; an empty string
clears it. No-op (returns False) on the start position.
'''
if self.node is None or self.node.parent is None:
return False
self.node.comment = text or ""
return True
def getMoveComment(self) -> str:
'''Text comment attached to the current move ('' if none).'''
if self.node is None:
return ""
return self.node.comment or ""
def goToNode(self, node) -> bool:
'''
Position the game on `node` (anywhere in the tree, including inside a
variation), rebuilding moveLog along the path from the root. Used to
jump straight to a move clicked in the notation view.
'''
if node is None:
return False
path = []
n = node
while n is not None and n.parent is not None:
path.append(n)
n = n.parent
path.reverse()
self.moveLog = []
# Rebuild moveLog directly. We deliberately do NOT replay via
# makeChessMove/_pgnMakeMove: that reads every move's comment aloud (TTS,
# blocking), making navigation take seconds when moves are annotated.
for nd in path:
self.node = nd.parent # board context before this move
self.moveLog.append(Move.fromChessMove(nd.move, self))
self.node = node
return True
# --- Transposition awareness (analysis): the same position can appear in
# several variations of one game by move-order inversion. ----------------
def _iter_nodes(self):
"""All nodes of the game tree (root + every variation), DFS order."""
out = []
def walk(n):
out.append(n)
for child in n.variations:
walk(child)
if self.pgn is not None:
walk(self.pgn)
return out
def _position_index(self):
"""zobrist -> [nodes with that exact position], DFS order (index 0 is the
CANONICAL first occurrence). Built on demand (analysis trees are small)."""
idx = {}
for n in self._iter_nodes():
try:
z = chess.polyglot.zobrist_hash(n.board())
except Exception:
continue
idx.setdefault(z, []).append(n)
return idx
def canonical_node(self, node=None):
"""The first (canonical) node sharing `node`'s exact position."""
node = node if node is not None else self.node
if node is None:
return None
occ = self._position_index().get(chess.polyglot.zobrist_hash(node.board()))
return occ[0] if occ else node
def transpositions_of(self, node=None):
"""Other nodes (besides `node`) with the same exact position; [] if unique."""
node = node if node is not None else self.node
if node is None:
return []
z = chess.polyglot.zobrist_hash(node.board())
return [n for n in self._position_index().get(z, []) if n is not node]
def is_frozen(self, node=None):
"""True if `node` is a DUPLICATE occurrence (not the canonical one): its
continuations belong to the canonical node, so no new moves should grow it."""
node = node if node is not None else self.node
if node is None:
return False
return self.canonical_node(node) is not node
def node_line_san(self, node) -> str:
"""SAN line from the root to `node`, e.g. '1.e4 d6 2.d4 Nf6'. '' for root."""
chain = []
n = node
while n is not None and n.parent is not None:
chain.append(n)
n = n.parent
chain.reverse()
board = self.pgn.board() if self.pgn is not None else chess.Board()
out = []
for nd in chain:
if board.turn == chess.WHITE:
out.append(f"{board.fullmove_number}.{board.san(nd.move)}")
else:
out.append(board.san(nd.move))
board.push(nd.move)
return " ".join(out)
def find_node_by_fen(self, fen: str):
"""The canonical node whose position matches `fen` (pieces+turn+castling+
en-passant), or None. For 'search a position inside this game'."""
try:
z = chess.polyglot.zobrist_hash(chess.Board(fen))
except Exception:
return None
occ = self._position_index().get(z)
return occ[0] if occ else None
def next_transposition(self, node=None):
"""The next node sharing `node`'s position, cycling through ALL its
occurrences (twins); None if the position is unique."""
node = node if node is not None else self.node
if node is None:
return None
occ = self._position_index().get(chess.polyglot.zobrist_hash(node.board()), [])
if len(occ) < 2:
return None
idx = next((k for k, n in enumerate(occ) if n is node), 0)
return occ[(idx + 1) % len(occ)]
def whiteToMove(self)->chess.Color:
return self.board().turn
def colorToMove(self)->str:
return "w" if self.board().turn else "b"
def colorAt(self, row:int, col:int)->str:
"""
Color of the piece in a board position
:param row:int
:param col:int
return:string
w or b
"""
p = self.board().piece_at((7-row)*8+col)
if p is None:
return "-"
if p.color:
return "w"
return "b"
def getValidMoves(self)->List[Move]:
return [Move.fromChessMove(m, self) for m in self.node.board().legal_moves]
def stdValidMoves(self)->List[Move]:
dest = []
for m in self.board().legal_moves:
# if chess.square_rank(m.from_square) != fromRow:
# continue
# if chess.square_file(m.from_square) != fromCol:
# continue
mm = Move.fromChessMove(m, self)
if m.promotion is not None:
mm.promoteToPiece(m.promotion)
dest.append(mm)
return dest
def piece_at(self, r:int, c:int)->str:
'''
Piece in a board position
Args:
r: piece row
c: piece column
Returns:
piece code in a format like --, wB, bN etc
'''
moved = self.board().piece_at((7-r)*8+c)
if moved is None:
return "--"
movedColor = moved.symbol().upper()
color = self.colorAt(r, c)
return color + movedColor
def inCheck(self)->bool:
return self.board().is_check()
def checkMate(self)->bool:
return self.board().is_checkmate()
def staleMate(self)->bool:
return self.board().is_stalemate()
class Move:
ranksToRows = {"1": 7, "2": 6, "3": 5, "4": 4, "5": 3, "6": 2, "7": 1, "8": 0}
rowsToRanks = {v: k for k, v in ranksToRows.items()}
filesToCols = {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7}
colsToFiles = {v: k for k, v in filesToCols.items()}
@classmethod
def fromChessMove(cls, m:chess.Move, game:GameState)->Move:
if m is None:
return None
move= cls((7-chess.square_rank(m.from_square),chess.square_file(m.from_square)),
(7 - chess.square_rank(m.to_square), chess.square_file(m.to_square)),
game
)
if m.promotion is not None:
move.promoteToPiece(m.promotion)
return move
def __init__(self, startSq:tuple[int,int], stopSq:tuple[int,int], game:GameState):
'''
Creates a chess move from a user move made on board
'''
self.startRow = startSq[0]
self.startCol = startSq[1]
self.stopRow = stopSq[0]
self.stopCol = stopSq[1]
self.uci:str = self.getRankFile(startSq[0], startSq[1]) + \
self.getRankFile(stopSq[0], stopSq[1])
self.move:chess.Move = chess.Move.from_uci(self.uci)
self.pieceMoved:str = game.piece_at(self.startRow, self.startCol)
self.pieceCaptured:str = game.piece_at(self.stopRow, self.stopCol)
try:
self.prettyPrint = game.board().san(self.move)
except Exception as e:
print('Conversion error:', str(e))
self.prettyPrint = self.move.uci()
self.enPassant = game.board().is_en_passant(self.move)
def promoteToPiece(self, p) -> "Move":
"""Adds the promotion suffix and returns `self`.
Accepts as input two forms historically passed by callers:
- `chess.PieceType` (int 1..6), used by internal code (e.g. stdValidMoves).
- A string ending with the piece symbol ('q'/'Q'/'wQ'/'bN'/...) as
returned by `BoardScreen.choosePromotion` (format "<color><piece>").
None / empty string / non-promotable piece -> no-op.
Returns `self` (Move) -- not `self.move` (chess.Move) -- so that
`move = move.promoteToPiece(piece)` keeps holding a Move and the
`__eq__` against the validMoves entries keeps working.
"""
if not p:
return self
if isinstance(p, int):
symbol = chess.piece_symbol(p)
else:
symbol = str(p).strip()[-1:].lower()
if symbol not in {"q", "r", "b", "n"}:
return self
if not self.uci.endswith(symbol):
self.uci = self.uci + symbol
self.move = chess.Move.from_uci(self.uci)