Disservin / chess-library

C++ chess library
https://disservin.github.io/chess-library/
MIT License
63 stars 20 forks source link

Add `moveFromUci` and `draw` methods #101

Open miskibin opened 1 month ago

miskibin commented 1 month ago

Adding methods like pushUci or isDraw would make library more appealing for new users.

My naive method for drawing board.

    const std::unordered_map<char, std::string> piece{
        {'p', "♟"},
        {' ', " "},
        {'r', "♜"},
        {'n', "♞"},
        {'b', "♝"},
        {'q', "♛"},
        {'k', "♚"},
        {'P', "♙"},
        {'R', "♖"},
        {'N', "♘"},
        {'B', "♗"},
        {'Q', "♕"},
        {'K', "♔"}};

std::vector<char> DrawableBoard::resolveFen(const std::string fen) const
{
    std::vector<char> piecesVec;
    int rowIdx, colIdx = 0;
    for (auto c : fen)
    {
        if (c == '/')
            rowIdx++;
        else
        {
            if (isdigit(c))
            {
                piecesVec.insert(piecesVec.end(), c - '0', ' ');
                colIdx += c - '0';
            }
            else
            {
                piecesVec.push_back(c);
                colIdx++;
            }
        }
    }
    return piecesVec;
}

void DrawableBoard::draw() const
{
    auto fen = this->getFen();
    draw(fen);    
    }

void DrawableBoard::draw(std::string fen) const
{
auto pieces = resolveFen(fen);
    for (auto i = 0; i < 8; i++)
    {
        for (auto j = 0; j < 8; j++)
        {
            char currentPiece = pieces[8 * i + j];
            // std::cout << " | " << pieces[8 * i + j];
            if (piece.count(currentPiece) > 0)
            {
                std::cout << " | " << piece.at(currentPiece);
            }
            else
            {
                std::cout << " | " << " "; // Print a space if the piece is not in the map
            }
        }
        std::cout << " |" << std::endl;
    }

}

image

I am new to c++ so i believe it could be done much better.

I can create PR for that if u want

Disservin commented 1 month ago

The board is already drawable by doing

std::cout << board << std::endl;

which is mainly good for debugging, any other representation is highly opinionated I think..

moves would need to be convered via one of the conversion functions described here https://disservin.github.io/chess-library/pages/move.html#other-formats

board.makeMove(uci::uciToMove(board, uci));