diff --git a/schach/src/main/java/de/hs_mannheim/informatik/chess/model/ChessEngine.java b/schach/src/main/java/de/hs_mannheim/informatik/chess/model/ChessEngine.java index 8f178df..81288de 100644 --- a/schach/src/main/java/de/hs_mannheim/informatik/chess/model/ChessEngine.java +++ b/schach/src/main/java/de/hs_mannheim/informatik/chess/model/ChessEngine.java @@ -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 loadGamesFromPgn(String path) throws IOException { + + PgnHolder pgnHolder = new PgnHolder(path); + try { + pgnHolder.loadPgn(); + } catch (Exception e) { + e.printStackTrace(); + } + List 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 moveList) { + board = new Board(); // Neues leeres Brett + moves.clear(); + currentMoveIndex = 0; + + for (Move move : moveList) { + board.doMove(move); + moves.add(move); + currentMoveIndex++; + } + + } + }