Skip to content

Commit

Permalink
Add GameNode.accept_subgame
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasf committed Dec 28, 2017
1 parent d60a067 commit ec37db3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
25 changes: 25 additions & 0 deletions chess/pgn.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,31 @@ def accept(self, visitor, _board=None):
if _board is None:
return visitor.result()

def accept_subgame(self, visitor):
"""
Traverses headers and game nodes in PGN order, as if the game was
starting from this node. Returns the visitor result.
"""
game = self.root()
visitor.begin_game()

dummy_game = Game.without_tag_roster()
dummy_game.setup(self.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)
visitor.end_headers()

self.accept(visitor)

visitor.visit_result(game.headers.get("Result", "*"))
visitor.end_game()
return visitor.result()

def __str__(self):
return self.accept(StringExporter(columns=None))

Expand Down
9 changes: 9 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2200,6 +2200,15 @@ def test_no_movetext(self):

self.assertTrue(chess.pgn.read_game(pgn) is None)

def test_subgame(self):
pgn = StringIO("1. d4 d5 (1... Nf6 2. c4 (2. Nf3 g6 3. g3))")
game = chess.pgn.read_game(pgn)
node = game.variations[0].variations[1]
subgame = node.accept_subgame(chess.pgn.GameModelCreator())
self.assertEqual(subgame.headers["FEN"], "rnbqkb1r/pppppppp/5n2/8/3P4/8/PPP1PPPP/RNBQKBNR w KQkq - 1 2")
self.assertEqual(subgame.variations[0].move, chess.Move.from_uci("c2c4"))
self.assertEqual(subgame.variations[1].move, chess.Move.from_uci("g1f3"))


class CraftyTestCase(unittest.TestCase):

Expand Down

0 comments on commit ec37db3

Please sign in to comment.