This repository has been archived on 2021-02-18. You can view files and clone it, but cannot push or open issues or pull requests.
chess/src/dev/kske/chess/board/Piece.java

103 lines
2.4 KiB
Java

package dev.kske.chess.board;
import java.util.Iterator;
import java.util.List;
/**
* Project: <strong>Chess</strong><br>
* File: <strong>Piece.java</strong><br>
* Created: <strong>01.07.2019</strong><br>
* Author: <strong>Kai S. K. Engelbart</strong>
*/
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<Move> getMoves(Position pos) {
List<Move> moves = getPseudolegalMoves(pos);
for (Iterator<Move> 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<Move> 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
}
public static enum Color {
WHITE, BLACK;
public Color opposite() {
return this == WHITE ? BLACK : WHITE;
}
public char firstChar() {
return this == WHITE ? 'w' : 'b';
}
}
}