package dev.kske.chess.board; import java.util.Iterator; import java.util.List; /** * Project: Chess
* File: Piece.java
* Created: 01.07.2019
* Author: Kai S. K. Engelbart */ public abstract class Piece implements Cloneable { private final Color color; protected Board board; private int moveCounter; public Piece(Color color, Board board) { this.color = color; this.board = board; } public List getMoves(Position pos) { List moves = getPseudolegalMoves(pos); for (Iterator iterator = moves.iterator(); iterator.hasNext();) { Move move = iterator.next(); board.move(move); if (board.checkCheck(getColor())) iterator.remove(); board.revert(); } return moves; } protected abstract List getPseudolegalMoves(Position pos); public abstract boolean isValidMove(Move move); protected boolean isFreePath(Move move) { // Only check destination by default return checkDestination(move); } /** * Checks if the destination of a move is empty or a piece from the opposing * team * * @param move The move to check * @return {@code false} if the move's destination is from the same team */ protected final boolean checkDestination(Move move) { return board.getDest(move) == null || board.getDest(move).getColor() != getColor(); } @Override public Object clone() { Piece piece = null; try { piece = (Piece) super.clone(); } catch (CloneNotSupportedException ex) { ex.printStackTrace(); } return piece; } public abstract Type getType(); public Color getColor() { return color; } public int getMoveCounter() { return moveCounter; } public void incMoveCounter() { ++moveCounter; } public void decMoveCounter() { --moveCounter; } public static enum Type { KING, QUEEN, ROOK, KNIGHT, BISHOP, PAWN } public static enum Color { WHITE, BLACK; public Color opposite() { return this == WHITE ? BLACK : WHITE; } } }