How do I import and and export a game in PGN after playing a move? #879
Answered
by
niklasf
Roy-Orbison
asked this question in
Q&A
-
I'm a Python noob, and I don't quite get how the various objects relate. The docs say that This is roughly what I have so far: import chess
import chess.engine
import chess.pgn
engine = chess.engine.SimpleEngine.popen_uci('stockfish')
pgn = '' # may be an empty string when new game, or a game in play, in PGN notation
if pgn == '':
game = chess.pgn.Game()
board = game.board()
# need to set starting colour
else:
import io
game = chess.pgn.read_game(io.StringIO(pgn))
board = game.board()
for move in game.mainline_moves():
board.push(move)
result = engine.play(board, chess.engine.Limit(time=2.0))
board.push(result.move)
checkmate = board.is_checkmate()
exporter = chess.pgn.StringExporter(columns=None, headers=False, variations=False, comments=False)
pgn = game.accept(exporter) |
Beta Was this translation helpful? Give feedback.
Answered by
niklasf
May 26, 2022
Replies: 1 comment
-
Extend mainline with a single moveTo edit a game, you can use methods like game = chess.pgn.Game()
node = game.end()
result = engine.play(node.board(), chess.engine.Limit(time=2.0))
node = node.add_main_variation(result.move)
# node now again points to the end of the game Convert to and from boardIf the game is completely linear with no side variations, you can also just work with board = game.end().board() # Create board with all moves of an existing game
result = engine.play(node.board(), chess.engine.Limit(time=2.0))
board.push(resul.move)
# ...
print(board.root().variation_san(board.move_stack)) # Print move stack in SAN directly
game = chess.pgn.Game.from_board(board) # Convert back to game, if needed |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Roy-Orbison
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Extend mainline with a single move
To edit a game, you can use methods like
GameNode.add_main_variation()
:Convert to and from board
If the game is completely linear with no side variations, you can also just work with
chess.Board
only.