From 8dffe28b81f97e42b4e7d420b50b795f83a41517 Mon Sep 17 00:00:00 2001 From: VALENTINE GIRAL Date: Fri, 9 May 2025 09:23:44 +0200 Subject: [PATCH] loading/saving system --- src/backend/Board.java | 60 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/src/backend/Board.java b/src/backend/Board.java index 8edcbe5..e4adb72 100644 --- a/src/backend/Board.java +++ b/src/backend/Board.java @@ -204,6 +204,7 @@ public class Board { } public ArrayList getValidMoves(Piece p) { + // Calculate the valid moves for each Piece type ArrayList moves = new ArrayList<>(); int x = p.getX(), y = p.getY(); boolean isWhite = p.isWhite(); @@ -283,17 +284,64 @@ public class Board { /* saving-loading feature :*/ public String[] toFileRep() { - //TODO - return null; + ArrayList fileLines = new ArrayList<>(); + + // First line: game state (turn number and current player) + fileLines.add(turnNumber + "," + (turnWhite ? "white" : "black")); + + // Second line: board dimensions + fileLines.add(line + "," + col); + + // Get all pieces on the board + ArrayList pieces = getPieces(); + + // Add one line per piece with format: pieceType,x,y,color + for (Piece piece : pieces) { + StringBuilder pieceInfo = new StringBuilder(); + pieceInfo.append(piece.getType()).append(","); + pieceInfo.append(piece.getX()).append(","); + pieceInfo.append(piece.getY()).append(","); + pieceInfo.append(piece.isWhite() ? "W" : "B"); + + fileLines.add(pieceInfo.toString()); + } + + return fileLines.toArray(new String[0]); } - public Board(String[] array) { - //TODO + public Board(String[] fileRepresentation) { + // Parse game state from first line + String[] gameState = fileRepresentation[0].split(","); + turnNumber = Integer.parseInt(gameState[0]); + turnWhite = gameState[1].equals("white"); + + // Parse board dimensions from second line + String[] dimensions = fileRepresentation[1].split(","); + line = Integer.parseInt(dimensions[0]); + col = Integer.parseInt(dimensions[1]); + + // Initialize the board with the specified dimensions + board = new Piece[line][col]; + + // Parse pieces from the remaining lines + for (int i = 2; i < fileRepresentation.length; i++) { + String[] pieceInfo = fileRepresentation[i].split(","); + + PieceType pieceType = PieceType.valueOf(pieceInfo[0]); + int x = Integer.parseInt(pieceInfo[1]); + int y = Integer.parseInt(pieceInfo[2]); + boolean isWhite = pieceInfo[3].equals("W"); + + // Create the piece and place it on the board + board[y][x] = new Piece(isWhite,pieceType, x, y); + } + + // Initialize other state variables + selectedPosition = null; + highlightedPositions = new ArrayList<>(); } - /* The following methods require more work ! */ - public boolean isHighlighted(int x, int y) { // Storing valid moves when piece is selected for (int[] pos : highlightedPositions) {