1
0
forked from pabulaner/vivi
vivi-exercises/chess/pieces/Bishop.java
2025-05-20 09:17:32 +02:00

60 lines
1.6 KiB
Java

package de.vivi.chess.pieces;
import de.vivi.chess.board.Board;
import de.vivi.chess.board.Field;
public class Bishop extends Piece {
public Bishop(Color color, Type type) {
super(color, type);
}
public Bishop(Color color, Type type, Field field) {
super(color, type, field);
}
@Override
public char getSymbol() {
if (getColor() == Color.WHITE) {
if (getType() == Type.BISHOP) {
symbol = '\u265D';
}
} else if (getColor() == Color.BLACK) {
if (getType() == Type.BISHOP) {
symbol = '\u2657';
}
}
return symbol;
}
@Override
public boolean isValidMove(Board board, Field from, Field to) {
int rowDiff = Math.abs(from.getRow() - to.getRow());
int colDiff = Math.abs(from.getColumn() - to.getColumn());
if (rowDiff != colDiff) {
return false;
}
int rowStep = to.getRow() > from.getRow() ? 1 : -1;
int colStep = to.getColumn() > from.getColumn() ? 1 : -1;
int steps = rowDiff - 1;
for (int i = 1; i <= steps; i++) {
if (board.getPiece(Field.from(from.getColumn() + i * rowStep,
from.getRow() + i * colStep)) != null) {
return false;
}
}
Piece destinationPiece = board.getPiece(Field.from(to.getColumn(), to.getRow()));
if (destinationPiece == null) {
return true;
} else if (destinationPiece.getColor() != this.getColor()) {
return true;
}
return false;
}
}