-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBishop.java
More file actions
54 lines (42 loc) · 2 KB
/
Bishop.java
File metadata and controls
54 lines (42 loc) · 2 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
51
52
53
54
public class Bishop extends Piece {
public Bishop(String position, boolean isWhite) {
super(position, isWhite);
}
@Override
public String isValidMove(String newPosition, Piece[][] board) {
// Convert positions like "C1" to board indices
int currentRow = Character.getNumericValue(position.charAt(1)) - 1; // '1' -> 7
int currentCol = position.charAt(0) - 'A'; // 'C' -> 2
int newRow = Character.getNumericValue(newPosition.charAt(1)) - 1; // '3' -> 5
int newCol = newPosition.charAt(0) - 'A'; // 'E' -> 4
// 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 diagonal (difference in rows == difference in columns)
if (Math.abs(newRow - currentRow) == Math.abs(newCol - currentCol)) {
// Determine direction of movement for both row and column
int rowDirection = (newRow > currentRow) ? 1 : -1;
int colDirection = (newCol > currentCol) ? 1 : -1;
// Check each square along the diagonal path for obstructions
int tempRow = currentRow + rowDirection;
int tempCol = currentCol + colDirection;
while (tempRow != newRow && tempCol != newCol) {
if (board[tempRow][tempCol] != null) {
return "Invalid Move"; // Blocked by another piece
}
tempRow += rowDirection;
tempCol += colDirection;
}
// 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";
}
}