0

i have a service, that gets a game from database and adding moves to it. also, it edits current pgn (string of moves).Is there any functions, that can get given string of moves and parse moves from it?

I was trying this, but had a problem

board = chess.Board()
    if game.moves!="":
        for move in game.moves.split():
            board.push(chess.Move.from_uci(move))

And after trying to append first move to a new game i've got this issue:

board.push(chess.Move.from_uci(move))
           ^^^^^^^^^^^^^^^^^^^^^^^^^
raise InvalidMoveError(f"expected uci string to be of length 4 or 5: {uci!r}")
chess.InvalidMoveError: expected uci string to be of length 4 or 5: '1.'
2
  • 1
    The error message is very clear. Did you read it? Did you see it says it has a problem interpreting "1." as a uci move? Do you understand what happened? Please provide an example of what game.moves is exactly, so we can help you out.
    – trincot
    Commented Nov 8 at 7:44
  • Have you tried checking the output of game.moves.split()? It looks like the problem might be game.moves is in the format "1. e4 e5 2. Nf3 Nc6" etc, so you will need to skip the segments that just have the move number. This should be pretty simple to implement with enumerate and index % 3 Commented Nov 8 at 7:46

1 Answer 1

0

Your game.moves has move numbers, like "1. e4", and likely does not have moves in UCI format either (which for example would be "e2e4").

To process PGN notation, use the chess.pgn library, and its read_game function.

Example:

import chess
import chess.pgn
import io

moves = "1. e4 e5 2. Nf3 *"
pgn = io.StringIO(moves)
game = chess.pgn.read_game(pgn)
board = game.board()
for move in game.mainline_moves():
    board.push(move)
    print(move)

This outputs:

e2e4
e7e5
g1f3

If in your attempt you had loaded game.moves from a file, then skip that, and load the pgn directly from that file with read_pgn:

pgn = open("yourfile.pgn")
game = chess.pgn.read_game(pgn)
# ...etc
1
  • Any feedback on this answer, @vladimirOmSu?
    – trincot
    Commented Nov 15 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.