Compare commits

..

2 Commits

Author SHA1 Message Date
Justin Muravjev cf870fec57 Merge remote-tracking branch 'origin/Main' into PMD-Korrektur 2025-06-24 10:53:19 +02:00
valen 49e88ac03e Korrektur von ChessEngine 2025-06-24 10:26:17 +02:00
2 changed files with 516 additions and 440 deletions

View File

@ -33,7 +33,6 @@
<version>1.3.4</version> <version>1.3.4</version>
</dependency> </dependency>
<!-- JUnit 5 -->
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId> <artifactId>junit-jupiter</artifactId>
@ -51,6 +50,47 @@
</dependencies> </dependencies>
<build> <build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.4.0</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.12.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.6.1</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins> <plugins>
<!-- Java Compiler Plugin --> <!-- Java Compiler Plugin -->
<plugin> <plugin>

View File

@ -1,11 +1,10 @@
package de.hs_mannheim.informatik.chess.model; package de.hs_mannheim.informatik.chess.model;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.ConsoleHandler; import java.util.logging.ConsoleHandler;
@ -21,10 +20,8 @@ import com.github.bhlangonijr.chesslib.move.Move;
import com.github.bhlangonijr.chesslib.pgn.PgnHolder; import com.github.bhlangonijr.chesslib.pgn.PgnHolder;
import com.github.bhlangonijr.chesslib.game.*; import com.github.bhlangonijr.chesslib.game.*;
import com.github.bhlangonijr.chesslib.move.MoveList; import com.github.bhlangonijr.chesslib.move.MoveList;
import java.time.LocalDate;
import com.github.bhlangonijr.chesslib.Side; import com.github.bhlangonijr.chesslib.Side;
public class ChessEngine { public class ChessEngine {
private Board board; private Board board;
private List<Move> moves = new ArrayList<>(); private List<Move> moves = new ArrayList<>();
@ -32,17 +29,13 @@ public class ChessEngine {
private static final Logger logger = Logger.getLogger(ChessEngine.class.getName()); private static final Logger logger = Logger.getLogger(ChessEngine.class.getName());
private int quicksaveWhiteTimeLeft = -1; private int quicksaveWhiteTimeLeft = -1;
private int quicksaveBlackTimeLeft = -1; private int quicksaveBlackTimeLeft = -1;
private int currentMoveIndex = 0; private int currentMoveIndex = 0;
private Timer whiteTimer; private Timer whiteTimer;
private Timer blackTimer; private Timer blackTimer;
private final GameMode mode; private final GameMode mode;
private String quicksaveFen = null; private String quicksaveFen = null;
private List<Move> quicksaveMoves = null; private List<Move> quicksaveMoves = null;
private int quicksaveMoveIndex = 0; private int quicksaveMoveIndex = 0;
private Opening detectedOpening = null; private Opening detectedOpening = null;
public ChessEngine() { public ChessEngine() {
@ -58,6 +51,7 @@ public class ChessEngine {
logging(); logging();
board = new Board(); board = new Board();
} }
public boolean move(MoveDTO move) { public boolean move(MoveDTO move) {
String from = "" + (char) ('A' + move.getFromCol()) + (8 - move.getFromRow()); String from = "" + (char) ('A' + move.getFromCol()) + (8 - move.getFromRow());
String to = "" + (char) ('A' + move.getToCol()) + (8 - move.getToRow()); String to = "" + (char) ('A' + move.getToCol()) + (8 - move.getToRow());
@ -65,26 +59,29 @@ public class ChessEngine {
if (board.legalMoves().contains(libMove)) { if (board.legalMoves().contains(libMove)) {
board.doMove(libMove); board.doMove(libMove);
// Replay? Dann abschneiden
if (currentMoveIndex < moves.size()) { if (currentMoveIndex < moves.size()) {
if (logger.isLoggable(Level.INFO)) {
logger.info("Replay-Modus: Züge nach " + currentMoveIndex + " werden entfernt."); logger.info("Replay-Modus: Züge nach " + currentMoveIndex + " werden entfernt.");
}
moves = new ArrayList<>(moves.subList(0, currentMoveIndex)); moves = new ArrayList<>(moves.subList(0, currentMoveIndex));
} }
moves.add(libMove); moves.add(libMove);
currentMoveIndex++; currentMoveIndex++;
if (logger.isLoggable(Level.INFO)) {
logger.info("Zug erfolgreich durchgeführt: " + libMove); logger.info("Zug erfolgreich durchgeführt: " + libMove);
}
// Opening-Erkennung nach jedem erfolgreichen Zug
String playedMovesUci = movesToUciString(moves); String playedMovesUci = movesToUciString(moves);
detectedOpening = Opening.detect(playedMovesUci); detectedOpening = Opening.detect(playedMovesUci);
if (detectedOpening != null) { if (detectedOpening != null && logger.isLoggable(Level.INFO)) {
logger.info("Aktuelles Opening erkannt: " + detectedOpening.getEco() + " - " + detectedOpening.getName()); logger.info("Aktuelles Opening erkannt: " + detectedOpening.getEco() + " - " + detectedOpening.getName());
// Optional: Speichere das Opening in ein Feld, falls benötigt
} }
return true; return true;
} }
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Ungültiger Zug: " + libMove); logger.warning("Ungültiger Zug: " + libMove);
}
return false; return false;
} }
@ -105,10 +102,12 @@ public class ChessEngine {
} }
public List<MoveDTO> getLegalDestinations(String from) { public List<MoveDTO> getLegalDestinations(String from) {
if (logger.isLoggable(Level.INFO)) {
logger.info("Hole legale Züge von: " + from); logger.info("Hole legale Züge von: " + from);
}
List<MoveDTO> destinations = new ArrayList<>(); List<MoveDTO> destinations = new ArrayList<>();
try { try {
Square fromSq = Square.valueOf(from.toUpperCase()); Square fromSq = Square.valueOf(from.toUpperCase(java.util.Locale.ROOT));
for (Move move : board.legalMoves()) { for (Move move : board.legalMoves()) {
if (move.getFrom().equals(fromSq)) { if (move.getFrom().equals(fromSq)) {
int fromRow = 8 - fromSq.getRank().ordinal() - 1; int fromRow = 8 - fromSq.getRank().ordinal() - 1;
@ -118,19 +117,27 @@ public class ChessEngine {
destinations.add(new MoveDTO(fromRow, fromCol, toRow, toCol)); destinations.add(new MoveDTO(fromRow, fromCol, toRow, toCol));
} }
} }
if (logger.isLoggable(Level.INFO)) {
logger.info("Es wurden " + destinations.size() + " Ziele gefunden."); logger.info("Es wurden " + destinations.size() + " Ziele gefunden.");
}
} catch (Exception e) { } catch (Exception e) {
if (logger.isLoggable(Level.SEVERE)) {
logger.severe("Fehler beim Holen der legalen Ziele: " + e.getMessage()); logger.severe("Fehler beim Holen der legalen Ziele: " + e.getMessage());
} }
}
return destinations; return destinations;
} }
public List<String> getMoveListStringsGrouped() { public List<String> getMoveListStringsGrouped() {
if (logger.isLoggable(Level.INFO)) {
logger.info("Gruppiere Züge für Anzeige."); logger.info("Gruppiere Züge für Anzeige.");
}
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < moves.size(); i++) { for (int i = 0; i < moves.size(); i++) {
if (i % 2 == 0) sb.append((i/2 + 1) + ". "); if (i % 2 == 0) {
sb.append((i / 2 + 1)).append(". ");
}
sb.append(moves.get(i).toString()).append(" "); sb.append(moves.get(i).toString()).append(" ");
if (i % 2 == 1 || i == moves.size() - 1) { if (i % 2 == 1 || i == moves.size() - 1) {
result.add(sb.toString().trim()); result.add(sb.toString().trim());
@ -144,17 +151,28 @@ public class ChessEngine {
this.quicksaveFen = board.getFen(); this.quicksaveFen = board.getFen();
this.quicksaveMoves = new ArrayList<>(moves); this.quicksaveMoves = new ArrayList<>(moves);
this.quicksaveMoveIndex = currentMoveIndex; this.quicksaveMoveIndex = currentMoveIndex;
if (whiteTimer != null) quicksaveWhiteTimeLeft = whiteTimer.getSecondsLeft(); if (whiteTimer != null) {
if (blackTimer != null) quicksaveBlackTimeLeft = blackTimer.getSecondsLeft(); quicksaveWhiteTimeLeft = whiteTimer.getSecondsLeft();
} }
if (blackTimer != null) {
quicksaveBlackTimeLeft = blackTimer.getSecondsLeft();
}
}
public boolean quickload() { public boolean quickload() {
if (quicksaveFen == null) return false; if (quicksaveFen == null) {
return false;
}
board = new Board(); board = new Board();
board.loadFromFen(quicksaveFen); board.loadFromFen(quicksaveFen);
moves = new ArrayList<>(quicksaveMoves); moves = new ArrayList<>(quicksaveMoves);
currentMoveIndex = quicksaveMoveIndex; currentMoveIndex = quicksaveMoveIndex;
if (whiteTimer != null && quicksaveWhiteTimeLeft != -1) whiteTimer.setSecondsLeft(quicksaveWhiteTimeLeft); if (whiteTimer != null && quicksaveWhiteTimeLeft != -1) {
if (blackTimer != null && quicksaveBlackTimeLeft != -1) blackTimer.setSecondsLeft(quicksaveBlackTimeLeft); whiteTimer.setSecondsLeft(quicksaveWhiteTimeLeft);
}
if (blackTimer != null && quicksaveBlackTimeLeft != -1) {
blackTimer.setSecondsLeft(quicksaveBlackTimeLeft);
}
return true; return true;
} }
@ -164,10 +182,11 @@ public class ChessEngine {
quicksaveMoveIndex = 0; quicksaveMoveIndex = 0;
} }
public PieceDTO getPieceAt(String square) { public PieceDTO getPieceAt(String square) {
if (logger.isLoggable(Level.INFO)) {
logger.info("Hole Figur an Feld: " + square); logger.info("Hole Figur an Feld: " + square);
Piece piece = board.getPiece(Square.valueOf(square.toUpperCase())); }
Piece piece = board.getPiece(Square.valueOf(square.toUpperCase(java.util.Locale.ROOT)));
return convertPieceToDTO(piece); return convertPieceToDTO(piece);
} }
@ -175,14 +194,21 @@ public class ChessEngine {
String from = "" + (char) ('A' + move.getFromCol()) + (8 - move.getFromRow()); String from = "" + (char) ('A' + move.getFromCol()) + (8 - move.getFromRow());
String to = "" + (char) ('A' + move.getToCol()) + (8 - move.getToRow()); String to = "" + (char) ('A' + move.getToCol()) + (8 - move.getToRow());
// Die Farbe bestimmen!
boolean isWhite = (8 - move.getFromRow()) < (8 - move.getToRow()); boolean isWhite = (8 - move.getFromRow()) < (8 - move.getToRow());
Piece promotion; Piece promotion;
switch (promotionPiece) { switch (promotionPiece) {
case "ROOK": promotion = isWhite ? Piece.WHITE_ROOK : Piece.BLACK_ROOK; break; case "ROOK":
case "KNIGHT": promotion = isWhite ? Piece.WHITE_KNIGHT : Piece.BLACK_KNIGHT; break; promotion = isWhite ? Piece.WHITE_ROOK : Piece.BLACK_ROOK;
case "BISHOP": promotion = isWhite ? Piece.WHITE_BISHOP : Piece.BLACK_BISHOP; break; break;
default: promotion = isWhite ? Piece.WHITE_QUEEN : Piece.BLACK_QUEEN; case "KNIGHT":
promotion = isWhite ? Piece.WHITE_KNIGHT : Piece.BLACK_KNIGHT;
break;
case "BISHOP":
promotion = isWhite ? Piece.WHITE_BISHOP : Piece.BLACK_BISHOP;
break;
default:
promotion = isWhite ? Piece.WHITE_QUEEN : Piece.BLACK_QUEEN;
break;
} }
Move libMove = new Move(Square.valueOf(from), Square.valueOf(to), promotion); Move libMove = new Move(Square.valueOf(from), Square.valueOf(to), promotion);
@ -195,15 +221,21 @@ public class ChessEngine {
} }
moves.add(libMove); moves.add(libMove);
currentMoveIndex++; currentMoveIndex++;
if (logger.isLoggable(Level.INFO)) {
logger.info("Promotionszug durchgeführt: " + libMove); logger.info("Promotionszug durchgeführt: " + libMove);
}
return true; return true;
} }
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Ungültiger Promotionszug: " + libMove); logger.warning("Ungültiger Promotionszug: " + libMove);
}
return false; return false;
} }
public BoardDTO getBoardAsDTO() { public BoardDTO getBoardAsDTO() {
if (logger.isLoggable(Level.INFO)) {
logger.info("Erstelle DTO-Abbild des Boards"); logger.info("Erstelle DTO-Abbild des Boards");
}
PieceDTO[][] dtoBoard = new PieceDTO[8][8]; PieceDTO[][] dtoBoard = new PieceDTO[8][8];
for (int rank = 8; rank >= 1; rank--) { for (int rank = 8; rank >= 1; rank--) {
for (int file = 0; file < 8; file++) { for (int file = 0; file < 8; file++) {
@ -217,26 +249,41 @@ public class ChessEngine {
private String pieceToUnicode(Piece piece) { private String pieceToUnicode(Piece piece) {
switch (piece) { switch (piece) {
case WHITE_KING: return "♔"; case WHITE_KING:
case WHITE_QUEEN: return "♕"; return "♔";
case WHITE_ROOK: return "♖"; case WHITE_QUEEN:
case WHITE_BISHOP: return "♗"; return "♕";
case WHITE_KNIGHT: return "♘"; case WHITE_ROOK:
case WHITE_PAWN: return "♙"; return "♖";
case BLACK_KING: return "♚"; case WHITE_BISHOP:
case BLACK_QUEEN: return "♛"; return "♗";
case BLACK_ROOK: return "♜"; case WHITE_KNIGHT:
case BLACK_BISHOP: return "♝"; return "♘";
case BLACK_KNIGHT: return "♞"; case WHITE_PAWN:
case BLACK_PAWN: return "♟"; return "♙";
default: return " "; case BLACK_KING:
return "♚";
case BLACK_QUEEN:
return "♛";
case BLACK_ROOK:
return "♜";
case BLACK_BISHOP:
return "♝";
case BLACK_KNIGHT:
return "♞";
case BLACK_PAWN:
return "♟";
default:
return " ";
} }
} }
public void setPositionToMoveIndex(int idx) { public void setPositionToMoveIndex(int idx) {
if (logger.isLoggable(Level.INFO)) {
logger.info("Setze Board auf Zug-Index: " + idx); logger.info("Setze Board auf Zug-Index: " + idx);
}
board = new Board(); board = new Board();
board.loadFromFen(initialFen); // Statt new Board() -> initialFen! board.loadFromFen(initialFen);
for (int i = 0; i < idx; i++) { for (int i = 0; i < idx; i++) {
board.doMove(moves.get(i)); board.doMove(moves.get(i));
} }
@ -245,20 +292,27 @@ public class ChessEngine {
String playedMovesUci = movesToUciString(moves.subList(0, idx)); String playedMovesUci = movesToUciString(moves.subList(0, idx));
detectedOpening = Opening.detect(playedMovesUci); detectedOpening = Opening.detect(playedMovesUci);
} }
public int getCurrentMoveIndex() { public int getCurrentMoveIndex() {
if (logger.isLoggable(Level.INFO)) {
logger.info("Hole aktuellen Zug-Index: " + currentMoveIndex); logger.info("Hole aktuellen Zug-Index: " + currentMoveIndex);
}
return currentMoveIndex; return currentMoveIndex;
} }
public int getMoveListSize() { public int getMoveListSize() {
if (logger.isLoggable(Level.INFO)) {
logger.info("Hole Anzahl gespielter Züge: " + moves.size()); logger.info("Hole Anzahl gespielter Züge: " + moves.size());
}
return moves.size(); return moves.size();
} }
private PieceDTO convertPieceToDTO(Piece piece) { private PieceDTO convertPieceToDTO(Piece piece) {
if (piece == null || piece.equals(Piece.NONE)) return null; if (piece == null || piece.equals(Piece.NONE)) {
return null;
}
String color = piece.name().startsWith("WHITE") ? "WHITE" : "BLACK"; String color = piece.name().startsWith("WHITE") ? "WHITE" : "BLACK";
String type = piece.name().substring(piece.name().indexOf('_') + 1); // "PAWN", "KING"... String type = piece.name().substring(piece.name().indexOf('_') + 1);
String symbol = pieceToUnicode(piece); String symbol = pieceToUnicode(piece);
return new PieceDTO(type, color, symbol); return new PieceDTO(type, color, symbol);
} }
@ -268,34 +322,39 @@ public class ChessEngine {
initialFen = fen; initialFen = fen;
} }
public boolean isMated() { public boolean isMated() {
boolean mated = board.isMated(); boolean mated = board.isMated();
if (logger.isLoggable(Level.INFO)) {
logger.info("isMated() = " + mated); logger.info("isMated() = " + mated);
}
return mated; return mated;
} }
public boolean isStalemate() { public boolean isStalemate() {
boolean stale = board.isStaleMate(); boolean stale = board.isStaleMate();
if (logger.isLoggable(Level.INFO)) {
logger.info("isStalemate() = " + stale); logger.info("isStalemate() = " + stale);
}
return stale; return stale;
} }
public boolean isDraw() { public boolean isDraw() {
boolean draw = board.isDraw(); boolean draw = board.isDraw();
if (logger.isLoggable(Level.INFO)) {
logger.info("isDraw() = " + draw); logger.info("isDraw() = " + draw);
}
return draw; return draw;
} }
public String getCurrentPlayer() { public String getCurrentPlayer() {
String player = board.getSideToMove().toString(); String player = board.getSideToMove().toString();
if (logger.isLoggable(Level.INFO)) {
logger.info("Am Zug: " + player); logger.info("Am Zug: " + player);
}
return player; return player;
} }
public void logging() { public void logging() {
// Eigener Handler nur für diese Klasse
ConsoleHandler handler = new ConsoleHandler(); ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.ALL); handler.setLevel(Level.ALL);
handler.setFormatter(new SimpleFormatter() { handler.setFormatter(new SimpleFormatter() {
@ -307,19 +366,19 @@ public class ChessEngine {
logger.setUseParentHandlers(false); logger.setUseParentHandlers(false);
logger.addHandler(handler); logger.addHandler(handler);
if (logger.isLoggable(Level.INFO)) {
logger.info("ChessEngine wurde initialisiert."); logger.info("ChessEngine wurde initialisiert.");
} }
}
public List<Game> loadGamesFromPgn(String path) throws IOException { public List<Game> loadGamesFromPgn(String path) throws IOException {
PgnHolder pgnHolder = new PgnHolder(path); PgnHolder pgnHolder = new PgnHolder(path);
try { try {
pgnHolder.loadPgn(); pgnHolder.loadPgn();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
List<Game> games = pgnHolder.getGames(); return pgnHolder.getGames();
return games;
} }
public void initTimers(int min, int sec) { public void initTimers(int min, int sec) {
@ -343,17 +402,14 @@ public class ChessEngine {
} }
public void saveAsPgn(Game game, String path, String dateiname) { public void saveAsPgn(Game game, String path, String dateiname) {
// Sicher alle Strings holen (nie null)
String event = safe(game.getRound().getEvent().getName()); String event = safe(game.getRound().getEvent().getName());
String site = safe(game.getRound().getEvent().getSite()); String site = safe(game.getRound().getEvent().getSite());
String round = "" + game.getRound().getNumber(); String round = "" + game.getRound().getNumber();
// Datum für PGN-Format (YYYY.MM.DD)
String date = safe(game.getRound().getEvent().getStartDate()).replace("-", "."); String date = safe(game.getRound().getEvent().getStartDate()).replace("-", ".");
String wName = safe(game.getWhitePlayer().getName()); String wName = safe(game.getWhitePlayer().getName());
String bName = safe(game.getBlackPlayer().getName()); String bName = safe(game.getBlackPlayer().getName());
String result = safe(game.getResult().getDescription()); String result = safe(game.getResult().getDescription());
// PGN-Header zusammenbauen
StringBuilder header = new StringBuilder(); StringBuilder header = new StringBuilder();
header.append("[Event \"" + event + "\"]\n"); header.append("[Event \"" + event + "\"]\n");
header.append("[Site \"" + site + "\"]\n"); header.append("[Site \"" + site + "\"]\n");
@ -363,23 +419,19 @@ public class ChessEngine {
header.append("[Black \"" + bName + "\"]\n"); header.append("[Black \"" + bName + "\"]\n");
header.append("[Result \"" + result + "\"]\n\n"); header.append("[Result \"" + result + "\"]\n\n");
// Züge als SAN holen StringBuilder movesSb = new StringBuilder();
StringBuilder moves = new StringBuilder();
String[] sanArray = game.getHalfMoves().toSanArray(); String[] sanArray = game.getHalfMoves().toSanArray();
for (int i = 0; i < sanArray.length; i++) { for (int i = 0; i < sanArray.length; i++) {
if (i % 2 == 0) { if (i % 2 == 0) {
moves.append((i / 2 + 1)).append(". "); movesSb.append((i / 2 + 1)).append(". ");
} }
moves.append(sanArray[i]).append(" "); movesSb.append(sanArray[i]).append(" ");
// Optional: Zeilenumbruch für Lesbarkeit
// if (i > 0 && i % 8 == 0) moves.append("\n");
} }
moves.append(result); // Ergebnis am Ende! movesSb.append(result);
String file = header + moves.toString(); String file = header + movesSb.toString();
// Datei schreiben
try { try {
Files.writeString(Path.of(path, dateiname), file, StandardCharsets.UTF_8); Files.writeString(Path.of(path, dateiname), file, StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
@ -387,7 +439,6 @@ public class ChessEngine {
} }
} }
// Hilfsfunktion für Null-Sicherheit
private String safe(String s) { private String safe(String s) {
return s == null ? "?" : s; return s == null ? "?" : s;
} }
@ -396,25 +447,20 @@ public class ChessEngine {
return getCurrentGame(this.board, this.moves, this.currentMoveIndex); return getCurrentGame(this.board, this.moves, this.currentMoveIndex);
} }
public Game getCurrentGame(Board board, java.util.List<Move> moves, int currentMoveIndex) { public Game getCurrentGame(Board board, List<Move> moves, int currentMoveIndex) {
// Event und Turnierdaten setzen
Event event = new Event(); Event event = new Event();
event.setName("Generated Game"); event.setName("Generated Game");
event.setSite("Local"); event.setSite("Local");
event.setStartDate(LocalDate.now().toString()); // Format: yyyy-MM-dd event.setStartDate(LocalDate.now().toString());
// Runde anlegen
Round round = new Round(event); Round round = new Round(event);
round.setNumber(1); round.setNumber(1);
// Spiel initialisieren Game game = new Game("1", round);
Game game = new Game("1", round); // "1" ist die Game-ID
// Spieler setzen (deine MyPlayer-Klasse)
game.setWhitePlayer(new MyPlayer("White")); game.setWhitePlayer(new MyPlayer("White"));
game.setBlackPlayer(new MyPlayer("Black")); game.setBlackPlayer(new MyPlayer("Black"));
// Ergebnis setzen
if (board.isMated()) { if (board.isMated()) {
game.setResult(board.getSideToMove() == Side.WHITE ? GameResult.BLACK_WON : GameResult.WHITE_WON); game.setResult(board.getSideToMove() == Side.WHITE ? GameResult.BLACK_WON : GameResult.WHITE_WON);
} else if (board.isStaleMate() || board.isDraw()) { } else if (board.isStaleMate() || board.isDraw()) {
@ -423,43 +469,37 @@ public class ChessEngine {
game.setResult(GameResult.ONGOING); game.setResult(GameResult.ONGOING);
} }
// Züge übernehmen
MoveList moveList = new MoveList(); MoveList moveList = new MoveList();
for (Move move : moves) { for (Move move : moves) {
moveList.add(move); moveList.add(move);
} }
game.setHalfMoves(moveList); game.setHalfMoves(moveList);
// Position auf aktuellen Zug setzen (letzter gespielter Halbzug)
if (currentMoveIndex > 0 && currentMoveIndex <= moveList.size()) { if (currentMoveIndex > 0 && currentMoveIndex <= moveList.size()) {
game.setPosition(currentMoveIndex - 1); game.setPosition(currentMoveIndex - 1);
} else { } else {
game.setPosition(moveList.size() - 1); game.setPosition(moveList.size() - 1);
} }
// FEN setzen: JETZT das aktuelle Board-FEN verwenden!
game.setBoard(new Board()); game.setBoard(new Board());
game.getBoard().loadFromFen(board.getFen()); game.getBoard().loadFromFen(board.getFen());
return game; return game;
} }
public void undoLastMove() { public void undoLastMove() {
if (currentMoveIndex > 0 && moves.size() > 0) { if (currentMoveIndex > 0 && !moves.isEmpty()) {
board.undoMove(); // 1. Brett zurücksetzen board.undoMove();
moves.remove(currentMoveIndex - 1); // 2. Zug aus Move-Liste löschen moves.remove(currentMoveIndex - 1);
currentMoveIndex--; // 3. Index anpassen currentMoveIndex--;
// 4. Erkennung Opening neu machen!
String playedMovesUci = movesToUciString(moves.subList(0, currentMoveIndex)); String playedMovesUci = movesToUciString(moves.subList(0, currentMoveIndex));
detectedOpening = Opening.detect(playedMovesUci); detectedOpening = Opening.detect(playedMovesUci);
} }
} }
public void loadMoves(List<Move> moveList) { public void loadMoves(List<Move> moveList) {
board = new Board(); // Neues leeres Brett board = new Board();
moves.clear(); moves.clear();
currentMoveIndex = 0; currentMoveIndex = 0;
@ -468,21 +508,17 @@ public class ChessEngine {
moves.add(move); moves.add(move);
currentMoveIndex++; currentMoveIndex++;
} }
} }
public Timer getWhiteTimer() { return whiteTimer; } public Timer getWhiteTimer() {
return whiteTimer;
public Timer getBlackTimer() { return blackTimer; } }
public Timer getBlackTimer() {
return blackTimer;
}
public GameMode getGameMode() { public GameMode getGameMode() {
// TODO Auto-generated method stub
return mode; return mode;
} }
} }