Skip to content

Commit

Permalink
Add GameNode.main_line()
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasf committed Sep 16, 2016
1 parent 1fa0293 commit e7e6531
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
5 changes: 5 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,11 @@ Features
>>> first_game.headers["Black"]
'Bordais'
>>> # Get the mainline as a list of moves.
>>> moves = first_game.main_line()
>>> first_game.board().variation_san(moves)
'1. e4 c5 2. c4 Nc6 3. Ne2 Nf6 4. Nbc3 Nb4 5. g3 Nd3#'
>>> # Iterate through the mainline of this embarrasingly short game.
>>> node = first_game
>>> while not node.is_end():
Expand Down
8 changes: 7 additions & 1 deletion chess/pgn.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,13 @@ def add_main_variation(self, move, comment=""):
self.variations.insert(0, node)
return node

def main_line(self):
"""Yields the moves of the main line starting in this node."""
node = self
while node.variations:
node = node.variations[0]
yield node.move

def add_line(self, moves, comment="", starting_comment="", nags=()):
"""
Creates a sequence of child nodes for the given list of moves.
Expand All @@ -268,7 +275,6 @@ def add_line(self, moves, comment="", starting_comment="", nags=()):

return node


def accept(self, visitor, _board=None):
"""
Traverse game nodes in PGN order using the given *visitor*. Returns
Expand Down
15 changes: 11 additions & 4 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1966,10 +1966,9 @@ def test_add_line(self):
game = chess.pgn.Game()
game.add_variation(chess.Move.from_uci("e2e4"))

tail = game.add_line([
chess.Move.from_uci("g1f3"),
chess.Move.from_uci("d7d5")
], starting_comment="start", comment="end", nags=(17, 42))
moves = [chess.Move.from_uci("g1f3"), chess.Move.from_uci("d7d5")]

tail = game.add_line(moves, starting_comment="start", comment="end", nags=(17, 42))

self.assertEqual(tail.parent.move, chess.Move.from_uci("g1f3"))
self.assertEqual(tail.parent.starting_comment, "start")
Expand All @@ -1980,6 +1979,14 @@ def test_add_line(self):
self.assertEqual(tail.comment, "end")
self.assertTrue(42 in tail.nags)

def test_main_line(self):
moves = [chess.Move.from_uci(uci) for uci in ["d2d3", "g8f6", "e2e4"]]

game = chess.pgn.Game()
game.add_line(moves)

self.assertEqual(list(game.main_line()), moves)


class StockfishTestCase(unittest.TestCase):

Expand Down

0 comments on commit e7e6531

Please sign in to comment.