diff --git a/source/benchmark.cpp b/source/benchmark.cpp index 1f74ec4..02528e5 100644 --- a/source/benchmark.cpp +++ b/source/benchmark.cpp @@ -1,11 +1,14 @@ +#include +#include +#include #include "benchmark.h" #include "search.h" #include "stopwatch.h" #include "tt.h" -#include -#include -const std::array fenPositions = { +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", "r1bq1k1r/pp2bppp/2n1pn2/2p5/2B1NB2/3P1N2/PPP2PPP/R2QR1K1 b - - 3 10", @@ -60,7 +63,7 @@ const std::array fenPositions = { void RunBenchmark() { Board board; - int depth = 5; + int depth = 6; int ply = 0; benchStarted = true; searchStopped = false; @@ -76,7 +79,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); } @@ -84,5 +87,7 @@ void RunBenchmark() { nodes = 0; TT.Clear(); benchStarted = false; + std::memset(killerMoves, 0, sizeof(killerMoves)); + history.Clear(); positionIndex = 0; } 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.cpp b/source/board.cpp index be515c8..2625a5f 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; @@ -31,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"; @@ -63,12 +61,12 @@ 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); - GenerateMoves(*this, sideToMove); - GenAttackMaps(*this); + hashKey = UTILS::GetHashKey(*this); + MOVEGEN::GenerateMoves(*this); + MOVEGEN::GenAttackMaps(*this); } void Board::PrintBoard() { @@ -160,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) { @@ -171,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) { @@ -179,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; @@ -196,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]; } } @@ -219,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 ^= 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; - + return; } - + int newEpTarget = noEPTarget; int attackerPiece = GetPieceType(move.MoveFrom()); @@ -330,30 +328,30 @@ 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; - 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 2cf90fd..b823299 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" @@ -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; @@ -45,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); @@ -53,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/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/main.cpp b/source/main.cpp index e28ce09..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[]) { - initLeaperAttacks(); - initSliderAttacks(); - InitZobrist(); + MOVEGEN::initLeaperAttacks(); + MOVEGEN::initSliderAttacks(); + UTILS::InitZobrist(); Board board; 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", 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 98f3eee..04a965f 100644 --- a/source/movegen.h +++ b/source/movegen.h @@ -1,8 +1,17 @@ #pragma once -#include "bitboards.h" +#include "bitboard.h" #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..ed8f828 100644 --- a/source/perft.cpp +++ b/source/perft.cpp @@ -1,8 +1,9 @@ #include "perft.h" #include "stopwatch.h" +#include "movegen.h" -U64 HelperPerft(Board board, int depth) { - GenerateMoves(board, board.sideToMove); +static U64 HelperPerft(Board board, int depth) { + MOVEGEN::GenerateMoves(board); if (depth == 1) return board.currentMoveIndex; if (depth == 0) return 1ULL; @@ -13,13 +14,14 @@ U64 HelperPerft(Board board, int depth) { Board copy = board; board.MakeMove(board.moveList[i]); nodes += HelperPerft(board, depth - 1); + positionIndex--; board = copy; } return nodes; } void Perft(Board &board, int depth) { - GenerateMoves(board, board.sideToMove); + MOVEGEN::GenerateMoves(board); U64 totalNodes = 0; @@ -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 diff --git a/source/search.cpp b/source/search.cpp index 33f7db9..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; @@ -118,7 +120,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; @@ -128,7 +130,7 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { alpha = bestScore; } - GenerateMoves(board, board.sideToMove); + MOVEGEN::GenerateMoves(board); SortMoves(board, ply); @@ -181,9 +183,9 @@ 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)) { + if (board.InCheck()) { depth++; } else { if (ply) { @@ -195,7 +197,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 +212,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; @@ -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 c92ceae..3df1649 100644 --- a/source/tt.cpp +++ b/source/tt.cpp @@ -1,83 +1,6 @@ #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) { +SEARCH::SearchResults TTable::ReadEntry(U64 &hashKey, int depth, int alpha, int beta) { TTEntry *current = &table[hashKey % hashSize]; if (current->hashKey == hashKey) { @@ -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..e8607c4 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; @@ -70,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 9b308d6..d9f72b4 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); } @@ -29,15 +29,15 @@ 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)); } } - GenerateMoves(board, board.sideToMove); - GenAttackMaps(board); + MOVEGEN::GenerateMoves(board); + MOVEGEN::GenAttackMaps(board); } static int ReadParam(std::string param, std::string &command) { @@ -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); @@ -72,7 +72,7 @@ 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; } 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); diff --git a/source/utils.cpp b/source/utils.cpp index 17f63f6..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; @@ -25,7 +95,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)); @@ -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); +}