Piece: expanding getLegalMoves for Queen/Knight/Bishop

This commit is contained in:
A.M. Rowsell 2025-08-30 18:46:18 -04:00
commit 6773da28fb
Signed by untrusted user who does not match committer: amr
GPG key ID: E0879EDBDB0CA7B1
4 changed files with 70 additions and 5 deletions

View file

@ -12,6 +12,9 @@ Piece::~Piece() {
return;
}
// TODO: Add operator overload for << to allow easy printing
// TODO: Test getPieceAt() function to see if it works as intended
// because the Piece class is instantiated in another class using
// unique_ptr, non-pure virtual functions apparently *must*
// have definitions, or the linker freaks out
@ -164,7 +167,7 @@ std::vector<Move> Rook::getLegalMoves(const Square &from, Board &board) const {
{0, -1}, // Left
{0, 1} // Right
};
for(auto& dir : directions) {
for(auto &dir : directions) {
int r = from.rank + dir[0];
int f = from.file + dir[1];
while(r >= 0 && r < 8 && f >= 0 && f < 8) {
@ -188,16 +191,64 @@ std::vector<Move> Rook::getLegalMoves(const Square &from, Board &board) const {
std::vector<Move> Queen::getLegalMoves(const Square &from, Board &board) const {
std::vector<Move> moveList;
std::vector<std::vector<int>> directions = {
{-1, 0}, // Up
{-1, -1}, // up-left
{-1, 1}, // up-right
{1, 0}, // Down
{1, -1}, // down-left
{1, 1}, // down-right
{0, -1}, // Left
{0, 1} // Right
};
for(auto &dir : directions) {
// establish r/f for square to check
int r = from.rank + dir[0];
int f = from.file + dir[1];
auto ra = static_cast<Rank>(r);
auto fi = static_cast<File>(f);
Square targetSquare = {ra, fi};
while(r >= 0 && r < 8 && f >= 0 && f < 8) {
const auto &target = board.boardGrid[r][f]; // examine the target square
if(!target) { // if square is empty (NULL)
moveList.push_back({from, targetSquare}); // then it's potentially a legal move
} else if(target && target->getColour() != this->getColour()) { // if it's occupied with a piece of opposite colour
moveList.push_back({from, targetSquare}); // then again it's potentially legal
break;
} else {
// otherwise it's one of our pieces
break;
}
r += dir[0];
f += dir[1];
}
}
return moveList;
}
std::vector<Move> Knight::getLegalMoves(const Square &from, Board &board) const {
std::vector<Move> moveList;
std::vector<std::vector<int>> directions = {
{-1, -2},
{-1, 2},
{-2, -1},
{-2, 1},
{1, -2},
{1, 2},
{2, -1},
{2, 1}
};
return moveList;
}
std::vector<Move> Bishop::getLegalMoves(const Square &from, Board &board) const {
std::vector<Move> moveList;
std::vector<std::vector<int>> directions = {
{-1, -1}, // up-left
{-1, 1}, // up-right
{1, -1}, // down-left
{1, 1}, // down-right
};
return moveList;
}