-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPawn.java
77 lines (70 loc) · 2.99 KB
/
Pawn.java
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
package Chess;
public class Pawn extends Piece{
public static boolean initialLocation = true;
public static int count = 0;
public Pawn(int color, Square location) {
super(color,location);
}
@Override
public boolean canMove(String to) {
boolean validMove = false;
Square targetLocation = location.getBoard().getSquareAt(to);
int rowDistance = targetLocation.getRowDistance(location,this.color);
if (this.location.isAtSameColumn(targetLocation)){
if(color == ChessBoard.WHITE && rowDistance > 0 && rowDistance <= 2){
if(rowDistance == 2){
if(initialLocation){
// Pawn is moving TWICE. Check two squares in front of are empty.
Square[] between = location.getBoard().getSquaresBetween(location,targetLocation);
validMove = targetLocation.isEmpty() && between[0].isEmpty();
}
} else{
validMove =targetLocation.isEmpty();
}
return validMove;
}else if( color == ChessBoard.BLACK && rowDistance < 0 && rowDistance >= -2){
if(rowDistance == -2){
if(initialLocation){
// Pawn is moving TWICE. Check two squares in front of are empty.
Square[] between = location.getBoard().getSquaresBetween(location,targetLocation);
validMove = targetLocation.isEmpty() && between[0].isEmpty();
}
}else{
validMove = targetLocation.isEmpty();
}
}
// if the target column is not at the same column, it should be a neighbour column
}else if(this.location.isNeighbourColumn(targetLocation)){
// pawn only move forward diagonals if there is an oppenen there (attack)
if(color == ChessBoard.WHITE && rowDistance == 1){
validMove = !targetLocation.isEmpty() && targetLocation.getPiece().getColor() == ChessBoard.BLACK;
}else if (color == ChessBoard.BLACK && rowDistance == -1){
validMove = !targetLocation.isEmpty() && targetLocation.getPiece().getColor() == ChessBoard.WHITE;
}
}
return validMove;
}
@Override
public void move(String to) {
Square targetLocation = location.getBoard().getSquareAt(to);
//promoteToQueen
if (targetLocation.isAtLastRow(color)) {
targetLocation.putNewQueen(color);
}else{
targetLocation.setPiece(this);
}
//clear previous location
location.clear();
//update current location
location = targetLocation;
location.getBoard().nextPlayer();
//piece has been moved at least once
count++;
if (count > 1)
initialLocation = false;
}
@Override
public String toString() {
return color == 0 ? "P":"p";
}
}