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
|
#include <array>
#include <cstdint>
#include "board.hpp"
#include "moves.hpp"
std::vector<Move> GetLegalMoves(board *b) {
std::vector<Move> moves;
moves.reserve(50); // almost all position dont have that many moves
constexpr std::array<int, 4> rook_Moves{-1, 1, 8, -8};
constexpr std::array<int, 4> bishop_Moves{-9, 9, -7, 7};
for (int i = 0; i < sizeof(b->pieces) / sizeof(b->pieces[0]); i++) {
Piece piece = b->pieces[i];
if (piece.type == NONE) {
continue;
}
if (piece.color != b->turn)
continue;
// Add support for other pieces
if (piece.type == BISHOP) {
GenerateSlidingMoves(b, i, bishop_Moves, moves);
}
if (piece.type == ROOK) {
GenerateSlidingMoves(b, i, rook_Moves, moves);
}
if (piece.type == QUEEN) {
GenerateSlidingMoves(b, i, rook_Moves, moves);
GenerateSlidingMoves(b, i, bishop_Moves, moves);
}
};
return moves;
}
Position IndexToPosition(int i) {
uint8_t rank = i / 8; // 0-7
uint8_t file = i % 8; // 0-7
return {rank, file};
}
void GenerateSlidingMoves(board *b, int from,
const std::array<int, 4> &directions,
std::vector<Move> &moves) {
for (int i = 0; i < directions.size(); i++) {
int direction = directions[i];
int i2 = from;
while (true) {
i2 += direction;
int oldFile = (i2 - direction) % 8;
int newFile = i2 % 8;
if (direction == 7 || direction == -7 || direction == 9 ||
direction == -9) {
if (std::abs(newFile - oldFile) != 1)
break;
}
if (i2 >= 64 || i2 < 0) {
break;
}
if (b->pieces[i2].color == b->turn && b->pieces[i2].type != NONE) {
break;
}
if ((direction == 1 || direction == -1) &&
(i2 / 8 != (i2 - direction) / 8)) {
break;
}
moves.push_back({IndexToPosition(from), IndexToPosition(i2)});
if (b->pieces[i2].color != b->turn && b->pieces[i2].type != NONE) {
break;
}
}
};
};
|