Files
chess/Pawn.java

42 lines
1.3 KiB
Java

import java.util.*;
import javax.swing.ImageIcon;
public class Pawn extends Piece {
boolean hasMoved;
int colorDir;
public Pawn(int x, int y, String color) {
super(x, y, color, new ImageIcon("sprites/" + color + "/pawn.png").getImage());
hasMoved = false;
colorDir = color.equals("White") ? -1 : 1;
}
public ArrayList<Position> getLegalMoves(Board board) {
ArrayList<Position> positions = new ArrayList<Position>();
// diagonal moves (captures)
Position test = new Position(pos.x + 1, pos.y + colorDir);
if (Board.inBounds(test) && !board.isOpen(test) && !board.getPiece(test).colorMatches(this)) {
positions.add(test);
}
test = new Position(pos.x - 1, pos.y + colorDir);
if (Board.inBounds(test) && !board.isOpen(test) && !board.getPiece(test).colorMatches(this)) {
positions.add(test);
}
// one square in front: if blocked return early
test = new Position(pos.x, pos.y + colorDir);
if (Board.inBounds(test) && board.isOpen(test)) {
positions.add(test);
} else return positions;
// two squares in front
test = new Position(pos.x, pos.y + 2 * colorDir);
if (!hasMoved && board.isOpen(test)) {
positions.add(test);
}
return positions;
}
}