Added empty save methods to PGNDatabase and PGNGame

This commit is contained in:
Kai S. K. Engelbart 2019-11-07 05:53:28 +01:00
parent e070bb584f
commit d6b5442ee9
Signed by: kske
GPG Key ID: 8BEB13EC5DF7EF13
3 changed files with 34 additions and 7 deletions

View File

@ -109,8 +109,14 @@ public class Log implements Iterable<MoveNode> {
} else reset();
}
/**
* @return {@code true} if the root node exists
*/
public boolean isEmpty() { return root == null; }
/**
* @return {@code true} if the current node has a parent node
*/
public boolean hasParent() { return !isEmpty() && current.hasParent(); }
/**

View File

@ -2,6 +2,7 @@ package dev.kske.chess.pgn;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
@ -18,15 +19,19 @@ import dev.kske.chess.exception.ChessException;
*/
public class PGNDatabase {
private final List<PGNGame> games = new ArrayList<>();
private final List<PGNGame> games = new ArrayList<>();
public void load(File pgnFile) throws FileNotFoundException, ChessException {
try (Scanner sc = new Scanner(pgnFile)) {
while (sc.hasNext())
games.add(PGNGame.parse(sc));
} catch (FileNotFoundException | ChessException e) {
throw e;
}
Scanner sc = new Scanner(pgnFile);
while (sc.hasNext())
games.add(PGNGame.parse(sc));
sc.close();
}
public void save(File pgnFile) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(pgnFile);
games.forEach(g -> g.writePGN(pw));
pw.close();
}
public List<PGNGame> getGames() { return games; }

View File

@ -1,5 +1,6 @@
package dev.kske.chess.pgn;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
@ -8,6 +9,7 @@ import java.util.regex.Pattern;
import dev.kske.chess.board.Board;
import dev.kske.chess.board.FENString;
import dev.kske.chess.board.Piece.Color;
import dev.kske.chess.exception.ChessException;
/**
@ -62,6 +64,20 @@ public class PGNGame {
return game;
}
public void writePGN(PrintWriter pw) {
// Write tag pairs
tagPairs.forEach((k, v) -> pw.printf("[%s \"%s\"]%n", k, v));
// Write movetext
board.getLog().forEach(m -> {
if (m.activeColor == Color.BLACK) pw.printf("%d. ", m.fullmoveCounter);
pw.print(m.move); // TODO: Convert to SAN
});
// TODO: Write game termination marker
// TODO: Check if the game has ended
}
public String getTag(String tagName) { return tagPairs.get(tagName); }
public boolean hasTag(String tagName) { return tagPairs.containsKey(tagName); }