-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueen.java
More file actions
85 lines (78 loc) · 2.88 KB
/
Copy pathQueen.java
File metadata and controls
85 lines (78 loc) · 2.88 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
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Queen.java
*
* @author Deep Patel
*
* REMARKS: This is a class which stores information about the queen
* piece and how it moves, which is in a straight line in any direction
* but cannot jump over pieces
*/
public class Queen extends Piece {
//Constructor
public Queen(boolean myPiece) {
super(myPiece);
}
/**
* This method is used to check if the move made by the queen piece is a valid
* move for the piece. Its a valid move either if it is a valid rook or bishop move
*
* Parameters:
* Board board - The method take in the current state of the board to validate the move
* Move move - The method takes in the move being made
*
* Returns a boolean to indicate whether the move was valid
*/
public boolean isValidMove(Board board, Move move) {
return (isValidBishopMove(board, move) || isValidRookMove(board, move));
}
//Checks if move is a valid rook move
private boolean isValidRookMove(Board board, Move move) {
if (move.getFromRow() == move.getToRow()) { // Moving horizontally
int minCol = Math.min(move.getFromCol(), move.getToCol());
int maxCol = Math.max(move.getFromCol(), move.getToCol());
for (int i = minCol + 1; i < maxCol; i++) {
if (board.getSymbol(move.getFromRow() - 1, i - 1) != ' ') {
return false;
}
}
return true;
} else if (move.getFromCol() == move.getToCol()) { //Vertically
int minRow = Math.min(move.getFromRow(), move.getToRow());
int maxRow = Math.max(move.getFromRow(), move.getToRow());
for (int i = minRow + 1; i < maxRow; i++) {
if (board.getSymbol(i - 1, move.getFromCol() - 1) != ' ') {
return false;
}
}
return true;
} else {
return false;
}
}
//Checks if move being made is a valid bishop move
private boolean isValidBishopMove(Board board, Move move) {
if (Math.abs(move.getToRow() - move.getFromRow()) != Math.abs(move.getToCol() - move.getFromCol())) {
return false; // Bishop must move diagonally
}
int rowDir;
int difference = move.getToRow() - move.getFromRow();
if (difference > 0) {
rowDir = 1;
} else {
rowDir = -1;
}
int colDir;
int diff = move.getToCol() - move.getFromCol();
if (diff > 0) {
colDir = 1;
} else {
colDir = -1;
}
for (int i = 1; i < Math.abs(move.getToRow() - move.getFromRow()); i++) {
if (board.getSymbol(move.getFromRow() - 1 + i * rowDir, move.getFromCol() - 1 + i * colDir) != ' ') {
return false; // Path must be clear for Bishop to move
}
}
return true;
}
}