1
0
forked from pabulaner/vivi
vivi-exercises/chess/pieces/Queen.java

65 lines
1.9 KiB
Java
Raw Normal View History

2025-05-20 09:17:32 +02:00
package de.vivi.chess.pieces;
import de.vivi.chess.board.Board;
import de.vivi.chess.board.Field;
public class Queen extends Piece {
public Queen(Color color, Type type) {
super(color, type);
}
public Queen(Color color, Type type, Field field) {
super(color, type, field);
}
@Override
public char getSymbol() {
if (getColor() == Color.WHITE) {
if (getType() == Type.QUEEN) {
symbol = '\u265B';
}
} else if (getColor() == Color.BLACK) {
if (getType() == Type.QUEEN) {
symbol = '\u2655';
}
}
return symbol;
}
@Override
public boolean isValidMove(Board board, Field from, Field to) {
if (to.equals(from)) {
return false;
}
int rowDiff = Math.abs(to.getRow() - from.getRow());
int colDiff = Math.abs(to.getColumn() - from.getColumn());
boolean straightLine = from.getRow() == to.getRow()
|| from.getColumn() == to.getColumn();
boolean diagonal = rowDiff == colDiff;
if (!straightLine && !diagonal) {
return false;
}
int rowDirection = Integer.compare(to.getRow(), from.getRow());
int colDirection = Integer.compare(to.getColumn(), from.getColumn());
int currentRow = from.getRow() + rowDirection;
int currentCol = from.getColumn() + colDirection;
while (currentRow != to.getRow() || currentCol != to.getColumn()) {
if (board.getPiece(Field.from(currentCol, currentRow)) != null) {
return false;
}
currentRow += rowDirection;
currentCol += colDirection;
}
Piece destinationPiece = board.getPiece(Field.from(to.getColumn(), to.getRow()));
return destinationPiece == null || destinationPiece.getColor() != this.getColor();
}
}