Chess: Add serialization of moves and squares

This commit is contained in:
Peter Elliott 2020-08-18 14:29:27 -06:00 committed by Andreas Kling
parent f69b419c05
commit ffece9cfba
Notes: sideshowbarker 2024-07-19 03:22:25 +09:00
2 changed files with 43 additions and 0 deletions

View file

@ -27,9 +27,30 @@
#include "Chess.h"
#include <AK/Assertions.h>
#include <AK/LogStream.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/Vector.h>
#include <stdlib.h>
String Chess::char_for_piece(Chess::Type type)
{
switch (type) {
case Type::Knight:
return "N";
case Type::Bishop:
return "B";
case Type::Rook:
return "R";
case Type::Queen:
return "Q";
case Type::King:
return "K";
case Type::Pawn:
default:
return "";
}
}
Chess::Square::Square(const StringView& name)
{
ASSERT(name.length() == 2);
@ -51,6 +72,23 @@ Chess::Square::Square(const StringView& name)
}
}
String Chess::Square::to_algebraic() const
{
StringBuilder builder;
builder.append(file - 'a');
builder.append(rank - '1');
return builder.build();
}
String Chess::Move::to_long_algebraic() const
{
StringBuilder builder;
builder.append(from.to_algebraic());
builder.append(to.to_algebraic());
builder.append(char_for_piece(promote_to).to_lowercase());
return builder.build();
}
Chess::Chess()
{
// Fill empty spaces.

View file

@ -43,6 +43,7 @@ public:
King,
None,
};
static String char_for_piece(Type type);
enum class Colour {
White,
@ -55,6 +56,7 @@ public:
Colour colour;
Type type;
bool operator==(const Piece& other) const { return colour == other.colour && type == other.type; }
};
static constexpr Piece EmptyPiece = { Colour::None, Type::None };
@ -84,6 +86,7 @@ public:
bool in_bounds() const { return rank < 8 && file < 8; }
bool is_light() const { return (rank % 2) != (file % 2); }
String to_algebraic() const;
};
struct Move {
@ -98,6 +101,8 @@ public:
{
}
bool operator==(const Move& other) const { return from == other.from && to == other.to && promote_to == other.promote_to; }
String to_long_algebraic() const;
};
Chess();