package dev.kske.chess.board;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import dev.kske.chess.board.Piece.Color;
/**
* Project: Chess
* File: PawnPromotion.java
* Created: 2 Nov 2019
*
* @since Chess v0.5-alpha
* @author Kai S. K. Engelbart
*/
public class PawnPromotion extends Move {
private final Constructor extends Piece> promotionPieceConstructor;
private final char promotionPieceChar;
public PawnPromotion(Position pos, Position dest, Class extends Piece> promotionPiece) throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
super(pos, dest);
// Cache piece constructor
promotionPieceConstructor = promotionPiece.getDeclaredConstructor(Color.class, Board.class);
promotionPieceConstructor.setAccessible(true);
// Cache piece first char
promotionPieceChar = (char) promotionPiece.getMethod("firstChar").invoke(promotionPieceConstructor.newInstance(null, null));
}
public PawnPromotion(int xPos, int yPos, int xDest, int yDest, Class extends Piece> promotionPiece)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
InstantiationException {
this(new Position(xPos, yPos), new Position(xDest, yDest), promotionPiece);
}
@Override
public void execute(Board board) {
try {
board.set(pos, promotionPieceConstructor.newInstance(board.get(pos).getColor(), board));
super.execute(board);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
e.printStackTrace();
}
}
@Override
public void revert(Board board, Piece capturedPiece) {
board.set(dest, new Pawn(board.get(dest).getColor(), board));
super.revert(board, capturedPiece);
}
@Override
public String toLAN() { return pos.toLAN() + dest.toLAN() + promotionPieceChar; }
}