-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueen.java
More file actions
50 lines (41 loc) · 1.89 KB
/
Queen.java
File metadata and controls
50 lines (41 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Queen extends Piece {
public Queen(String position, boolean isWhite) {
super(position, isWhite);
}
@Override
public String isValidMove(String newPosition, Piece[][] board) {
// Convert positions like "A2" to board indices
int currentRow = Character.getNumericValue(position.charAt(1)) - 1;
int currentCol = Character.toUpperCase(position.charAt(0)) - 'A';
int newRow = Character.getNumericValue(newPosition.charAt(1)) - 1;
int newCol = Character.toUpperCase(newPosition.charAt(0)) - 'A';
// Ensure within board limits
if (newRow < 0 || newRow > 7 || newCol < 0 || newCol > 7) {
return "Out of bounds";
}
// Prevent moving to the same position
if (newPosition.equals(position)) {
return "Can't move to the same position";
}
// Check if the move is vertical, horizontal, or diagonal
if (currentRow == newRow || currentCol == newCol || Math.abs(newRow - currentRow) == Math.abs(newCol - currentCol)) {
// Check for obstacles in the path
int rowStep = Integer.compare(newRow, currentRow); // Can be -1, 0, or 1
int colStep = Integer.compare(newCol, currentCol); // Can be -1, 0, or 1
int row = currentRow + rowStep;
int col = currentCol + colStep;
while (row != newRow || col != newCol) {
if (board[row][col] != null) {
return "Invalid Move"; // Blocked by another piece
}
row += rowStep;
col += colStep;
}
// Allow the move if the target square is empty or contains an opponent's piece
if (board[newRow][newCol] == null || board[newRow][newCol].isWhite() != isWhite) {
return "Valid Move";
}
}
return "Invalid Move";
}
}