-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKing.java
More file actions
72 lines (53 loc) · 2.52 KB
/
King.java
File metadata and controls
72 lines (53 loc) · 2.52 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class King extends ChessPiece{
public King(String type, String color){
super(type,color, 10);
}
public boolean isMoveValidWithoutChangingState(int startRow, int startCol, int endRow, int endCol, ChessPiece[][] board){
int rowDiff = Math.abs(endRow - startRow);
int colDiff = Math.abs(endCol - startCol);
// King cannot move more than one square away in any direction
if (rowDiff > 1 || colDiff > 1) {
return false;
}
// Ensure the destination square is within the board bounds
if (endRow < 0 || endRow >= board.length || endCol < 0 || endCol >= board[0].length) {
return false; // Destination is outside the board
}
// Check if the destination square is occupied
ChessPiece destinationPiece = board[endRow][endCol];
ChessPiece currPiece = board[startRow][startCol];
if (destinationPiece != null) {
// If the destination square is occupied by a piece of the same color, it's not a valid move
if (destinationPiece.getColor().equals(currPiece.getColor())) {
return false;
}
}
return true;
}
public boolean isValidMove(int startRow, int startCol, int endRow, int endCol, ChessPiece[][] board) {
int rowDiff = Math.abs(endRow - startRow);
int colDiff = Math.abs(endCol - startCol);
// Check if the move is more than one square in any direction
if (rowDiff > 1 || colDiff > 1) {
return false; // King cannot move more than one square away
}
// Ensure the destination square is within the board bounds
if (endRow < 0 || endRow >= board.length || endCol < 0 || endCol >= board[0].length) {
return false; // Destination is outside the board
}
// Check if the destination square is occupied
ChessPiece destinationPiece = board[endRow][endCol];
ChessPiece currPiece = board[startRow][startCol];
if (destinationPiece != null) {
// If the destination square is occupied by a piece of the same color, it's not a valid move
if (destinationPiece.getColor().equals(currPiece.getColor())) {
//System.out.println(destinationPiece.getColor());
// System.out.println(this.getColor());
return false;
}
}
// The move is valid (either moving to an empty square or capturing an opponent's piece)
return true;
//return false;
}
}