Implemented game serialization to the PGN format #16

Merged
CyB3RC0nN0R merged 9 commits from f/pgn_save into master 2019-12-11 07:53:46 +01:00
Showing only changes of commit 546b818345 - Show all commits

View File

@ -2,6 +2,7 @@ package dev.kske.chess.pgn;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -12,6 +13,7 @@ import java.util.regex.Pattern;
import dev.kske.chess.board.Board; import dev.kske.chess.board.Board;
import dev.kske.chess.board.FENString; import dev.kske.chess.board.FENString;
import dev.kske.chess.board.Move; import dev.kske.chess.board.Move;
import dev.kske.chess.board.Piece.Color;
import dev.kske.chess.exception.ChessException; import dev.kske.chess.exception.ChessException;
/** /**
@ -82,23 +84,26 @@ public class PGNGame {
// Collect SAN moves // Collect SAN moves
Board clone = new Board(board, true); Board clone = new Board(board, true);
List<String> sanMoves = new ArrayList<>(); List<String> chunks = new ArrayList<>();
while (clone.getLog().hasParent()) { while (clone.getLog().hasParent()) {
Move move = clone.getLog().getLast().move; Move move = clone.getLog().getLast().move;
clone.revert(); clone.revert();
sanMoves.add(move.toSAN(clone)); String chunk = clone.getLog().getLast().activeColor == Color.WHITE ? String.format(" %d. ", clone.getLog().getLast().fullmoveCounter)
: " ";
chunk += move.toSAN(clone);
chunks.add(chunk);
} }
Collections.reverse(chunks);
// Write movetext // Write movetext
for (int i = sanMoves.size() - 1; i >= 0; i--) String line = "";
pw.printf("%s ", sanMoves.get(i)); for (String chunk : chunks)
if (line.length() + chunk.length() <= 80) line += chunk;
// Write movetext else {
// board.getLog().forEach(m -> { // Flush line
// if (m.activeColor == Color.BLACK) pw.printf("%d. ", m.fullmoveCounter); pw.println(line);
// pw.printf("%s ", m.move.toSAN(board)); line = "";
// }); }
// Write game termination marker // Write game termination marker
pw.print(tagPairs.get("Result")); pw.print(tagPairs.get("Result"));