Compare commits

...

2 Commits

Author SHA1 Message Date
mathy 696c0a8d89 Merge branch 'master' of https://gitarero.ecam.fr/mathys.balme/OOP_1B6_Project.git 2025-05-06 16:17:09 +02:00
mathy a59b367e0e added saving/loading from file 2025-05-06 16:16:57 +02:00
1 changed files with 81 additions and 5 deletions

View File

@ -224,16 +224,92 @@ public class Board {
return piece.getValidMoves(this);
}
/* saving-loading feature : */
public String[] toFileRep() {
// TODO
return null;
String[] rep = new String[height + 1]; // height lines for the board + 1 for turn info
// taking each row
for (int y = 0; y < height; y++) {
StringBuilder line = new StringBuilder();
//now each column
for (int x = 0; x < width; x++) {
if (board[x][y] == null) {
line.append("-"); //empty square
} else {
// Convert each piece to a character using the same logic as toString()
Piece piece = board[x][y];
String pieceChar = piece.getType().getSummary(); //get the character representation
// Make black pieces lowercase, just like in toString()
if (!piece.isWhite()) {
pieceChar = pieceChar.toLowerCase();
}
line.append(pieceChar);
}
// Add a comma after each square except the last one
if (x < width - 1) {
line.append(",");
}
}
rep[y] = line.toString();//store line
}
// Add turn information as the last line
rep[height] = isTurnWhite() ? "W" : "B";
return rep;
}
public Board(String[] array) {
// TODO
public Board(String[] fileRepresentation) {
// Determine board dimensions from the file
this.height = fileRepresentation.length - 1; // Last line is turn info
this.width = fileRepresentation[0].split(",").length;//width counting with commas
this.board = new Piece[width][height];
this.selectedX = -1;//no position selected at beginning
this.selectedY = -1;
this.highlightedPositions = new ArrayList<>();//no highlighted position at beginning
// Process each row
for (int y = 0; y < height; y++) {
String[] squares = fileRepresentation[y].split(",");//split rows with commas
for (int x = 0; x < width; x++) {//take the square infos
String squareData = squares[x];
// Skip empty squares
if (squareData.equals("-")) {
continue;
}
char pieceChar = squareData.charAt(0);//take the character of the piece
// Determine color by case: uppercase = white, lowercase = black
boolean isWhite = Character.isUpperCase(pieceChar);
// Convert to uppercase for the fromSummary method if it's lowercase
if (!isWhite) {
pieceChar = Character.toUpperCase(pieceChar);
}
// Get piece type
PieceType type = PieceType.fromSummary(pieceChar);
// Create the piece
setPiece(isWhite, type, x, y);
}
}
// Set turn information
String turnInfo = fileRepresentation[height];
this.turnNumber = turnInfo.equals("W") ? 0 : 1;//white=even, black=odd
clearConsole();
System.out.println(toString());
}
/* additional functionality to implement later */
public void undoLastMove() {
// TODO