diff --git a/cpp/src/coords.hpp b/cpp/src/coords.hpp index 51a6f6c..88a6787 100644 --- a/cpp/src/coords.hpp +++ b/cpp/src/coords.hpp @@ -1,10 +1,18 @@ #pragma once #include +#include +#include +#include + +static std::string _FILES = "abcdefgh"; +static std::string _RANKS = "12345678"; struct Coords { int x, y; + Coords(int x, int y): x(x), y(y) {} + int8_t to_index() const { return this->y * 8 + this->x; } @@ -13,7 +21,50 @@ struct Coords { return {idx % 8, idx / 8}; } + static Coords from_algebraic(std::string pos) { + if (pos.size() != 2) + throw std::invalid_argument( + "An algebraic coordinate should only have two characters" + ); + + int x = _FILES.find(pos[0]); + if (x == std::string::npos) + throw std::invalid_argument("The first character of the given " + "algebraic coordinate is invalid"); + + int y = _RANKS.find(pos[1]); + if (y == std::string::npos) + throw std::invalid_argument("The second character of the given " + "algebraic coordinate is invalid"); + + return Coords{x, y}; + } + + std::string to_algebraic() const { + std::string ret; + if (x > 7 || y > 7) + throw std::invalid_argument( + "Can't give the algebraic vesion of an invalid coord" + ); + ret += _FILES[x]; + ret += _RANKS[y]; + return ret; + } + bool is_within_bounds() const { return this->to_index() < 64; } }; + +inline bool operator==(const Coords& a, const Coords& b) { + return a.x == b.x && a.y == b.y; +} + +inline bool operator!=(const Coords& a, const Coords& b) { + return !(a == b); +} + +inline std::ostream& operator<<(std::ostream& os, const Coords& coords) { + os << coords.to_algebraic(); + return os; +} diff --git a/cpp/tests/positions.cpp b/cpp/tests/positions.cpp new file mode 100644 index 0000000..591ccef --- /dev/null +++ b/cpp/tests/positions.cpp @@ -0,0 +1,20 @@ +#include "../src/coords.hpp" +#include "lib.hpp" + +int main() { + ASSERT_EQUALS(Coords(0, 0).to_algebraic(), "a1"); + ASSERT_EQUALS(Coords(1, 0).to_algebraic(), "b1"); + + ASSERT_EQUALS(Coords(2, 1).to_algebraic(), "c2"); + ASSERT_EQUALS(Coords(4, 2).to_algebraic(), "e3"); + + ASSERT_EQUALS(Coords(7, 7).to_algebraic(), "h8"); + + ASSERT_EQUALS(Coords::from_algebraic("a1"), Coords(0, 0)); + ASSERT_EQUALS(Coords::from_algebraic("b1"), Coords(1, 0)); + + ASSERT_EQUALS(Coords::from_algebraic("c2"), Coords(2, 1)); + ASSERT_EQUALS(Coords::from_algebraic("e3"), Coords(4, 2)); + + ASSERT_EQUALS(Coords::from_algebraic("h8"), Coords(7, 7)); +}