import java.util.*; import javax.swing.ImageIcon; public class King extends Piece { boolean hasMoved; static int[] xDir = {-1, 0, 1, -1, 1, -1, 0, 1}; static int[] yDir = {-1, -1, -1, 0, 0, 1, 1, 1}; public King(int x, int y, String color) { super(x, y, color, new ImageIcon("sprites/" + color + "/king.png").getImage()); hasMoved = false; } public Piece copy() { Piece newP = new King(this.pos.x, this.pos.y, this.color); return newP; } public ArrayList getPseudoLegalMoves(Board board) { ArrayList positions = new ArrayList(); for (int i = 0; i < xDir.length; i++) { Position test = new Position(pos.x + xDir[i], pos.y + yDir[i]); if (!Board.inBounds(test)) continue; if (board.isOpen(test)) { positions.add(test); continue; } if (!board.getPiece(test).colorMatches(this)) { positions.add(test); } } int colorPos = this.color.equals("White") ? 7 : 0; boolean leftOpen = true; boolean rightOpen = true; if (!this.hasMoved && !inCheck(board,pos)){ if(board.getPiece(7,colorPos) instanceof Rook && !Rook.class.cast(board.getPiece(7,colorPos)).hasMoved){ ArrayList right = this.slide(board,1,0,2); for (Position p : new ArrayList<>(right)){ if (inCheck(board,p)){ rightOpen = false; } } if (rightOpen) {positions.add(new Position(pos.x+2,pos.y));} } if (board.getPiece(0,colorPos) instanceof Rook && !Rook.class.cast(board.getPiece(0,colorPos)).hasMoved){ ArrayList left = this.slide(board,-1,0,2); for (Position p : new ArrayList<>(left)){ if (inCheck(board,p)){ leftOpen = false; } } if (leftOpen) positions.add(new Position(pos.x - 2, pos.y)); }} return positions; } public ArrayList getLegalMoves(Board board) { ArrayList positions = getPseudoLegalMoves(board); for (Position p : new ArrayList<>(positions)) { Piece tempPiece = board.getPiece(p); board.setPiece(pos, null); board.setPiece(p, this); if (inCheck(board, p)) { positions.remove(p); } board.setPiece(p, tempPiece); board.setPiece(pos, this); } return positions; } public boolean inCheck(Board board, Position pos) { for (Piece[] pieces : board.board) { for (Piece p : pieces) { if (p == null) continue; if (!p.colorMatches(this) && !(p instanceof King)) { ArrayList ar = p.getPseudoLegalMoves(board); for (Position posi : ar) { if (pos.equals(posi)) return true; } } } } return false; } }