added algebraic support for coordinates
This commit is contained in:
parent
bdd8011577
commit
2493892b05
@ -1,10 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
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;
|
||||
}
|
||||
|
20
cpp/tests/positions.cpp
Normal file
20
cpp/tests/positions.cpp
Normal file
@ -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));
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user