#include <cstdint>
// Piece values in centipawns
const int PIECE_VALUES[12] = {
100, 320, 330, 500, 900, 20000, // white P N B R Q K
100, 320, 330, 500, 900, 20000 // black p n b r q k
};
// Piece-square tables (middlegame, from White's perspective)
const int PST_MG[6][64] = {
// Pawn
{ 0, 0, 0, 0, 0, 0, 0, 0,
50, 50, 50, 50, 50, 50, 50, 50,
10, 10, 20, 30, 30, 20, 10, 10,
5, 5, 10, 25, 25, 10, 5, 5,
0, 0, 0, 20, 20, 0, 0, 0,
5, -5,-10, 0, 0,-10, -5, 5,
5, 10, 10,-20,-20, 10, 10, 5,
0, 0, 0, 0, 0, 0, 0, 0 },
// Knight
{ -50,-40,-30,-30,-30,-30,-40,-50,
-40,-20, 0, 0, 0, 0,-20,-40,
-30, 0, 10, 15, 15, 10, 0,-30,
-30, 5, 15, 20, 20, 15, 5,-30,
-30, 0, 15, 20, 20, 15, 0,-30,
-30, 5, 10, 15, 15, 10, 5,-30,
-40,-20, 0, 5, 5, 0,-20,-40,
-50,-40,-30,-30,-30,-30,-40,-50 },
// Bishop
{ -20,-10,-10,-10,-10,-10,-10,-20,
-10, 0, 0, 0, 0, 0, 0,-10,
-10, 0, 10, 10, 10, 10, 0,-10,
-10, 5, 5, 10, 10, 5, 5,-10,
-10, 0, 10, 10, 10, 10, 0,-10,
-10, 10, 10, 10, 10, 10, 10,-10,
-10, 5, 0, 0, 0, 0, 5,-10,
-20,-10,-10,-10,-10,-10,-10,-20 },
// Rook
{ 0, 0, 0, 0, 0, 0, 0, 0,
5, 10, 10, 10, 10, 10, 10, 5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
0, 0, 0, 5, 5, 0, 0, 0 },
// Queen
{ -20,-10,-10, -5, -5,-10,-10,-20,
-10, 0, 0, 0, 0, 0, 0,-10,
-10, 0, 5, 5, 5, 5, 0,-10,
-5, 0, 5, 5, 5, 5, 0, -5,
0, 0, 5, 5, 5, 5, 0, -5,
-10, 5, 5, 5, 5, 5, 0,-10,
-10, 0, 5, 0, 0, 0, 0,-10,
-20,-10,-10, -5, -5,-10,-10,-20 },
// King
{ -30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-20,-30,-30,-40,-40,-30,-30,-20,
-10,-20,-20,-20,-20,-20,-20,-10,
20, 20, 0, 0, 0, 0, 20, 20,
20, 30, 10, 0, 0, 10, 30, 20 }
};
int evaluate(const BitboardBoard& board) {
int score = 0;
for (int pt = 0; pt < 6; pt++) {
uint64_t bb = board.pieces[pt];
while (bb) {
int sq = __builtin_ctzll(bb);
score += PIECE_VALUES[pt] + PST_MG[pt][sq ^ 56]; // flip for white
bb &= bb - 1;
}
bb = board.pieces[pt + 6];
while (bb) {
int sq = __builtin_ctzll(bb);
score -= PIECE_VALUES[pt + 6] + PST_MG[pt][sq]; // black uses same table
bb &= bb - 1;
}
}
// Mobility bonus
uint64_t mobility = countMobility(board);
score += popcount(mobility & board.occupancy[WHITE]) * 5;
score -= popcount(mobility & board.occupancy[BLACK]) * 5;
// King safety
score += evaluateKingSafety(board, WHITE);
score -= evaluateKingSafety(board, BLACK);
return board.sideToMove == WHITE ? score : -score;
}