-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPosition.cpp
executable file
·1304 lines (1078 loc) · 51.5 KB
/
Position.cpp
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Position.h"
unsigned long long Position::pieceHash[2][6][8][8];
unsigned long long Position::turnHash[2];
Position::Position() {
}
Position::Position(string FEN) {
stringstream ss(FEN);
string str;
// initializations
king[0] = king[1] = NULL;
//"6rk/6b1/8/4B3/5Q1K/8/8/8 w - - 0 1"
// the pieces
ss >> str;
size_t j = 0;
for(int i = 7; i >= 0; i--) {
int k = 0;
while(j < str.size() && str[j] != '/') {
if(isdigit(str[j]))
for(int cnt = 0; cnt < str[j] - '0'; cnt++)
board[i][k++] = NULL;
if(isalpha(str[j])) {
if(islower(str[j])) {
board[i][k] = new Piece(Piece::getType(str[j]), BLACK, i, k);
pieces[BLACK].push_back(board[i][k]);
}
else {
board[i][k] = new Piece(Piece::getType(str[j]), WHITE, i, k);
pieces[WHITE].push_back(board[i][k]);
}
if(board[i][k]->type == KING)
king[board[i][k]->color] = board[i][k];
k++;
}
j++;
}
if(k != 8 || (j == str.size() && i != 0)) {
printf("FEN notation is not correct!\n");
throw new exception();
}
j++; // jump over '/' character
}
// checks
if(king[0] == NULL || king[1] == NULL) {
printf("No king?!\n");
throw new exception();
}
// who's turn
ss >> str;
turn = str[0] == 'w' ? WHITE : BLACK;
// castling rights
ss >> str;
// we artificially mark the rooks as to have moved
if(str.find('K') == string::npos && this->board[0][7] != NULL) this->board[0][7]->timesMoved = 1;
if(str.find('Q') == string::npos && this->board[0][0] != NULL) this->board[0][0]->timesMoved = 1;
if(str.find('k') == string::npos && this->board[7][7] != NULL) this->board[7][7]->timesMoved = 1;
if(str.find('q') == string::npos && this->board[7][0] != NULL) this->board[7][0]->timesMoved = 1;
if((king[WHITE]->squareRow != 0 || king[WHITE]->squareCol != 4)
&& (str.find('K') != string::npos || str.find('Q') != string::npos)) {
printf("Something is wrong with castling rights in FEN! (white)\n");
throw new exception;
}
if((king[BLACK]->squareRow != 7 || king[BLACK]->squareCol != 4)
&& (str.find('k') != string::npos || str.find('q') != string::npos)) {
printf("Something is wrong with castling rights in FEN! (black)\n");
throw new exception;
}
// is en-passant available?
ss >> str;
epRow = epCol = -1;
if(str != "-") {
epRow = str[1] - '1';
epCol = str[0] - 'a';
}
// half-move clock
ss >> str;
halfMoveClock = atoi(str.c_str());
// move number
ss >> str;
moveNumber = atoi(str.c_str());
lastCapturedPiece = NULL;
piecesGivingCheck(givingCheck);
generateRandomTable();
computeHashValue();
}
Position::Position(const Position &p) {
// printf("Copy constructor!\n");
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
if(p.board[i][j] == NULL)
this->board[i][j] = NULL;
else {
Piece *cpy = new Piece(*(p.board[i][j]));
this->board[i][j] = cpy;
this->pieces[cpy->color].push_back(cpy);
}
this->turn = p.turn;
this->epRow = p.epRow;
this->epCol = p.epCol;
this->halfMoveClock = p.halfMoveClock;
this->moveNumber = p.moveNumber;
for(list<Piece*> :: const_iterator it = p.givingCheck.begin(); it != p.givingCheck.end(); it++)
this->givingCheck.push_back(this->board[(*it)->squareRow][(*it)->squareCol]);
this->king[0] = this->board[p.king[0]->squareRow][p.king[0]->squareCol];
this->king[1] = this->board[p.king[1]->squareRow][p.king[1]->squareCol];
// no need to copy prevGivingCheck, lastCapturedPiece etc. (will never use)
this->prevGivingCheck.clear();
this->lastCapturedPiece = NULL;
this->hashValue = p.hashValue;
this->halfMoveClock = p.halfMoveClock;
this->moveNumber = p.moveNumber;
}
Position::~Position() {
for(int i = 0; i < 2; i++)
for(list<Piece*> :: iterator it = pieces[i].begin(); it != pieces[i].end(); it++)
delete *it;
}
bool Position::equals(const Position &p) {
if(this->turn != p.turn)
return false;
if(this->epRow != p.epRow || this->epCol != p.epCol) {
// printf("EP squares not equal");
// throw new exception();
return false;
}
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++) {
if((this->board[i][j] == NULL) != (p.board[i][j] == NULL))
return false;
if(this->board[i][j] == NULL)
continue;
if(this->board[i][j]->color != p.board[i][j]->color
|| this->board[i][j]->type != p.board[i][j]->type)
return false;
}
string castle1 = "";
if(this->board[0][7] != NULL && this->board[0][7]->timesMoved == 0) castle1 += "K";
if(this->board[0][0] != NULL && this->board[0][0]->timesMoved == 0) castle1 += "Q";
if(this->board[7][7] != NULL && this->board[7][7]->timesMoved == 0) castle1 += "k";
if(this->board[7][0] != NULL && this->board[7][0]->timesMoved == 0) castle1 += "q";
string castle2 = "";
if(p.board[0][7] != NULL && p.board[0][7]->timesMoved == 0) castle1 += "K";
if(p.board[0][0] != NULL && p.board[0][0]->timesMoved == 0) castle1 += "Q";
if(p.board[7][7] != NULL && p.board[7][7]->timesMoved == 0) castle1 += "k";
if(p.board[7][0] != NULL && p.board[7][0]->timesMoved == 0) castle1 += "q";
if(castle1 != castle2) {
// printf("Castling rights not equal");
// throw new exception();
return false;
}
return true;
}
void Position::generateRandomTable() {
tr1::minstd_rand randomEngine;
tr1::uniform_int<unsigned long long> dist(0, (unsigned long long)(-1));
//randomEngine.seed(time(NULL));
randomEngine.seed(13);
for(int c = 0; c < 2; c++)
for(int i = 0; i < 6; i++)
for(int j = 0; j < 8; j++)
for(int k = 0; k < 8; k++) {
pieceHash[c][i][j][k] = dist(randomEngine);
// printf("%d\n", hash[i][j][k]);
}
for(int c = 0; c < 2; c++)
turnHash[c] = dist(randomEngine);
}
unsigned long long Position::getPieceHashValue(Piece* piece) {
return pieceHash[piece->color][piece->type][piece->squareRow][piece->squareCol];
}
void Position::computeHashValue() {
this->hashValue = 0;
for(int side = 0; side < 2; side++)
for(list<Piece*> :: iterator it = this->pieces[side].begin(); it != this->pieces[side].end(); it++)
hashValue ^= getPieceHashValue(*it);
hashValue ^= turnHash[turn];
}
string Position::toFEN() {
int num;
string ret = "";
char aux[5];
for(int i = 7; i >= 0; i--) {
for(int j = 0; j <= 7; j++) {
num = 0;
while(j <= 7 && board[i][j] == NULL) {
num++;
j++;
}
if(num > 0) {
sprintf(aux, "%d", num);
ret += string(aux);
j--;
}
else ret += board[i][j]->getNotation();
}
if(i > 0)
ret += "/";
}
ret += string(" ") + (turn == WHITE ? "w" : "b");
ret += " ";
string castle = "";
if(this->board[0][7] != NULL && this->board[0][7]->timesMoved == 0) castle += "K";
if(this->board[0][0] != NULL && this->board[0][0]->timesMoved == 0) castle += "Q";
if(this->board[7][7] != NULL && this->board[7][7]->timesMoved == 0) castle += "k";
if(this->board[7][0] != NULL && this->board[7][0]->timesMoved == 0) castle += "q";
if(castle.size() == 0)
castle = "-";
ret += castle;
ret += " ";
if(epRow == -1)
ret += "-";
else {
ret += (char)('a' + epCol);
ret += (char)('1' + epRow);
}
sprintf(aux, " %d", halfMoveClock);
ret += string(aux);
sprintf(aux, " %d", moveNumber);
ret += string(aux);
return ret;
}
void Position::performMove(Move *m) {
// saving stuff so we can revert
lastMove = m;
prevHashValue = hashValue;
prevEpRow = epRow;
prevEpCol = epCol;
prevHalfMoveClock = halfMoveClock;
prevMoveNumber = moveNumber;
// assume EP will be off
epRow = epCol = -1;
halfMoveClock++;
// if a pawn moved or it was a capture then the clock must be set to 0
if(this->board[m->fromRow][m->fromCol]->type == PAWN || this->board[m->toRow][m->toCol] != NULL)
halfMoveClock = 0;
if(turn == BLACK)
moveNumber++;
if(!m->isSpecial) { // "normal" moves
// deleting the current piece from the hash value
hashValue ^= getPieceHashValue(this->board[m->fromRow][m->fromCol]);
// is it a double pawn advance? => en-passant will become available
if(this->board[m->fromRow][m->fromCol]->type == PAWN && abs(m->fromRow - m->toRow) == 2) {
// between fromRow and toRow
epRow = (m->fromRow + m->toRow) / 2;
epCol = m->fromCol;
}
lastCapturedPiece = this->board[m->toRow][m->toCol];
// making the move
if(lastCapturedPiece != NULL) {
pieces[1 - turn].erase(find(pieces[1 - turn].begin(), pieces[1 - turn].end(), lastCapturedPiece));
// delete from hash
hashValue ^= getPieceHashValue(lastCapturedPiece);
}
this->board[m->toRow][m->toCol] = this->board[m->fromRow][m->fromCol];
this->board[m->fromRow][m->fromCol] = NULL;
this->board[m->toRow][m->toCol]->squareRow = m->toRow;
this->board[m->toRow][m->toCol]->squareCol = m->toCol;
this->board[m->toRow][m->toCol]->timesMoved++;
// add to hash
hashValue ^= getPieceHashValue(this->board[m->toRow][m->toCol]);
}
else { // special moves
if(m->special == KINGSIDE_CASTLE || m->special == QUEENSIDE_CASTLE) {
lastCapturedPiece = NULL;
// deleting the king from the hash value
hashValue ^= getPieceHashValue(this->board[m->fromRow][m->fromCol]);
// move the king
this->board[m->toRow][m->toCol] = this->board[m->fromRow][m->fromCol];
this->board[m->fromRow][m->fromCol] = NULL;
this->board[m->toRow][m->toCol]->squareRow = m->toRow;
this->board[m->toRow][m->toCol]->squareCol = m->toCol;
this->board[m->toRow][m->toCol]->timesMoved++;
// add the king to the hash value
hashValue ^= getPieceHashValue(this->board[m->toRow][m->toCol]);
// move the rook
int rookFromCol = (m->special == KINGSIDE_CASTLE ? 7 : 0);
int rookToCol = (m->special == KINGSIDE_CASTLE ? m->fromCol + 1 : m->fromCol - 1);
// deleting the rook from the hash value
hashValue ^= getPieceHashValue(this->board[m->fromRow][rookFromCol]);
this->board[m->toRow][rookToCol] = this->board[m->fromRow][rookFromCol];
this->board[m->fromRow][rookFromCol] = NULL;
this->board[m->toRow][rookToCol]->squareRow = m->toRow;
this->board[m->toRow][rookToCol]->squareCol = rookToCol;
this->board[m->toRow][rookToCol]->timesMoved++;
// add the rook to the hash value
hashValue ^= getPieceHashValue(this->board[m->toRow][rookToCol]);
}
else if(m->special == EN_PASSANT) {
if(prevEpRow != 2 && prevEpRow != 5) {
printf("Something wrong with prevEP: row %d, col %d\n", prevEpRow, prevEpCol);
throw new exception();
}
int advDir = this->board[m->fromRow][m->fromCol]->color == WHITE ? 1 : -1;
// capturing the other pawn
lastCapturedPiece = this->board[m->toRow - advDir][m->toCol];
this->board[m->toRow - advDir][m->toCol] = NULL;
pieces[1 - turn].erase(find(pieces[1 - turn].begin(), pieces[1 - turn].end(), lastCapturedPiece));
// deleting the moving pawn from the hash value
hashValue ^= getPieceHashValue(this->board[m->fromRow][m->fromCol]);
// deleting the captured pawn from the hash value
hashValue ^= getPieceHashValue(lastCapturedPiece);
// moving the pawn
this->board[m->toRow][m->toCol] = this->board[m->fromRow][m->fromCol];
this->board[m->fromRow][m->fromCol] = NULL;
this->board[m->toRow][m->toCol]->squareRow = m->toRow;
this->board[m->toRow][m->toCol]->squareCol = m->toCol;
this->board[m->toRow][m->toCol]->timesMoved++;
// add the moving pawn to the hash value
hashValue ^= getPieceHashValue(this->board[m->toRow][m->toCol]);
}
else if(m->special == PROMOTION) {
lastCapturedPiece = this->board[m->toRow][m->toCol];
lastPromotedPawn = this->board[m->fromRow][m->fromCol];
// delete promoting pawn from hash
hashValue ^= getPieceHashValue(lastPromotedPawn);
// making the move
if(lastCapturedPiece != NULL) {
pieces[1 - turn].erase(find(pieces[1 - turn].begin(), pieces[1 - turn].end(), lastCapturedPiece));
// delete captured piece from hash
hashValue ^= getPieceHashValue(lastCapturedPiece);
}
// erase the pawn
pieces[turn].erase(find(pieces[turn].begin(), pieces[turn].end(), lastPromotedPawn));
// promoting to the selected piece
this->board[m->toRow][m->toCol] = new Piece(m->promotionTo, turn, m->toRow, m->toCol);
this->board[m->fromRow][m->fromCol] = NULL;
pieces[turn].push_back(this->board[m->toRow][m->toCol]);
// adding the new piece to the hash value
hashValue ^= getPieceHashValue(this->board[m->toRow][m->toCol]);
}
}
hashValue ^= turnHash[turn];
hashValue ^= turnHash[1 - turn];
// it's the opponent's turn
turn = (color_t)(1 - turn);
prevGivingCheck.clear();
prevGivingCheck = givingCheck;
givingCheck.clear();
piecesGivingCheck(givingCheck);
}
void Position::revertLastMove() {
if(lastMove == NULL) {
printf("Last move doesn't exist!\n");
throw new exception();
}
if(lastMove->fromRow == -1) {
printf("Invalid last move!\n");
throw new exception();
}
if(!lastMove->isSpecial) { // "normal" moves
this->board[lastMove->fromRow][lastMove->fromCol] = this->board[lastMove->toRow][lastMove->toCol];
this->board[lastMove->toRow][lastMove->toCol] = lastCapturedPiece;
if(lastCapturedPiece != NULL)
pieces[turn].push_back(lastCapturedPiece);
this->board[lastMove->fromRow][lastMove->fromCol]->squareRow = lastMove->fromRow;
this->board[lastMove->fromRow][lastMove->fromCol]->squareCol = lastMove->fromCol;
this->board[lastMove->fromRow][lastMove->fromCol]->timesMoved--;
}
else { // special moves
if(lastMove->special == KINGSIDE_CASTLE || lastMove->special == QUEENSIDE_CASTLE) {
// unmove the king
this->board[lastMove->fromRow][lastMove->fromCol] = this->board[lastMove->toRow][lastMove->toCol];
this->board[lastMove->toRow][lastMove->toCol] = NULL;
this->board[lastMove->fromRow][lastMove->fromCol]->squareRow = lastMove->fromRow;
this->board[lastMove->fromRow][lastMove->fromCol]->squareCol = lastMove->fromCol;
this->board[lastMove->fromRow][lastMove->fromCol]->timesMoved--;
// unmove the rook
int rookFromCol = (lastMove->special == KINGSIDE_CASTLE ? 7 : 0);
int rookToCol = (lastMove->special == KINGSIDE_CASTLE ? lastMove->fromCol + 1 : lastMove->fromCol - 1);
this->board[lastMove->fromRow][rookFromCol] = this->board[lastMove->toRow][rookToCol];
this->board[lastMove->toRow][rookToCol] = NULL;
this->board[lastMove->fromRow][rookFromCol]->squareRow = lastMove->fromRow;
this->board[lastMove->fromRow][rookFromCol]->squareCol = rookFromCol;
this->board[lastMove->fromRow][rookFromCol]->timesMoved--;
}
else if(lastMove->special == EN_PASSANT) {
int advDir = this->board[lastMove->toRow][lastMove->toCol]->color == WHITE ? 1 : -1;
// uncapturing the other pawn
this->board[lastMove->toRow - advDir][lastMove->toCol] = lastCapturedPiece;
pieces[turn].push_back(lastCapturedPiece);
// unmoving the pawn
this->board[lastMove->fromRow][lastMove->fromCol] = this->board[lastMove->toRow][lastMove->toCol];
this->board[lastMove->toRow][lastMove->toCol] = NULL;
this->board[lastMove->fromRow][lastMove->fromCol]->squareRow = lastMove->fromRow;
this->board[lastMove->fromRow][lastMove->fromCol]->squareCol = lastMove->fromCol;
this->board[lastMove->fromRow][lastMove->fromCol]->timesMoved--;
}
else if(lastMove->special == PROMOTION) {
// erasing the newly created piece
//delete this->board[lastMove->toRow][lastMove->toCol];
pieces[1 - turn].erase(find(pieces[1 - turn].begin(), pieces[1 - turn].end(), this->board[lastMove->toRow][lastMove->toCol]));
if(lastCapturedPiece != NULL)
pieces[turn].push_back(lastCapturedPiece);
this->board[lastMove->toRow][lastMove->toCol] = lastCapturedPiece;
// reseting the pawn
this->board[lastMove->fromRow][lastMove->fromCol] = lastPromotedPawn;
pieces[1 - turn].push_back(lastPromotedPawn);
}
}
// it was your turn
turn = (color_t)(1 - turn);
givingCheck = prevGivingCheck;
epRow = prevEpRow;
epCol = prevEpCol;
halfMoveClock = prevHalfMoveClock;
moveNumber = prevMoveNumber;
hashValue = prevHashValue;
}
bool Position::isDrawByRules() {
for(int side = 0; side < 2; side++)
if(this->pieces[side].size() == 1) { // this side has just the king
if(this->pieces[1 - side].size() == 1) // lone king
return true;
if(this->pieces[1 - side].size() == 2) { // king + minor piece
for(list<Piece*> :: iterator it = this->pieces[1 - side].begin(); it != this->pieces[1 - side].end(); it++)
if((*it)->getValue() == 3)
return true;
}
}
// 50-move rule
if(halfMoveClock >= 50)
return true;
return false;
}
int Position::getNumberOfPieces() {
return (int)(pieces[WHITE].size() + pieces[BLACK].size());
}
void Position::debug_printBoard() {
printf("BOARD (turn = %d):\n", this->turn);
for(int i = 7; i >= 0; i--) {
for(int j = 0; j < 8; j++)
if(this->board[i][j] == NULL)
printf("_ ");
else
printf("%c ", this->board[i][j]->getNotation());
printf("\n");
}
}
double Position::getEstimatedScore(difficulty_t difficulty) {
double score = 0.0;
// material balance / count
int whiteMaterial = 0;
int blackMaterial = 0;
for(int side = 0; side < 2; side++)
for(list<Piece*> :: iterator it = pieces[side].begin(); it != pieces[side].end(); it++) {
if((*it)->type != KING && (*it)->type != PAWN) {
if(side == WHITE)
whiteMaterial += (*it)->getValue();
else
blackMaterial -= (*it)->getValue();
}
if(side == turn)
score += (*it)->getValue();
else
score -= (*it)->getValue();
}
// endgame: when both sides have less that or equal to 10 material count left ?!?
// (not counting kings and pawns)
bool isEndgame = (whiteMaterial <= ENDGAME_BOUND && blackMaterial <= ENDGAME_BOUND);
if(!isEndgame) {
for(int side = 0; side < 2; side++)
for(list<Piece*> :: iterator it = pieces[side].begin(); it != pieces[side].end(); it++) {
// developed pieces bonus
if((*it)->type != KING && !((*it)->isOnHomeSquare())) {
if(side == turn)
score += this->getPieceDevelopmentBonus(*it);
else
score -= this->getPieceDevelopmentBonus(*it);
}
// controlling center bonus
if(controlsCenter(*it)) {
if(side == turn)
score += CONTROL_CENTER_BONUS;
else
score -= CONTROL_CENTER_BONUS;
}
}
// safe king bonus
for(int side = 0; side < 2; side++)
if(kingIsSafe((color_t)side)) {
if(side == turn)
score += SAFE_KING_BONUS;
else
score -= SAFE_KING_BONUS;
}
if(difficulty >= MEDIUM) {
// connected rooks
for(int side = 0; side < 2; side++) {
Piece *rook1 = NULL;
Piece *rook2 = NULL;
for(list<Piece*> :: iterator it = pieces[side].begin(); it != pieces[side].end(); it++)
if((*it)->type == ROOK) {
if(rook1 == NULL)
rook1 = *it;
else {
rook2 = *it;
break;
}
}
if(rook1 != NULL && rook2 != NULL
&& this->pieceDirectlyAttacksSquare(rook1, rook2->squareRow, rook2->squareCol)) {
if(side == turn)
score += CONNECTED_ROOKS_BONUS;
else
score -= CONNECTED_ROOKS_BONUS;
}
}
}
}
else { // add endgame bonuses if it's the case
// the kings' distance to center
score += KING_DISTANCE_TO_CENTER_BONUS * pieceDistanceToCenter(king[1 - turn]);
score -= KING_DISTANCE_TO_CENTER_BONUS * pieceDistanceToCenter(king[turn]);
if(difficulty >= MEDIUM) {
bool occupiedCols[8];
int pawnIslands;
for(int side = 0; side < 2; side++) {
memset(occupiedCols, 0, sizeof(occupiedCols));
for(list<Piece*> :: iterator it = pieces[side].begin(); it != pieces[side].end(); it++) {
// passed pawns
if((*it)->type == PAWN && pawnIsPassed(*it)) {
int promotionRow = ((*it)->color == WHITE ? 7 : 0);
double value = PASSED_PAWN_BONUS;
// if it's close to promoting, it's more valuable
if(abs(promotionRow - (*it)->squareRow) < 2)
value += 1.0;
if(side == turn)
score += value;
else
score -= value;
}
if((*it)->type == PAWN)
occupiedCols[(*it)->squareCol] = true;
}
// pawn islands
pawnIslands = 0;
for(int i = 0; i < 8; ) {
while(i < 8 && !occupiedCols[i])
i++;
if(i < 8) {
while(i < 8 && occupiedCols[i])
i++;
pawnIslands++;
}
}
if(side == turn)
score -= pawnIslands * 0.1;
else
score -= pawnIslands * 0.1;
}
}
}
// general advantages
if(difficulty >= MEDIUM) {
int numBishops;
for(int side = 0; side < 2; side++) {
numBishops = 0;
for(list<Piece*> :: iterator it = pieces[side].begin(); it != pieces[side].end(); it++) {
if((*it)->type == BISHOP)
numBishops++;
}
// bishop pair
if(numBishops >= 2) {
if(side == turn)
score += BISHOP_PAIR_BONUS;
else
score -= BISHOP_PAIR_BONUS;
}
}
}
return score;
}
double Position::getPieceDevelopmentBonus(Piece *piece) {
if(piece->type == KING)
return 0.0;
vector<Move*> moves;
getPieceAvailableMoves(piece, moves);
double bonus = 0.0;
if(piece->type == QUEEN)
bonus = (double)moves.size() * 0.02;
else if(piece->type == ROOK) {
// rook on 2nd/7th
bonus = (double)moves.size() * 0.05;
if(piece->squareRow == (piece->color == WHITE ? 6 : 1))
bonus += ROOK_PIG_BONUS;
}
else if(piece->type == BISHOP)
bonus = (double)moves.size() * 0.07;
else if(piece->type == KNIGHT) {
bonus = (double)moves.size() * 0.05;
// if it's more advanced, it's more valuable
bonus += (abs(piece->squareRow - (piece->color == WHITE ? 0 : 7))) * 0.05;
}
else if(piece->type == PAWN) {
// how much it advanced
bonus = (piece->squareRow - (piece->color == WHITE ? 1 : 6)) * 0.05;
}
deallocateMoveList(moves);
return bonus;
}
bool Position::kingIsSafe(color_t side) {
int safeRow = side == WHITE ? 0 : 7;
if(king[side]->squareRow != safeRow)
return false;
int forward = side == WHITE ? 1 : -1;
// he must have pieces in front of him
for(int j = king[side]->squareCol - 1; j <= king[side]->squareCol + 1; j++)
if(j >= 0 && j < 8 && this->board[king[side]->squareRow + forward][j] == NULL)
return false;
return true;
}
bool Position::controlsCenter(Piece *piece) {
for(int pi = 3; pi <= 4; pi++)
for(int pj = 3; pj <= 4; pj++)
if(pieceDirectlyAttacksSquare(piece, pi, pj))
return true;
return false;
}
bool Position::pawnIsPassed(Piece *piece) {
int advDir = piece->color == WHITE ? 1 : -1;
// check for pawns on the files to the left/right
for(int d = -1; d <= 1; d += 2)
if(piece->squareCol + d >= 0 && piece->squareCol + d <= 7) {
for(int pi = piece->squareRow + advDir; pi >= 1 && pi <= 6; pi += advDir)
if(this->board[pi][piece->squareCol + d] != NULL
&& this->board[pi][piece->squareCol + d]->type == PAWN
&& this->board[pi][piece->squareCol + d]->color == 1 - turn)
return false;
}
return true;
}
int Position::pieceDistanceToCenter(Piece *piece) {
if(piece == NULL) {
printf("NULL piece!\n");
throw new exception;
}
int rows = min(abs(piece->squareRow - 3), abs(piece->squareRow - 4));
int cols = min(abs(piece->squareCol - 3), abs(piece->squareCol - 4));
return rows + cols;
}
pair<int, int> Position::getRelativePosition(Piece *p1, Piece *p2) {
// compute relative position
int diri = p1->squareRow - p2->squareRow;
int dirj = p1->squareCol - p2->squareCol;
// normalize
if(diri < 0) diri = -1;
if(diri > 0) diri = 1;
if(dirj < 0) dirj = -1;
if(dirj > 0) dirj = 1;
return make_pair(diri, dirj);
}
pair<int, int> Position::getRelativePosition(Piece *p1, int row, int col) {
// compute relative position
int diri = p1->squareRow - row;
int dirj = p1->squareCol - col;
// normalize
if(diri < 0) diri = -1;
if(diri > 0) diri = 1;
if(dirj < 0) dirj = -1;
if(dirj > 0) dirj = 1;
return make_pair(diri, dirj);
}
bool Position::isSquareAttacked(int row, int col) {
for(list<Piece*> :: iterator it = pieces[1 - turn].begin(); it != pieces[1 - turn].end(); it++)
if(pieceDirectlyAttacksSquare(*it, row, col))
return true;
return false;
}
void Position::piecesAttackingSquare(int row, int col, list<Piece*> &attackingSquare) {
for(list<Piece*> :: iterator it = pieces[1 - turn].begin(); it != pieces[1 - turn].end(); it++)
if(pieceDirectlyAttacksSquare(*it, row, col))
attackingSquare.push_back(*it);
}
bool Position::isInCheck() {
// check if the current player's king is attacked by any of the opponent's pieces
return isSquareAttacked(king[turn]->squareRow, king[turn]->squareCol);
}
void Position::piecesGivingCheck(list<Piece*> &givingCheck) {
// check which of the opponent's pieces attacks the king
return piecesAttackingSquare(king[turn]->squareRow, king[turn]->squareCol, givingCheck);
}
pair<int, int> Position::isPinned(Piece *piece) {
// compute relative position towards the king
int diri = king[turn]->squareRow - piece->squareRow;
int dirj = king[turn]->squareCol - piece->squareCol;
if(!(diri != 0 && dirj != 0 && abs(diri) != abs(dirj))) { // may be pinned
// normalize
if(diri > 0) diri = 1;
if(diri < 0) diri = -1;
if(dirj > 0) dirj = 1;
if(dirj < 0) dirj = -1;
// check if the path between this piece and the king is clear
int pi = piece->squareRow + diri;
int pj = piece->squareCol + dirj;
while((pi != king[turn]->squareRow || pj != king[turn]->squareCol) && this->board[pi][pj] == NULL) {
pi += diri;
pj += dirj;
}
if(pi != king[turn]->squareRow || pj != king[turn]->squareCol) // we found a piece before the king
return make_pair(NOT_PIN, NOT_PIN);
// find the first piece on the opposite side
diri = -diri;
dirj = -dirj;
pi = piece->squareRow + diri;
pj = piece->squareCol + dirj;
while(pi >= 0 && pi < 8 && pj >= 0 && pj < 8 && this->board[pi][pj] == NULL) {
pi += diri;
pj += dirj;
}
if(pi >= 0 && pi < 8 && pj >= 0 && pj < 8) { // a piece was found
if(diri != 0 && dirj != 0) {
// it's a diagonal => we need bishops or queens
if((this->board[pi][pj]->type == QUEEN || this->board[pi][pj]->type == BISHOP)
&& this->board[pi][pj]->color == (color_t)(1 - turn))
return make_pair(diri, dirj);
}
else {
// it's a rank of file => we need rooks or queens
if((this->board[pi][pj]->type == QUEEN || this->board[pi][pj]->type == ROOK)
&& this->board[pi][pj]->color == (color_t)(1 - turn))
return make_pair(diri, dirj);
}
}
}
return make_pair(NOT_PIN, NOT_PIN);
}
bool Position::pieceDirectlyAttacksSquare(Piece *piece, int row, int col) {
if(piece->type == KNIGHT || piece->type == KING)
return piece->possiblyReachableSquare(row, col);
if(piece->type == PAWN) {
int advDir = piece->color == WHITE ? 1 : -1;
return piece->squareRow + advDir == row && abs(piece->squareCol - col) == 1;
}
if(piece->possiblyReachableSquare(row, col)) { // pre-check
pair<int, int> dir = getRelativePosition(piece, row, col);
int diri = -dir.first;
int dirj = -dir.second;
// it's own square doesn't count
if(diri == 0 && dirj == 0)
return false;
int pi = piece->squareRow + diri;
int pj = piece->squareCol + dirj;
// go along the path
while((pi != row || pj != col) && this->board[pi][pj] == NULL) {
pi += diri;
pj += dirj;
}
if(pi != row || pj != col) // didn't reach destination
return false;
else
return true;
}
return false;
}
void Position::getKingAvailableCastlingMoves(color_t side, vector<Move*> &moves) {
// the king must not have moved to be able castle
if(king[side]->timesMoved == 0 && king[side]->squareCol == 4) {
int row = (side == WHITE ? 0 : 7);
// king side castling
if(this->board[row][7] != NULL && this->board[row][7]->type == ROOK
&& this->board[row][7]->color == WHITE && this->board[row][7]->timesMoved == 0
&& pieceDirectlyAttacksSquare(this->board[row][7], king[side]->squareRow, king[side]->squareCol)) {
// and last, check if the king moves through check
bool throughCheck = false;
for(int col = king[side]->squareCol; col <= king[side]->squareCol + 2; col++)
if(isSquareAttacked(row, col)) {
throughCheck = true;
break;
}
if(!throughCheck)
moves.push_back(new Move(king[side]->squareRow, king[side]->squareCol,
king[side]->squareRow, king[side]->squareCol + 2, KINGSIDE_CASTLE));
}
// queen side castling
if(this->board[row][0] != NULL && this->board[row][0]->type == ROOK
&& this->board[row][0]->color == WHITE && this->board[row][0]->timesMoved == 0
&& pieceDirectlyAttacksSquare(this->board[row][0], king[side]->squareRow, king[side]->squareCol)) {
// and last, check if the king moves through check
bool throughCheck = false;
for(int col = king[side]->squareCol - 2; col <= king[side]->squareCol; col++)
if(isSquareAttacked(row, col)) {
throughCheck = true;
break;
}
if(!throughCheck)
moves.push_back(new Move(king[side]->squareRow, king[side]->squareCol,
king[side]->squareRow, king[side]->squareCol - 2, QUEENSIDE_CASTLE));
}
}
}
void Position::getPieceAvailableMoves(Piece *piece, vector<Move*> &moves, bool justQCaptures) {
if(piece->type == KING) {
// the king must not move into check
int ni, nj;
for(int d = 0; d < 8; d++) {
ni = piece->squareRow + Piece::di[QUEEN][d];
nj = piece->squareCol + Piece::dj[QUEEN][d];
if(ni >= 0 && ni < 8 && nj >= 0 && nj < 8
&& (this->board[ni][nj] == NULL || this->board[ni][nj]->color == (color_t)(1 - turn))) {
// temporarily delete the king
this->board[piece->squareRow][piece->squareCol] = NULL;
if(!isSquareAttacked(ni, nj)
&& (this->board[ni][nj] == NULL || this->board[ni][nj]->color == (color_t)(1 - turn))) {
if(!(justQCaptures && (this->board[ni][nj] == NULL || this->board[ni][nj]->type == PAWN)))
moves.push_back(new Move(piece->squareRow, piece->squareCol, ni, nj));
}
// reset the king
this->board[piece->squareRow][piece->squareCol] = piece;