-
-
Notifications
You must be signed in to change notification settings - Fork 574
Expand file tree
/
Copy pathpgn.py
More file actions
1914 lines (1514 loc) · 60.4 KB
/
Copy pathpgn.py
File metadata and controls
1914 lines (1514 loc) · 60.4 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
from __future__ import annotations
import abc
import dataclasses
import enum
import itertools
import logging
import re
import typing
import chess
import chess.engine
import chess.svg
from typing import Any, Callable, Dict, Generic, Iterable, Iterator, List, Literal, Mapping, MutableMapping, Set, TextIO, Tuple, Type, TypeVar, Optional, Union
from chess import Color, Square
LOGGER = logging.getLogger(__name__)
# Reference of Numeric Annotation Glyphs (NAGs):
# https://en.wikipedia.org/wiki/Numeric_Annotation_Glyphs
NAG_NULL = 0
NAG_GOOD_MOVE = 1
"""A good move. Can also be indicated by ``!`` in PGN notation."""
NAG_MISTAKE = 2
"""A mistake. Can also be indicated by ``?`` in PGN notation."""
NAG_BRILLIANT_MOVE = 3
"""A brilliant move. Can also be indicated by ``!!`` in PGN notation."""
NAG_BLUNDER = 4
"""A blunder. Can also be indicated by ``??`` in PGN notation."""
NAG_SPECULATIVE_MOVE = 5
"""A speculative move. Can also be indicated by ``!?`` in PGN notation."""
NAG_DUBIOUS_MOVE = 6
"""A dubious move. Can also be indicated by ``?!`` in PGN notation."""
NAG_FORCED_MOVE = 7
NAG_SINGULAR_MOVE = 8
NAG_WORST_MOVE = 9
NAG_DRAWISH_POSITION = 10
NAG_QUIET_POSITION = 11
NAG_ACTIVE_POSITION = 12
NAG_UNCLEAR_POSITION = 13
NAG_WHITE_SLIGHT_ADVANTAGE = 14
NAG_BLACK_SLIGHT_ADVANTAGE = 15
NAG_WHITE_MODERATE_ADVANTAGE = 16
NAG_BLACK_MODERATE_ADVANTAGE = 17
NAG_WHITE_DECISIVE_ADVANTAGE = 18
NAG_BLACK_DECISIVE_ADVANTAGE = 19
NAG_WHITE_ZUGZWANG = 22
NAG_BLACK_ZUGZWANG = 23
NAG_WHITE_MODERATE_COUNTERPLAY = 132
NAG_BLACK_MODERATE_COUNTERPLAY = 133
NAG_WHITE_DECISIVE_COUNTERPLAY = 134
NAG_BLACK_DECISIVE_COUNTERPLAY = 135
NAG_WHITE_MODERATE_TIME_PRESSURE = 136
NAG_BLACK_MODERATE_TIME_PRESSURE = 137
NAG_WHITE_SEVERE_TIME_PRESSURE = 138
NAG_BLACK_SEVERE_TIME_PRESSURE = 139
NAG_NOVELTY = 146
TAG_REGEX = re.compile(r"^\[([A-Za-z0-9][A-Za-z0-9_+#=:-]*)\s+\"([^\r]*)\"\]\s*$")
TAG_NAME_REGEX = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_+#=:-]*\Z")
MOVETEXT_REGEX = re.compile(r"""
(
[NBKRQ]?[a-h]?[1-8]?[\-x]?[a-h][1-8](?:=?[nbrqkNBRQK])?
|[PNBRQK]?@[a-h][1-8]
|--
|Z0
|0000
|@@@@
|O-O(?:-O)?
|0-0(?:-0)?
)
|(\{.*)
|(;.*)
|(\$[0-9]+)
|(\()
|(\))
|(\*|1-0|0-1|1/2-1/2)
|(\!N)
|([\?!]{1,2})
|(TN)
""", re.DOTALL | re.VERBOSE)
SKIP_MOVETEXT_REGEX = re.compile(r""";|\{|\}""")
CLOCK_REGEX = re.compile(r"""(?P<prefix>\s?)\[%clk\s(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+(?:\.\d*)?)\](?P<suffix>\s?)""")
EMT_REGEX = re.compile(r"""(?P<prefix>\s?)\[%emt\s(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+(?:\.\d*)?)\](?P<suffix>\s?)""")
EVAL_REGEX = re.compile(r"""
(?P<prefix>\s?)
\[%eval\s(?:
\#(?P<mate>[+-]?\d+)
|(?P<cp>[+-]?(?:\d{0,10}\.\d{1,2}|\d{1,10}\.?))
)(?:
,(?P<depth>\d+)
)?\]
(?P<suffix>\s?)
""", re.VERBOSE)
CAL_REGEX = re.compile(r"""
(?P<prefix>\s?)
\[%(?:cal)\s(?P<arrows>
[RGYB][a-h][1-8](?:[a-h][1-8])?
(?:,[RGYB][a-h][1-8](?:[a-h][1-8])?)*
)\]
(?P<suffix>\s?)
""", re.VERBOSE)
CSL_REGEX = re.compile(r"""
(?P<prefix>\s?)
\[%(?:csl)\s(?P<arrows>
[RGYB][a-h][1-8]?
(?:,[RGYB][a-h][1-8]?)*
)\]
(?P<suffix>\s?)
""", re.VERBOSE)
def _condense_affix(infix: str) -> Callable[[typing.Match[str]], str]:
def repl(match: typing.Match[str]) -> str:
if infix:
return match.group("prefix") + infix + match.group("suffix")
else:
return match.group("prefix") and match.group("suffix")
return repl
TAG_ROSTER = ["Event", "Site", "Date", "Round", "White", "Black", "Result"]
class SkipType(enum.Enum):
SKIP = None
SKIP = SkipType.SKIP
ResultT = TypeVar("ResultT", covariant=True)
class TimeControlType(enum.Enum):
UNKNOW = 0
UNLIMITED = 1
STANDARD = 2
RAPID = 3
BLITZ = 4
BULLET = 5
@dataclasses.dataclass
class TimeControlPart:
moves: int = 0
time: int = 0
increment: float = 0
delay: float = 0
@dataclasses.dataclass
class TimeControl:
"""
PGN TimeControl Parser
Spec: http://www.saremba.de/chessgml/standards/pgn/pgn-complete.htm#c9.6
Not Yet Implemented:
- Hourglass/Sandclock ('*' prefix)
- Differentiating between Bronstein and Simple Delay (Not part of the PGN Spec)
- More Info: https://en.wikipedia.org/wiki/Chess_clock#Timing_methods
"""
parts: list[TimeControlPart] = dataclasses.field(default_factory=list)
type: TimeControlType = TimeControlType.UNKNOW
class _AcceptFrame:
def __init__(self, node: ChildNode, *, is_variation: bool = False, sidelines: bool = True):
self.state = "pre"
self.node = node
self.is_variation = is_variation
self.variations = iter(itertools.islice(node.parent.variations, 1, None) if sidelines else [])
self.in_variation = False
class GameNode(abc.ABC):
parent: Optional[GameNode]
"""The parent node or ``None`` if this is the root node of the game."""
move: Optional[chess.Move]
"""
The move leading to this node or ``None`` if this is the root node of the
game.
"""
variations: List[ChildNode]
"""A list of child nodes."""
comment: str
"""
A comment that goes behind the move leading to this node. Comments
that occur before any moves are assigned to the root node.
"""
starting_comment: str
nags: Set[int]
def __init__(self, *, comment: str = "") -> None:
self.parent = None
self.move = None
self.variations = []
self.comment = comment
# Deprecated: These should be properties of ChildNode, but need to
# remain here for backwards compatibility.
self.starting_comment = ""
self.nags = set()
@abc.abstractmethod
def board(self) -> chess.Board:
"""
Gets a board with the position of the node.
For the root node, this is the default starting position (for the
``Variant``) unless the ``FEN`` header tag is set.
It's a copy, so modifying the board will not alter the game.
Complexity is `O(n)`.
"""
@abc.abstractmethod
def ply(self) -> int:
"""
Returns the number of half-moves up to this node, as indicated by
fullmove number and turn of the position.
See :func:`chess.Board.ply()`.
Usually this is equal to the number of parent nodes, but it may be
more if the game was started from a custom position.
Complexity is `O(n)`.
"""
def turn(self) -> Color:
"""
Gets the color to move at this node. See :data:`chess.Board.turn`.
Complexity is `O(n)`.
"""
return self.ply() % 2 == 0
def root(self) -> GameNode:
node = self
while node.parent:
node = node.parent
return node
def game(self) -> Game:
"""
Gets the root node, i.e., the game.
Complexity is `O(n)`.
"""
root = self.root()
assert isinstance(root, Game), "GameNode not rooted in Game"
return root
def end(self) -> GameNode:
"""
Follows the main variation to the end and returns the last node.
Complexity is `O(n)`.
"""
node = self
while node.variations:
node = node.variations[0]
return node
def is_end(self) -> bool:
"""
Checks if this node is the last node in the current variation.
Complexity is `O(1)`.
"""
return not self.variations
def starts_variation(self) -> bool:
"""
Checks if this node starts a variation (and can thus have a starting
comment). The root node does not start a variation and can have no
starting comment.
For example, in ``1. e4 e5 (1... c5 2. Nf3) 2. Nf3``, the node holding
1... c5 starts a variation.
Complexity is `O(1)`.
"""
if not self.parent or not self.parent.variations:
return False
return self.parent.variations[0] != self
def is_mainline(self) -> bool:
"""
Checks if the node is in the mainline of the game.
Complexity is `O(n)`.
"""
node = self
while node.parent:
parent = node.parent
if not parent.variations or parent.variations[0] != node:
return False
node = parent
return True
def is_main_variation(self) -> bool:
"""
Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation.
Complexity is `O(1)`.
"""
if not self.parent:
return True
return not self.parent.variations or self.parent.variations[0] == self
def __getitem__(self, move: Union[int, chess.Move, GameNode]) -> ChildNode:
try:
return self.variations[move] # type: ignore
except TypeError:
for variation in self.variations:
if variation.move == move or variation == move:
return variation
raise KeyError(move)
def __contains__(self, move: Union[int, chess.Move, GameNode]) -> bool:
try:
self[move]
except KeyError:
return False
else:
return True
def variation(self, move: Union[int, chess.Move, GameNode]) -> ChildNode:
"""
Gets a child node by either the move or the variation index.
"""
return self[move]
def has_variation(self, move: Union[int, chess.Move, GameNode]) -> bool:
"""Checks if this node has the given variation."""
return move in self
def promote_to_main(self, move: Union[int, chess.Move, GameNode]) -> None:
"""Promotes the given *move* to the main variation."""
variation = self[move]
self.variations.remove(variation)
self.variations.insert(0, variation)
def promote(self, move: Union[int, chess.Move, GameNode]) -> None:
"""Moves a variation one up in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1]
def demote(self, move: Union[int, chess.Move, GameNode]) -> None:
"""Moves a variation one down in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i < len(self.variations) - 1:
self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1]
def remove_variation(self, move: Union[int, chess.Move, GameNode]) -> None:
"""Removes a variation."""
self.variations.remove(self.variation(move))
def add_variation(self, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = []) -> ChildNode:
"""Creates a child node with the given attributes."""
# Instanciate ChildNode only in this method.
return ChildNode(self, move, comment=comment, starting_comment=starting_comment, nags=nags)
def add_main_variation(self, move: chess.Move, *, comment: str = "", nags: Iterable[int] = []) -> ChildNode:
"""
Creates a child node with the given attributes and promotes it to the
main variation.
"""
node = self.add_variation(move, comment=comment, nags=nags)
self.variations.insert(0, self.variations.pop())
return node
def next(self) -> Optional[ChildNode]:
"""
Returns the first node of the mainline after this node, or ``None`` if
this node does not have any children.
Complexity is `O(1)`.
"""
return self.variations[0] if self.variations else None
def mainline(self) -> Mainline[ChildNode]:
"""Returns an iterable over the mainline starting after this node."""
return Mainline(self, lambda node: node)
def mainline_moves(self) -> Mainline[chess.Move]:
"""Returns an iterable over the main moves after this node."""
return Mainline(self, lambda node: node.move)
def add_line(self, moves: Iterable[chess.Move], *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = []) -> GameNode:
"""
Creates a sequence of child nodes for the given list of moves.
Adds *comment* and *nags* to the last node of the line and returns it.
"""
node = self
# Add line.
for move in moves:
node = node.add_variation(move, starting_comment=starting_comment)
starting_comment = ""
# Merge comment and NAGs.
if node.comment:
node.comment += " " + comment
else:
node.comment = comment
node.nags.update(nags)
return node
def eval(self) -> Optional[chess.engine.PovScore]:
"""
Parses the first valid ``[%eval ...]`` annotation in the comment of
this node, if any.
Complexity is `O(n)`.
"""
match = EVAL_REGEX.search(self.comment)
if not match:
return None
turn = self.turn()
if match.group("mate"):
mate = int(match.group("mate"))
score: chess.engine.Score = chess.engine.Mate(mate)
if mate == 0:
# Resolve this ambiguity in the specification in favor of
# standard chess: The player to move after mate is the player
# who has been mated.
return chess.engine.PovScore(score, turn)
else:
score = chess.engine.Cp(round(float(match.group("cp")) * 100))
return chess.engine.PovScore(score if turn else -score, turn)
def eval_depth(self) -> Optional[int]:
"""
Parses the first valid ``[%eval ...]`` annotation in the comment of
this node and returns the corresponding depth, if any.
Complexity is `O(1)`.
"""
match = EVAL_REGEX.search(self.comment)
return int(match.group("depth")) if match and match.group("depth") else None
def set_eval(self, score: Optional[chess.engine.PovScore], depth: Optional[int] = None) -> None:
"""
Replaces the first valid ``[%eval ...]`` annotation in the comment of
this node or adds a new one.
"""
eval = ""
if score is not None:
depth_suffix = "" if depth is None else f",{max(depth, 0):d}"
cp = score.white().score()
if cp is not None:
eval = f"[%eval {float(cp) / 100:.2f}{depth_suffix}]"
elif score.white().mate():
eval = f"[%eval #{score.white().mate()}{depth_suffix}]"
self.comment, found = EVAL_REGEX.subn(_condense_affix(eval), self.comment, count=1)
if not found and eval:
if self.comment and not self.comment.endswith(" "):
self.comment += " "
self.comment += eval
def arrows(self) -> List[chess.svg.Arrow]:
"""
Parses all ``[%cal ...]`` annotations in the comment
of this node.
Returns a list of :class:`arrows <chess.svg.Arrow>`.
"""
arrows = []
for match in CAL_REGEX.finditer(self.comment):
for group in match.group("arrows").split(","):
arrows.append(chess.svg.Arrow.from_pgn(group))
return arrows
def csl(self) -> List[chess.svg.Arrow]:
"""
Parses all ``[%csl ...]`` annotations in the comment of this node.
Returns a list of :class:`arrows <chess.svg.Arrow>`.
"""
arrows = []
for match in CSL_REGEX.finditer(self.comment):
for group in match.group("arrows").split(","):
arrows.append(chess.svg.Arrow.from_pgn(group))
return arrows
def set_cal(self, arrows: Iterable[Union[chess.svg.Arrow, Tuple[Square, Square]]]) -> None:
"""
Replaces all valid ``[%cal ...]`` annotations in
the comment of this node or adds new ones.
"""
cal: List[str] = []
for arrow in arrows:
try:
tail, head = arrow # type: ignore
arrow = chess.svg.Arrow(tail, head)
except TypeError:
pass
cal.append(arrow.pgn()) # type: ignore
self.comment = CAL_REGEX.sub(_condense_affix(""), self.comment)
prefix = ""
if cal:
prefix += f"[%cal {','.join(cal)}]"
if prefix and self.comment and not self.comment.startswith(" ") and not self.comment.startswith("\n"):
self.comment = prefix + " " + self.comment
else:
self.comment = prefix + self.comment
def set_csl(self, arrows: Iterable[Union[chess.svg.Arrow, Tuple[Square, Square]]]) -> None:
"""
Replaces all valid ``[%csl ...]`` annotations in
the comment of this node or adds new ones.
"""
csl: List[str] = []
for arrow in arrows:
try:
tail, head = arrow # type: ignore
arrow = chess.svg.Arrow(tail, head)
except TypeError:
pass
csl.append(arrow.pgn()) # type: ignore
self.comment = CSL_REGEX.sub(_condense_affix(""), self.comment)
prefix = ""
if csl:
prefix += f"[%csl {','.join(csl)}]"
if prefix and self.comment and not self.comment.startswith(" ") and not self.comment.startswith("\n"):
self.comment = prefix + " " + self.comment
else:
self.comment = prefix + self.comment
def clock(self) -> Optional[float]:
"""
Parses the first valid ``[%clk ...]`` annotation in the comment of
this node, if any.
Returns the player's remaining time to the next time control after this
move, in seconds.
"""
match = CLOCK_REGEX.search(self.comment)
if match is None:
return None
return int(match.group("hours")) * 3600 + int(match.group("minutes")) * 60 + float(match.group("seconds"))
def set_clock(self, seconds: Optional[float]) -> None:
"""
Replaces the first valid ``[%clk ...]`` annotation in the comment of
this node or adds a new one.
"""
clk = ""
if seconds is not None:
seconds = max(0, seconds)
hours = int(seconds // 3600)
minutes = int(seconds % 3600 // 60)
seconds = seconds % 3600 % 60
seconds_part = f"{seconds:06.3f}".rstrip("0").rstrip(".")
clk = f"[%clk {hours:d}:{minutes:02d}:{seconds_part}]"
self.comment, found = CLOCK_REGEX.subn(_condense_affix(clk), self.comment, count=1)
if not found and clk:
if self.comment and not self.comment.endswith(" ") and not self.comment.endswith("\n"):
self.comment += " "
self.comment += clk
def emt(self) -> Optional[float]:
"""
Parses the first valid ``[%emt ...]`` annotation in the comment of
this node, if any.
Returns the player's elapsed move time use for the comment of this
move, in seconds.
"""
match = EMT_REGEX.search(self.comment)
if match is None:
return None
return int(match.group("hours")) * 3600 + int(match.group("minutes")) * 60 + float(match.group("seconds"))
def set_emt(self, seconds: Optional[float]) -> None:
"""
Replaces the first valid ``[%emt ...]`` annotation in the comment of
this node or adds a new one.
"""
emt = ""
if seconds is not None:
seconds = max(0, seconds)
hours = int(seconds // 3600)
minutes = int(seconds % 3600 // 60)
seconds = seconds % 3600 % 60
seconds_part = f"{seconds:06.3f}".rstrip("0").rstrip(".")
emt = f"[%emt {hours:d}:{minutes:02d}:{seconds_part}]"
self.comment, found = EMT_REGEX.subn(_condense_affix(emt), self.comment, count=1)
if not found and emt:
if self.comment and not self.comment.endswith(" ") and not self.comment.endswith("\n"):
self.comment += " "
self.comment += emt
@abc.abstractmethod
def accept(self, visitor: BaseVisitor[ResultT]) -> ResultT:
"""
Traverses game nodes in PGN order using the given *visitor*. Starts with
the move leading to this node. Returns the *visitor* result.
"""
def accept_subgame(self, visitor: BaseVisitor[ResultT]) -> ResultT:
"""
Traverses headers and game nodes in PGN order, as if the game was
starting after this node. Returns the *visitor* result.
"""
if visitor.begin_game() is not SKIP:
game = self.game()
board = self.board()
dummy_game = Game.without_tag_roster()
dummy_game.setup(board)
visitor.begin_headers()
for tagname, tagvalue in game.headers.items():
if tagname not in dummy_game.headers:
visitor.visit_header(tagname, tagvalue)
for tagname, tagvalue in dummy_game.headers.items():
visitor.visit_header(tagname, tagvalue)
if visitor.end_headers() is not SKIP:
visitor.visit_board(board)
if self.variations:
self.variations[0]._accept(board, visitor)
visitor.visit_result(game.headers.get("Result", "*"))
visitor.end_game()
return visitor.result()
def __str__(self) -> str:
return self.accept(StringExporter(columns=None))
class ChildNode(GameNode):
"""
A child node of a game, with the move leading to it.
Extends :class:`~chess.pgn.GameNode`.
"""
parent: GameNode
"""The parent node."""
move: chess.Move
"""The move leading to this node."""
starting_comment: str
"""
A comment for the start of a variation. Only nodes that
actually start a variation (:func:`~chess.pgn.GameNode.starts_variation()`
checks this) can have a starting comment. The root node can not have
a starting comment.
"""
nags: Set[int]
"""
A set of NAGs as integers. NAGs always go behind a move, so the root
node of the game will never have NAGs.
"""
def __init__(self, parent: GameNode, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = []) -> None:
super().__init__(comment=comment)
self.parent = parent
self.move = move
self.parent.variations.append(self)
self.nags.update(nags)
self.starting_comment = starting_comment
def board(self) -> chess.Board:
stack: List[chess.Move] = []
node: GameNode = self
while node.move is not None and node.parent is not None:
stack.append(node.move)
node = node.parent
board = node.game().board()
while stack:
board.push(stack.pop())
return board
def ply(self) -> int:
ply = 0
node: GameNode = self
while node.parent is not None:
ply += 1
node = node.parent
return node.game().ply() + ply
def san(self) -> str:
"""
Gets the standard algebraic notation of the move leading to this node.
See :func:`chess.Board.san()`.
Do not call this on the root node.
Complexity is `O(n)`.
"""
return self.parent.board().san(self.move)
def uci(self, *, chess960: Optional[bool] = None) -> str:
"""
Gets the UCI notation of the move leading to this node.
See :func:`chess.Board.uci()`.
Do not call this on the root node.
Complexity is `O(n)`.
"""
return self.parent.board().uci(self.move, chess960=chess960)
def end(self) -> ChildNode:
"""
Follows the main variation to the end and returns the last node.
Complexity is `O(n)`.
"""
return typing.cast(ChildNode, super().end())
def _accept_node(self, parent_board: chess.Board, visitor: BaseVisitor[ResultT]) -> None:
if self.starting_comment:
visitor.visit_comment(self.starting_comment)
visitor.visit_move(parent_board, self.move)
parent_board.push(self.move)
visitor.visit_board(parent_board)
parent_board.pop()
for nag in sorted(self.nags):
visitor.visit_nag(nag)
if self.comment:
visitor.visit_comment(self.comment)
def _accept(self, parent_board: chess.Board, visitor: BaseVisitor[ResultT], *, sidelines: bool = True) -> None:
stack = [_AcceptFrame(self, sidelines=sidelines)]
while stack:
top = stack[-1]
if top.in_variation:
top.in_variation = False
visitor.end_variation()
if top.state == "pre":
top.node._accept_node(parent_board, visitor)
top.state = "variations"
elif top.state == "variations":
try:
variation = next(top.variations)
except StopIteration:
if top.node.variations:
parent_board.push(top.node.move)
stack.append(_AcceptFrame(top.node.variations[0], sidelines=True))
top.state = "post"
else:
top.state = "end"
else:
if visitor.begin_variation() is not SKIP:
stack.append(_AcceptFrame(variation, sidelines=False, is_variation=True))
top.in_variation = True
elif top.state == "post":
parent_board.pop()
top.state = "end"
else:
stack.pop()
def accept(self, visitor: BaseVisitor[ResultT]) -> ResultT:
self._accept(self.parent.board(), visitor, sidelines=False)
return visitor.result()
def __repr__(self) -> str:
try:
parent_board = self.parent.board()
except ValueError:
return f"<{type(self).__name__} at {id(self):#x} (dangling: {self.move})>"
else:
return "<{} at {:#x} ({}{} {} ...)>".format(
type(self).__name__,
id(self),
parent_board.fullmove_number,
"." if parent_board.turn == chess.WHITE else "...",
parent_board.san(self.move))
GameT = TypeVar("GameT", bound="Game")
class Game(GameNode):
"""
The root node of a game with extra information such as headers and the
starting position. Extends :class:`~chess.pgn.GameNode`.
"""
headers: Headers
"""
A mapping of headers. By default, the following 7 headers are provided
(Seven Tag Roster):
>>> import chess.pgn
>>>
>>> game = chess.pgn.Game()
>>> game.headers
Headers(Event='?', Site='?', Date='????.??.??', Round='?', White='?', Black='?', Result='*')
"""
errors: List[Exception]
"""
A list of errors (such as illegal or ambiguous moves) encountered while
parsing the game.
"""
def __init__(self, headers: Optional[Union[Mapping[str, str], Iterable[Tuple[str, str]]]] = None) -> None:
super().__init__()
self.headers = Headers(headers)
self.errors = []
def board(self) -> chess.Board:
return self.headers.board()
def ply(self) -> int:
# Optimization: Parse FEN only for custom starting positions.
return self.board().ply() if "FEN" in self.headers else 0
def setup(self, board: Union[chess.Board, str]) -> None:
"""
Sets up a specific starting position. This sets (or resets) the
``FEN``, ``SetUp``, and ``Variant`` header tags.
"""
try:
fen = board.fen() # type: ignore
setup = typing.cast(chess.Board, board)
except AttributeError:
setup = chess.Board(board) # type: ignore
setup.chess960 = setup.has_chess960_castling_rights()
fen = setup.fen()
if fen == type(setup).starting_fen:
self.headers.pop("FEN", None)
self.headers.pop("SetUp", None)
else:
self.headers["FEN"] = fen
self.headers["SetUp"] = "1"
if type(setup).aliases[0] == "Standard" and setup.chess960:
self.headers["Variant"] = "Chess960"
elif type(setup).aliases[0] != "Standard":
self.headers["Variant"] = type(setup).aliases[0]
self.headers["FEN"] = fen
else:
self.headers.pop("Variant", None)
def accept(self, visitor: BaseVisitor[ResultT]) -> ResultT:
"""
Traverses the game in PGN order using the given *visitor*. Returns
the *visitor* result.
"""
if visitor.begin_game() is not SKIP:
for tagname, tagvalue in self.headers.items():
visitor.visit_header(tagname, tagvalue)
if visitor.end_headers() is not SKIP:
board = self.board()
visitor.visit_board(board)
if self.comment:
visitor.visit_comment(self.comment)
if self.variations:
self.variations[0]._accept(board, visitor)
visitor.visit_result(self.headers.get("Result", "*"))
visitor.end_game()
return visitor.result()
def time_control(self) -> TimeControl:
"""
Returns the time control of the game. If the game has no time control
information, the default time control ('UNKNOWN') is returned.
"""
time_control_header = self.headers.get("TimeControl", "")
return parse_time_control(time_control_header)
@classmethod
def from_board(cls: Type[GameT], board: chess.Board) -> GameT:
"""Creates a game from the move stack of a :class:`~chess.Board()`."""
# Setup the initial position.
game = cls()
game.setup(board.root())
node: GameNode = game
# Replay all moves.
for move in board.move_stack:
node = node.add_variation(move)
game.headers["Result"] = board.result()
return game
@classmethod
def without_tag_roster(cls: Type[GameT]) -> GameT:
"""Creates an empty game without the default Seven Tag Roster."""
return cls(headers={})
@classmethod
def builder(cls: Type[GameT]) -> GameBuilder[Game]:
return GameBuilder(Game=cls)
def __repr__(self) -> str:
return "<{} at {:#x} ({!r} vs. {!r}, {!r} at {!r}{})>".format(
type(self).__name__,
id(self),
self.headers.get("White", "?"),
self.headers.get("Black", "?"),
self.headers.get("Date", "????.??.??"),
self.headers.get("Site", "?"),
f", {len(self.errors)} errors" if self.errors else "")
HeadersT = TypeVar("HeadersT", bound="Headers")
class Headers(MutableMapping[str, str]):
def __init__(self, data: Optional[Union[Mapping[str, str], Iterable[Tuple[str, str]]]] = None, **kwargs: str) -> None:
self._tag_roster: Dict[str, str] = {}
self._others: Dict[str, str] = {}
if data is None:
data = {
"Event": "?",
"Site": "?",
"Date": "????.??.??",
"Round": "?",
"White": "?",
"Black": "?",