i put getValidMove into move class for more clarity
This commit is contained in:
parent
db431b8d0b
commit
c2cf49475d
|
|
@ -14,6 +14,7 @@ public class Board {
|
|||
private boolean turnWhite = true;
|
||||
private ArrayList<int[]> highlightedSquares = new ArrayList<>();
|
||||
private int[] enPassantTarget = null; // [x,y] coordinates of en passant target square
|
||||
private Move moveHelper = new Move();
|
||||
|
||||
public Board(int colNum, int lineNum) {
|
||||
this.width = colNum;
|
||||
|
|
@ -192,7 +193,7 @@ public class Board {
|
|||
selectedX = x;
|
||||
selectedY = y;
|
||||
hasSelectedPiece = true;
|
||||
highlightedSquares = getValidMoves(clicked);
|
||||
highlightedSquares = moveHelper.getValidMoves(clicked, board, width, height, enPassantTarget);
|
||||
}
|
||||
} else {
|
||||
// Check if clicked again on the same square to unselect
|
||||
|
|
|
|||
|
|
@ -1,5 +1,55 @@
|
|||
package backend;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Move {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public ArrayList<int[]> getValidMoves(Piece piece, Piece[][] board, int width, int height, int[] enPassantTarget) {
|
||||
ArrayList<int[]> moves = new ArrayList<>();
|
||||
int x = piece.getX();
|
||||
int y = piece.getY();
|
||||
PieceType type = piece.getType();
|
||||
|
||||
if (type == PieceType.Pawn) {
|
||||
int dir = piece.isWhite() ? 1 : -1;
|
||||
int startRow = piece.isWhite() ? 1 : 6;
|
||||
|
||||
int oneStep = y + dir;
|
||||
if (inBounds(x, oneStep, width, height) && board[x][oneStep] == null) {
|
||||
moves.add(new int[]{x, oneStep});
|
||||
int twoStep = y + 2 * dir;
|
||||
if (y == startRow && inBounds(x, twoStep, width, height) &&
|
||||
board[x][twoStep] == null && board[x][oneStep] == null) {
|
||||
moves.add(new int[]{x, twoStep});
|
||||
}
|
||||
}
|
||||
|
||||
for (int dx : new int[]{-1, 1}) {
|
||||
int nx = x + dx;
|
||||
int ny = y + dir;
|
||||
if (inBounds(nx, ny, width, height)) {
|
||||
if (board[nx][ny] != null && board[nx][ny].isWhite() != piece.isWhite()) {
|
||||
moves.add(new int[]{nx, ny});
|
||||
}
|
||||
else if (board[nx][ny] == null && enPassantTarget != null &&
|
||||
nx == enPassantTarget[0] && ny == enPassantTarget[1]) {
|
||||
int capturedY = y;
|
||||
if (inBounds(nx, capturedY, width, height) &&
|
||||
board[nx][capturedY] != null &&
|
||||
board[nx][capturedY].getType() == PieceType.Pawn &&
|
||||
board[nx][capturedY].isWhite() != piece.isWhite()) {
|
||||
moves.add(new int[]{nx, ny});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return moves;
|
||||
}
|
||||
|
||||
private boolean inBounds(int x, int y, int width, int height) {
|
||||
return x >= 0 && x < width && y >= 0 && y < height;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue