90 lines
2.7 KiB
Java
90 lines
2.7 KiB
Java
package dev.kske.chess.board;
|
|
|
|
import java.util.Objects;
|
|
|
|
/**
|
|
* Project: <strong>Chess</strong><br>
|
|
* File: <strong>Move.java</strong><br>
|
|
* Created: <strong>02.07.2019</strong><br>
|
|
*
|
|
* @since Chess v0.1-alpha
|
|
* @author Kai S. K. Engelbart
|
|
*/
|
|
public class Move {
|
|
|
|
protected final Position pos, dest;
|
|
protected final int xDist, yDist, xSign, ySign;
|
|
|
|
public Move(Position pos, Position dest) {
|
|
this.pos = pos;
|
|
this.dest = dest;
|
|
xDist = Math.abs(dest.x - pos.x);
|
|
yDist = Math.abs(dest.y - pos.y);
|
|
xSign = (int) Math.signum(dest.x - pos.x);
|
|
ySign = (int) Math.signum(dest.y - pos.y);
|
|
}
|
|
|
|
public Move(int xPos, int yPos, int xDest, int yDest) { this(new Position(xPos, yPos), new Position(xDest, yDest)); }
|
|
|
|
public void execute(Board board) {
|
|
// Move the piece to the move's destination square and clean the old position
|
|
board.set(dest, board.get(pos));
|
|
board.set(pos, null);
|
|
}
|
|
|
|
public void revert(Board board, Piece capturedPiece) {
|
|
// Move the piece to the move's position square and clean the destination
|
|
board.set(pos, board.get(dest));
|
|
board.set(dest, capturedPiece);
|
|
}
|
|
|
|
public static Move fromLAN(String move) {
|
|
Position pos = Position.fromLAN(move.substring(0, 2));
|
|
Position dest = Position.fromLAN(move.substring(2));
|
|
if (move.length() == 5) {
|
|
try {
|
|
return new PawnPromotion(pos, dest, Piece.fromFirstChar(move.charAt(4)));
|
|
} catch (NoSuchMethodException | SecurityException | IllegalArgumentException e) {
|
|
e.printStackTrace();
|
|
return null;
|
|
}
|
|
} else return new Move(pos, dest);
|
|
}
|
|
|
|
public String toLAN() { return getPos().toLAN() + getDest().toLAN(); }
|
|
|
|
public boolean isHorizontal() { return getyDist() == 0; }
|
|
|
|
public boolean isVertical() { return getxDist() == 0; }
|
|
|
|
public boolean isDiagonal() { return getxDist() == getyDist(); }
|
|
|
|
@Override
|
|
public String toString() { return toLAN(); }
|
|
|
|
@Override
|
|
public int hashCode() { return Objects.hash(getDest(), getPos(), getxDist(), getxSign(), getyDist(), getySign()); }
|
|
|
|
@Override
|
|
public boolean equals(Object obj) {
|
|
if (this == obj) return true;
|
|
if (obj == null) return false;
|
|
if (getClass() != obj.getClass()) return false;
|
|
Move other = (Move) obj;
|
|
return Objects.equals(getDest(), other.getDest()) && Objects.equals(getPos(), other.getPos()) && getxDist() == other.getxDist()
|
|
&& getxSign() == other.getxSign() && getyDist() == other.getyDist() && getySign() == other.getySign();
|
|
}
|
|
|
|
public Position getPos() { return pos; }
|
|
|
|
public Position getDest() { return dest; }
|
|
|
|
public int getxDist() { return xDist; }
|
|
|
|
public int getyDist() { return yDist; }
|
|
|
|
public int getxSign() { return xSign; }
|
|
|
|
public int getySign() { return ySign; }
|
|
}
|