summaryrefslogtreecommitdiff
path: root/src/engine/bitboard.c
blob: 80cdb7814d9bf7e590562e9b031f6c033b94b4ad (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "bitboard.h"
#include <stdio.h>
#include <inttypes.h>
#include <assert.h>

position_t position_starting() {
  return (position_t) {
    .bitboards = {
      16ULL,
      8ULL,
      129ULL,
      36ULL,
      66ULL,
      65280ULL,
      1152921504606846976ULL,
      576460752303423488ULL,
      9295429630892703744ULL,
      2594073385365405696ULL,
      4755801206503243776ULL,
      71776119061217280ULL,
    },
    .castling =
      WHITE_SHORT_CASTLE | WHITE_LONG_CASTLE |
      BLACK_SHORT_CASTLE | BLACK_LONG_CASTLE,
    .turn = WHITE_TURN,
    .passantable_file = 0,
    .halfmove_clock = 0,
    .fullmove_clock = 1
  };
}

void assert_valid_position(position_t position) {
  assert(check_valid_position(position) == true);
}

bool check_valid_position(position_t position) {
  if (position.castling >
    (
      WHITE_SHORT_CASTLE | WHITE_LONG_CASTLE |
      BLACK_SHORT_CASTLE | BLACK_LONG_CASTLE
    )
  ) return false;
  if (position.turn != WHITE_TURN && position.turn != BLACK_TURN) return false;
  if (position.passantable_file > 8) return false; // 0 means no passant
  if (position.bitboards[WHITE_KING] == 0) return false;
  if (position.bitboards[BLACK_KING] == 0) return false;
  return true;
}

bitboard_t whites(position_t position) {
  return
    position.bitboards[WHITE_KING] |
    position.bitboards[WHITE_QUEEN] |
    position.bitboards[WHITE_ROOK] |
    position.bitboards[WHITE_BISHOP] |
    position.bitboards[WHITE_KNIGHT] |
    position.bitboards[WHITE_PAWN];
}

bitboard_t blacks(position_t position) {
  return
    position.bitboards[BLACK_KING] |
    position.bitboards[BLACK_QUEEN] |
    position.bitboards[BLACK_ROOK] |
    position.bitboards[BLACK_BISHOP] |
    position.bitboards[BLACK_KNIGHT] |
    position.bitboards[BLACK_PAWN];
}

void print_bitboard(bitboard_t bitboard) {
  printf("Bitboard(%" PRIu64 ")\n", bitboard);
  for (int i = 7; i >= 0; i--) {
    for (int j = 0; j < 8; j++) {
      printf("%" PRIu64 "", (bitboard >> (8 * i + j)) & 1);
    }
    printf("\n");
  }
}