-
Notifications
You must be signed in to change notification settings - Fork 54
/
position.cpp
2381 lines (2161 loc) · 105 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
/*
Apery, a USI shogi playing engine derived from Stockfish, a UCI chess playing engine.
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2015-2018 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
Copyright (C) 2011-2018 Hiraoka Takuya
Apery is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Apery is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "position.hpp"
#include "move.hpp"
#include "mt64bit.hpp"
#include "generateMoves.hpp"
#include "tt.hpp"
#include "search.hpp"
Key Position::zobrist_[PieceTypeNum][SquareNum][ColorNum];
Key Position::zobHand_[HandPieceNum][ColorNum];
Key Position::zobExclusion_;
const HuffmanCode HuffmanCodedPos::boardCodeTable[PieceNone] = {
{Binary< 0>::value, 1}, // Empty
{Binary< 1>::value, 4}, // BPawn
{Binary< 11>::value, 6}, // BLance
{Binary< 111>::value, 6}, // BKnight
{Binary< 1011>::value, 6}, // BSilver
{Binary< 11111>::value, 8}, // BBishop
{Binary< 111111>::value, 8}, // BRook
{Binary< 1111>::value, 6}, // BGold
{Binary< 0>::value, 0}, // BKing 玉の位置は別途、位置を符号化する。使用しないので numOfBit を 0 にしておく。
{Binary< 1001>::value, 4}, // BProPawn
{Binary< 100011>::value, 6}, // BProLance
{Binary< 100111>::value, 6}, // BProKnight
{Binary< 101011>::value, 6}, // BProSilver
{Binary< 10011111>::value, 8}, // BHorse
{Binary< 10111111>::value, 8}, // BDragona
{Binary< 0>::value, 0}, // 使用しないので numOfBit を 0 にしておく。
{Binary< 0>::value, 0}, // 使用しないので numOfBit を 0 にしておく。
{Binary< 101>::value, 4}, // WPawn
{Binary< 10011>::value, 6}, // WLance
{Binary< 10111>::value, 6}, // WKnight
{Binary< 11011>::value, 6}, // WSilver
{Binary< 1011111>::value, 8}, // WBishop
{Binary< 1111111>::value, 8}, // WRook
{Binary< 101111>::value, 6}, // WGold
{Binary< 0>::value, 0}, // WKing 玉の位置は別途、位置を符号化する。
{Binary< 1101>::value, 4}, // WProPawn
{Binary< 110011>::value, 6}, // WProLance
{Binary< 110111>::value, 6}, // WProKnight
{Binary< 111011>::value, 6}, // WProSilver
{Binary< 11011111>::value, 8}, // WHorse
{Binary< 11111111>::value, 8}, // WDragon
};
// 盤上の bit 数 - 1 で表現出来るようにする。持ち駒があると、盤上には Empty の 1 bit が増えるので、
// これで局面の bit 数が固定化される。
const HuffmanCode HuffmanCodedPos::handCodeTable[HandPieceNum][ColorNum] = {
{{Binary< 0>::value, 3}, {Binary< 100>::value, 3}}, // HPawn
{{Binary< 1>::value, 5}, {Binary< 10001>::value, 5}}, // HLance
{{Binary< 11>::value, 5}, {Binary< 10011>::value, 5}}, // HKnight
{{Binary< 101>::value, 5}, {Binary< 10101>::value, 5}}, // HSilver
{{Binary< 111>::value, 5}, {Binary< 10111>::value, 5}}, // HGold
{{Binary< 11111>::value, 7}, {Binary< 1011111>::value, 7}}, // HBishop
{{Binary< 111111>::value, 7}, {Binary< 1111111>::value, 7}}, // HRook
};
HuffmanCodeToPieceHash HuffmanCodedPos::boardCodeToPieceHash;
HuffmanCodeToPieceHash HuffmanCodedPos::handCodeToPieceHash;
const CharToPieceUSI g_charToPieceUSI;
namespace {
const char* PieceToCharCSATable[PieceNone] = {
" * ", "+FU", "+KY", "+KE", "+GI", "+KA", "+HI", "+KI", "+OU", "+TO", "+NY", "+NK", "+NG", "+UM", "+RY", "", "",
"-FU", "-KY", "-KE", "-GI", "-KA", "-HI", "-KI", "-OU", "-TO", "-NY", "-NK", "-NG", "-UM", "-RY"
};
inline const char* pieceToCharCSA(const Piece pc) {
return PieceToCharCSATable[pc];
}
const char* PieceToCharUSITable[PieceNone] = {
"", "P", "L", "N", "S", "B", "R", "G", "K", "+P", "+L", "+N", "+S", "+B", "+R", "", "",
"p", "l", "n", "s", "b", "r", "g", "k", "+p", "+l", "+n", "+s", "+b", "+r"
};
inline const char* pieceToCharUSI(const Piece pc) {
return PieceToCharUSITable[pc];
}
}
CheckInfo::CheckInfo(const Position& pos) {
const Color them = oppositeColor(pos.turn());
const Square ksq = pos.kingSquare(them);
pinned = pos.pinnedBB();
dcBB = pos.discoveredCheckBB();
checkBB[Pawn ] = pos.attacksFrom<Pawn >(them, ksq);
checkBB[Lance ] = pos.attacksFrom<Lance >(them, ksq);
checkBB[Knight ] = pos.attacksFrom<Knight>(them, ksq);
checkBB[Silver ] = pos.attacksFrom<Silver>(them, ksq);
checkBB[Bishop ] = pos.attacksFrom<Bishop>(ksq);
checkBB[Rook ] = pos.attacksFrom<Rook >(ksq);
checkBB[Gold ] = pos.attacksFrom<Gold >(them, ksq);
checkBB[King ] = allZeroBB();
// todo: ここで AVX2 使えそう。
// checkBB のreadアクセスは switch (pt) で場合分けして、余計なコピー減らした方が良いかも。
checkBB[ProPawn ] = checkBB[Gold];
checkBB[ProLance ] = checkBB[Gold];
checkBB[ProKnight] = checkBB[Gold];
checkBB[ProSilver] = checkBB[Gold];
checkBB[Horse ] = checkBB[Bishop] | pos.attacksFrom<King>(ksq);
checkBB[Dragon ] = checkBB[Rook ] | pos.attacksFrom<King>(ksq);
}
Bitboard Position::attacksFrom(const PieceType pt, const Color c, const Square sq, const Bitboard& occupied) {
switch (pt) {
case Occupied: return allZeroBB();
case Pawn: return pawnAttack(c, sq);
case Lance: return lanceAttack(c, sq, occupied);
case Knight: return knightAttack(c, sq);
case Silver: return silverAttack(c, sq);
case Bishop: return bishopAttack(sq, occupied);
case Rook: return rookAttack(sq, occupied);
case Gold:
case ProPawn:
case ProLance:
case ProKnight:
case ProSilver: return goldAttack(c, sq);
case King: return kingAttack(sq);
case Horse: return horseAttack(sq, occupied);
case Dragon: return dragonAttack(sq, occupied);
default: UNREACHABLE; return allOneBB();
}
}
// 実際に指し手が合法手かどうか判定
// 連続王手の千日手は排除しない。
// 確実に駒打ちではないときは、MUSTNOTDROP == true とする。
// 確実に玉の移動で無いときは、FROMMUSTNOTKING == true とする。英語として正しい?
// 遠隔駒で王手されているとき、その駒の利きがある場所に逃げる手を検出出来ない場合があるので、
// そのような手を指し手生成してはいけない。
template <bool MUSTNOTDROP, bool FROMMUSTNOTKING>
bool Position::pseudoLegalMoveIsLegal(const Move move, const Bitboard& pinned) const {
// 駒打ちは、打ち歩詰めや二歩は指し手生成時や、killerをMovePicker::nextMove() 内で排除しているので、常に合法手
// (連続王手の千日手は省いていないけれど。)
if (!MUSTNOTDROP && move.isDrop())
return true;
assert(!move.isDrop());
const Color us = turn();
const Square from = move.from();
if (!FROMMUSTNOTKING && pieceToPieceType(piece(from)) == King) {
const Color them = oppositeColor(us);
// 玉の移動先に相手の駒の利きがあれば、合法手でないので、false
return !attackersToIsAny(them, move.to());
}
// 玉以外の駒の移動
return !isPinnedIllegal(from, move.to(), kingSquare(us), pinned);
}
template bool Position::pseudoLegalMoveIsLegal<false, false>(const Move move, const Bitboard& pinned) const;
template bool Position::pseudoLegalMoveIsLegal<false, true >(const Move move, const Bitboard& pinned) const;
template bool Position::pseudoLegalMoveIsLegal<true, false>(const Move move, const Bitboard& pinned) const;
bool Position::pseudoLegalMoveIsEvasion(const Move move, const Bitboard& pinned) const {
assert(isOK());
// 玉の移動
if (move.pieceTypeFrom() == King) {
// 遠隔駒で王手されたとき、王手している遠隔駒の利きには移動しないように指し手を生成している。
// その為、移動先に他の駒の利きが無いか調べるだけで良い。
const bool canMove = !attackersToIsAny(oppositeColor(turn()), move.to());
assert(canMove == (pseudoLegalMoveIsLegal<false, false>(move, pinned)));
return canMove;
}
// 玉の移動以外
Bitboard target = checkersBB();
const Square checkSq = target.firstOneFromSQ11();
if (target)
// 両王手のとき、玉の移動以外の手は指せない。
return false;
const Color us = turn();
const Square to = move.to();
// 移動、又は打った駒が、王手をさえぎるか、王手している駒を取る必要がある。
target = betweenBB(checkSq, kingSquare(us)) | checkersBB();
return target.isSet(to) && pseudoLegalMoveIsLegal<false, true>(move, pinned);
}
// Searching: true なら探索時に内部で生成した手の合法手判定を行う。
// ttMove で hash 値が衝突した時などで、大駒の不成など明らかに価値の低い手が生成される事がある。
// これは非合法手として省いて良い。
// false なら、外部入力の合法手判定なので、ルールと同一の条件になる事が望ましい。
template <bool Searching> bool Position::moveIsPseudoLegal(const Move move) const {
const Color us = turn();
const Color them = oppositeColor(us);
const Square to = move.to();
if (move.isDrop()) {
const PieceType ptFrom = move.pieceTypeDropped();
if (!hand(us).exists(pieceTypeToHandPiece(ptFrom)) || piece(to) != Empty)
return false;
if (inCheck()) {
// 王手されているので、合駒でなければならない。
Bitboard target = checkersBB();
const Square checksq = target.firstOneFromSQ11();
if (target)
// 両王手は合駒出来無い。
return false;
target = betweenBB(checksq, kingSquare(us));
if (!target.isSet(to))
// 玉と、王手した駒との間に駒を打っていない。
return false;
}
if (ptFrom == Pawn) {
if ((bbOf(Pawn, us) & fileMask(makeFile(to))))
// 二歩
return false;
const SquareDelta TDeltaN = (us == Black ? DeltaN : DeltaS);
if (to + TDeltaN == kingSquare(them) && isPawnDropCheckMate(us, to))
// 王手かつ打ち歩詰め
return false;
}
}
else {
const Square from = move.from();
const PieceType ptFrom = move.pieceTypeFrom();
if (piece(from) != colorAndPieceTypeToPiece(us, ptFrom) || bbOf(us).isSet(to))
return false;
if (!attacksFrom(ptFrom, us, from).isSet(to))
return false;
if (Searching) {
switch (ptFrom) {
case Pawn :
if (move.isPromotion()) {
if (!canPromote(us, makeRank(to)))
return false;
}
else if (canPromote(us, makeRank(to)))
return false;
break;
case Lance :
if (move.isPromotion()) {
if (!canPromote(us, makeRank(to)))
return false;
}
else {
// 1段目の不成は非合法なので省く。2段目の不成と3段目の駒を取らない不成もついでに省く。
const Rank toRank = makeRank(to);
if (us == Black ? isInFrontOf<Black, Rank3, Rank7>(toRank) : isInFrontOf<White, Rank3, Rank7>(toRank))
return false;
if (canPromote(us, toRank) && !move.isCapture())
return false;
}
break;
case Knight:
// hash 値が衝突して別の局面の合法手の ttMove が入力されても、桂馬である事は確定。(桂馬は移動元、移動先が特殊なので。)
// よって、行きどころの無い駒になる move は生成されない。
// 特にチェックすべき事は無いので、break
break;
case Silver: case Bishop: case Rook :
if (move.isPromotion())
if (!canPromote(us, makeRank(to)) && !canPromote(us, makeRank(from)))
return false;
break;
default: // 成れない駒
if (move.isPromotion())
return false;
}
}
if (inCheck()) {
if (ptFrom == King) {
Bitboard occ = occupiedBB();
occ.clearBit(from);
if (attackersToIsAny(them, to, occ))
// 王手から逃げていない。
return false;
}
else {
// 玉以外の駒を移動させたとき。
Bitboard target = checkersBB();
const Square checksq = target.firstOneFromSQ11();
if (target)
// 両王手なので、玉が逃げない手は駄目
return false;
target = betweenBB(checksq, kingSquare(us)) | checkersBB();
if (!target.isSet(to))
// 玉と、王手した駒との間に移動するか、王手した駒を取る以外は駄目。
return false;
}
}
}
return true;
}
template bool Position::moveIsPseudoLegal<true >(const Move move) const;
template bool Position::moveIsPseudoLegal<false>(const Move move) const;
#if !defined NDEBUG
// 過去(又は現在)に生成した指し手が現在の局面でも有効か判定。
// あまり速度が要求される場面で使ってはいけない。
bool Position::moveIsLegal(const Move move) const {
return MoveList<LegalAll>(*this).contains(move);
}
#endif
// 局面の更新
void Position::doMove(const Move move, StateInfo& newSt) {
const CheckInfo ci(*this);
doMove(move, newSt, ci, moveGivesCheck(move, ci));
}
// 局面の更新
void Position::doMove(const Move move, StateInfo& newSt, const CheckInfo& ci, const bool moveIsCheck) {
assert(isOK());
assert(move);
assert(&newSt != st_);
Key boardKey = getBoardKey();
Key handKey = getHandKey();
boardKey ^= zobTurn();
memcpy(&newSt, st_, offsetof(StateInfo, boardKey));
newSt.previous = st_;
st_ = &newSt;
st_->cl.size = 1;
const Color us = turn();
const Square to = move.to();
const PieceType ptCaptured = move.cap();
PieceType ptTo;
if (move.isDrop()) {
ptTo = move.pieceTypeDropped();
const HandPiece hpTo = pieceTypeToHandPiece(ptTo);
handKey -= zobHand(hpTo, us);
boardKey += zobrist(ptTo, to, us);
prefetch(csearcher()->tt.firstEntry(boardKey + handKey));
const int handnum = hand(us).numOf(hpTo);
const int listIndex = evalList_.squareHandToList[HandPieceToSquareHand[us][hpTo] + handnum];
const Piece pcTo = colorAndPieceTypeToPiece(us, ptTo);
st_->cl.listindex[0] = listIndex;
st_->cl.clistpair[0].oldlist[0] = evalList_.list0[listIndex];
st_->cl.clistpair[0].oldlist[1] = evalList_.list1[listIndex];
evalList_.list0[listIndex] = kppArray[pcTo ] + (EvalIndex)to;
evalList_.list1[listIndex] = kppArray[inverse(pcTo)] + (EvalIndex)inverse(to);
evalList_.listToSquareHand[listIndex] = to;
evalList_.squareHandToList[to] = listIndex;
st_->cl.clistpair[0].newlist[0] = evalList_.list0[listIndex];
st_->cl.clistpair[0].newlist[1] = evalList_.list1[listIndex];
hand_[us].minusOne(hpTo);
xorBBs(ptTo, to, us);
piece_[to] = colorAndPieceTypeToPiece(us, ptTo);
if (moveIsCheck) {
// Direct checks
st_->checkersBB = setMaskBB(to);
st_->continuousCheck[us] += 2;
}
else {
st_->checkersBB = allZeroBB();
st_->continuousCheck[us] = 0;
}
}
else {
const Square from = move.from();
const PieceType ptFrom = move.pieceTypeFrom();
ptTo = move.pieceTypeTo(ptFrom);
byTypeBB_[ptFrom].xorBit(from);
byTypeBB_[ptTo].xorBit(to);
byColorBB_[us].xorBit(from, to);
piece_[from] = Empty;
piece_[to] = colorAndPieceTypeToPiece(us, ptTo);
boardKey -= zobrist(ptFrom, from, us);
boardKey += zobrist(ptTo, to, us);
if (ptCaptured) {
// 駒を取ったとき
const HandPiece hpCaptured = pieceTypeToHandPiece(ptCaptured);
const Color them = oppositeColor(us);
boardKey -= zobrist(ptCaptured, to, them);
handKey += zobHand(hpCaptured, us);
byTypeBB_[ptCaptured].xorBit(to);
byColorBB_[them].xorBit(to);
hand_[us].plusOne(hpCaptured);
const int toListIndex = evalList_.squareHandToList[to];
st_->cl.listindex[1] = toListIndex;
st_->cl.clistpair[1].oldlist[0] = evalList_.list0[toListIndex];
st_->cl.clistpair[1].oldlist[1] = evalList_.list1[toListIndex];
st_->cl.size = 2;
const int handnum = hand(us).numOf(hpCaptured);
evalList_.list0[toListIndex] = kppHandArray[us ][hpCaptured] + handnum;
evalList_.list1[toListIndex] = kppHandArray[them][hpCaptured] + handnum;
const Square squarehand = HandPieceToSquareHand[us][hpCaptured] + handnum;
evalList_.listToSquareHand[toListIndex] = squarehand;
evalList_.squareHandToList[squarehand] = toListIndex;
st_->cl.clistpair[1].newlist[0] = evalList_.list0[toListIndex];
st_->cl.clistpair[1].newlist[1] = evalList_.list1[toListIndex];
st_->material += (us == Black ? capturePieceScore(ptCaptured) : -capturePieceScore(ptCaptured));
}
prefetch(csearcher()->tt.firstEntry(boardKey + handKey));
// Occupied は to, from の位置のビットを操作するよりも、
// Black と White の or を取る方が速いはず。
byTypeBB_[Occupied] = bbOf(Black) | bbOf(White);
if (ptTo == King)
kingSquare_[us] = to;
else {
const Piece pcTo = colorAndPieceTypeToPiece(us, ptTo);
const int fromListIndex = evalList_.squareHandToList[from];
st_->cl.listindex[0] = fromListIndex;
st_->cl.clistpair[0].oldlist[0] = evalList_.list0[fromListIndex];
st_->cl.clistpair[0].oldlist[1] = evalList_.list1[fromListIndex];
evalList_.list0[fromListIndex] = kppArray[pcTo ] + (EvalIndex)to;
evalList_.list1[fromListIndex] = kppArray[inverse(pcTo)] + (EvalIndex)inverse(to);
evalList_.listToSquareHand[fromListIndex] = to;
evalList_.squareHandToList[to] = fromListIndex;
st_->cl.clistpair[0].newlist[0] = evalList_.list0[fromListIndex];
st_->cl.clistpair[0].newlist[1] = evalList_.list1[fromListIndex];
}
if (move.isPromotion())
st_->material += (us == Black ? (pieceScore(ptTo) - pieceScore(ptFrom)) : -(pieceScore(ptTo) - pieceScore(ptFrom)));
if (moveIsCheck) {
// Direct checks
st_->checkersBB = ci.checkBB[ptTo] & setMaskBB(to);
// Discovery checks
const Square ksq = kingSquare(oppositeColor(us));
if (isDiscoveredCheck(from, to, ksq, ci.dcBB)) {
switch (squareRelation(from, ksq)) {
case DirecMisc: assert(false); break; // 最適化の為のダミー
case DirecFile:
// from の位置から縦に利きを調べると相手玉と、空き王手している駒に当たっているはず。味方の駒が空き王手している駒。
st_->checkersBB |= rookAttackFile(from, occupiedBB()) & bbOf(us);
break;
case DirecRank:
st_->checkersBB |= attacksFrom<Rook>(ksq) & bbOf(Rook, Dragon, us);
break;
case DirecDiagNESW: case DirecDiagNWSE:
st_->checkersBB |= attacksFrom<Bishop>(ksq) & bbOf(Bishop, Horse, us);
break;
default: UNREACHABLE;
}
}
st_->continuousCheck[us] += 2;
}
else {
st_->checkersBB = allZeroBB();
st_->continuousCheck[us] = 0;
}
}
goldsBB_ = bbOf(Gold, ProPawn, ProLance, ProKnight, ProSilver);
st_->boardKey = boardKey;
st_->handKey = handKey;
++st_->pliesFromNull;
turn_ = oppositeColor(us);
st_->hand = hand(turn());
assert(isOK());
}
void Position::undoMove(const Move move) {
assert(isOK());
assert(move);
const Color them = turn();
const Color us = oppositeColor(them);
const Square to = move.to();
turn_ = us;
// ここで先に turn_ を戻したので、以下、move は us の指し手とする。
if (move.isDrop()) {
const PieceType ptTo = move.pieceTypeDropped();
byTypeBB_[ptTo].xorBit(to);
byColorBB_[us].xorBit(to);
piece_[to] = Empty;
const HandPiece hp = pieceTypeToHandPiece(ptTo);
hand_[us].plusOne(hp);
const int toListIndex = evalList_.squareHandToList[to];
const int handnum = hand(us).numOf(hp);
evalList_.list0[toListIndex] = kppHandArray[us ][hp] + handnum;
evalList_.list1[toListIndex] = kppHandArray[them][hp] + handnum;
const Square squarehand = HandPieceToSquareHand[us][hp] + handnum;
evalList_.listToSquareHand[toListIndex] = squarehand;
evalList_.squareHandToList[squarehand] = toListIndex;
}
else {
const Square from = move.from();
const PieceType ptFrom = move.pieceTypeFrom();
const PieceType ptTo = move.pieceTypeTo(ptFrom);
const PieceType ptCaptured = move.cap(); // todo: st_->capturedType 使えば良い。
if (ptTo == King)
kingSquare_[us] = from;
else {
const Piece pcFrom = colorAndPieceTypeToPiece(us, ptFrom);
const int toListIndex = evalList_.squareHandToList[to];
evalList_.list0[toListIndex] = kppArray[pcFrom ] + (EvalIndex)from;
evalList_.list1[toListIndex] = kppArray[inverse(pcFrom)] + (EvalIndex)inverse(from);
evalList_.listToSquareHand[toListIndex] = from;
evalList_.squareHandToList[from] = toListIndex;
}
if (ptCaptured) {
// 駒を取ったとき
byTypeBB_[ptCaptured].xorBit(to);
byColorBB_[them].xorBit(to);
const HandPiece hpCaptured = pieceTypeToHandPiece(ptCaptured);
const Piece pcCaptured = colorAndPieceTypeToPiece(them, ptCaptured);
piece_[to] = pcCaptured;
const int handnum = hand(us).numOf(hpCaptured);
const int toListIndex = evalList_.squareHandToList[HandPieceToSquareHand[us][hpCaptured] + handnum];
evalList_.list0[toListIndex] = kppArray[pcCaptured ] + (EvalIndex)to;
evalList_.list1[toListIndex] = kppArray[inverse(pcCaptured)] + (EvalIndex)inverse(to);
evalList_.listToSquareHand[toListIndex] = to;
evalList_.squareHandToList[to] = toListIndex;
hand_[us].minusOne(hpCaptured);
}
else
// 駒を取らないときは、colorAndPieceTypeToPiece(us, ptCaptured) は 0 または 16 になる。
// 16 になると困るので、駒を取らないときは明示的に Empty にする。
piece_[to] = Empty;
byTypeBB_[ptFrom].xorBit(from);
byTypeBB_[ptTo].xorBit(to);
byColorBB_[us].xorBit(from, to);
piece_[from] = colorAndPieceTypeToPiece(us, ptFrom);
}
// Occupied は to, from の位置のビットを操作するよりも、
// Black と White の or を取る方が速いはず。
byTypeBB_[Occupied] = bbOf(Black) | bbOf(White);
goldsBB_ = bbOf(Gold, ProPawn, ProLance, ProKnight, ProSilver);
// key などは StateInfo にまとめられているので、
// previous のポインタを st_ に代入するだけで良い。
st_ = st_->previous;
assert(isOK());
}
namespace {
// SEE の順番
template <PieceType PT> struct SEENextPieceType {}; // これはインスタンス化しない。
template <> struct SEENextPieceType<Pawn > { static const PieceType value = Lance; };
template <> struct SEENextPieceType<Lance > { static const PieceType value = Knight; };
template <> struct SEENextPieceType<Knight > { static const PieceType value = ProPawn; };
template <> struct SEENextPieceType<ProPawn > { static const PieceType value = ProLance; };
template <> struct SEENextPieceType<ProLance > { static const PieceType value = ProKnight; };
template <> struct SEENextPieceType<ProKnight> { static const PieceType value = Silver; };
template <> struct SEENextPieceType<Silver > { static const PieceType value = ProSilver; };
template <> struct SEENextPieceType<ProSilver> { static const PieceType value = Gold; };
template <> struct SEENextPieceType<Gold > { static const PieceType value = Bishop; };
template <> struct SEENextPieceType<Bishop > { static const PieceType value = Horse; };
template <> struct SEENextPieceType<Horse > { static const PieceType value = Rook; };
template <> struct SEENextPieceType<Rook > { static const PieceType value = Dragon; };
template <> struct SEENextPieceType<Dragon > { static const PieceType value = King; };
template <PieceType PT> FORCE_INLINE PieceType nextAttacker(const Position& pos, const Square to, const Bitboard& opponentAttackers,
Bitboard& occupied, Bitboard& attackers, const Color turn)
{
if (opponentAttackers.andIsAny(pos.bbOf(PT))) {
const Bitboard bb = opponentAttackers & pos.bbOf(PT);
const Square from = bb.constFirstOneFromSQ11();
occupied.xorBit(from);
// todo: 実際に移動した方向を基にattackersを更新すれば、template, inline を使用しなくても良さそう。
// その場合、キャッシュに乗りやすくなるので逆に速くなるかも。
if (PT == Pawn || PT == Lance)
attackers |= (lanceAttack(oppositeColor(turn), to, occupied) & (pos.bbOf(Rook, Dragon) | pos.bbOf(Lance, turn)));
if (PT == Gold || PT == ProPawn || PT == ProLance || PT == ProKnight || PT == ProSilver || PT == Horse || PT == Dragon)
attackers |= (lanceAttack(oppositeColor(turn), to, occupied) & pos.bbOf(Lance, turn))
| (lanceAttack(turn, to, occupied) & pos.bbOf(Lance, oppositeColor(turn)))
| (rookAttack(to, occupied) & pos.bbOf(Rook, Dragon))
| (bishopAttack(to, occupied) & pos.bbOf(Bishop, Horse));
if (PT == Silver)
attackers |= (lanceAttack(oppositeColor(turn), to, occupied) & pos.bbOf(Lance, turn))
| (rookAttack(to, occupied) & pos.bbOf(Rook, Dragon))
| (bishopAttack(to, occupied) & pos.bbOf(Bishop, Horse));
if (PT == Bishop)
attackers |= (bishopAttack(to, occupied) & pos.bbOf(Bishop, Horse));
if (PT == Rook)
attackers |= (lanceAttack(oppositeColor(turn), to, occupied) & pos.bbOf(Lance, turn))
| (lanceAttack(turn, to, occupied) & pos.bbOf(Lance, oppositeColor(turn)))
| (rookAttack(to, occupied) & pos.bbOf(Rook, Dragon));
if (PT == Pawn || PT == Lance || PT == Knight)
if (canPromote(turn, makeRank(to)))
return PT + PTPromote;
if (PT == Silver || PT == Bishop || PT == Rook)
if (canPromote(turn, makeRank(to)) || canPromote(turn, makeRank(from)))
return PT + PTPromote;
return PT;
}
return nextAttacker<SEENextPieceType<PT>::value>(pos, to, opponentAttackers, occupied, attackers, turn);
}
template <> FORCE_INLINE PieceType nextAttacker<King>(const Position&, const Square, const Bitboard&,
Bitboard&, Bitboard&, const Color)
{
return King;
}
}
Score Position::see(const Move move, const int asymmThreshold) const {
const Square to = move.to();
Square from;
PieceType ptCaptured;
Bitboard occ = occupiedBB();
Bitboard attackers;
Bitboard opponentAttackers;
Color turn = oppositeColor(this->turn());
Score swapList[32];
if (move.isDrop()) {
opponentAttackers = attackersTo(turn, to, occ);
if (!opponentAttackers)
return ScoreZero;
attackers = opponentAttackers | attackersTo(oppositeColor(turn), to, occ);
swapList[0] = ScoreZero;
ptCaptured = move.pieceTypeDropped();
}
else {
from = move.from();
occ.xorBit(from);
opponentAttackers = attackersTo(turn, to, occ);
if (!opponentAttackers) {
if (move.isPromotion()) {
const PieceType ptFrom = move.pieceTypeFrom();
return capturePieceScore(move.cap()) + promotePieceScore(ptFrom);
}
return capturePieceScore(move.cap());
}
attackers = opponentAttackers | attackersTo(oppositeColor(turn), to, occ);
swapList[0] = capturePieceScore(move.cap());
ptCaptured = move.pieceTypeFrom();
if (move.isPromotion()) {
const PieceType ptFrom = move.pieceTypeFrom();
swapList[0] += promotePieceScore(ptFrom);
ptCaptured += PTPromote;
}
}
int slIndex = 1;
do {
swapList[slIndex] = -swapList[slIndex - 1] + capturePieceScore(ptCaptured);
ptCaptured = nextAttacker<Pawn>(*this, to, opponentAttackers, occ, attackers, turn);
attackers &= occ;
++slIndex;
turn = oppositeColor(turn);
opponentAttackers = attackers & bbOf(turn);
if (ptCaptured == King) {
if (opponentAttackers)
swapList[slIndex++] = CaptureKingScore;
break;
}
} while (opponentAttackers);
if (asymmThreshold) {
for (int i = 0; i < slIndex; i += 2) {
if (swapList[i] < asymmThreshold)
swapList[i] = -CaptureKingScore;
}
}
// nega max 的に駒の取り合いの点数を求める。
while (--slIndex)
swapList[slIndex-1] = std::min(-swapList[slIndex], swapList[slIndex-1]);
return swapList[0];
}
Score Position::seeSign(const Move move) const {
if (move.isCapture()) {
const PieceType ptFrom = move.pieceTypeFrom();
const Square to = move.to();
if (capturePieceScore(ptFrom) <= capturePieceScore(piece(to)))
return static_cast<Score>(1);
}
return see(move);
}
namespace {
// them(相手) 側の玉が逃げられるか。
// sq : 王手した相手の駒の位置。紐付きか、桂馬の位置とする。よって、玉は sq には行けない。
// bb : sq の利きのある場所のBitboard。よって、玉は bb のビットが立っている場所には行けない。
// sq と ksq の位置の Occupied Bitboard のみは、ここで更新して評価し、元に戻す。
// (実際にはテンポラリのOccupied Bitboard を使うので、元には戻さない。)
bool canKingEscape(const Position& pos, const Color us, const Square sq, const Bitboard& bb) {
const Color them = oppositeColor(us);
const Square ksq = pos.kingSquare(them);
Bitboard kingMoveBB = bb.notThisAnd(pos.bbOf(them).notThisAnd(kingAttack(ksq)));
kingMoveBB.clearBit(sq); // sq には行けないので、クリアする。xorBit(sq)ではダメ。
if (kingMoveBB) {
Bitboard tempOccupied = pos.occupiedBB();
tempOccupied.setBit(sq);
tempOccupied.clearBit(ksq);
do {
const Square to = kingMoveBB.firstOneFromSQ11();
// 玉の移動先に、us 側の利きが無ければ、true
if (!pos.attackersToIsAny(us, to, tempOccupied))
return true;
} while (kingMoveBB);
}
// 玉の移動先が無い。
return false;
}
// them(相手) 側の玉以外の駒が sq にある us 側の駒を取れるか。
bool canPieceCapture(const Position& pos, const Color them, const Square sq, const Bitboard& dcBB) {
// 玉以外で打った駒を取れる相手側の駒の Bitboard
Bitboard fromBB = pos.attackersToExceptKing(them, sq);
if (fromBB) {
const Square ksq = pos.kingSquare(them);
do {
const Square from = fromBB.firstOneFromSQ11();
if (!pos.isDiscoveredCheck(from, sq, ksq, dcBB))
// them 側から見て、pin されていない駒で、打たれた駒を取れるので、true
return true;
} while (fromBB);
}
// 玉以外の駒で、打った駒を取れない。
return false;
}
// pos.discoveredCheckBB<false>() を遅延評価するバージョン。
bool canPieceCapture(const Position& pos, const Color them, const Square sq) {
Bitboard fromBB = pos.attackersToExceptKing(them, sq);
if (fromBB) {
const Square ksq = pos.kingSquare(them);
const Bitboard dcBB = pos.discoveredCheckBB<false>();
do {
const Square from = fromBB.firstOneFromSQ11();
if (!pos.isDiscoveredCheck(from, sq, ksq, dcBB))
// them 側から見て、pin されていない駒で、打たれた駒を取れるので、true
return true;
} while (fromBB);
}
// 玉以外の駒で、打った駒を取れない。
return false;
}
}
// us が sq へ歩を打ったとき、them の玉が詰むか。
// us が sq へ歩を打つのは王手であると仮定する。
// 打ち歩詰めのとき、true を返す。
bool Position::isPawnDropCheckMate(const Color us, const Square sq) const {
const Color them = oppositeColor(us);
// 玉以外の駒で、打たれた歩が取れるなら、打ち歩詰めではない。
if (canPieceCapture(*this, them, sq))
return false;
// todo: ここで玉の位置を求めるのは、上位で求めたものと2重になるので無駄。後で整理すること。
const Square ksq = kingSquare(them);
// 玉以外で打った歩を取れないとき、玉が歩を取るか、玉が逃げるか。
// 利きを求める際に、occupied の歩を打った位置の bit を立てた Bitboard を使用する。
// ここでは歩の Bitboard は更新する必要がない。
// color の Bitboard も更新する必要がない。(相手玉が動くとき、こちらの打った歩で玉を取ることは無い為。)
const Bitboard tempOccupied = occupiedBB() | setMaskBB(sq);
Bitboard kingMoveBB = bbOf(them).notThisAnd(kingAttack(ksq));
// 少なくとも歩を取る方向には玉が動けるはずなので、do while を使用。
assert(kingMoveBB);
do {
const Square to = kingMoveBB.firstOneFromSQ11();
if (!attackersToIsAny(us, to, tempOccupied))
// 相手玉の移動先に自駒の利きがないなら、打ち歩詰めではない。
return false;
} while (kingMoveBB);
return true;
}
inline void Position::xorBBs(const PieceType pt, const Square sq, const Color c) {
byTypeBB_[Occupied].xorBit(sq);
byTypeBB_[pt].xorBit(sq);
byColorBB_[c].xorBit(sq);
}
// 相手玉が1手詰みかどうかを判定。
// 1手詰みなら、詰みに至る指し手の一部の情報(from, to のみとか)を返す。
// 1手詰みでないなら、Move::moveNone() を返す。
// Bitboard の状態を途中で更新する為、const 関数ではない。(更新後、元に戻すが。)
template <Color US> Move Position::mateMoveIn1Ply() {
const Color Them = oppositeColor(US);
const Square ksq = kingSquare(Them);
const SquareDelta TDeltaS = (US == Black ? DeltaS : DeltaN);
assert(!attackersToIsAny(Them, kingSquare(US)));
// 駒打ちを調べる。
const Bitboard dropTarget = nOccupiedBB(); // emptyBB() ではないので注意して使うこと。
const Hand ourHand = hand(US);
// 王手する前の状態の dcBB。
// 間にある駒は相手側の駒。
// 駒打ちのときは、打った後も、打たれる前の状態の dcBB を使用する。
const Bitboard dcBB_betweenIsThem = discoveredCheckBB<false>();
// 飛車打ち
if (ourHand.exists<HRook>()) {
// 合駒されるとややこしいので、3手詰み関数の中で調べる。
// ここでは離れた位置から王手するのは考えない。
Bitboard toBB = dropTarget & rookStepAttacks(ksq);
while (toBB) {
const Square to = toBB.firstOneFromSQ11();
// 駒を打った場所に自駒の利きがあるか。(無ければ玉で取られて詰まない)
if (attackersToIsAny(US, to)) {
// 玉が逃げられず、他の駒で取ることも出来ないか
if (!canKingEscape(*this, US, to, rookAttackToEdge(to))
&& !canPieceCapture(*this, Them, to, dcBB_betweenIsThem))
{
return makeDropMove(Rook, to);
}
}
}
}
// 香車打ち
// 飛車で詰まなければ香車でも詰まないので、else if を使用。
// 玉が 9(1) 段目にいれば香車で王手出来無いので、それも省く。
else if (ourHand.exists<HLance>() && isInFrontOf<US, Rank9, Rank1>(makeRank(ksq))) {
const Square to = ksq + TDeltaS;
if (piece(to) == Empty && attackersToIsAny(US, to)) {
if (!canKingEscape(*this, US, to, lanceAttackToEdge(US, to))
&& !canPieceCapture(*this, Them, to, dcBB_betweenIsThem))
{
return makeDropMove(Lance, to);
}
}
}
// 角打ち
if (ourHand.exists<HBishop>()) {
Bitboard toBB = dropTarget & bishopStepAttacks(ksq);
while (toBB) {
const Square to = toBB.firstOneFromSQ11();
if (attackersToIsAny(US, to)) {
if (!canKingEscape(*this, US, to, bishopAttackToEdge(to))
&& !canPieceCapture(*this, Them, to, dcBB_betweenIsThem))
{
return makeDropMove(Bishop, to);
}
}
}
}
// 金打ち
if (ourHand.exists<HGold>()) {
Bitboard toBB;
if (ourHand.exists<HRook>())
// 飛車打ちを先に調べたので、尻金だけは省く。
toBB = dropTarget & (goldAttack(Them, ksq) ^ pawnAttack(US, ksq));
else
toBB = dropTarget & goldAttack(Them, ksq);
while (toBB) {
const Square to = toBB.firstOneFromSQ11();
if (attackersToIsAny(US, to)) {
if (!canKingEscape(*this, US, to, goldAttack(US, to))
&& !canPieceCapture(*this, Them, to, dcBB_betweenIsThem))
{
return makeDropMove(Gold, to);
}
}
}
}
if (ourHand.exists<HSilver>()) {
Bitboard toBB;
if (ourHand.exists<HGold>()) {
// 金打ちを先に調べたので、斜め後ろから打つ場合だけを調べる。
if (ourHand.exists<HBishop>())
// 角打ちを先に調べたので、斜めからの王手も除外できる。銀打ちを調べる必要がない。
goto silver_drop_end;
// 斜め後ろから打つ場合を調べる必要がある。
toBB = dropTarget & (silverAttack(Them, ksq) & inFrontMask(US, makeRank(ksq)));
}
else {
if (ourHand.exists<HBishop>())
// 斜め後ろを除外。前方から打つ場合を調べる必要がある。
toBB = dropTarget & goldAndSilverAttacks(Them, ksq);
else
toBB = dropTarget & silverAttack(Them, ksq);
}
while (toBB) {
const Square to = toBB.firstOneFromSQ11();
if (attackersToIsAny(US, to)) {
if (!canKingEscape(*this, US, to, silverAttack(US, to))
&& !canPieceCapture(*this, Them, to, dcBB_betweenIsThem))
{
return makeDropMove(Silver, to);
}
}
}
}
silver_drop_end:
if (ourHand.exists<HKnight>()) {
Bitboard toBB = dropTarget & knightAttack(Them, ksq);
while (toBB) {
const Square to = toBB.firstOneFromSQ11();
// 桂馬は紐が付いている必要はない。
// よって、このcanKingEscape() 内での to の位置に逃げられないようにする処理は無駄。
if (!canKingEscape(*this, US, to, allZeroBB())
&& !canPieceCapture(*this, Them, to, dcBB_betweenIsThem))
{
return makeDropMove(Knight, to);
}
}
}
// 歩打ちで詰ますと反則なので、調べない。
// 駒を移動する場合
// moveTarget は桂馬以外の移動先の大まかな位置。飛角香の遠隔王手は含まない。
const Bitboard moveTarget = bbOf(US).notThisAnd(kingAttack(ksq));
const Bitboard pinned = pinnedBB();
const Bitboard dcBB_betweenIsUs = discoveredCheckBB<true>();
{
// 竜による移動
Bitboard fromBB = bbOf(Dragon, US);
while (fromBB) {
const Square from = fromBB.firstOneFromSQ11();
// 遠隔王手は考えない。
Bitboard toBB = moveTarget & attacksFrom<Dragon>(from);
if (toBB) {
xorBBs(Dragon, from, US);
// 動いた後の dcBB: to の位置の occupied や checkers は関係ないので、ここで生成できる。
const Bitboard dcBB_betweenIsThem_after = discoveredCheckBB<false>();
// to の位置の Bitboard は canKingEscape の中で更新する。
do {
const Square to = toBB.firstOneFromSQ11();
// 王手した駒の場所に自駒の利きがあるか。(無ければ玉で取られて詰まない)
if (unDropCheckIsSupported(US, to)) {
// 玉が逃げられない
// かつ、(空き王手 または 他の駒で取れない)
// かつ、王手した駒が pin されていない
if (!canKingEscape(*this, US, to, attacksFrom<Dragon>(to, occupiedBB() ^ setMaskBB(ksq)))
&& (isDiscoveredCheck(from, to, ksq, dcBB_betweenIsUs)
|| !canPieceCapture(*this, Them, to, dcBB_betweenIsThem_after))
&& !isPinnedIllegal(from, to, kingSquare(US), pinned))
{
xorBBs(Dragon, from, US);
return makeCaptureMove(Dragon, from, to, *this);
}
}
} while (toBB);
xorBBs(Dragon, from, US);
}
}
}
// Txxx は先手、後手の情報を吸収した変数。数字は先手に合わせている。