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); /** * Checks, if the squares between the position and the destination of a move are * free. * * @param move The move to check */ protected boolean isFreePath(Move move) { for (int i = move.pos.x + move.xSign, j = move.pos.y + move.ySign; i != move.dest.x || j != move.dest.y; i += move.xSign, j += move.ySign) if (board.getBoardArr()[i][j] != null) return false; 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; /** * @return The first character of this {@link Type} in algebraic notation and lower case */ public char firstChar() { return this == KNIGHT ? 'n' : Character.toLowerCase(this.toString().charAt(0)); } } public static enum Color { WHITE, BLACK; public static Color fromFirstChar(char c) { return Character.toLowerCase(c) == 'w' ? WHITE : BLACK; } public char firstChar() { return this == WHITE ? 'w' : 'b'; } public Color opposite() { return this == WHITE ? BLACK : WHITE; } } }