11-add-attack-detection (#15)
All checks were successful
Python tests (make) / test (push) Successful in 10s

works on #11

Reviewed-on: #15
Co-authored-by: Josh <josh@joshuaschuett.com>
Co-committed-by: Josh <josh@joshuaschuett.com>
This commit is contained in:
2025-08-19 15:56:28 +00:00
committed by Josh
parent 54537e404b
commit e5a75c0737
4 changed files with 209 additions and 5 deletions

View File

@@ -530,6 +530,50 @@ int gen_pseudo_moves(const struct Board *board, struct Move *moves, bool capture
return count;
}
uint64_t attackers_to(const struct Board *board, int sq, enum Color by) {
uint64_t occ = board->occ[BOTH];
uint64_t pawns = (by == WHITE) ? board->pieces[P] : board->pieces[p];
uint64_t knights = (by == WHITE) ? board->pieces[N] : board->pieces[n];
uint64_t bishops = (by == WHITE) ? board->pieces[B] : board->pieces[b];
uint64_t rooks = (by == WHITE) ? board->pieces[R] : board->pieces[r];
uint64_t queens = (by == WHITE) ? board->pieces[Q] : board->pieces[q];
uint64_t kings = (by == WHITE) ? board->pieces[K] : board->pieces[k];
uint64_t attacks = 0;
attacks |= PAWN_ATTACKS[by ^ 1][sq] & pawns;
attacks |= KNIGHT_ATTACKS[sq] & knights;
attacks |= KING_ATTACKS[sq] & kings;
// Squares than can see sq given the occupancy of both sides but intersect
// with the specified color pieces.
attacks |= bishop_attacks(sq, occ) & (bishops | queens);
attacks |= rook_attacks(sq, occ) & (rooks | queens);
return attacks;
}
bool in_check(const struct Board *board, enum Color side) {
uint64_t king_bb = (side == WHITE) ? board->pieces[K] : board->pieces[k];
// Do we need this check here?
// This would be an illegal position.
if (!king_bb) return false;
int king_sq = pop_lsb_index(&king_bb);
// Is the king square in the attack map of opposite side?
return attackers_to(board, king_sq, side ^ 1) != 0;
}
bool square_attacked(const struct Board *board, int sq, enum Color by) {
// Should we have another way to calculate this and have
// earlier exits in the code? For example, we could iterate
// each piece type and return boolean sooner and skip the
// ray scanning.
return attackers_to(board, sq, by) != 0;
}
void print_board(const struct Board *board) {
const char PIECE_CH[12] = {