Search code examples
pythondata-manipulationchesspython-chess

How can I manipulate this chess notation with python?


I'm trying to use some chess related libraries in python (e.g. chessnut and chess) and they use the following notation

r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4

I've searched about it and didn't find anything. How can I manipulate this and how can I transform the standart algebraic notation (e.g. "d4 Nc6 e4 e5 f4 f6 dxe5 fxe5") into this new one?


Solution

  • For FEN info : https://en.wikipedia.org/wiki/Forsyth–Edwards_Notation

    There are two ways to obtain a FEN from a san in python : With a .pgn file :

    import chess
    import chess.pgn
    
    pgn = open("your_pgn_file.pgn")
    game = chess.pgn.read_game(pgn)
    board = game.board()
    
    for move in game.mainline_moves():
        board.push(move)
    print(board.fen())
    

    or from a single san mainline :

    import chess
    
    board = chess.Board()
    san_mainline = "d4 Nc6 e4 e5 f4 f6 dxe5 fxe5"
    
    for move in san_mainline.split():
        board.push_san(move)
    print(board.fen())