101 lines
2.7 KiB
Java
101 lines
2.7 KiB
Java
import static java.lang.Integer.signum;
|
|
import static java.lang.Math.abs;
|
|
|
|
class Piece {
|
|
Kind kind;
|
|
Color color;
|
|
Board board;
|
|
int row;
|
|
int col;
|
|
|
|
Piece(Kind kind, Color color, Board board, int row, int col) {
|
|
if (row < 1 || row > 8 || col < 1 || col > 8)
|
|
throw new IllegalArgumentException("Invalid pos " + row + "/" + col);
|
|
this.kind = kind;
|
|
this.color = color;
|
|
this.board = board;
|
|
this.row = row;
|
|
this.col = col;
|
|
board.add(this);
|
|
}
|
|
|
|
char charRep() {
|
|
switch (kind) {
|
|
case QUEEN:
|
|
return queenCharRep();
|
|
case KNIGHT:
|
|
return knightCharRep();
|
|
}
|
|
throw new IllegalArgumentException("Unknown piece " + kind);
|
|
}
|
|
|
|
String showPiece() {
|
|
switch (kind) {
|
|
case QUEEN:
|
|
return queenShowPiece();
|
|
case KNIGHT:
|
|
return knightShowPiece();
|
|
}
|
|
throw new IllegalArgumentException("Unknown piece " + kind);
|
|
}
|
|
|
|
boolean canCapture(Piece other) {
|
|
switch (kind) {
|
|
case QUEEN:
|
|
return queenCanCapture(other);
|
|
case KNIGHT:
|
|
return knightCanCapture(other);
|
|
}
|
|
throw new IllegalArgumentException("Unknown piece " + kind);
|
|
}
|
|
|
|
char queenCharRep() {
|
|
if (color == Color.WHITE)
|
|
return 'q';
|
|
else
|
|
return 'Q';
|
|
}
|
|
|
|
char knightCharRep() {
|
|
if (color == Color.WHITE)
|
|
return 'n';
|
|
else
|
|
return 'N';
|
|
}
|
|
|
|
String queenShowPiece() {
|
|
return "" + color.toString().toLowerCase() + " queen at (" + row + ", " + col + ")";
|
|
}
|
|
|
|
String knightShowPiece() {
|
|
return "" + color.toString().toLowerCase() + " knight at (" + row + ", " + col + ")";
|
|
}
|
|
|
|
boolean queenCanCapture(Piece other) {
|
|
if (board != other.board || color == other.color)
|
|
return false;
|
|
if (other.row != row &&
|
|
other.col != col &&
|
|
abs(other.row - row) != abs(other.col - col))
|
|
return false;
|
|
final int dr = signum(other.row - row);
|
|
final int dc = signum(other.col - col);
|
|
int r = row + dr;
|
|
int c = col + dc;
|
|
while (r != other.row || c != other.col) {
|
|
if (board.pieceAt(r, c) != null) return false;
|
|
r += dr;
|
|
c += dc;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
boolean knightCanCapture(Piece other) {
|
|
if (board != other.board || color == other.color)
|
|
return false;
|
|
final int dr = abs(row - other.row);
|
|
final int dc = abs(col - other.col);
|
|
return dr == 2 && dc == 1 || dr == 1 && dc == 2;
|
|
}
|
|
}
|