#include #include #include class Piece { public: Piece(int x, int y) : x {x}, y {y} {} virtual ~Piece() = default; virtual bool can_move(int new_x, int new_y) const = 0; virtual bool can_attack(Piece const& target) const { return can_move(target.x, target.y); } int get_x() const { return x; } int get_y() const { return y; } protected: int x; int y; bool out_of_bounds(int new_x, int new_y); }; class Pawn : public Piece { public: Pawn(int x, int y, int direction) : Piece{x, y}, direction {direction} {} virtual bool can_move(int new_x, int new_y) const override { return (x == new_x) && (y + direction == new_y); } virtual bool can_attack(Piece const& target) const override { if (std::abs(target.get_x() - x) != 1) { return false; } return y + direction == target.get_y(); } private: int direction; }; class Rook : public Piece { public: using Piece::Piece; virtual bool can_move(int new_x, int new_y) const override { return (x == new_x) != (y == new_y); } }; class Queen : public Rook { public: using Rook::Rook; virtual bool can_move(int new_x, int new_y) const override { return Rook::can_move(x, y) || (std::abs(x-new_x) == std::abs(y-new_y)); } }; int main() { std::vector pieces { new Pawn {1,1, 1}, // White pawn new Pawn {3,5, -1}, // Black pawn new Rook {2,2}, new Queen {6,2} }; std::cout << std::boolalpha; std::cout << "== White Pawn ==" << std::endl; std::cout << (pieces[0]->can_move(1,2) == true) << " "; std::cout << (pieces[0]->can_move(1,1) == false) << std::endl; std::cout << "== Black Pawn ==" << std::endl; std::cout << (pieces[1]->can_move(3,4) == true) << " "; std::cout << (pieces[1]->can_move(4,4) == false) << std::endl; std::cout << "== Rook ==" << std::endl; std::cout << (pieces[2]->can_move(2,7) == true) << " "; std::cout << (pieces[2]->can_move(1,1) == false) << std::endl; std::cout << "== Queen ==" << std::endl; std::cout << (pieces[3]->can_move(4,4) == true) << " "; std::cout << (pieces[3]->can_move(5,0) == false) << std::endl; std::cout << "== Can Attack ==" << std::endl; std::cout << (pieces[0]->can_attack(*pieces[2]) == true) << " "; std::cout << (pieces[1]->can_attack(*pieces[3]) == false) << " "; std::cout << (pieces[2]->can_attack(*pieces[3]) == true) << " "; std::cout << (pieces[3]->can_attack(*pieces[1]) == true) << std::endl; }