loading/saving system

This commit is contained in:
Valentine GIRAL 2025-05-09 09:23:44 +02:00
parent 1796c22554
commit 8dffe28b81
1 changed files with 54 additions and 6 deletions

View File

@ -204,6 +204,7 @@ public class Board {
} }
public ArrayList<int[]> getValidMoves(Piece p) { public ArrayList<int[]> getValidMoves(Piece p) {
// Calculate the valid moves for each Piece type
ArrayList<int[]> moves = new ArrayList<>(); ArrayList<int[]> moves = new ArrayList<>();
int x = p.getX(), y = p.getY(); int x = p.getX(), y = p.getY();
boolean isWhite = p.isWhite(); boolean isWhite = p.isWhite();
@ -283,17 +284,64 @@ public class Board {
/* saving-loading feature :*/ /* saving-loading feature :*/
public String[] toFileRep() { public String[] toFileRep() {
//TODO ArrayList<String> fileLines = new ArrayList<>();
return null;
// 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<Piece> 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) { public Board(String[] fileRepresentation) {
//TODO // 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) { public boolean isHighlighted(int x, int y) {
// Storing valid moves when piece is selected // Storing valid moves when piece is selected
for (int[] pos : highlightedPositions) { for (int[] pos : highlightedPositions) {