2019-10-09 21:03:39 +02:00
|
|
|
package dev.kske.chess.pgn;
|
|
|
|
|
2020-01-19 22:12:33 +01:00
|
|
|
import java.io.*;
|
2019-10-09 21:03:39 +02:00
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.List;
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
import dev.kske.chess.exception.ChessException;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Project: <strong>Chess</strong><br>
|
|
|
|
* File: <strong>PGNDatabase.java</strong><br>
|
|
|
|
* Created: <strong>4 Oct 2019</strong><br>
|
2019-11-08 15:22:12 +01:00
|
|
|
* <br>
|
|
|
|
* Contains a series of {@link PGNGame} objects that can be stored inside a PGN
|
|
|
|
* file.
|
2020-01-19 22:12:33 +01:00
|
|
|
*
|
2019-10-26 07:55:21 +02:00
|
|
|
* @since Chess v0.5-alpha
|
|
|
|
* @author Kai S. K. Engelbart
|
2019-10-09 21:03:39 +02:00
|
|
|
*/
|
|
|
|
public class PGNDatabase {
|
|
|
|
|
2019-11-07 05:53:28 +01:00
|
|
|
private final List<PGNGame> games = new ArrayList<>();
|
2019-10-09 21:03:39 +02:00
|
|
|
|
2019-11-08 15:22:12 +01:00
|
|
|
/**
|
|
|
|
* Loads PGN games from a file.
|
2020-01-19 22:12:33 +01:00
|
|
|
*
|
2019-11-08 15:22:12 +01:00
|
|
|
* @param pgnFile the file to load the games from
|
|
|
|
* @throws FileNotFoundException if the specified file is not found
|
|
|
|
* @throws ChessException if an error occurs while parsing the file
|
|
|
|
*/
|
2020-05-19 16:50:12 +02:00
|
|
|
public void load(File pgnFile)
|
|
|
|
throws FileNotFoundException, ChessException {
|
2020-01-19 22:12:33 +01:00
|
|
|
try (Scanner sc = new Scanner(pgnFile)) {
|
|
|
|
while (sc.hasNext())
|
|
|
|
games.add(PGNGame.parse(sc));
|
|
|
|
}
|
2019-11-07 05:53:28 +01:00
|
|
|
}
|
|
|
|
|
2019-11-08 15:22:12 +01:00
|
|
|
/**
|
|
|
|
* Saves PGN games to a file.
|
2020-01-19 22:12:33 +01:00
|
|
|
*
|
2019-11-08 15:22:12 +01:00
|
|
|
* @param pgnFile the file to save the games to.
|
|
|
|
* @throws IOException if the file could not be created
|
|
|
|
*/
|
|
|
|
public void save(File pgnFile) throws IOException {
|
|
|
|
pgnFile.getParentFile().mkdirs();
|
2020-01-19 22:12:33 +01:00
|
|
|
try (PrintWriter pw = new PrintWriter(pgnFile)) {
|
|
|
|
games.forEach(g -> g.writePGN(pw));
|
|
|
|
}
|
2019-10-09 21:03:39 +02:00
|
|
|
}
|
2019-10-20 08:52:51 +02:00
|
|
|
|
2020-01-19 22:12:33 +01:00
|
|
|
/**
|
|
|
|
* @return all games contained inside this database
|
|
|
|
*/
|
2019-10-20 08:52:51 +02:00
|
|
|
public List<PGNGame> getGames() { return games; }
|
2019-10-09 21:03:39 +02:00
|
|
|
}
|