added comments to the undo method
This commit is contained in:
parent
f5eeb1ef87
commit
c555ba8350
|
|
@ -261,41 +261,41 @@ return false; }
|
|||
* Reverts the board state back one move.
|
||||
*/
|
||||
public void undoLastMove() {
|
||||
if (previousStates.isEmpty()) {
|
||||
if (previousStates.isEmpty()) { //If previousStates is empty, so we just print a mess
|
||||
System.out.println("There are no moves to undo.");
|
||||
return;
|
||||
}
|
||||
|
||||
// 1) Pop off the most recent snapshot
|
||||
Board prev = previousStates.remove(previousStates.size() - 1);
|
||||
|
||||
// 2) Restore the board array
|
||||
// Pop off the most recent snapshot
|
||||
Board prev = previousStates.remove(previousStates.size() - 1); //previousStates is stack of full-board copies taken before each move.
|
||||
//By removing the last entry,getting back a Board object (prev) that represents
|
||||
// Restore the board array the entire game state just before the move we want to undo.
|
||||
this.board = new Piece[width][height];
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) { //We re-create this.board (your 2D array of Piece references) and copy each cell from prev.board.
|
||||
for (int y = 0; y < height; y++) { //That means any piece that was on e4 in the snapshot winds up back on e4 now
|
||||
this.board[x][y] = prev.board[x][y];
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Restore all other game‐state fields
|
||||
// Restore all other game‐state fields, Copy every field from that snapshot back into THIS:
|
||||
this.chosenPiece = prev.chosenPiece;
|
||||
this.turnNumber= prev.turnNumber;
|
||||
this.isTurnWhite= prev.isTurnWhite;
|
||||
this.lastMove= prev.lastMove;
|
||||
this.highlightedSquares = new ArrayList<>(prev.highlightedSquares);
|
||||
|
||||
// 4) **Critical**: reset each Piece’s own coordinates to match its array slot
|
||||
// reset each Piece’s own coordinates to match its array slot
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
Piece p = this.board[x][y];
|
||||
Piece p = this.board[x][y]; // we grab whenever is at the xy coordinates and store it in p varaible
|
||||
if (p != null) {
|
||||
p.setX(x);
|
||||
p.setY(y);
|
||||
p.setX(x); //By writing those indices back into p via setX(x)/setY(y)
|
||||
p.setY(y); // we restore each piece’s private coordinates to their pre-move values.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5) Clear any lingering selection or highlights
|
||||
// Clear any lingering selection or highlights
|
||||
this.chosenPiece = null;
|
||||
this.highlightedSquares.clear();
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue