bhlangonijr / chesslib

chess library for legal move generation, FEN/PGN parsing and more
Apache License 2.0
225 stars 78 forks source link

How to generate pgn string from a Board #10

Closed rulogarcillan closed 5 years ago

rulogarcillan commented 5 years ago

Hello,

Is it possible to obtain a pgn string having only one board where movements have been made? The only way I see is creating a game but I can not add my board

bhlangonijr commented 5 years ago

Hello @rulogarcillan, Yes, you can do the follow:

        Board board = new Board();
        MoveList moves = new MoveList();

        // play the game and track the moves in a MoveList
        Move move = new Move(Square.E2, Square.E4);
        board.doMove(move);
        moves.add(move);
        move = new Move(Square.D7, Square.D5);
        board.doMove(move);
        moves.add(move);

        // Set up the game information and add the moves
        Event event = GameFactory.newEvent("Tournament");
        Round round = GameFactory.newRound(event, 1 );
        Game game = GameFactory.newGame("1", round);
        game.setBlackPlayer(new GenericPlayer("1", "Player1"));
        game.setWhitePlayer(new GenericPlayer("2", "Player2"));
        // Set up other game info ...
        game.setHalfMoves(moves); // set the moves in SAN format

        System.out.println(game.toString());

You don't really need to set a Board to the Game. Important to mention that the PGN standard require some contextual information that cannot be derived from the Board itself (Player names, event name, round, etc). That's why you need to set up a game.

rulogarcillan commented 5 years ago

Now it is much clearer.

Thank you very much, great library