-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.cpp
More file actions
564 lines (487 loc) · 18.1 KB
/
Copy pathBoard.cpp
File metadata and controls
564 lines (487 loc) · 18.1 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//
// Created by Benedikt Hornig on 05.09.22.
//
#include <bitset>
#include <iostream>
#include <array>
#include "Board.h"
bool initializedGlobalVars = false;
std::vector<Bitboard> BB_FORWARD_SLIDES_MASKS, BB_BACKWARD_SLIDES_MASKS;
std::vector<std::map<Bitboard, Bitboard>> BB_FORWARD_SLIDES_MOVES, BB_BACKWARD_SLIDES_MOVES;
Board::Board(){
initializeGlobalVars();
singles = BB_A1 | BB_A7 | BB_D2 | BB_D8 | BB_E1 | BB_E7 | BB_H2 | BB_H8;
doubles = BB_B2 | BB_B8 | BB_C1 | BB_C7 | BB_F2 | BB_F8 | BB_G1 | BB_G7;
occupied[WHITE] = BB_A1 | BB_B8 | BB_C7 | BB_D2 | BB_E1 | BB_F8 | BB_G7 | BB_H2;
occupied[BLACK] = BB_A7 | BB_B2 | BB_C1 | BB_D8 | BB_E7 | BB_F2 | BB_G1 | BB_H8;
turn = WHITE;
}
Board::Board(BoardState state) {
initializeGlobalVars();
singles = state.singles;
doubles = state.doubles;
occupied[WHITE] = state.occupied[WHITE];
occupied[BLACK] = state.occupied[BLACK];
turn = state.turn;
}
void Board::visualizeAllBitboards() {
// only for debugging
printf("white\n");
visualizeBitboard(occupied[WHITE]);
printf("black\n");
visualizeBitboard(occupied[BLACK]);
printf("singles\n");
visualizeBitboard(singles);
printf("doubles\n");
visualizeBitboard(doubles);
}
void Board::visualizeBitboard(const Bitboard bb){
// helper function to visualize the bitboards
std::bitset<64> bs(bb);
std::string boardString;
std::string fileString;
int i = 0;
for (const auto &bit: bs.to_string()){
fileString = " " + fileString;
fileString = bit + fileString;
i++;
if (i%8 == 0) {
boardString.append(fileString + "\n");
fileString = "";
}
}
std::cout << boardString + "\n";
}
void Board::visualizeBoard(const Color perspective) const{
// print the board to the console from the perspective given
printf("\n----------------------");
Square square;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (j % 8 == 0){
printf("\n");
}
if (perspective){
square = (56 - 8 * i) + j;
} else {
square = i * 8 + 7 - j;
}
Bitboard bb_square = BB_SQUARES[square];
if (bb_square & singles)
(bb_square & occupied[WHITE]) ? printf("S ") : printf("s ");
else if (bb_square & doubles)
(bb_square & occupied[WHITE]) ? printf("D ") : printf("d ");
else
printf(". ");
}
}
printf("\n----------------------\n");
}
Bitboard Board::slidingMoves(const Square square, const Bitboard occupiedBoard, const std::array<int, 2>& deltas) {
// return a move mask representing possible sliding moves from a square given occupancies on a board and the move directions
/* Example
* Given occupiedBoard
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
* result
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
*/
Bitboard res = BB_EMPTY;
for (const auto &delta: deltas) {
Square sq = square;
while (true) {
sq += delta;
if (!(0 <= sq && sq < 64) || squareDistance(sq, sq - delta) > 2 || occupiedBoard & BB_SQUARES[sq]) break;
res |= BB_SQUARES[sq];
}
}
return res;
}
std::tuple<std::vector<Bitboard>, std::vector<std::map<Bitboard, Bitboard>>> Board::createMoveTable(const std::array<int, 2>& deltas){
// create a move table for each square and each possible configuration of blocking pieces
std::vector<Bitboard> maskTable;
std::vector<std::map<Bitboard, Bitboard>> moveTable;
for (const auto &square: SQUARES){
if (squareRank(square) % 2 != squareFile(square) % 2) {
// skip white tiles
maskTable.emplace_back();
moveTable.emplace_back();
continue;
}
std::map<Bitboard, Bitboard> moves;
Bitboard mask = slidingMoves(square, BB_EMPTY, deltas);
for (const auto &subset: getSubsets(mask)) {
// subset represents a possible configuration of blocking pieces
moves[subset] = slidingMoves(square, subset, deltas);
}
maskTable.push_back(mask);
moveTable.push_back(moves);
}
return {maskTable, moveTable};
}
void Board::initializeGlobalVars(){
if (initializedGlobalVars) return;
// initialize slide masks and moves
std::tuple<std::vector<Bitboard>, std::vector<std::map<Bitboard, Bitboard>>> maskMoveTable;
const std::array<int, 2> forwardMoves = {7, 9};
maskMoveTable = createMoveTable(forwardMoves);
BB_FORWARD_SLIDES_MASKS = get<0>(maskMoveTable);
BB_FORWARD_SLIDES_MOVES = get<1>(maskMoveTable);
const std::array<int, 2> backwardMoves = {-9, -7};
maskMoveTable = createMoveTable(backwardMoves);
BB_BACKWARD_SLIDES_MASKS = get<0>(maskMoveTable);
BB_BACKWARD_SLIDES_MOVES = get<1>(maskMoveTable);
initializedGlobalVars = true;
}
Bitboard Board::getPieceToCrown() const {
// returns a piece (as bitboard) if there is a piece waiting to be crowned
Bitboard pieceToCrown = singles & occupied[turn];
pieceToCrown &= turn ? BB_RANK_8 : BB_RANK_1;
return pieceToCrown;
}
// Move Generator
std::vector<Move> Board::getLegalMoves() {
if (isOver())
return {};
// return if already generated
if (!legalMoves.empty())
return legalMoves;
// Basic moves //
for (const auto &fromSquare: scanReversed(singles & occupied[turn])){
// single slide
Bitboard forwardMoves;
if (turn){
Bitboard blockMask = BB_FORWARD_SLIDES_MASKS[fromSquare] & (occupied[WHITE] | occupied[BLACK]);
forwardMoves = BB_FORWARD_SLIDES_MOVES[fromSquare][blockMask];
} else {
Bitboard blockMask = BB_BACKWARD_SLIDES_MASKS[fromSquare] & (occupied[WHITE] | occupied[BLACK]);
forwardMoves = BB_BACKWARD_SLIDES_MOVES[fromSquare][blockMask];
}
for (const auto &toSquare: scanReversed(forwardMoves)) {
Bitboard otherSingles = singles & occupied[turn] ^ BB_SQUARES[fromSquare];
if ((turn == WHITE ? (BB_SQUARES[toSquare] & BB_RANK_8) : (BB_SQUARES[toSquare] & BB_RANK_1)) && otherSingles) {
// crown moves, if there is another single available
for (const auto &crownPiece: scanReversed(otherSingles)) {
legalMoves.emplace_back(fromSquare, toSquare, false, crownPiece, toSquare);
}
} else {
// normal slide moves
legalMoves.emplace_back(fromSquare, toSquare, false);
}
}
}
// double slide
for (const auto &fromSquare: scanReversed(doubles & occupied[turn])) {
Bitboard backwardMoves;
if (turn)
backwardMoves = BB_BACKWARD_SLIDES_MOVES[fromSquare][BB_BACKWARD_SLIDES_MASKS[fromSquare] & (occupied[WHITE] | occupied[BLACK])];
else
backwardMoves = BB_FORWARD_SLIDES_MOVES[fromSquare][BB_FORWARD_SLIDES_MASKS[fromSquare] & (occupied[WHITE] | occupied[BLACK])];
for (const auto &toSquare: scanReversed(backwardMoves)) {
if ((turn == WHITE ? (BB_SQUARES[toSquare] & BB_RANK_1) : (BB_SQUARES[toSquare] & BB_RANK_8)) && getPieceToCrown())
// crowning after bear off is possible
legalMoves.emplace_back(fromSquare, toSquare, false, toSquare, mostSignificantBit(getPieceToCrown()));
else
legalMoves.emplace_back(fromSquare, toSquare, false);
}
// transpose
//If you have a single adjacent to one of your doubles,
// and in a nearer row than the double, you can take
// the top checker of that double and transfer it onto the single.
// A transpose can only be made backward (toward the owner), not forward.
Square toSquare = turn ? fromSquare - 7 : fromSquare + 7;
if (toSquare >= 0 && toSquare < 64 && (BB_SQUARES[toSquare] & singles & occupied[turn])){
Bitboard crowningSingles = (singles & occupied[turn]) ^ BB_SQUARES[toSquare];
if ((turn == WHITE ? BB_SQUARES[fromSquare] & BB_RANK_8 : BB_SQUARES[fromSquare] & BB_RANK_1) && crowningSingles)
// crowning after transpose is possible
for (const auto &crowningPiece: scanReversed(crowningSingles)) {
legalMoves.emplace_back(fromSquare, toSquare, false, crowningPiece, fromSquare);
}
else
legalMoves.emplace_back(fromSquare, toSquare, false);
}
toSquare = turn ? fromSquare - 9 : fromSquare + 9;
if (toSquare >= 0 && toSquare < 64 && (BB_SQUARES[toSquare] & singles & occupied[turn])){
Bitboard crowningSingles = (singles & occupied[turn]) ^ BB_SQUARES[toSquare];
if ((turn == WHITE ? BB_SQUARES[fromSquare] & BB_RANK_8 : BB_SQUARES[fromSquare] & BB_RANK_1) && crowningSingles)
// crowning after transpose is possible
for (const auto &crowningPiece: scanReversed(crowningSingles)) {
legalMoves.emplace_back(fromSquare, toSquare, false, crowningPiece, fromSquare);
}
else
legalMoves.emplace_back(fromSquare, toSquare, false);
}
}
// impasse
if (legalMoves.empty()) {
for (const auto &fromSquare: scanReversed(occupied[turn])) {
if ((BB_SQUARES[fromSquare] & doubles) && getPieceToCrown()) {
// crowning is possible after removing a piece of a double
if ((turn && BB_SQUARES[fromSquare] & BB_RANK_8) || (!turn && BB_SQUARES[fromSquare] & BB_RANK_1))
// additional crowning move possible if two singles on furthest rank
legalMoves.emplace_back(fromSquare, -1, true, mostSignificantBit(getPieceToCrown()), fromSquare);
legalMoves.emplace_back(fromSquare, -1, true, fromSquare, mostSignificantBit(getPieceToCrown()));
} else
legalMoves.emplace_back(fromSquare, -1, true);
}
}
return legalMoves;
}
bool Board::isOver() const{
// game ends if there are no pieces left for either side
if (!occupied[WHITE] || !occupied[BLACK]) {
return true;
}
return false;
}
void Board::makeMove(const Move& move) {
// add state to board history
boardHistory.push_back(getBoardState());
moveHistory.push_back(move);
Bitboard fromSquare = BB_SQUARES[move.getFromSquare()];
Bitboard toSquare = BB_SQUARES[move.getToSquare()];
if (move.isRemoving()) {
// handle impasse moves
if (singles & fromSquare) {
singles ^= fromSquare;
occupied[turn] ^= fromSquare;
} else {
doubles ^= fromSquare;
singles |= fromSquare;
}
} else {
// normal moves
// check if it is a single or a double
if (singles & fromSquare) {
occupied[turn] ^= fromSquare;
singles ^= fromSquare;
// Do not allow a single to be moved on another single
/*if (singles & toSquare) { // debug
BoardState cur = getBoardState();
for (int i = 0; i < boardHistory.size(); ++i) {
setBoardState(boardHistory[i]);
visualizeBoard(WHITE);
std::cout << std::string(moveHistory[i]) << std::endl;
visualizeAllBitboards();
}
setBoardState(cur);
visualizeBoard(WHITE);
visualizeAllBitboards();
}*/
assert(!(singles & toSquare));
singles |= toSquare;
} else if (doubles & fromSquare) {
doubles ^= fromSquare;
if (singles & toSquare) {
// transpose
singles |= fromSquare;
singles ^= toSquare;
doubles |= toSquare;
} else {
occupied[turn] ^= fromSquare;
doubles |= toSquare;
}
// check for bear off moves and handle them automatically
if ((turn == WHITE && BB_RANK_1 & toSquare) || (turn == BLACK && BB_RANK_8 & toSquare)) {
doubles ^= toSquare;
singles |= toSquare;
}
} else {
/*BoardState cur = getBoardState(); // debug
for (int i = 0; i < boardHistory.size(); ++i) {
setBoardState(boardHistory[i]);
visualizeBoard(WHITE);
std::cout << std::string(moveHistory[i]) << std::endl;
visualizeAllBitboards();
}
setBoardState(cur);
visualizeBoard(WHITE);
visualizeAllBitboards();*/
assert(false);
}
occupied[turn] |= toSquare;
}
if (move.isCrowning()) {
Bitboard pieceToCrown = BB_SQUARES[move.getPieceToCrown()];
Bitboard crowningPiece = BB_SQUARES[move.getCrowningPiece()];
singles ^= pieceToCrown | crowningPiece;
doubles |= pieceToCrown;
occupied[turn] ^= crowningPiece;
}
/*if ((singles ^ doubles ^ occupied[WHITE] ^ occupied[BLACK]) != BB_EMPTY // debug
|| (singles & doubles) != BB_EMPTY || (occupied[WHITE] & occupied[BLACK]) != BB_EMPTY) {
BoardState cur = getBoardState();
for (int i = 0; i < boardHistory.size(); ++i) {
setBoardState(boardHistory[i]);
visualizeBoard(WHITE);
std::cout << std::string(moveHistory[i]) << std::endl;
visualizeAllBitboards();
}
setBoardState(cur);
visualizeBoard(WHITE);
visualizeAllBitboards();
}*/
assert((singles ^ doubles ^ occupied[WHITE] ^ occupied[BLACK]) == BB_EMPTY);
assert((singles & doubles) == BB_EMPTY);
assert((occupied[WHITE] & occupied[BLACK]) == BB_EMPTY);
turn = !turn;
legalMoves.clear();
}
void Board::undoMove() {
setBoardState(boardHistory.back());
boardHistory.pop_back();
moveHistory.pop_back();
}
std::string Board::getBoardNotation() {
// return a notation similar to the FEN notation for chess
std::string res;
int skip = 0;
for (int i = 0; i < 64; ++i) {
if (skip == 8) {
res += std::to_string(skip);
skip = 0;
}
if (i > 0 && i % 8 == 0) {
if (skip > 0) {
res += std::to_string(skip);
skip = 0;
}
res += "/";
}
if (BB_SQUARES[i] & occupied[WHITE]) {
if (skip > 0) {
res += std::to_string(skip);
skip = 0;
}
if (BB_SQUARES[i] & singles)
res += "S";
else
res += "D";
} else if (BB_SQUARES[i] & occupied[BLACK]) {
if (skip > 0) {
res += std::to_string(skip);
skip = 0;
}
if (BB_SQUARES[i] & singles)
res += "s";
else
res += "d";
} else {
skip++;
}
}
if (skip != 0)
res += std::to_string(skip);
res += " - ";
res += turn ? "w" : "b";
return res;
}
void Board::setBoardByNotation(const std::string& notation) {
// set up the board like in the given FEN-like notation
clearBoard();
Square sq = 0;
for (const auto &piece: notation) {
switch (piece) {
case 'S':
singles |= BB_SQUARES[sq];
occupied[WHITE] |= BB_SQUARES[sq];
break;
case 'D':
doubles |= BB_SQUARES[sq];
occupied[WHITE] |= BB_SQUARES[sq];
break;
case 's':
singles |= BB_SQUARES[sq];
occupied[BLACK] |= BB_SQUARES[sq];
break;
case 'd':
doubles |= BB_SQUARES[sq];
occupied[BLACK] |= BB_SQUARES[sq];
break;
case 'w':
turn = WHITE;
break;
case 'b':
turn = BLACK;
break;
case '/':
case ' ':
case '-':
sq--;
break;
default:
sq += piece - '0' - 1;
break;
}
sq++;
}
}
void Board::clearBoard() {
singles = BB_EMPTY;
doubles = BB_EMPTY;
occupied[WHITE] = BB_EMPTY;
occupied[BLACK] = BB_EMPTY;
turn = WHITE;
}
void Board::setBoardState(const BoardState boardState) {
singles = boardState.singles;
doubles = boardState.doubles;
occupied[WHITE] = boardState.occupied[WHITE];
occupied[BLACK] = boardState.occupied[BLACK];
turn = boardState.turn;
}
Color Board::getTurn() const {
return turn;
}
Color Board::getResult() {
if (isOver()) {
return occupied[WHITE] ? BLACK : WHITE;
}
return NO_COLOR;
}
BoardState Board::getBoardState() {
return {singles, doubles, occupied[WHITE], occupied[BLACK], turn};
}
Bitboard Board::getSingles(const Color color) const {
return occupied[color] & singles;
}
Bitboard Board::getDoubles(const Color color) const {
return occupied[color] & doubles;
}
void Board::setPieceAt(PieceType piece, Square square) {
Bitboard bbSquare = BB_SQUARES[square];
switch (piece) {
case WHITE_SINGLE:
singles |= bbSquare;
occupied[WHITE] |= bbSquare;
break;
case WHITE_DOUBLE:
doubles |= bbSquare;
occupied[WHITE] |= bbSquare;
break;
case BLACK_SINGLE:
singles |= bbSquare;
occupied[BLACK] |= bbSquare;
break;
case BLACK_DOUBLE:
doubles |= bbSquare;
occupied[BLACK] |= bbSquare;
break;
}
}
int Board::getPieceCount(Color color) {
return popCount(occupied[color]);
}