This repository has been archived on 2021-02-18. You can view files and clone it, but cannot push or open issues or pull requests.
chess/src/dev/kske/chess/piece/Rook.java

84 lines
2.4 KiB
Java
Raw Normal View History

package dev.kske.chess.piece;
import java.util.ArrayList;
import java.util.List;
import dev.kske.chess.Board;
import dev.kske.chess.Move;
import dev.kske.chess.Position;
/**
* Project: <strong>Chess</strong><br>
* File: <strong>Rook.java</strong><br>
* Created: <strong>01.07.2019</strong><br>
* Author: <strong>Kai S. K. Engelbart</strong>
*/
public class Rook extends Piece {
public Rook(Color color, Board board) {
super(color, board);
}
@Override
public boolean isValidMove(Move move) {
return (move.isHorizontal() || move.isVertical()) && isFreePath(move);
}
@Override
protected boolean isFreePath(Move move) {
if (move.isHorizontal()) {
for (int i = move.pos.x + move.xSign; i != move.dest.x; i += move.xSign)
if (board.getBoardArr()[i][move.pos.y] != null) return false;
} else {
for (int i = move.pos.y + move.ySign; i != move.dest.y; i += move.ySign)
if (board.getBoardArr()[move.pos.x][i] != null) return false;
}
return checkDestination(move);
}
@Override
protected List<Move> getPseudolegalMoves(Position pos) {
List<Move> moves = new ArrayList<>();
// Horizontal moves to the right
for (int i = pos.x + 1; i < 8; i++) {
Move move = new Move(pos, new Position(i, pos.y));
if (board.getDest(move) == null || board.getDest(move).getColor() != getColor()) {
moves.add(move);
if (board.getDest(move) != null) break;
} else break;
}
// Horizontal moves to the left
for (int i = pos.x - 1; i >= 0; i--) {
Move move = new Move(pos, new Position(i, pos.y));
if (board.getDest(move) == null || board.getDest(move).getColor() != getColor()) {
moves.add(move);
if (board.getDest(move) != null) break;
} else break;
}
// Vertical moves to the top
for (int i = pos.y - 1; i >= 0; i--) {
Move move = new Move(pos, new Position(pos.x, i));
if (board.getDest(move) == null || board.getDest(move).getColor() != getColor()) {
moves.add(move);
if (board.getDest(move) != null) break;
} else break;
}
// Vertical moves to the bottom
for (int i = pos.y + 1; i < 8; i++) {
Move move = new Move(pos, new Position(pos.x, i));
if (board.getDest(move) == null || board.getDest(move).getColor() != getColor()) {
moves.add(move);
if (board.getDest(move) != null) break;
} else break;
}
return moves;
}
@Override
public Type getType() { return Type.ROOK; }
}