summaryrefslogtreecommitdiff
path: root/src/engine/moves/king.c
blob: 9ce3eb8a07bcecc101a4206d99d9f04a32046228 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "../moves.h"

void get_king_moves(moves_t* moves, position_t position) {
  assert_valid_position(position);

  bitboard_t friendly_king;
  int king_square;
  bitboard_t friendly_pieces;
  if (position.turn == WHITE_TURN) {
    friendly_pieces = whites(position);
    friendly_king = position.bitboards[WHITE_KING];
  } else {
    friendly_pieces = blacks(position);
    friendly_king = position.bitboards[BLACK_KING];
  }
  king_square = __builtin_ctzll(friendly_king);

  bitboard_t movement;
  if (king_square >= 10) {
    movement = 920078ULL << (king_square - 10);
  } else {
    movement = 920078ULL >> -(king_square - 10);
  }
  if (friendly_king & BITMASK_FILE_A) {
    movement &= BITMASK_FILE_A | BITMASK_FILE_B;
  } else if (friendly_king & BITMASK_FILE_H) {
    movement &= BITMASK_FILE_G | BITMASK_FILE_H;
  }

  movement &= ~friendly_pieces;
  while (movement) {
    int to = __builtin_ctzll(movement);
    movement &= movement - 1;
    add_move(moves, king_square, to);
  }
}