diff --git a/src/model/utils/move.cpp b/src/model/utils/move.cpp index 6a47969..2e8907a 100644 --- a/src/model/utils/move.cpp +++ b/src/model/utils/move.cpp @@ -24,3 +24,31 @@ int Move::score_guess(const Board& b) const { return ret; } + +Move Move::from_string(std::string move) { + if (!(4 <= move.size() && move.size() <= 5)) + throw std::invalid_argument("Move must be 4 or 5 characters long"); + Move ret; + ret.source_square = Coords::from_algebraic(move.substr(0, 2)).to_index(); + ret.target_square = Coords::from_algebraic(move.substr(2, 2)).to_index(); + if (move.size() == 5) + switch (move[4]) { + case 'n': + ret.promoting_to = Knigt; + break; + case 'b': + ret.promoting_to = Bishop; + break; + case 'r': + ret.promoting_to = Rook; + break; + case 'q': + ret.promoting_to = Queen; + break; + default: + throw std::invalid_argument("Promotion piece must be one of 'nbrq'" + ); + } + ret.target_square = Coords::from_algebraic(move.substr(2, 2)).to_index(); + return ret; +} diff --git a/src/model/utils/move.hpp b/src/model/utils/move.hpp index ad2fe8d..340abab 100644 --- a/src/model/utils/move.hpp +++ b/src/model/utils/move.hpp @@ -15,6 +15,8 @@ struct Move { int score_guess(const Board&) const; + static Move from_string(std::string); + std::string to_string() const { std::stringstream ss; ss << Coords::from_index(source_square) diff --git a/tests/move.cpp b/tests/move.cpp new file mode 100644 index 0000000..8f146e4 --- /dev/null +++ b/tests/move.cpp @@ -0,0 +1,13 @@ +#include "../src/model/board/board.hpp" +#include "lib.hpp" + +int main() { + std::string str_move = "a2a3"; + ASSERT_EQUALS(str_move, Move::from_string(str_move).to_string()); + + str_move = "b2f4"; + ASSERT_EQUALS(str_move, Move::from_string(str_move).to_string()); + + str_move = "a2a1r"; + ASSERT_EQUALS(str_move, Move::from_string(str_move).to_string()); +}