Valentins pgn methods for saving and loading pgn files in ChessEngine

SavePgn
Justin 2025-06-23 03:01:16 +02:00
parent 0d37de1cd9
commit 24f6339b06
1 changed files with 68 additions and 0 deletions

View File

@ -1,4 +1,5 @@
package de.hs_mannheim.informatik.chess.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.ConsoleHandler;
@ -10,7 +11,9 @@ import java.util.logging.SimpleFormatter;
import com.github.bhlangonijr.chesslib.Board;
import com.github.bhlangonijr.chesslib.Piece;
import com.github.bhlangonijr.chesslib.Square;
import com.github.bhlangonijr.chesslib.game.Game;
import com.github.bhlangonijr.chesslib.move.Move;
import com.github.bhlangonijr.chesslib.pgn.PgnHolder;
public class ChessEngine {
private Board board;
@ -223,4 +226,69 @@ public class ChessEngine {
logger.info("ChessEngine wurde initialisiert.");
}
public List<Game> loadGamesFromPgn(String path) throws IOException {
PgnHolder pgnHolder = new PgnHolder(path);
try {
pgnHolder.loadPgn();
} catch (Exception e) {
e.printStackTrace();
}
List<Game> games = pgnHolder.getGames();
return games;
}
public void saveAsPgn(Game game, String path, String dateiname) {
String event = game.getRound().getEvent().getName();
String site = game.getRound().getEvent().getSite();
String round = "" + game.getRound().getNumber();
String date = game.getRound().getEvent().getStartDate();
String wName = game.getWhitePlayer().getName();
String bName = game.getBlackPlayer().getName();
String result = game.getResult().getDescription();
StringBuilder header = new StringBuilder();
header.append("[Event \"" + event + "\"]\n");
header.append("[Site \"" + site + "\"]\n");
header.append("[Date \"" + date + "\"]\n");
header.append("[Round \"" + round + "\"]\n");
header.append("[White \"" + wName + "\"]\n");
header.append("[Black \"" + bName + "\"]\n");
header.append("[Result \"" + result + "\"]\n");
header.append("\n");
StringBuilder sb = new StringBuilder();
String[] sanArray = game.getHalfMoves().toSanArray();
for (int i = 0; i < sanArray.length; i++) {
if (i % 2 == 0) {
sb.append((i / 2 + 1)).append(". ");
}
sb.append(sanArray[i]).append(" ");
}
sb.append(result); // Endergebnis muss auch am Ende stehen!
String file = header.toString() + sb.toString();
// try {
// Files.writeString(Path.of(path, dateiname), file, StandardCharsets.UTF_8);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
public void loadMoves(List<Move> moveList) {
board = new Board(); // Neues leeres Brett
moves.clear();
currentMoveIndex = 0;
for (Move move : moveList) {
board.doMove(move);
moves.add(move);
currentMoveIndex++;
}
}
}