-
Notifications
You must be signed in to change notification settings - Fork 0
/
sgflib.py
1844 lines (1591 loc) · 65.1 KB
/
sgflib.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# sgflib.py (Smart Game Format parser & utility library)
# Copyright © 2000-2022 David John Goodger (goodger@python.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
====================================================
Smart Game Format Parser & Utility Library: sgflib
====================================================
version 2.0a (2021-01-13~)
Homepage: http://gotools.sourceforge.net
Copyright © 2000-2022 David Goodger (goodger@python.org). sgflib.py comes with
ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to
redistribute it and/or modify it under the terms of the GNU General Public
License; see the source code for details.
Description
===========
This library contains a parser and utility classes for SGF, the Smart Game
Format, file format 4 (FF[4]). SGF is a text only, tree based file format
designed to store game records of board games for two players, most commonly
for the game of Go. (See `the official SGF specification
<https://www.red-bean.com/sgf/>`_.)
Given a bytestring containing a complete SGF data instance (the contents of a
.sgf file), the `Parser` class will create a `Collection` object consisting of
one or more `GameTree` instances (one per game in the SGF file), each
containing `Node` instances and (optionally) branch `GameTree` objects
(variations). Each `Node` contains a mapping of properties, ID-value pairs.
All property values are lists, and can have multiple entries.
Tree traversal methods are provided through the `Cursor` class.
The default representation (using ``str()``/``bytes()`` or ``print()``) of
each class of SGF objects is the Smart Game Format itself.
The parser does not require valid SGF, nor does it validate the SGF data
supplied. The construction classes do not validate the resulting SGF.
In addition, this library contains several utility classes:
* CLI: Base class for command-line interface utilities.
* Summary, SummaryCLI: Summarize one or more SGF files.
* NormalizerCLI: Put an SGF collection into a normalized form.
* MergerCLI: Merge two or more SGF game trees into one.
.. * LabelerCLI: Label variations in an SGF file (collection of games).
"""
# Revision History:
#
# * 2.0a (2021-01-13~): Rewrite for Python 3.0. Modernized.
#
# * 1.0 (2000-03-27): First public release. Ready for prime time.
#
# * 0.1 (2000-01-16): Initial idea & started coding.
import sys
import os
import os.path
import warnings
import argparse
import datetime
import re
import textwrap
import collections
import itertools
import math
from copy import deepcopy
TEXT_ENCODING = 'UTF-8'
"""Encoding used for all text output."""
NAME_ENCODING = 'ASCII'
"""Encoding used for all property names and non-text values."""
PRETTY_INDENT_SPACES = 2
"""Per-level indent for pretty-formatted output."""
class Error(Exception):
"""Base class for sgflib exceptions."""
pass
# Parsing Exceptions
class ParseError(Error):
"""Base class for parsing exceptions."""
pass
class EndOfDataParseError(ParseError):
"""Raised by `Parser.parse_branches()`, `Parser.parse_node()`."""
pass
class TreeParseError(ParseError):
"""Raised by `Parser.parse_game_tree()`."""
pass
class NodePropertyParseError(ParseError):
"""Raised by `Parser.parse_node()`."""
pass
class PropertyValueParseError(ParseError):
"""Raised by `Parser.parsePropertyValue()`."""
pass
# Tree Construction Exceptions
class TreeConstructionError(Error):
"""Base class for game tree construction exceptions."""
pass
class NodeConstructionError(TreeConstructionError):
"""Raised by `Node.update()`."""
pass
class DuplicatePropertyError(TreeConstructionError):
"""Raised by `Node.add_property()`."""
pass
class MergeError(TreeConstructionError):
"""Raised by `Collection.merge()` & `GameTree.merge()`."""
pass
# Tree Navigation Exceptions
class TreeNavigationError(Error):
"""Base class for game tree navigation, and raised by `Cursor.next()`."""
pass
class TreeEndError(TreeNavigationError):
"""Raised by `Cursor.next()`, `Cursor.previous()`."""
pass
# Miscellaneous Exceptions
class PropertyError(Error):
"""Raised by `Node` methods."""
pass
class Collection(list):
"""
A `Collection` is a `list` of one or more `GameTree` objects.
"""
path = None
def __str__(self):
"""
SGF text representation, accessed via `str(collection)`.
Separates game trees with a blank line.
"""
return '\n\n'.join(str(item) for item in self)
def pretty(self):
"""
Pretty-formatted SGF text representation, accessed via
`str(collection)`. Separates game trees with a blank line.
"""
return '\n\n'.join(item.pretty() for item in self) + '\n'
def __bytes__(self):
"""
SGF bytes representation, accessed via `bytes(collection)`.
Separates game trees with a blank line.
"""
return b'\n\n'.join(bytes(item) for item in self)
def __repr__(self):
"""
The canonical string representation of the `Collection`.
"""
return f'{self.__class__.__name__}({repr(self[0])}, ...)'
def cursor(self, gamenum=0):
"""Returns a `Cursor` object for navigation of the given `GameTree`."""
return Cursor(self[gamenum])
@classmethod
def load(cls, path=None, data=None, parser_class=None):
"""
Return a `Collection` loaded a filesystem `path` (`None` or "-" reads
from <stdin>) or from `data`.
The default `parser_class` is `Parser`. `RootNodeParser` may be passed
in instead.
"""
if data is None:
if path == '-':
path = None
if path:
with open(path, 'rb') as src:
data = src.read()
else:
# read bytestring from <stdin>:
data = sys.stdin.buffer.read()
if parser_class is None:
parser_class = Parser
parser = parser_class(data)
collection = parser.parse()
collection.path = path
return collection
def save(self, file_or_path=None, pretty=False):
"""
Output as a bytestring to `file_or_path` (`None` or "-" writes to
<stdout>), optionally `pretty`-formatted.
"""
if pretty:
output = bytes(self.pretty(), encoding=TEXT_ENCODING)
else:
output = bytes(self)
if file_or_path == '-':
file_or_path = None
if hasattr(file_or_path, 'write'):
file_or_path.write(output)
elif file_or_path:
with open(file_or_path, 'wb') as dest:
dest.write(output)
else:
sys.stdout.buffer.write(output)
def normalize(self):
"""Normalize `self`."""
for gametree in self:
gametree.normalize()
def merge(self, other, comment=None, comments_everywhere=True,
ignore_property_values=None):
"""
Merge `other` into `self`. Identify variant branches & sources of
comments with prefix `comment`.
"""
if len(self) != 1:
path = self.path if self.path else '<data:self>'
raise MergeError(
f'"{path}" is a collection of {len(self)} games. '
'A multi-game collection cannot be merged. '
'Only one game can be merged at a time.')
if len(other) != 1:
path = other.path if other.path else '<data:other>'
raise MergeError(
f'"{path}" is a collection of {len(other)} games. '
'A multi-game collection cannot be merged. '
'Only one game can be merged at a time.')
self[0].merge(
other[0], comment, comments_everywhere, ignore_property_values)
self.normalize()
class GameTree(list):
"""
An SGF game tree: a sequence of `Node` objects (game plays) and optional
branches (game variations).
Instance attributes:
self : list of `Node`
Game tree 'trunk' (main line of game or branch), all plays prior to any
branches.
self.branches : list of `GameTree`
Variations of a game. `self.branches[0]` is the main line of the game
(trunk of the tree). Branches begin immediately following the last
`Node` in the main `GameTree` sequence.
"""
def __init__(self, nodelist=None, branches=None, comment=None):
"""
Arguments:
- nodelist : `GameTree` or list of `Node` or `Node` -- Stored in `self`.
- branches : list of `GameTree` -- Stored in `self.branches`.
- comment : added to the first node.
"""
if isinstance(nodelist, GameTree):
self.extend(nodelist)
self.branches = nodelist.branches
elif isinstance(nodelist, list):
self.extend(nodelist)
elif isinstance(nodelist, Node):
self.append(nodelist)
elif nodelist is not None:
raise TreeConstructionError(
f'Unable to construct a GameTree from supplied nodelist '
f'(type {type(nodelist)}.')
self.branches = [] if branches is None else branches
self.prefix_comment(comment)
def deepcopy(self):
copy = self.__class__(
[node.deepcopy() for node in self],
[branch.deepcopy() for branch in self.branches])
return copy
def __eq__(self, other):
return super().__eq__(other) and self.branches == other.branches
def __str__(self):
"""Return an SGF representation of this `GameTree`."""
parts = ['(']
parts.extend(str(item) for item in self)
parts.extend(str(branch) for branch in self.branches)
parts.append(')')
return '\n'.join(parts)
def pretty(self, indent=0):
"""Return a pretty-formatted SGF representation of this `GameTree`."""
indent += 1
parts = ['(']
parts.extend(item.pretty(indent) for item in self)
parts.extend(branch.pretty(indent) for branch in self.branches)
spaces = ' ' * indent * PRETTY_INDENT_SPACES
return (
f'\n{spaces}'.join(parts)
+ f'\n{" "*(indent-1)*PRETTY_INDENT_SPACES})')
def __bytes__(self):
"""Return an SGF bytes representation of this `GameTree`."""
parts = [b'(']
parts.extend(bytes(item) for item in self)
parts.extend(bytes(branch) for branch in self.branches)
parts.append(b')')
return b'\n'.join(parts)
def __repr__(self):
nodelist = branches = ''
if self:
nodelist = f'nodelist=[{repr(self[0])}, ...], '
if self.branches:
branches = f'branches=[{repr(self.branches[0])}, ...]'
return f'{self.__class__.__name__}({nodelist}{branches})'
def trunk(self):
"""
Return the main line of the game (nodes and variation A) as a new
`GameTree`.
"""
if self.branches:
return GameTree(self + self.branches[0].trunk())
else:
return self
# def cursor(self):
# """Return a `Cursor` object for navigation of this `GameTree`."""
# return Cursor(self)
def property_search(self, pid, getall=0):
"""
Search this `GameTree` for nodes containing matching properties.
Return a `GameTree` containing the matched node(s).
Arguments:
- pid : string -- ID of properties to search for.
- getall : boolean -- Set to true (1) to return all `Node`'s that
match, or to false (0) to return only the first match.
"""
matches = []
for n in self:
if n.has_key(pid):
matches.append(n)
if not getall:
break
else: # getall or not matches:
for v in self.branches:
matches = matches + v.property_search(pid, getall)
if not getall and matches:
break
return GameTree(matches)
def normalize(self):
while self.branches:
if len(self.branches) == 1:
self.extend(self.branches[0])
self.branches = self.branches[0].branches
else:
for index, branch in enumerate(self.branches):
branch.normalize()
break
def merge(self, other, comment=None, comments_everywhere=True,
ignore_property_values=None):
"""
Merge the `other` GameTree into `self`. Identify variant branches &
plays with prefix `comment` (once, at point of deviation).
"""
# TODO: add labels to branches
# In case either `self` or `other` are empty:
i = -1
other = other.deepcopy()
for (i, my_node, other_node) in zip(itertools.count(), self, other):
if my_node.equivalent(other_node):
my_node.merge(
other_node, comment, comments_everywhere,
ignore_property_values)
else:
# Make the rest of self & other into branches:
self_branch = GameTree(self[i:], self.branches)
del self[i:]
other_branch = GameTree(other[i:], other.branches, comment)
self.branches = [self_branch, other_branch]
break
else:
if i == -1:
# Either `self` or `other` is empty, prior to branches.
if self:
if not other.branches:
# `other` is empty; leave `self` alone:
return
elif not self.branches:
# `self` is empty; copy data from `other`:
if other:
other[0].prefix_comment(comment)
self[:] = other
self.branches = other.branches
return
# Else branches exist in both; merge them.
# Check for leftover nodes. If unequal lengths, make self & other
# equal-length by converting any remainder into a branch:
if len(self) > len(other):
if other.branches:
self_branch = GameTree(self[i+1:], self.branches)
del self[i+1:]
self.branches = [self_branch]
# Else no need to convert, as there's nothing left to merge.
elif len(other) > len(self):
other_branch = GameTree(other[i+1:], other.branches, comment)
del other[i+1:]
other.branches = [other_branch]
if not other.branches:
return
if not self.branches:
self.branches.append(GameTree([Node(C='')]))
# Merge branches:
for self_branch in self.branches[:]:
for (i, other_branch) in enumerate(other.branches[:]):
if self_branch[0].equivalent(other_branch[0]):
self_branch.merge(
other_branch, comment, comments_everywhere,
ignore_property_values)
del other.branches[i]
break
for other_branch in other.branches:
other_branch.prefix_comment(comment)
self.branches.extend(other.branches)
def prefix_comment(self, comment):
if not comment:
return
if self:
self[0].prefix_comment(comment)
else:
for branch in self.branches:
branch.prefix_comment(comment)
class Node(dict):
"""
An SGF node (one move or play, or initial setup), consisting of properties
(name:value pairs). Property values may be scalars or lists; see
`self.list_properties`.
Example: Let ``node`` be a `Node` parsed from ';B[aa]BL[250]C[comment]':
* node['BL'] => '250'
* node['B'] => 'aa'
"""
def resolve_property_id(self, name):
if name in self.property_ids:
return name
elif name in self.property_names:
return self.property_names[name]
else:
raise PropertyError(
f"Unknown SGF property name or ID: '{name}'")
def __getattr__(self, name):
key = self.resolve_property_id(name)
try:
return self[key]
except KeyError as error:
if name == key:
raise PropertyError(f"No '{name}' property ID in Node") from None
else:
raise PropertyError(
f"No '{name}' property (SGF ID '{key}') in Node") from None
def __setattr__(self, name, value):
key = self.resolve_property_id(name)
self[key] = value
def __delattr__(self, name):
key = self.resolve_property_id(name)
try:
del self[key]
except KeyError as error:
if name == key:
raise PropertyError(f"No '{name}' property ID in Node") from None
else:
raise PropertyError(
f"No '{name}' property (SGF ID '{key}') in Node") from None
def __str__(self):
"""Return an SGF text representation of this `Node`."""
parts = [';']
for (name, value) in self.items():
parts.append(name)
parts.append('[')
if name in self.list_properties:
parts.append(']['.join(
self.escape_text(str(item)) for item in value))
else:
parts.append(self.escape_text(str(value)))
parts.append(']')
return ''.join(parts)
def pretty(self, indent=0):
return str(self)
def __bytes__(self):
"""SGF bytes representation."""
parts = [b';']
for (name, value) in self.items():
encoding = (
TEXT_ENCODING if name in self.text_properties
else NAME_ENCODING)
parts.append(bytes(name, NAME_ENCODING))
parts.append(b'[')
if name in self.list_properties:
parts.append(b']['.join(
bytes(self.escape_text(str(item)), encoding)
for item in value))
else:
parts.append(bytes(self.escape_text(str(value)), encoding))
parts.append(b']')
return b''.join(parts)
def __repr__(self):
content = ', '.join(f'{name}={value!r}' for name, value in self.items())
return f'{self.__class__.__name__}({content})'
def deepcopy(self):
copy = self.__class__()
dict.update(copy, deepcopy(dict(self.items())))
return copy
chars_to_escape = ['\\', ']']
"""List of characters that need to be backslash-escaped."""
chars_to_escape_pattern = None
"""Regexp pattern for isolating characters for backslash escaping.
Initialized when `Node.escape_text` is first executed."""
def compile_chars_to_escape_pattern(self):
return re.compile(
'(' + '|'.join(re.escape(char) for char in self.chars_to_escape)
+ ')')
def escape_text(self, text):
"""Add backslash-escapes to property value characters that need them."""
if self.chars_to_escape_pattern is None:
object.__setattr__(
self, 'chars_to_escape_pattern',
self.compile_chars_to_escape_pattern())
return ''.join(
# escapable characters are at all odd indexes:
('\\' if index % 2 else '') + part
for (index, part) in enumerate(
self.chars_to_escape_pattern.split(text)))
def set_encoding(self, encoding):
object.__setattr__(self, 'encoding', encoding)
def equivalent(self, other):
"""
Return True iff `self` and `other` are equivalent: both the same type
of node (setup or move), same player & coordinates if a move, etc.
"""
my_type = self.node_type()
other_type = other.node_type()
if my_type is None or other_type is None:
return True
if my_type != other_type:
return False
if my_type == 'move':
# Check that the same player played, and the coordinates match:
self_props = set(self.keys())
self_player = self_props & self.move_required_properties
if (num_players := len(self_player)) != 1:
raise PropertyError(
f'Expected 1 player move in `self` node, {num_players} '
f'found.')
other_props = set(other.keys())
other_player = other_props & self.move_required_properties
if (num_players := len(other_player)) != 1:
raise PropertyError(
f'Expected 1 player move in `other` node, {num_players} '
f'found.')
if self_player != other_player:
return False
player = self_player.pop()
if self[player] != other[player]:
# different coordinates
return False
return True
def node_type(self):
props = set(self.keys())
if not props or 'C' in props and not self.C:
return None
for (node_type, node_type_properties) in self.node_types.items():
if props & node_type_properties:
return node_type
else:
raise PropertyError(
f'Unknown node type for node with properties {props}')
def merge(self, other, comment=None, comments_everywhere=True,
ignore_property_values=None):
"""
Merge the `other` Node with `self`. Any differing comment in `other`
will be prefixed with `comment` before merging into `self`.
Assumes the equivalence/compatibility of `self` and `other`; this
should be tested prior to calling.
"""
other = other.deepcopy()
if comment is None:
comment = ''
else:
comment = f'{comment}\n'
if ignore_property_values is None:
ignore_property_values = dict()
for (property_id, other_value) in other.items():
ignore_values = (
self.ignore_property_values.get(property_id, set())
| ignore_property_values.get(property_id, set()))
if ( property_id in self.scalar_properties
and ((any in ignore_values)
or (other_value in ignore_values))):
continue
elif property_id == 'C':
if 'C' in self and self['C']:
if self['C'].strip() != other_value.strip():
if comments_everywhere:
self['C'] = (
f'{self["C"].strip()}\n\n'
f'{comment}{other_value.strip()}')
else:
self['C'] = (
f'{self["C"].strip()}\n\n'
f'{other_value.strip()}')
else:
if comments_everywhere:
self['C'] = f'{comment}{other_value.strip()}'
else:
self['C'] = f'{other_value.strip()}'
elif property_id in self:
if property_id in self.scalar_properties:
if other_value != self[property_id]:
self.merge_differing_scalar_property_values(
property_id, other_value, ignore_values)
# Else equal values, so nothing to do.
else:
self_values = set(self[property_id])
other_values = set(other_value)
if extras := (other_values - self_values):
self[property_id].extend(extras)
else:
if property_id in self.scalar_properties:
self[property_id] = other_value
else:
self[property_id] = other_value[:]
def merge_differing_scalar_property_values(
self, property_id, other_value, ignore_values):
self_value = self[property_id]
if self_value in ignore_values:
# Clear value so the value from other is used instead:
del self[property_id]
self_value = None
if not other_value:
# Empty other value, nothing to do:
return
if not self_value:
# Empty self value, use value from other:
self[property_id] = other_value
return
if ( property_id in self.real_properties and
math.isclose(float(self_value), float(other_value))):
# Ignore equivalent real-number values:
return
if (property_id in self.text_properties and
self_value.lower() == other_value.lower()):
# Ignore differences in text case:
return
raise MergeError(f"""\
Game nodes cannot be merged because the values for shared property \
"{property_id}" differ: "{self_value}" vs "{other_value}". \
Maybe use an option:
* "--ignore-property '{property_id}={other_value}'"
* "--ignore-property '{property_id}={self_value}'"
* "--ignore-property {property_id}" (ignores all values)""")
def update(self, other):
"""
`Dictionary` method not applicable to `Node`
Raise `NodeConstructionError`.
"""
raise NodeConstructionError(
'The update() method is not supported by Node; add properties '
'individually or use `merge(other)` instead.')
def prefix_comment(self, comment):
if not comment:
return
if 'C' in self and self['C'].strip():
self['C'] = f'{comment}\n{self["C"]}'
else:
self['C'] = f'{comment}'
property_ids = {
'AB': 'add_black',
'AE': 'add_empty',
'AN': 'annotation',
'AP': 'application',
'AR': 'arrow',
'AS': 'who_adds_stones',
'AW': 'add_white',
'B': 'black',
'BL': 'black_time_left',
'BM': 'bad_move',
'BR': 'black_rank',
'BT': 'black_team',
'C': 'comment',
'CA': 'charset',
'CP': 'copyright',
'CR': 'circle',
'DD': 'dim_points',
'DM': 'even_position',
'DO': 'doubtful',
'DT': 'date',
'EV': 'event',
'FF': 'file_format',
'FG': 'figure',
'GB': 'good_for_black',
'GC': 'game_comment',
'GM': 'game',
'GN': 'game_name',
'GW': 'good_for_white',
'HA': 'handicap',
'HO': 'hotspot',
'IP': 'initial_position',
'IT': 'interesting',
'IY': 'invert_y_axis',
'KM': 'komi',
'KO': 'ko',
'LB': 'label',
'LN': 'line',
'MA': 'mark',
'MN': 'set_move_number',
'N': 'node_name',
'OB': 'overtime_stones_black',
'ON': 'opening',
'OT': 'overtime',
'OW': 'overtime_stones_white',
'PB': 'player_black',
'PC': 'place',
'PL': 'player_to_play',
'PM': 'print_move_mode',
'PW': 'player_white',
'RE': 'result',
'RO': 'round',
'RU': 'rules',
'SE': 'markup',
'SL': 'selected',
'SO': 'source',
'SQ': 'square',
'ST': 'style',
'SU': 'setup_type',
'SZ': 'size',
'TB': 'territory_black',
'TE': 'tesuji',
'TM': 'time_limit',
'TR': 'triangle',
'TW': 'territory_white',
'UC': 'unclear_position',
'US': 'user',
'V': 'value',
'VW': 'view',
'W': 'white',
'WL': 'white_time_left',
'WR': 'white_rank',
'WT': 'white_team',
}
"""Mapping of SGF property ID to property name."""
property_names = {value: key for (key, value) in property_ids.items()}
"""Mapping of property name to SGF property ID."""
list_properties = {
'AB', 'AE', 'AR', 'AW', 'CR', 'DD', 'LB', 'LN', 'MA', 'SL', 'SQ',
'TB', 'TR', 'TW', 'VW',}
"""IDs of properties with multiple values, stored in lists. Other
properties are scalars (single values; see `Node.scalar_properties`)."""
scalar_properties = {
'AN', 'AP', 'AS', 'B', 'BL', 'BM', 'BR', 'BT', 'C', 'CA', 'CP', 'DM',
'DO', 'DT', 'EV', 'FF', 'FG', 'GB', 'GC', 'GM', 'GN', 'GW', 'HA',
'HO', 'IP', 'IT', 'IY', 'KM', 'KO', 'MN', 'N', 'OB', 'ON', 'OT', 'OW',
'PB', 'PC', 'PL', 'PM', 'PW', 'RE', 'RO', 'RU', 'SE', 'SO', 'ST',
'SU', 'SZ', 'TE', 'TM', 'UC', 'US', 'V', 'W', 'WL', 'WR', 'WT',}
"""IDs of properties with single values. Other properties have multiple
values (see `Node.list_properties`)."""
text_properties = {
'AN', 'AP', 'AS', 'BR', 'BT', 'C', 'CA', 'CP', 'DT', 'EV', 'FG', 'GC',
'GN', 'IP', 'IY', 'LB', 'N', 'ON', 'OT', 'PB', 'PC', 'PW', 'RE', 'RO',
'RU', 'SO', 'SU', 'US', 'WR', 'WT',}
"""IDs of properties with values of type text & simpletext, encoded per
the CA/charset property. Other properties are ASCII-encoded."""
real_properties = {'KM', 'BL', 'TM', 'V', 'WL',}
"""IDs of properties with real-number values."""
root_only_properties = {
'AP', 'CA', 'FF', 'GM', 'ST', 'SZ', 'AN', 'BR', 'BT', 'CP', 'DT',
'EV', 'GN', 'GC', 'ON', 'OT', 'PB', 'PW', 'PC', 'RE', 'RO', 'RU',
'SO', 'TM', 'US', 'WR', 'WT',}
"""IDs of properties that only appear in the root node (which is also a
setup node)."""
setup_properties = {'AB', 'AW', 'AE', 'PL',}
"""IDs of properties that appear in setup nodes (incl. the root node)."""
root_properties = root_only_properties | setup_properties
"""IDs of properties that appear in root nodes."""
move_properties = {
'B', 'W', 'KO', 'MN', 'BM', 'DO', 'IT', 'TE', 'BL', 'OB', 'OW', 'WL',}
"""IDs of properties that appear in move nodes."""
move_required_properties = {'B', 'W',}
"""IDs of properties that must appear in move nodes."""
ignore_property_values = {
'RE': {'?'},
'AP': {any},}
"""Property IDs & sets of values to ignore when merging game trees.
`any` may be used to signify any value (value kept from primary game)."""
node_types = {
'root': root_properties,
'setup': setup_properties,
'move': move_properties,
}
game_types = {
1: 'Go',
2: 'Othello',
3: 'chess',
4: 'Gomoku+Renju',
5: "Nine Men's Morris",
6: 'Backgammon',
7: 'Chinese chess',
8: 'Shogi',
9: 'Lines of Action',
10: 'Ataxx',
11: 'Hex',
12: 'Jungle',
13: 'Neutron',
14: "Philosopher's Football",
15: 'Quadrature',
16: 'Trax',
17: 'Tantrix',
18: 'Amazons',
19: 'Octi',
20: 'Gess',
21: 'Twixt',
22: 'Zertz',
23: 'Plateau',
24: 'Yinsh',
25: 'Punct',
26: 'Gobblet',
27: 'hive',
28: 'Exxit',
29: 'Hnefatal',
30: 'Kuba',
31: 'Tripples',
32: 'Chase',
33: 'Tumbling Down',
34: 'Sahara',
35: 'Byte',
36: 'Focus',
37: 'Dvonn',
38: 'Tamsk',
39: 'Gipf',
40: 'Kropki',
}
"""Mapping of game type numbers to names."""
# class Cursor:
# """
# `GameTree` navigation tool.
# Instance attributes:
# - self.game : `GameTree` -- The root `GameTree`.
# - self.gametree : `GameTree` -- The current `GameTree`.
# - self.node : `Node` -- The current Node.
# - self.nodenum : integer -- The offset of `self.node` from the root of
# `self.game`. The nodenum of the root node is 0.
# - self.index : integer -- The offset of `self.node` within `self.gametree`.
# - self.stack : list of `GameTree` -- A record of `GameTree` objects traversed.
# - self.children : list of `Node` -- All child nodes of the current node.
# - self.at_end : boolean -- Flags if we are at the end of a branch.
# - self.at_start : boolean -- Flags if we are at the start of the game.
# """
# def __init__(self, gametree):
# self.game = gametree # root GameTree
# self.reset()
# def reset(self):
# """Set `Cursor` to point to the start of the root `GameTree`, `self.game`."""
# self.gametree = self.game
# self.nodenum = 0
# self.index = 0
# self.stack = []
# self.node = self.gametree[self.index]
# self._set_children()
# self._set_flags()
# def next(self, branch=0):
# """
# Move the `Cursor` to & return the next `Node`.
# Argument:
# * branch : integer, default 0 -- Branch number. A non-zero value is
# only valid at a branching, where branches exist.
# Raise `TreeEndError` if the end of a branch is exceeded.
# Raise `TreeNavigationError` if a non-existent branch is accessed.
# """
# if self.index + 1 < len(self.gametree): # more main line?
# if branch != 0:
# raise TreeNavigationError("Nonexistent branch.")
# self.index = self.index + 1
# elif self.gametree.branches: # branches exist?
# if branch < len(self.gametree.branches):
# self.stack.append(self.gametree)
# self.gametree = self.gametree.branches[branch]
# self.index = 0
# else:
# raise TreeNavigationError("Nonexistent branch.")
# else:
# raise TreeEndError
# self.node = self.gametree[self.index]
# self.nodenum = self.nodenum + 1
# self._set_children()
# self._set_flags()
# return self.node
# def previous(self):