CyB3RC0nN0R
9cfd06230c
+ Cloning support in Board and Piece - Using clones for board operations that interfere with rendering - Fixed repaint calls + Unit test for testing board cloning
81 lines
1.9 KiB
Java
81 lines
1.9 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 {
|
|
|
|
protected Color color;
|
|
protected Board board;
|
|
|
|
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();
|
|
Piece capturePiece = board.move(move);
|
|
if (board.checkCheck(getColor()))
|
|
iterator.remove();
|
|
board.revert(move, capturePiece);
|
|
}
|
|
return moves;
|
|
}
|
|
|
|
protected abstract List<Move> 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 static enum Type {
|
|
KING, QUEEN, ROOK, KNIGHT, BISHOP, PAWN;
|
|
}
|
|
|
|
public static enum Color {
|
|
WHITE, BLACK;
|
|
|
|
public Color opposite() {
|
|
return this == WHITE ? BLACK : WHITE;
|
|
}
|
|
}
|
|
}
|