2025-02-02 20:17:27 +01:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <cstdint>
|
2025-02-02 22:39:06 +01:00
|
|
|
#include <iostream>
|
|
|
|
#include <stdexcept>
|
|
|
|
#include <string>
|
|
|
|
|
|
|
|
static std::string _FILES = "abcdefgh";
|
|
|
|
static std::string _RANKS = "12345678";
|
2025-02-02 20:17:27 +01:00
|
|
|
|
|
|
|
struct Coords {
|
|
|
|
int x, y;
|
|
|
|
|
2025-02-02 22:39:06 +01:00
|
|
|
Coords(int x, int y): x(x), y(y) {}
|
|
|
|
|
2025-02-02 20:17:27 +01:00
|
|
|
int8_t to_index() const {
|
|
|
|
return this->y * 8 + this->x;
|
|
|
|
}
|
|
|
|
|
|
|
|
static Coords from_index(int idx) {
|
|
|
|
return {idx % 8, idx / 8};
|
|
|
|
}
|
|
|
|
|
2025-02-02 22:39:06 +01:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2025-02-02 20:17:27 +01:00
|
|
|
bool is_within_bounds() const {
|
|
|
|
return this->to_index() < 64;
|
|
|
|
}
|
|
|
|
};
|
2025-02-02 22:39:06 +01:00
|
|
|
|
|
|
|
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;
|
|
|
|
}
|