markdown
int history[2][64][64];
Move killerMoves[MAX_PLY][2];
int counterMoves[64][64];
void clearHistory() {
memset(history, 0, sizeof(history));
memset(killerMoves, 0, sizeof(killerMoves));
memset(counterMoves, 0, sizeof(counterMoves));
}
void updateHistory(Color color, int from, int to, int depth) {
int& entry = history[color][from][to];
entry += depth * depth;
if (entry > 4000000) {
for (int i = 0; i < 64; i++)
for (int j = 0; j < 64; j++)
history[color][i][j] /= 2;
}
}
void updateKillers(Move move, int ply) {
if (move != killerMoves[ply][0]) {
killerMoves[ply][1] = killerMoves[ply][0];
killerMoves[ply][0] = move;
}
}
void updateCounterMove(int from, int to, Move move) {
counterMoves[from][to] = move;
}
void scoreMoves(Move* moves, int numMoves, int ply, Color side,
Move prevMove) {
for (int i = 0; i < numMoves; i++) {
Move& m = moves[i];
m.score = 0;
if (isCapture(m)) {
int victimVal = PIECE_VALUES[board.pieceAt(m.to)] * 10;
int attackerVal = PIECE_VALUES[board.pieceAt(m.from)];
m.score = 1000000 + victimVal - attackerVal + SEE(m);
}
else if (m.flags & PROMOTION) {
m.score = 900000 + PIECE_VALUES[m.promotionPiece];
}
else if (m == killerMoves[ply][0]) {
m.score = 800000;
}
else if (m == killerMoves[ply][1]) {
m.score = 700000;
}
else if (prevMove && counterMoves[prevMove.from][prevMove.to] == m) {
m.score = 600000;
}
else {
m.score = history[side][m.from][m.to];
}
}
}
void sortMoveList(Move* moves, int numMoves) {
std::sort(moves, moves + numMoves, [](const Move& a, const Move& b) {
return a.score > b.score;
});
}
int SEE(const Move& move) {
int target = PIECE_VALUES[board.pieceAt(move.to)];
int gain[32];
int depth = 0;
uint64_t occ = board.occupancy[BOTH];
uint64_t attackers = getAttackers(move.from, occ);
int side = board.pieceAtColor(move.from);
gain[0] = target;
while (true) {
depth++;
gain[depth] = PIECEValues[leastAttacker(attackers)] - gain[depth-1];
attackers ^= leastAttackerBB(attackers);
side ^= 1;
if (gain[depth] < 0) break;
}
while (--depth) {
gain[depth-1] = -std::max(-gain[depth-1], gain[depth]);
}
return gain[0];
}