From f8d8c20695684a545b536e83a9977c25028232d5 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 25 Jul 2026 18:07:29 +0200 Subject: adding get legal moves --- src/moves.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'src/moves.cpp') diff --git a/src/moves.cpp b/src/moves.cpp index f417499..65a380a 100644 --- a/src/moves.cpp +++ b/src/moves.cpp @@ -1,3 +1,63 @@ +#include +#include + +#include "board.hpp" #include "moves.hpp" +std::vector GetLegalMoves(board *b) { + std::vector moves; + moves.reserve(50); // almost all position dont have that many moves + + constexpr std::array rook_Moves{-1, 1, 8, -8}; + constexpr std::array bishop_Moves{-9, 9, -7, 7}; + + for (int i = 0; i < sizeof(b->pieces) / sizeof(b->pieces[0]); i++) { + Piece piece = b->pieces[i]; + if (piece.type == NONE) { + continue; + } + if (piece.color != b->turn) + continue; + + // Add support for other pieces + if (piece.type == BISHOP) { + GenerateSlidingMoves(b, i, bishop_Moves, moves); + } + if (piece.type == ROOK) { + GenerateSlidingMoves(b, i, rook_Moves, moves); + } + }; + + return moves; +} +Position IndexToPosition(int i) { + uint8_t rank = i / 8; // 0-7 + uint8_t file = i % 8; // 0-7 + return {rank, file}; +} +void GenerateSlidingMoves(board *b, int from, + const std::array &directions, + std::vector &moves) { + for (int i = 0; i < directions.size(); i++) { + int direction = directions[i]; + int i2 = from; + while (true) { + i2 += direction; + if (i2 >= 64 || i2 < 0) { + break; + } + if (b->pieces[i2].color == b->turn && b->pieces[i2].type != NONE) { + break; + } + if ((direction == 1 || direction == -1) && + (i2 / 8 != (i2 - direction) / 8)) { + break; + } + moves.push_back({IndexToPosition(i2), IndexToPosition(i2)}); + if (b->pieces[i2].color != b->turn && b->pieces[i2].type != NONE) { + break; + } + } + }; +}; -- cgit v1.2.3