From 4fc940c57e101bdaf7f0b04b282dab152581b79b Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 19:24:16 +0100 Subject: [PATCH 01/11] renamed bitboard file --- source/{bitboards.cpp => bitboard.cpp} | 2 +- source/{bitboards.h => bitboard.h} | 0 source/board.h | 2 +- source/movegen.h | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename source/{bitboards.cpp => bitboard.cpp} (95%) rename source/{bitboards.h => bitboard.h} (100%) diff --git a/source/bitboards.cpp b/source/bitboard.cpp similarity index 95% rename from source/bitboards.cpp rename to source/bitboard.cpp index 4448f7d..668edf8 100644 --- a/source/bitboards.cpp +++ b/source/bitboard.cpp @@ -1,4 +1,4 @@ -#include "bitboards.h" +#include "bitboard.h" void Bitboard::PrintBoard() const { for (int rank = 7; rank >= 0; rank--) { diff --git a/source/bitboards.h b/source/bitboard.h similarity index 100% rename from source/bitboards.h rename to source/bitboard.h diff --git a/source/board.h b/source/board.h index 2cf90fd..3ef20c9 100644 --- a/source/board.h +++ b/source/board.h @@ -1,6 +1,6 @@ #pragma once #include -#include "bitboards.h" +#include "bitboard.h" #include "types.h" #include "move.h" diff --git a/source/movegen.h b/source/movegen.h index 98f3eee..b69e40c 100644 --- a/source/movegen.h +++ b/source/movegen.h @@ -1,5 +1,5 @@ #pragma once -#include "bitboards.h" +#include "bitboard.h" #include "move.h" #include "board.h" -- 2.47.3 From 9c3b76d6a0fd7a3d9ab60303d763af759c0ba4a7 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 19:42:22 +0100 Subject: [PATCH 02/11] small refactor in board --- source/board.cpp | 6 ++---- source/board.h | 5 +++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/source/board.cpp b/source/board.cpp index be515c8..ebb845c 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -6,10 +6,6 @@ #include #include "utils.h" -void Board::Init() { - SetByFen(StartingFen); -} - void Board::Reset() { castlingRights = 0; enPassantTarget = noEPTarget; @@ -20,6 +16,8 @@ void Board::Reset() { colors = std::array(); moveList = std::array(); + attackMaps = std::array, 2>(); + currentMoveIndex = 0; hashKey = 0ULL; diff --git a/source/board.h b/source/board.h index 3ef20c9..aeb9ee2 100644 --- a/source/board.h +++ b/source/board.h @@ -13,12 +13,13 @@ inline U64 positionHistory[1000]; class Board { public: Board() { - Init(); + SetByFen(StartingFen); } std::array pieces; std::array colors; - U64 attackMaps[2][64]; + std::array, 2> attackMaps; + //U64 attackMaps[2][64]; Bitboard occupied; -- 2.47.3 From 1ce08aa0cb180a542793048492f02e87730f94b6 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 19:51:43 +0100 Subject: [PATCH 03/11] small benchmark adjustments --- source/benchmark.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/source/benchmark.cpp b/source/benchmark.cpp index 1f74ec4..db6e0a3 100644 --- a/source/benchmark.cpp +++ b/source/benchmark.cpp @@ -1,11 +1,12 @@ +#include +#include +#include #include "benchmark.h" #include "search.h" #include "stopwatch.h" #include "tt.h" -#include -#include -const std::array fenPositions = { +constexpr std::array fenPositions = { "rnbq1k1r/ppp1bppp/4pn2/8/2B5/2NP1N2/PPP2PPP/R1BQR1K1 b - - 2 8", "rnbq1k1r/pp2bppp/4pn2/2p5/2B2B2/2NP1N2/PPP2PPP/R2QR1K1 b - - 1 9", "r1bq1k1r/pp2bppp/2n1pn2/2p5/2B1NB2/3P1N2/PPP2PPP/R2QR1K1 b - - 3 10", @@ -60,7 +61,7 @@ const std::array fenPositions = { void RunBenchmark() { Board board; - int depth = 5; + int depth = 6; int ply = 0; benchStarted = true; searchStopped = false; @@ -76,7 +77,7 @@ void RunBenchmark() { Stopwatch sw; for (int i = 0; i < fenPositions.size(); i++) { - board.SetByFen(fenPositions[i].c_str()); + board.SetByFen(fenPositions[i]); PVS(board, depth, -inf, inf, ply); } -- 2.47.3 From 968d0f53773cd2d3de8bb75a1b61d728d6416d65 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 19:56:23 +0100 Subject: [PATCH 04/11] refactor in evaluate --- source/evaluate.cpp | 3 +++ source/evaluate.h | 5 ++++- source/search.cpp | 4 ++-- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/source/evaluate.cpp b/source/evaluate.cpp index 6c7cb31..37ab761 100644 --- a/source/evaluate.cpp +++ b/source/evaluate.cpp @@ -1,5 +1,7 @@ #include "evaluate.h" +namespace HCE { + static int GetPhaseWeight(Board &board, int color) { int phase = 0; @@ -60,3 +62,4 @@ int Evaluate(Board &board) { return board.sideToMove ? -score : score; } +} \ No newline at end of file diff --git a/source/evaluate.h b/source/evaluate.h index 5bec50d..0f2514c 100644 --- a/source/evaluate.h +++ b/source/evaluate.h @@ -1,6 +1,8 @@ #pragma once #include "board.h" +namespace HCE { + constexpr int phaseMax = 24; constexpr int phaseValues[4] { @@ -154,4 +156,5 @@ constexpr int scoreSquares[64] { a1, b1, c1, d1, e1, f1, g1, h1 }; -int Evaluate(Board &board); \ No newline at end of file +int Evaluate(Board &board); +} diff --git a/source/search.cpp b/source/search.cpp index 33f7db9..21085ea 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -118,7 +118,7 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { } } - int bestScore = Evaluate(board); + int bestScore = HCE::Evaluate(board); if (bestScore>= beta) { return bestScore; @@ -181,7 +181,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { if (depth <= 0) return Quiescence(board, alpha, beta, ply); - const int staticEval = Evaluate(board); + const int staticEval = HCE::Evaluate(board); if (board.InCheck(board.sideToMove)) { depth++; -- 2.47.3 From 23e1f8a165f52420167c645738b68f50f2af3766 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 20:04:02 +0100 Subject: [PATCH 05/11] small adjustment in move --- source/move.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/move.h b/source/move.h index e2ea3b2..0f04047 100644 --- a/source/move.h +++ b/source/move.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include #include "types.h" @@ -14,7 +15,7 @@ enum MOVE_FLAGS { knightPromoCapture, bishopPromoCapture, rookPromoCapture, queenPromoCapture }; -constexpr std::array moveTypes { +constexpr std::array moveTypes { "quiet", "doublePawnPush", "kingCastle", "QueenCastle", "capture", "epCapture", -- 2.47.3 From 20ab2f476a20437c670c5bc10bcd0d63eff1c1c7 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 20:20:24 +0100 Subject: [PATCH 06/11] refactor in several areas --- source/board.cpp | 16 ++++++------ source/board.h | 4 +-- source/main.cpp | 4 +-- source/movegen.cpp | 57 +++++++++++++++++++++++-------------------- source/movegen.h | 61 ++++++++-------------------------------------- source/perft.cpp | 4 +-- source/search.cpp | 10 ++++---- source/uci.cpp | 4 +-- source/utils.cpp | 2 +- 9 files changed, 62 insertions(+), 100 deletions(-) diff --git a/source/board.cpp b/source/board.cpp index ebb845c..0d6da91 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -65,8 +65,8 @@ void Board::SetByFen(std::string_view fen) { occupied = colors[White] | colors[Black]; hashKey = GetHashKey(*this); - GenerateMoves(*this, sideToMove); - GenAttackMaps(*this); + MOVEGEN::GenerateMoves(*this); + MOVEGEN::GenAttackMaps(*this); } void Board::PrintBoard() { @@ -158,10 +158,10 @@ U64 Board::GetAttackMaps(bool side) { return combined; } -bool Board::InCheck(bool side) { - Bitboard myKingSquare = colors[side] & pieces[King]; +bool Board::InCheck() { + Bitboard myKingSquare = colors[sideToMove] & pieces[King]; - return GetAttackMaps(!side) & myKingSquare; + return GetAttackMaps(!sideToMove) & myKingSquare; } void Board::SetPiece(int piece, int square, bool color) { @@ -340,18 +340,18 @@ void Board::MakeMove(Move move) { enPassantTarget = newEpTarget; - GenAttackMaps(*this); + MOVEGEN::GenAttackMaps(*this); positionIndex++; positionHistory[positionIndex] = hashKey; } -bool Board::InPossibleZug(bool side) { +bool Board::InPossibleZug() { Bitboard toCheck; // For all pieces other than pawns and king for (int piece = Knight; piece <= Queen; piece++) { - toCheck |= (pieces[piece] & colors[side]); + toCheck |= (pieces[piece] & colors[sideToMove]); } return !toCheck; diff --git a/source/board.h b/source/board.h index aeb9ee2..b823299 100644 --- a/source/board.h +++ b/source/board.h @@ -46,7 +46,7 @@ public: int GetPieceColor(int square); U64 GetAttackMaps(bool side); - bool InCheck(bool side); + bool InCheck(); void SetPiece(int piece, int square, bool color); void RemovePiece(int piece, int square, bool color); @@ -54,5 +54,5 @@ public: void Promote(int square, int pieceType, int color, bool isCapture); void MakeMove(Move move); - bool InPossibleZug(bool side); + bool InPossibleZug(); }; diff --git a/source/main.cpp b/source/main.cpp index e28ce09..4578caf 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -5,8 +5,8 @@ #include "benchmark.h" int main(int argc, char* argv[]) { - initLeaperAttacks(); - initSliderAttacks(); + MOVEGEN::initLeaperAttacks(); + MOVEGEN::initSliderAttacks(); InitZobrist(); Board board; diff --git a/source/movegen.cpp b/source/movegen.cpp index 5bf4a41..82b0387 100644 --- a/source/movegen.cpp +++ b/source/movegen.cpp @@ -1,22 +1,24 @@ #include "movegen.h" -Bitboard pawnAttacks[2][64]; -Bitboard knightAttacks[64]; -Bitboard kingAttacks[64]; +namespace MOVEGEN { + +static Bitboard pawnAttacks[2][64]; +static Bitboard knightAttacks[64]; +static Bitboard kingAttacks[64]; -Bitboard bishopMasks[64]; -Bitboard rookMasks[64]; +static Bitboard bishopMasks[64]; +static Bitboard rookMasks[64]; -Bitboard bishopAttacks[64][512]; -Bitboard rookAttacks[64][4096]; +static Bitboard bishopAttacks[64][512]; +static Bitboard rookAttacks[64][4096]; static Bitboard notAfile = ~files[A]; static Bitboard notHfile = ~files[H]; static Bitboard notABfile = notAfile & ~files[B]; static Bitboard notHGfile = notHfile & ~files[G]; -Bitboard maskPawnAttacks(int side, int square) { +static Bitboard maskPawnAttacks(int side, int square) { Bitboard attacks; Bitboard attacker = Bitboard::GetSquare(square); @@ -33,7 +35,7 @@ Bitboard maskPawnAttacks(int side, int square) { return attacks; } -Bitboard maskKnightAttacks(int square) { +static Bitboard maskKnightAttacks(int square) { Bitboard attacks; Bitboard attacker = Bitboard::GetSquare(square); @@ -50,7 +52,7 @@ Bitboard maskKnightAttacks(int square) { return attacks; } -Bitboard maskKingAttacks(int square) { +static Bitboard maskKingAttacks(int square) { Bitboard attacks; Bitboard attacker = Bitboard::GetSquare(square); @@ -67,7 +69,7 @@ Bitboard maskKingAttacks(int square) { return attacks; } -Bitboard maskBishopAttacks(int square) { +static Bitboard maskBishopAttacks(int square) { Bitboard attacks; // target rank and files @@ -96,7 +98,7 @@ Bitboard maskBishopAttacks(int square) { return attacks; } -Bitboard maskRookAttacks(int square) { +static Bitboard maskRookAttacks(int square) { Bitboard attacks; // target rank and files @@ -125,7 +127,7 @@ Bitboard maskRookAttacks(int square) { return attacks; } -Bitboard bishopAttacksOnTheFly(int square, Bitboard block) { +static Bitboard bishopAttacksOnTheFly(int square, Bitboard block) { Bitboard attacks; // target rank and files @@ -164,7 +166,7 @@ Bitboard bishopAttacksOnTheFly(int square, Bitboard block) { return attacks; } -Bitboard rookAttacksOnTheFly(int square, Bitboard block) { +static Bitboard rookAttacksOnTheFly(int square, Bitboard block) { Bitboard attacks; // target rank and files @@ -238,7 +240,7 @@ void initSliderAttacks() { } } -Bitboard getBishopAttack(int square, U64 occupancy) { +static Bitboard getBishopAttack(int square, U64 occupancy) { occupancy &= bishopMasks[square]; occupancy *= bishopMagicNumbers[square]; occupancy >>= (64 - bishopRelevantBits[square]); @@ -246,7 +248,7 @@ Bitboard getBishopAttack(int square, U64 occupancy) { return bishopAttacks[square][occupancy]; } -Bitboard getRookAttack(int square, U64 occupancy) { +static Bitboard getRookAttack(int square, U64 occupancy) { occupancy &= rookMasks[square]; occupancy *= rookMagicNumbers[square]; occupancy >>= (64 - rookRelevantBits[square]); @@ -254,7 +256,7 @@ Bitboard getRookAttack(int square, U64 occupancy) { return rookAttacks[square][occupancy]; } -Bitboard getQueenAttack(int square, U64 occupancy) { +static Bitboard getQueenAttack(int square, U64 occupancy) { U64 bishopOccupancy = occupancy; U64 rookOccupancy = occupancy; @@ -269,7 +271,7 @@ Bitboard getQueenAttack(int square, U64 occupancy) { return rookAttacks[square][rookOccupancy] | bishopAttacks[square][bishopOccupancy]; } -Bitboard getPieceAttacks(int square, int piece, int color, U64 occupancy) { +static Bitboard getPieceAttacks(int square, int piece, int color, U64 occupancy) { if (piece == Pawn) { return pawnAttacks[color][square]; } else if (piece == Knight) { @@ -987,18 +989,19 @@ void GenAttackMaps(Board &board) { } } -void GenerateMoves(Board &board, bool side) { +void GenerateMoves(Board &board) { board.ResetMoves(); - if (board.InCheck(side)) { - GenCheckEvasions(board, side); + if (board.InCheck()) { + GenCheckEvasions(board, board.sideToMove); return; } - GenPawnMoves(board, side); - GenKnightMoves(board, side); - GenKingMoves(board, side, false); - GenBishopMoves(board, side); - GenRookMoves(board, side); - GenQueenMoves(board, side); + GenPawnMoves(board, board.sideToMove); + GenKnightMoves(board, board.sideToMove); + GenKingMoves(board, board.sideToMove, false); + GenBishopMoves(board, board.sideToMove); + GenRookMoves(board, board.sideToMove); + GenQueenMoves(board, board.sideToMove); } +} \ No newline at end of file diff --git a/source/movegen.h b/source/movegen.h index b69e40c..04a965f 100644 --- a/source/movegen.h +++ b/source/movegen.h @@ -3,6 +3,15 @@ #include "move.h" #include "board.h" +namespace MOVEGEN { + +void initLeaperAttacks(); +void initSliderAttacks(); + +void GenAttackMaps(Board &board); + +void GenerateMoves(Board &board); + // bishop relevant occupancy bit count constexpr int bishopRelevantBits[64] = { 6, 5, 5, 5, 5, 5, 5, 6, @@ -160,54 +169,4 @@ constexpr U64 bishopMagicNumbers[64] = { 0x8918844842082200ULL, 0x4010011029020020ULL }; - -// pawn attacks table [side][square] -extern Bitboard pawnAttacks[2][64]; - -extern Bitboard knightAttacks[64]; -extern Bitboard kingAttacks[64]; - -extern Bitboard bishopMasks[64]; -extern Bitboard rookMasks[64]; - -// bishop attacks table [square][occupancies] -extern Bitboard bishopAttacks[64][512]; - -// rook attacks table [square][occupancies] -extern Bitboard rookAttacks[64][4096]; - -// generate pawn masks -Bitboard maskPawnAttacks(int square, int side); - -// generate knight masks -Bitboard maskKnightAttacks(int square); - -// generate king masks -Bitboard maskKingAttacks(int square); - -// generate bishop masks -Bitboard maskBishopAttacks(int square); - -//generate bishop attacks -Bitboard bishopAttacksOnTheFly(int square, Bitboard block); - -// generate rook masks -Bitboard maskRookAttacks(int square); - -//generate rook attacks -Bitboard rookAttacksOnTheFly(int square, Bitboard block); - -void initLeaperAttacks(); -void initSliderAttacks(); - -Bitboard getBishopAttack(int square, U64 occupancy); -Bitboard getRookAttack(int square, U64 occupancy); -Bitboard getQueenAttack(int square, U64 occupancy); - -// Returns Bitboard of piece attacks from given square -// Returns attacks regardless of board (so occupancy is 0ULL) -Bitboard getPieceAttacks(int square, int piece, int color); - -void GenAttackMaps(Board &board); - -void GenerateMoves(Board &board, bool side); \ No newline at end of file +} \ No newline at end of file diff --git a/source/perft.cpp b/source/perft.cpp index 8c89554..fdddbeb 100644 --- a/source/perft.cpp +++ b/source/perft.cpp @@ -2,7 +2,7 @@ #include "stopwatch.h" U64 HelperPerft(Board board, int depth) { - GenerateMoves(board, board.sideToMove); + MOVEGEN::GenerateMoves(board); if (depth == 1) return board.currentMoveIndex; if (depth == 0) return 1ULL; @@ -19,7 +19,7 @@ U64 HelperPerft(Board board, int depth) { } void Perft(Board &board, int depth) { - GenerateMoves(board, board.sideToMove); + MOVEGEN::GenerateMoves(board); U64 totalNodes = 0; diff --git a/source/search.cpp b/source/search.cpp index 21085ea..d4e5994 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -128,7 +128,7 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { alpha = bestScore; } - GenerateMoves(board, board.sideToMove); + MOVEGEN::GenerateMoves(board); SortMoves(board, ply); @@ -183,7 +183,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { const int staticEval = HCE::Evaluate(board); - if (board.InCheck(board.sideToMove)) { + if (board.InCheck()) { depth++; } else { if (ply) { @@ -195,7 +195,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { // Null Move Pruning if (!doingNullMove && staticEval >= beta) { - if (depth >= 3 && !board.InPossibleZug(board.sideToMove)) { + if (depth >= 3 && !board.InPossibleZug()) { Board copy = board; copy.MakeMove(Move()); @@ -210,10 +210,10 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { } } - GenerateMoves(board, board.sideToMove); + MOVEGEN::GenerateMoves(board); if (board.currentMoveIndex == 0) { - if (board.InCheck(board.sideToMove)) { // checkmate + if (board.InCheck()) { // checkmate return -99000 + ply; } else { // stalemate return 0; diff --git a/source/uci.cpp b/source/uci.cpp index 9b308d6..aeef780 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -36,8 +36,8 @@ void ParsePosition(Board &board, std::string_view command) { } } - GenerateMoves(board, board.sideToMove); - GenAttackMaps(board); + MOVEGEN::GenerateMoves(board); + MOVEGEN::GenAttackMaps(board); } static int ReadParam(std::string param, std::string &command) { diff --git a/source/utils.cpp b/source/utils.cpp index 17f63f6..6396104 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -25,7 +25,7 @@ int parseSquare(std::string_view str) { } Move parseMove(Board &board, std::string_view str) { - GenerateMoves(board, board.sideToMove); + MOVEGEN::GenerateMoves(board); int from = parseSquare(str.substr(0, 2)); int to = parseSquare(str.substr(2, 2)); -- 2.47.3 From 8d5024a4a4d78e364371ed267ca05c7fe352f4d1 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 20:23:22 +0100 Subject: [PATCH 07/11] bugfix: perft --- source/perft.cpp | 5 ++++- source/perft.h | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/source/perft.cpp b/source/perft.cpp index fdddbeb..ed8f828 100644 --- a/source/perft.cpp +++ b/source/perft.cpp @@ -1,7 +1,8 @@ #include "perft.h" #include "stopwatch.h" +#include "movegen.h" -U64 HelperPerft(Board board, int depth) { +static U64 HelperPerft(Board board, int depth) { MOVEGEN::GenerateMoves(board); if (depth == 1) return board.currentMoveIndex; @@ -13,6 +14,7 @@ U64 HelperPerft(Board board, int depth) { Board copy = board; board.MakeMove(board.moveList[i]); nodes += HelperPerft(board, depth - 1); + positionIndex--; board = copy; } return nodes; @@ -28,6 +30,7 @@ void Perft(Board &board, int depth) { Board copy = board; board.MakeMove(board.moveList[i]); U64 nodeCount = HelperPerft(board, depth - 1); + positionIndex--; board = copy; totalNodes += nodeCount; board.moveList[i].PrintMove(); diff --git a/source/perft.h b/source/perft.h index fe787c6..13d0ac6 100644 --- a/source/perft.h +++ b/source/perft.h @@ -1,5 +1,4 @@ #pragma once #include "board.h" -#include "movegen.h" void Perft(Board &board, int depth); \ No newline at end of file -- 2.47.3 From 0ffc2c77deb781cd07ed011bcc72a974baa68df2 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 20:39:12 +0100 Subject: [PATCH 08/11] bigger refactor in several files --- source/board.cpp | 32 ++++++++++---------- source/main.cpp | 4 +-- source/tt.cpp | 79 +----------------------------------------------- source/tt.h | 14 --------- source/uci.cpp | 4 +-- source/utils.cpp | 71 +++++++++++++++++++++++++++++++++++++++++++ source/utils.h | 19 ++++++++++++ 7 files changed, 111 insertions(+), 112 deletions(-) diff --git a/source/board.cpp b/source/board.cpp index 0d6da91..21540d4 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -29,8 +29,8 @@ void Board::SetByFen(std::string_view fen) { // Starting from top left int currSquare = a8; - std::vector tokens = split(fen, ' '); - std::vector pieceTokens = split(tokens[0], '/'); + std::vector tokens = UTILS::split(fen, ' '); + std::vector pieceTokens = UTILS::split(tokens[0], '/'); constexpr std::string_view pieceTypes = "pnbrqk"; @@ -61,10 +61,10 @@ void Board::SetByFen(std::string_view fen) { else if (piece == 'q') castlingRights |= blackQueenRight; } - if (tokens[3] != "-") enPassantTarget = parseSquare(tokens[3]); + if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]); occupied = colors[White] | colors[Black]; - hashKey = GetHashKey(*this); + hashKey = UTILS::GetHashKey(*this); MOVEGEN::GenerateMoves(*this); MOVEGEN::GenAttackMaps(*this); } @@ -169,7 +169,7 @@ void Board::SetPiece(int piece, int square, bool color) { colors[color].SetBit(square); occupied.SetBit(square); - hashKey ^= zKeys[color][piece][square]; + hashKey ^= UTILS::zKeys[color][piece][square]; } void Board::RemovePiece(int piece, int square, bool color) { @@ -177,14 +177,14 @@ void Board::RemovePiece(int piece, int square, bool color) { colors[color].PopBit(square); occupied.PopBit(square); - hashKey ^= zKeys[color][piece][square]; + hashKey ^= UTILS::zKeys[color][piece][square]; } // Updates castling rights static void UpdateCastlingRights(Board &board, int square, int type, int color) { if (type == Rook) { // Removing old rights - board.hashKey ^= zCastle[board.castlingRights]; + board.hashKey ^= UTILS::zCastle[board.castlingRights]; int queenSideRook = color ? a8 : a1; int kingSideRook = color ? h8 : h1; @@ -194,15 +194,15 @@ static void UpdateCastlingRights(Board &board, int square, int type, int color) board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight; } - board.hashKey ^= zCastle[board.castlingRights]; + board.hashKey ^= UTILS::zCastle[board.castlingRights]; } else if (type == King) { // Removing old rights - board.hashKey ^= zCastle[board.castlingRights]; + board.hashKey ^= UTILS::zCastle[board.castlingRights]; board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight; board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight; - board.hashKey ^= zCastle[board.castlingRights]; + board.hashKey ^= UTILS::zCastle[board.castlingRights]; } } @@ -224,14 +224,14 @@ void Board::MakeMove(Move move) { int newEpTarget = noEPTarget; sideToMove = !sideToMove; - hashKey ^= zSide; + hashKey ^= UTILS::zSide; if (enPassantTarget != noEPTarget) { - hashKey ^= zEnPassant[enPassantTarget % 8]; + hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; } if (newEpTarget != noEPTarget) { - hashKey ^= zEnPassant[newEpTarget % 8]; + hashKey ^= UTILS::zEnPassant[newEpTarget % 8]; } enPassantTarget = newEpTarget; @@ -328,14 +328,14 @@ void Board::MakeMove(Move move) { UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor); sideToMove = !attackerColor; - hashKey ^= zSide; + hashKey ^= UTILS::zSide; if (enPassantTarget != noEPTarget) { - hashKey ^= zEnPassant[enPassantTarget % 8]; + hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; } if (newEpTarget != noEPTarget) { - hashKey ^= zEnPassant[newEpTarget % 8]; + hashKey ^= UTILS::zEnPassant[newEpTarget % 8]; } enPassantTarget = newEpTarget; diff --git a/source/main.cpp b/source/main.cpp index 4578caf..93eb880 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -1,13 +1,13 @@ #include "board.h" #include "movegen.h" #include "uci.h" -#include "tt.h" +#include "utils.h" #include "benchmark.h" int main(int argc, char* argv[]) { MOVEGEN::initLeaperAttacks(); MOVEGEN::initSliderAttacks(); - InitZobrist(); + UTILS::InitZobrist(); Board board; diff --git a/source/tt.cpp b/source/tt.cpp index c92ceae..e65b2b7 100644 --- a/source/tt.cpp +++ b/source/tt.cpp @@ -1,82 +1,5 @@ #include "tt.h" -static U64 initialSeed = 0x60919C48E57863B9; - -// 2[colors] * 6[pieces] * 64[squares] -U64 zKeys[2][6][64]; - -// There are 8 files -U64 zEnPassant[8]; - -// 16 possible castling right variations -U64 zCastle[16]; - -U64 zSide; - -// PRNG using xorshift -static U64 RandomNum() { - initialSeed ^= initialSeed << 13; - initialSeed ^= initialSeed >> 7; - initialSeed ^= initialSeed << 17; - return initialSeed; -} - -void InitZobrist() { - // init piece square keys - for (int i = White; i <= Black; i++) { - for (int j = Pawn; j <= King; j++) { - for (int k = a1; k <= h8; k++) { - zKeys[i][j][k] = RandomNum(); - } - } - } - - // init en passant file keys - for (int i = 0; i < 8; i++) { - zEnPassant[i] = RandomNum(); - } - - // init castling rights keys - for (int i = 0; i < 16; i++) { - zCastle[i] = RandomNum(); - } - - // init side key - zSide = RandomNum(); -} - -U64 GetHashKey(Board &board) { - U64 key = 0ULL; - - // XORing pieces - for (int color = White; color <= Black; color++) { - for (int piece = Pawn; piece <= King; piece++) { - Bitboard pieceSet = board.pieces[piece] & board.colors[color]; - - while (pieceSet) { - int square = pieceSet.getLS1BIndex(); - - key ^= zKeys[color][piece][square]; - - pieceSet.PopBit(square); - } - } - } - - // XORing en passant - if (board.enPassantTarget != -1) { - key ^= zEnPassant[board.enPassantTarget % 8]; - } - - // XORing castling rights - key ^= zCastle[board.castlingRights]; - - // XORing side to move - if (board.sideToMove) key ^= zSide; - - return key; -} - SearchResults TTable::ReadEntry(U64 &hashKey, int depth, int alpha, int beta) { TTEntry *current = &table[hashKey % hashSize]; @@ -104,4 +27,4 @@ void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move b current->score = score; current->depth = depth; current->bestMove = bestMove; -} +} \ No newline at end of file diff --git a/source/tt.h b/source/tt.h index e167cf6..1b973ab 100644 --- a/source/tt.h +++ b/source/tt.h @@ -3,20 +3,6 @@ #include "search.h" #include -// 2[colors] * 6[pieces] * 64[squares] -extern U64 zKeys[2][6][64]; - -// There are 8 files -extern U64 zEnPassant[8]; - -// 16 possible castling right variations -extern U64 zCastle[16]; - -extern U64 zSide; - -void InitZobrist(); -U64 GetHashKey(Board &board); - class TTEntry { public: U64 hashKey; diff --git a/source/uci.cpp b/source/uci.cpp index aeef780..e9a735c 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -29,10 +29,10 @@ void ParsePosition(Board &board, std::string_view command) { } if (movesIndex != std::string::npos) { - std::vector moves = split(command.substr(movesIndex + 6, command.length() - (movesIndex + 5)), ' '); + std::vector moves = UTILS::split(command.substr(movesIndex + 6, command.length() - (movesIndex + 5)), ' '); for (std::string_view move : moves) { - board.MakeMove(parseMove(board, move)); + board.MakeMove(UTILS::parseMove(board, move)); } } diff --git a/source/utils.cpp b/source/utils.cpp index 6396104..12f8bf6 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -1,6 +1,76 @@ #include "utils.h" #include "movegen.h" +namespace UTILS { + +// Zobrist // + +U64 initialSeed = 0x60919C48E57863B9; + +// PRNG using xorshift +static U64 RandomNum() { + initialSeed ^= initialSeed << 13; + initialSeed ^= initialSeed >> 7; + initialSeed ^= initialSeed << 17; + return initialSeed; +} + +void InitZobrist() { + // init piece square keys + for (int i = White; i <= Black; i++) { + for (int j = Pawn; j <= King; j++) { + for (int k = a1; k <= h8; k++) { + zKeys[i][j][k] = RandomNum(); + } + } + } + + // init en passant file keys + for (int i = 0; i < 8; i++) { + zEnPassant[i] = RandomNum(); + } + + // init castling rights keys + for (int i = 0; i < 16; i++) { + zCastle[i] = RandomNum(); + } + + // init side key + zSide = RandomNum(); +} + +U64 GetHashKey(Board &board) { + U64 key = 0ULL; + + // XORing pieces + for (int color = White; color <= Black; color++) { + for (int piece = Pawn; piece <= King; piece++) { + Bitboard pieceSet = board.pieces[piece] & board.colors[color]; + + while (pieceSet) { + int square = pieceSet.getLS1BIndex(); + + key ^= zKeys[color][piece][square]; + + pieceSet.PopBit(square); + } + } + } + + // XORing en passant + if (board.enPassantTarget != -1) { + key ^= zEnPassant[board.enPassantTarget % 8]; + } + + // XORing castling rights + key ^= zCastle[board.castlingRights]; + + // XORing side to move + if (board.sideToMove) key ^= zSide; + + return key; +} + std::vector split(std::string_view str, char delim) { std::vector results; @@ -76,3 +146,4 @@ Move parseMove(Board &board, std::string_view str) { return Move(from, to, flag); } +} diff --git a/source/utils.h b/source/utils.h index 6c23585..0156f55 100644 --- a/source/utils.h +++ b/source/utils.h @@ -6,8 +6,27 @@ #include "move.h" #include "board.h" +namespace UTILS { + +// Zobrist // + +// 2[colors] * 6[pieces] * 64[squares] +inline U64 zKeys[2][6][64]; + +// There are 8 files +inline U64 zEnPassant[8]; + +// 16 possible castling right variations +inline U64 zCastle[16]; + +inline U64 zSide; + +void InitZobrist(); +U64 GetHashKey(Board &board); + std::vector split(std::string_view str, char delim); int parseSquare(std::string_view str); Move parseMove(Board &board, std::string_view str); +} -- 2.47.3 From 47195080807a364fc62e44baabecf6a515298363 Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 20:45:58 +0100 Subject: [PATCH 09/11] small refactor in uci --- source/uci.cpp | 4 ++-- source/uci.h | 7 ------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/source/uci.cpp b/source/uci.cpp index e9a735c..723f139 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -12,7 +12,7 @@ #include "perft.h" #include "utils.h" -void ParsePosition(Board &board, std::string_view command) { +static void ParsePosition(Board &board, std::string_view command) { if (command.find("startpos") != std::string::npos) { board.SetByFen(StartingFen); } @@ -58,7 +58,7 @@ static int ReadParam(std::string param, std::string &command) { return 0; } -void ParseGo(Board &board, std::string &command) { +static void ParseGo(Board &board, std::string &command) { SearchParams params; params.wtime = ReadParam("wtime", command); diff --git a/source/uci.h b/source/uci.h index a565f06..11a231e 100644 --- a/source/uci.h +++ b/source/uci.h @@ -13,12 +13,5 @@ public: SearchParams(){} }; -// Initializes the position with given parameters -void ParsePosition(Board &board, std::string_view command); - -// Parse UCI "go" command -// GUI sends the engine this command if it should start searching for the best move -void ParseGo(Board &board, std::string &command); - // main UCI loop void UCILoop(Board &board); -- 2.47.3 From f2d76b11339c18d534f8e38c41861c43a8d12d7b Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 20:47:09 +0100 Subject: [PATCH 10/11] clearing killer and history after bench --- source/benchmark.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/benchmark.cpp b/source/benchmark.cpp index db6e0a3..db3e04d 100644 --- a/source/benchmark.cpp +++ b/source/benchmark.cpp @@ -85,5 +85,7 @@ void RunBenchmark() { nodes = 0; TT.Clear(); benchStarted = false; + std::memset(killerMoves, 0, sizeof(killerMoves)); + history.Clear(); positionIndex = 0; } -- 2.47.3 From 729ba94123c69894d7231782b3c3895f23269acd Mon Sep 17 00:00:00 2001 From: rektdie Date: Thu, 20 Mar 2025 21:14:07 +0100 Subject: [PATCH 11/11] final refactor | bench 900613 --- source/benchmark.cpp | 2 ++ source/board.cpp | 24 ++++++++++++------------ source/search.cpp | 3 +++ source/search.h | 3 +++ source/tt.cpp | 2 +- source/tt.h | 2 +- source/uci.cpp | 8 ++++---- 7 files changed, 26 insertions(+), 18 deletions(-) diff --git a/source/benchmark.cpp b/source/benchmark.cpp index db3e04d..02528e5 100644 --- a/source/benchmark.cpp +++ b/source/benchmark.cpp @@ -6,6 +6,8 @@ #include "stopwatch.h" #include "tt.h" +using namespace SEARCH; + constexpr std::array fenPositions = { "rnbq1k1r/ppp1bppp/4pn2/8/2B5/2NP1N2/PPP2PPP/R1BQR1K1 b - - 2 8", "rnbq1k1r/pp2bppp/4pn2/2p5/2B2B2/2NP1N2/PPP2PPP/R2QR1K1 b - - 1 9", diff --git a/source/board.cpp b/source/board.cpp index 21540d4..2625a5f 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -217,28 +217,28 @@ void Board::Promote(int square, int pieceType, int color, bool isCapture) { } void Board::MakeMove(Move move) { - nodes++; - - // Null Move + SEARCH::nodes++; + + // Null Move if (!move) { - int newEpTarget = noEPTarget; - + int newEpTarget = noEPTarget; + sideToMove = !sideToMove; hashKey ^= UTILS::zSide; - + if (enPassantTarget != noEPTarget) { - hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; + hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; } - + if (newEpTarget != noEPTarget) { - hashKey ^= UTILS::zEnPassant[newEpTarget % 8]; + hashKey ^= UTILS::zEnPassant[newEpTarget % 8]; } - + enPassantTarget = newEpTarget; - + return; } - + int newEpTarget = noEPTarget; int attackerPiece = GetPieceType(move.MoveFrom()); diff --git a/source/search.cpp b/source/search.cpp index d4e5994..6874efe 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -6,6 +6,8 @@ #include "tt.h" #include "stopwatch.h" +namespace SEARCH { + U64 nodes = 0; bool benchStarted = false; @@ -361,3 +363,4 @@ void SearchPosition(Board &board, SearchParams params) { void StopSearch() { searchStopped = true; } +} \ No newline at end of file diff --git a/source/search.h b/source/search.h index 55cb9bb..1458400 100644 --- a/source/search.h +++ b/source/search.h @@ -5,6 +5,8 @@ #include "move.h" #include +namespace SEARCH { + constexpr int maxDepth = 64; constexpr int maxHistory = 16384; @@ -108,3 +110,4 @@ constexpr int moveScoreTable[6][6] = { }; void ListScores(Board &board); +} \ No newline at end of file diff --git a/source/tt.cpp b/source/tt.cpp index e65b2b7..3df1649 100644 --- a/source/tt.cpp +++ b/source/tt.cpp @@ -1,6 +1,6 @@ #include "tt.h" -SearchResults TTable::ReadEntry(U64 &hashKey, int depth, int alpha, int beta) { +SEARCH::SearchResults TTable::ReadEntry(U64 &hashKey, int depth, int alpha, int beta) { TTEntry *current = &table[hashKey % hashSize]; if (current->hashKey == hashKey) { diff --git a/source/tt.h b/source/tt.h index 1b973ab..e8607c4 100644 --- a/source/tt.h +++ b/source/tt.h @@ -56,7 +56,7 @@ public: return count; } - SearchResults ReadEntry(U64 &hashKey, int depth, int alpha, int beta); + SEARCH::SearchResults ReadEntry(U64 &hashKey, int depth, int alpha, int beta); void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move besteMove); }; diff --git a/source/uci.cpp b/source/uci.cpp index 723f139..d9f72b4 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -72,7 +72,7 @@ static void ParseGo(Board &board, std::string &command) { params.btime = ReadParam("movetime", command); } - auto worker = std::thread(SearchPosition, std::ref(board), params); + auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params); worker.detach(); } @@ -118,9 +118,9 @@ void UCILoop(Board &board) { // Clearing TT.Clear(); - std::memset(killerMoves, 0, sizeof(killerMoves)); + std::memset(SEARCH::killerMoves, 0, sizeof(SEARCH::killerMoves)); - history.Clear(); + SEARCH::history.Clear(); positionIndex = 0; continue; @@ -141,7 +141,7 @@ void UCILoop(Board &board) { // parse UCI "stop" command if (input.find("stop") != std::string::npos) { // stop the loop - StopSearch(); + SEARCH::StopSearch(); continue; } -- 2.47.3