#include <cstdint>
#include <cstdio>
struct PerftResult {
uint64_t nodes;
uint64_t captures;
uint64_t enPassant;
uint64_t castles;
uint64_t promotions;
uint64_t checks;
uint64_t checkmates;
uint64_t stalemates;
};
PerftResult perft(BitboardBoard& board, int depth) {
PerftResult result = {0, 0, 0, 0, 0, 0, 0, 0};
markdown
if (depth == 0) {
result.nodes = 1;
return result;
}
Move moves[256];
int numMoves = generateLegalMoves(board, moves);
if (depth == 1 && numMoves == 0) {
if (isInCheck(board)) result.checkmates = 1;
else result.stalemates = 1;
result.nodes = 1;
return result;
}
for (int i = 0
PerftResult child;
makeMove(board, moves[i]);
child = perft(board, depth - 1);
result.nodes += child.nodes;
result.captures += child.captures + (isCapture(moves[i]) ? 1 : 0);
result.enPassant += child.enPassant + (isEnPassant(moves[i]) ? 1 : 0);
result.castles += child.castles + (isCastle(moves[i]) ? 1 : 0);
result.promotions += child.promotions + (isPromotion(moves[i]) ? 1 : 0);
result.checks += child.checks + (isInCheck(board) ? 1 : 0);
result.checkmates += child.checkmates;
result.stalemates += child.stalemates;
unmakeMove(board, moves[i]);
}
return result;
}
void perftDivide(BitboardBoard& board, int depth) {
Move moves[256];
int numMoves = generateLegalMoves(board, moves);
uint64_t total = 0;
markdown
printf("Perft(%d) divide:\n", depth);
for (int i = 0
makeMove(board, moves[i]);
PerftResult result = perft(board, depth - 1);
unmakeMove(board, moves[i]);
char moveStr[8];
formatMove(moves[i], moveStr);
printf("%s: %llu\n", moveStr, result.nodes);
total += result.nodes;
}
printf("Total: %llu\n", total);
}
void runPerftTests() {
struct TestCase { const char* fen; int depth; uint64_t expected; };
TestCase tests[] = {
{"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", 5, 4865609ULL},
{"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", 4, 4085603ULL},
{"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", 4, 43237ULL},
{"r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1", 4, 4085603ULL},
{"rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8", 3, 62379ULL},
};
markdown
for (auto& tc : tests) {
BitboardBoard board;
board.loadFEN(tc.fen);
PerftResult result = perft(board, tc.depth);
printf("FEN: %s\nDepth %d: %llu (expected %llu) %s\n",
tc.fen, tc.depth, result.nodes, tc.expected,
result.nodes == tc.expected ? "PASS" : "FAIL");
}
}