From 1796c225548fb201b9d23bb1a2c2ff9422dfc8a5 Mon Sep 17 00:00:00 2001 From: VALENTINE GIRAL Date: Fri, 9 May 2025 08:56:26 +0200 Subject: [PATCH] new comments + valid piece moves only --- src/backend/Board.java | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/backend/Board.java b/src/backend/Board.java index a44596d..8edcbe5 100644 --- a/src/backend/Board.java +++ b/src/backend/Board.java @@ -9,12 +9,15 @@ public class Board { private int [] selectedPosition = null; // No piece selected initially private int turnNumber=0; // Tracks the number of turns elapsed private boolean turnWhite=true; // True if it's White's turn, False if it's Black's turn - private ArrayList highlightedPositions = new ArrayList<>();//this list contain all the board positions + private ArrayList highlightedPositions = new ArrayList<>();// List containing all board positions + private boolean inBounds(int x, int y) { + // Verify the bounds of the board return x >= 0 && y >= 0 && x < col && y < line; } private boolean hasEnemy(int x, int y, boolean isWhite) { + // Detect an enemy piece, meaning from a different color return board[y][x] != null && board[y][x].isWhite() != isWhite; } @@ -84,7 +87,7 @@ public class Board { PieceType.Knight, PieceType.Rook }; - // place black pieces (false = black) + // Place black pieces (false = black) for (int x=0;x<8;x++) { // Row 0: black major pieces setPiece(false,backRow[x],x,0); @@ -102,7 +105,7 @@ public class Board { } public void cleanBoard() { - // removes all pieces from the board, readying it to add pieces for a new game + // Removes all pieces from the board, readying it to add pieces for a new game // Iterate over each row and column and set the board position to null for (int y = 0; y < line; y++) { for (int x = 0; x < col; x++) { @@ -175,11 +178,23 @@ public class Board { // If a piece is selected and the user clicks a new position else { - movePiece(selectedX,selectedY,x,y); - // Update turn - this.turnNumber++; - this.turnWhite=!this.turnWhite; - + // Check if the move is valid by checking if it exists in highlightedPositions + boolean isValidMove = false; + for (int[] pos : highlightedPositions) { + if (pos[0] == x && pos[1] == y) { + isValidMove = true; + break; + } + } + + // Only move the piece if the destination is valid + if (isValidMove) { + movePiece(selectedX, selectedY, x, y); + // Update turn + this.turnNumber++; + this.turnWhite = !this.turnWhite; + } + // Deselect the position after moving this.selectedPosition = null; highlightedPositions.clear();//Clear after move @@ -280,6 +295,7 @@ public class Board { /* The following methods require more work ! */ public boolean isHighlighted(int x, int y) { + // Storing valid moves when piece is selected for (int[] pos : highlightedPositions) { if (pos[0] == x && pos[1] == y) return true;