rshogi-core 0.2.0

A high-performance shogi engine core library with NNUE evaluation
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
//! MovePicker サポートメソッド
//!
//! MovePicker が必要とする Position のメソッドを実装する。

use super::Position;
use crate::bitboard::{
    Bitboard, Direct, between_bb, bishop_effect, direct_of, gold_effect, king_effect,
    knight_effect, lance_effect, pawn_effect, ray_effect, rook_effect, silver_effect,
};
use crate::movegen::{ExtMoveBuffer, GenType, generate_evasions, generate_with_type};
use crate::types::{Color, Move, Piece, PieceType, Square, Value};

impl Position {
    // =========================================================================
    // 指し手の妥当性チェック
    // =========================================================================

    /// pseudo-legal チェック(TT手の妥当性確認用)
    ///
    /// 指し手が現在の局面で pseudo-legal かどうかを確認する。
    /// 完全な合法性(自玉への王手回避など)はチェックしない。
    ///
    /// YaneuraOuの実装を参考に、王手中の不正な手を早期リジェクトする。
    /// 成らない手の制限は行わない(特殊な詰み手順の発見を可能にするため)。
    ///
    /// ## パフォーマンスについて
    ///
    /// この最適化によるNPS改善は誤差範囲内(+0.3%)だった。
    /// これはTT手検証で王手中の不正な手が出現する頻度が低いため。
    /// パフォーマンスよりもコードの正確性向上が主な目的。
    pub fn pseudo_legal(&self, m: Move) -> bool {
        if m.is_none() {
            return false;
        }

        // PASS の場合は can_pass() で判定
        if m.is_pass() {
            return self.can_pass();
        }

        let us = self.side_to_move();
        let to = m.to();

        if m.is_drop() {
            // 駒打ち
            let pt = m.drop_piece_type();

            // 手駒にあるか
            if !self.hand(us).has(pt) {
                return false;
            }

            // 移動先が空きか
            if self.piece_on(to).is_some() {
                return false;
            }

            // 王手中の合駒チェック
            if self.in_check() {
                let checkers = self.checkers();
                debug_assert!(
                    !checkers.is_empty(),
                    "checkers should not be empty when in_check() is true"
                );
                let checker_sq = checkers.lsb().unwrap();

                // 両王手なら合駒不可
                if checkers.count() > 1 {
                    return false;
                }

                // 王と王手駒の間に打つ手でなければ不可
                let king_sq = self.king_square(us);
                if !between_bb(checker_sq, king_sq).contains(to) {
                    return false;
                }
            }

            // 二歩チェック(歩の場合)
            if pt == PieceType::Pawn {
                let file_mask = crate::bitboard::FILE_BB[to.file().index()];
                if !(self.pieces(us, PieceType::Pawn) & file_mask).is_empty() {
                    return false;
                }
            }

            true
        } else {
            // 駒移動
            let from = m.from();
            let pc = self.piece_on(from);

            // 移動元に自分の駒があるか
            if pc.is_none() || pc.color() != us {
                return false;
            }

            // 駒の動きとして正しいか
            let pt = pc.piece_type();
            let occupied = self.occupied();

            // 成りフラグの検証
            // TTからの手が現在の局面の駒種と一致しない場合のパニックを防ぐ
            if m.is_promote() {
                // 成りフラグが立っている場合、駒種が成れるかチェック
                if !pt.can_promote() {
                    return false;
                }
                // 成れる段(敵陣 = from or to が敵陣)かどうかチェック
                let in_enemy_zone = if us == Color::Black {
                    from.rank().index() <= 2 || to.rank().index() <= 2
                } else {
                    from.rank().index() >= 6 || to.rank().index() >= 6
                };
                if !in_enemy_zone {
                    return false;
                }
            }

            let attacks = match pt {
                PieceType::Pawn => pawn_effect(us, from),
                PieceType::Lance => lance_effect(us, from, occupied),
                PieceType::Knight => knight_effect(us, from),
                PieceType::Silver => silver_effect(us, from),
                PieceType::Gold
                | PieceType::ProPawn
                | PieceType::ProLance
                | PieceType::ProKnight
                | PieceType::ProSilver => gold_effect(us, from),
                PieceType::Bishop => bishop_effect(from, occupied),
                PieceType::Rook => rook_effect(from, occupied),
                PieceType::Horse => bishop_effect(from, occupied) | king_effect(from),
                PieceType::Dragon => rook_effect(from, occupied) | king_effect(from),
                PieceType::King => king_effect(from),
            };

            if !attacks.contains(to) {
                return false;
            }

            // 移動先に自分の駒がないか
            let to_pc = self.piece_on(to);
            if to_pc.is_some() && to_pc.color() == us {
                return false;
            }

            // 成りの場合、成れない駒は成れない
            if m.is_promotion() && !pt.can_promote() {
                return false;
            }

            // 【参考実装】成らない手の制限(YaneuraOu の generate_all_legal_moves = false 相当)
            // 特殊な詰み手順(歩不成での打ち歩詰め回避、角不成での利き調整など)の
            // 発見を可能にするため、本実装では有効化しない。
            // NPS改善も誤差範囲内だったため、制限しないことによるデメリットはない。
            //
            // if !m.is_promotion() {
            //     match pt {
            //         PieceType::Pawn => {
            //             // 歩の不成: 敵陣での不成を禁止
            //             if is_enemy_field(us, to) {
            //                 return false;
            //             }
            //         }
            //         PieceType::Lance => {
            //             // 香の不成: 1-2段目(先手)/ 8-9段目(後手)への不成を禁止
            //             if is_deep_enemy_field(us, to) {
            //                 return false;
            //             }
            //         }
            //         PieceType::Bishop | PieceType::Rook => {
            //             // 大駒の不成: 敵陣に関わる移動での不成を禁止
            //             if is_enemy_field(us, from) || is_enemy_field(us, to) {
            //                 return false;
            //             }
            //         }
            //         _ => {}
            //     }
            // }

            // 王手中の駒移動チェック
            let checkers = self.checkers();
            if !checkers.is_empty() {
                // 玉以外を動かす場合
                if pt != PieceType::King {
                    // 両王手なら玉を動かす以外は不可
                    if checkers.count() > 1 {
                        return false;
                    }

                    // 王手を遮断しているか、王手駒を取る手でなければ不可
                    debug_assert!(
                        !checkers.is_empty(),
                        "checkers should not be empty in this branch"
                    );
                    let checker_sq = checkers.lsb().unwrap();
                    let king_sq = self.king_square(us);
                    let valid_targets = between_bb(checker_sq, king_sq) | checkers;
                    if !valid_targets.contains(to) {
                        return false;
                    }
                }
            }

            true
        }
    }

    // =========================================================================
    // 指し手に関する情報取得
    // =========================================================================

    /// 指し手で動く駒を取得
    ///
    /// PASSの場合は Piece::NONE を返す
    #[inline]
    pub fn moved_piece(&self, m: Move) -> Piece {
        if m.is_pass() {
            Piece::NONE
        } else if m.is_drop() {
            // 駒打ちの場合は、手番と駒種から駒を構築
            Piece::make(self.side_to_move(), m.drop_piece_type())
        } else {
            self.piece_on(m.from())
        }
    }

    /// capture_stage: 捕獲手かどうか(ProbCut等の判定用)
    ///
    /// PASSは捕獲手ではない
    #[inline]
    pub fn capture_stage(&self, m: Move) -> bool {
        !m.is_pass() && !m.is_drop() && self.piece_on(m.to()).is_some()
    }

    /// pseudo-legal判定(生成モード指定版)
    ///
    /// 互換性のため `generate_all_legal_moves` パラメータを受け取るが、
    /// 成らない手の制限は行わないため、常に `pseudo_legal()` と同じ動作をする。
    #[inline]
    pub fn pseudo_legal_with_all(&self, m: Move, _generate_all_legal_moves: bool) -> bool {
        self.pseudo_legal(m)
    }

    /// 取る手かどうか
    #[inline]
    pub fn is_capture(&self, m: Move) -> bool {
        // PASS は駒を取らない
        if m.is_pass() || m.is_drop() {
            false
        } else {
            self.piece_on(m.to()).is_some()
        }
    }

    /// 指し手で動いた後の駒(成り後・打ち駒を含む)を取得
    #[inline]
    pub fn moved_piece_after_move(&self, m: Move) -> Piece {
        debug_assert!(m.has_piece_info(), "Move must carry piece info");
        m.moved_piece_after()
    }

    /// 取る手または成る手かどうか
    #[inline]
    pub fn is_capture_or_promotion(&self, m: Move) -> bool {
        self.is_capture(m) || m.is_promotion()
    }

    /// 取る手または歩成りの手かどうか(ProbCut用)
    /// YaneuraOu: capture_or_pawn_promotion
    #[inline]
    pub fn capture_or_pawn_promotion(&self, m: Move) -> bool {
        self.is_capture(m)
            || (m.is_promotion() && self.moved_piece(m).piece_type() == PieceType::Pawn)
    }

    // =========================================================================
    // 歩の陣形インデックス
    // =========================================================================

    /// PawnHistory 用のインデックスを計算
    ///
    /// 歩の配置に基づくハッシュ値からインデックスを計算する。
    pub fn pawn_history_index(&self) -> usize {
        (self.pawn_key() as usize) & (crate::search::PAWN_HISTORY_SIZE - 1)
    }

    // =========================================================================
    // 指し手生成(MovePicker用)
    // =========================================================================

    /// 捕獲手を生成(ExtMoveBufferに直接書き込み)
    ///
    /// generate関数がExtMoveBufferに直接書き込むため、中間バッファ不要。
    pub fn generate_captures(&self, moves: &mut ExtMoveBuffer) -> usize {
        if self.in_check() {
            // 王手回避手を生成してから捕獲手のみフィルタ
            generate_evasions(self, moves);
            moves.retain(|m| self.is_capture(m));
        } else {
            generate_with_type(self, GenType::CapturesProPlus, moves, None);
        }
        moves.len()
    }

    /// 静かな手を生成(ExtMoveBufferに直接書き込み、既存の要素の後に追加)
    ///
    /// generate関数がExtMoveBufferに直接書き込むため、中間バッファ不要。
    /// offset は互換性のために維持するが、moves.len() と等しい必要がある。
    pub fn generate_quiets(&self, moves: &mut ExtMoveBuffer, offset: usize) -> usize {
        if self.in_check() {
            return 0;
        }

        debug_assert_eq!(
            offset,
            moves.len(),
            "offset should equal buffer length: offset={offset}, len={}",
            moves.len()
        );

        let start_len = moves.len();
        // YaneuraOu標準のQUIETS相当: 成りも含む静かな手を生成する
        generate_with_type(self, GenType::Quiets, moves, None);
        moves.len() - start_len
    }

    /// 回避手を生成(ExtMoveBufferに直接書き込み)
    ///
    /// generate関数がExtMoveBufferに直接書き込むため、中間バッファ不要。
    pub fn generate_evasions_ext(&self, moves: &mut ExtMoveBuffer) -> usize {
        debug_assert!(self.in_check());
        generate_with_type(self, GenType::Evasions, moves, None);
        moves.len()
    }

    // =========================================================================
    // SEE (Static Exchange Evaluation)
    // =========================================================================

    /// SEE >= threshold かどうかを判定(YO準拠: swap/resアルゴリズム)
    ///
    /// YaneuraOu/Stockfish と同じアルゴリズムで静的駒交換評価を判定する。
    /// 成りボーナスは考慮しない(YO準拠)。
    pub fn see_ge(&self, m: Move, threshold: Value) -> bool {
        // PASSは駒交換が発生しないので >= 0
        if m.is_pass() {
            return threshold.raw() <= 0;
        }

        let is_drop = m.is_drop();
        let to = m.to();

        // YO: swap = PieceValue[piece_on(to)] - threshold
        // 取られる駒の価値(駒打ちは空きマスに打つので 0)
        let captured_value = if is_drop {
            0
        } else {
            let captured = self.piece_on(to);
            if captured.is_some() {
                see_piece_value(captured.piece_type())
            } else {
                0
            }
        };
        let mut swap = captured_value - threshold.raw();

        // toの駒価値がthreshold未満 → 取り返されなくてもfalse
        if swap < 0 {
            return false;
        }

        // YO: swap = PieceValue[from_pt] - swap
        // 動かす駒の価値(駒打ちは打つ駒種)
        let from_value = if is_drop {
            see_piece_value(m.drop_piece_type())
        } else {
            see_piece_value(self.piece_on(m.from()).piece_type())
        };
        swap = from_value - swap;

        // 動かす駒を取り返されても閾値以上 → true
        if swap <= 0 {
            return true;
        }

        // YO: occupied = pieces() ^ from ^ to
        // 駒打ちの場合は from を無効化(XORしない)
        let mut occupied = if is_drop {
            self.occupied() ^ Bitboard::from_square(to)
        } else {
            self.occupied() ^ Bitboard::from_square(m.from()) ^ Bitboard::from_square(to)
        };
        let mut stm = self.side_to_move();
        let mut attackers = self.attackers_to_occ(to, occupied);
        let mut res = 1i32;

        loop {
            stm = !stm;
            attackers &= occupied;

            let mut stm_attackers = attackers & self.pieces_c(stm);
            if stm_attackers.is_empty() {
                break;
            }

            // YO: ピン処理 — ピンされた駒は攻撃に参加できない
            // pinners(~stm): stmの玉をピンしている(!stm側の)駒
            // rshogi の pinners[c] は「!c側の駒がc側の王をピンしている」という意味なので、
            // stm の王をピンしている駒を取得するには pinners[stm] を使う(YOは pinners[~stm])
            if !(self.state().pinners[stm.index()] & occupied).is_empty() {
                stm_attackers &= !self.blockers_for_king(stm);
                if stm_attackers.is_empty() {
                    break;
                }
            }

            res ^= 1;

            // 最も価値の低い攻撃駒を選択
            let (attacker_sq, attacker_value) =
                self.least_valuable_attacker(stm_attackers, stm, to, occupied);

            // YO: swap = PieceValue[pt] - swap; if (swap < res) break;
            swap = attacker_value - swap;
            if swap < res {
                break;
            }

            // 玉で取る場合の特別処理
            if attacker_value == see_piece_value(PieceType::King) {
                return if !(attackers & self.pieces_c(!stm)).is_empty() {
                    res ^ 1 != 0
                } else {
                    res != 0
                };
            }

            // 駒をoccupiedから取り除く
            occupied ^= Bitboard::from_square(attacker_sq);

            // X-ray攻撃の追加: attacker_sqが遮っていた背後の駒を追加
            if let Some(dir) = direct_of(to, attacker_sq) {
                let ray = ray_effect(dir, to, occupied);
                let extras = match dir {
                    Direct::RU | Direct::RD | Direct::LU | Direct::LD => {
                        ray & (self.pieces_pt(PieceType::Bishop) | self.pieces_pt(PieceType::Horse))
                    }
                    Direct::U => {
                        let rookers =
                            self.pieces_pt(PieceType::Rook) | self.pieces_pt(PieceType::Dragon);
                        let lance = self.pieces(Color::White, PieceType::Lance);
                        ray & (rookers | lance)
                    }
                    Direct::D => {
                        let rookers =
                            self.pieces_pt(PieceType::Rook) | self.pieces_pt(PieceType::Dragon);
                        let lance = self.pieces(Color::Black, PieceType::Lance);
                        ray & (rookers | lance)
                    }
                    Direct::L | Direct::R => {
                        ray & (self.pieces_pt(PieceType::Rook) | self.pieces_pt(PieceType::Dragon))
                    }
                };
                attackers |= extras;
            }
        }

        res != 0
    }

    /// 最も価値の低い攻撃駒を探す(YO準拠: 成りは考慮しない)
    fn least_valuable_attacker(
        &self,
        attackers: Bitboard,
        stm: Color,
        _to: Square,
        _occupied: Bitboard,
    ) -> (Square, i32) {
        // YO準拠: 価値の低い順にチェック(成り考慮なし)
        // Pawn(90) → Lance(315) → Knight(405) → Silver(495)
        // → GOLDS(540): Gold,ProPawn,ProLance,ProKnight,ProSilver
        // → Bishop(855) → Rook(990) → Horse(945) → Dragon(1395) → King
        // 注: Rook(990)がHorse(945)より先はYO準拠(価値昇順ではない)

        // Pawn
        let bb = attackers & self.pieces(stm, PieceType::Pawn);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Pawn));
        }
        // Lance
        let bb = attackers & self.pieces(stm, PieceType::Lance);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Lance));
        }
        // Knight
        let bb = attackers & self.pieces(stm, PieceType::Knight);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Knight));
        }
        // Silver (495 < Gold 540)
        let bb = attackers & self.pieces(stm, PieceType::Silver);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Silver));
        }
        // GOLDS (Gold, ProPawn, ProLance, ProKnight, ProSilver) — すべて540
        for pt in [
            PieceType::Gold,
            PieceType::ProPawn,
            PieceType::ProLance,
            PieceType::ProKnight,
            PieceType::ProSilver,
        ] {
            let bb = attackers & self.pieces(stm, pt);
            if !bb.is_empty() {
                return (bb.lsb().unwrap(), see_piece_value(PieceType::Gold));
            }
        }
        // Bishop (855)
        let bb = attackers & self.pieces(stm, PieceType::Bishop);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Bishop));
        }
        // YaneuraOu準拠: Rook(990) を Horse(945) より先に選択 (yaneuraou-search.cpp:2632-2669)
        // 価値昇順ではないが、YOとのノード数一致のために順序を合わせる
        // Rook (990)
        let bb = attackers & self.pieces(stm, PieceType::Rook);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Rook));
        }
        // Horse (945)
        let bb = attackers & self.pieces(stm, PieceType::Horse);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Horse));
        }
        // Dragon
        let bb = attackers & self.pieces(stm, PieceType::Dragon);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::Dragon));
        }
        // King
        let bb = attackers & self.pieces(stm, PieceType::King);
        if !bb.is_empty() {
            return (bb.lsb().unwrap(), see_piece_value(PieceType::King));
        }

        unreachable!(
            "least_valuable_attacker should always find an attacker when attackers is non-empty"
        );
    }
}

// =============================================================================
// ヘルパー関数
// =============================================================================

/// SEE用の駒価値(YO準拠)
fn see_piece_value(pt: PieceType) -> i32 {
    use PieceType::*;
    match pt {
        Pawn => 90,
        Lance => 315,
        Knight => 405,
        Silver => 495,
        Gold | ProPawn | ProLance | ProKnight | ProSilver => 540,
        Bishop => 855,
        Horse => 945,
        Rook => 990,
        Dragon => 1395,
        King => 15000,
    }
}

// 【参考実装】成らない手の制限用ヘルパー関数
// pseudo_legal 内のコメントアウトされた実装で使用する。
//
// /// 敵陣かどうか(1-3段目/7-9段目)
// #[inline]
// fn is_enemy_field(us: Color, sq: Square) -> bool {
//     match us {
//         Color::Black => sq.rank().index() < 3,
//         Color::White => sq.rank().index() > 5,
//     }
// }
//
// /// 深い敵陣かどうか(1-2段目/8-9段目)- 香の不成禁止用
// #[inline]
// fn is_deep_enemy_field(us: Color, sq: Square) -> bool {
//     match us {
//         Color::Black => sq.rank().index() < 2,
//         Color::White => sq.rank().index() > 6,
//     }
// }

// =============================================================================
// テスト
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{File, Rank};

    #[test]
    fn test_moved_piece() {
        let mut pos = Position::new();
        pos.set_hirate();

        // 7六歩
        let m = Move::from_usi("7g7f").unwrap();
        let pc = pos.moved_piece(m);
        assert_eq!(pc, Piece::B_PAWN);

        // 駒打ち
        let drop = Move::new_drop(PieceType::Pawn, Square::new(File::File5, Rank::Rank5));
        // 手駒に歩を追加してテスト
        pos.hand[Color::Black.index()] = pos.hand[Color::Black.index()].add(PieceType::Pawn);
        let pc_drop = pos.moved_piece(drop);
        assert_eq!(pc_drop, Piece::B_PAWN);
    }

    #[test]
    fn test_is_capture() {
        let mut pos = Position::new();
        let sq76 = Square::new(File::File7, Rank::Rank6);
        let sq75 = Square::new(File::File7, Rank::Rank5);
        let sq77 = Square::new(File::File7, Rank::Rank7);
        let sq59 = Square::new(File::File5, Rank::Rank9);
        let sq51 = Square::new(File::File5, Rank::Rank1);

        pos.put_piece(Piece::B_PAWN, sq77);
        pos.put_piece(Piece::W_PAWN, sq75);
        pos.put_piece(Piece::B_KING, sq59);
        pos.put_piece(Piece::W_KING, sq51);
        pos.king_square[Color::Black.index()] = sq59;
        pos.king_square[Color::White.index()] = sq51;

        // 7六歩(取らない)
        let m1 = Move::new_move(sq77, sq76, false);
        assert!(!pos.is_capture(m1));

        // 配置を変更
        pos.board[sq77.index()] = Piece::NONE;
        pos.put_piece(Piece::B_PAWN, sq76);

        // 7五歩(取る)
        let m2 = Move::new_move(sq76, sq75, false);
        assert!(pos.is_capture(m2));

        // 駒打ち
        pos.hand[Color::Black.index()] = pos.hand[Color::Black.index()].add(PieceType::Gold);
        let drop = Move::new_drop(PieceType::Gold, Square::new(File::File5, Rank::Rank5));
        assert!(!pos.is_capture(drop));
    }

    #[test]
    fn test_pseudo_legal_basic() {
        let mut pos = Position::new();
        pos.set_hirate();

        // 7六歩 - 合法
        let m1 = Move::from_usi("7g7f").unwrap();
        assert!(pos.pseudo_legal(m1));

        // 7五歩 - 2マス進む(違法)
        let m2 = Move::from_usi("7g7e").unwrap();
        assert!(!pos.pseudo_legal(m2));

        // 空マスから動く
        let sq55 = Square::new(File::File5, Rank::Rank5);
        let sq54 = Square::new(File::File5, Rank::Rank4);
        let m3 = Move::new_move(sq55, sq54, false);
        assert!(!pos.pseudo_legal(m3));
    }

    #[test]
    fn test_see_ge_simple_capture() {
        let mut pos = Position::new();
        let sq55 = Square::new(File::File5, Rank::Rank5);
        let sq54 = Square::new(File::File5, Rank::Rank4);
        let sq59 = Square::new(File::File5, Rank::Rank9);
        let sq51 = Square::new(File::File5, Rank::Rank1);

        // 5五に先手歩、5四に後手金
        pos.put_piece(Piece::B_PAWN, sq55);
        pos.put_piece(Piece::W_GOLD, sq54);
        pos.put_piece(Piece::B_KING, sq59);
        pos.put_piece(Piece::W_KING, sq51);
        pos.king_square[Color::Black.index()] = sq59;
        pos.king_square[Color::White.index()] = sq51;

        // 5四歩(金を取る)→ 金の価値を得る
        let m = Move::new_move(sq55, sq54, false);
        assert!(pos.see_ge(m, Value::new(0)));
        assert!(pos.see_ge(m, Value::new(400))); // 金(540) - 歩(90) = 450 > 400
    }

    #[test]
    fn test_pawn_history_index() {
        let mut pos = Position::new();
        pos.set_hirate();

        let idx = pos.pawn_history_index();
        assert!(idx < crate::search::PAWN_HISTORY_SIZE);
    }

    /// X-ray攻撃のテスト: to を占有から外さないと誤って得と判定されるケース
    ///
    /// 配置(先手番):
    /// - 5四: 先手歩(from)
    /// - 5五: 後手歩(to)
    /// - 5八: 後手飛
    ///
    /// 5四歩で5五の歩を取ると、後手飛のX-rayが通り交換は損。
    /// to を占有から外さない旧実装では飛車の利きが見えず、SEE が誤って true になる。
    #[test]
    fn test_see_xray_attack() {
        let mut pos = Position::new();
        let from = Square::new(File::File5, Rank::Rank4);
        let to = Square::new(File::File5, Rank::Rank5);
        let rook_sq = Square::new(File::File5, Rank::Rank8);
        let b_king = Square::new(File::File1, Rank::Rank9);
        let w_king = Square::new(File::File9, Rank::Rank1);

        pos.put_piece(Piece::B_PAWN, from);
        pos.put_piece(Piece::W_PAWN, to);
        pos.put_piece(Piece::W_ROOK, rook_sq);
        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;

        let m = Move::new_move(from, to, false);

        assert!(!pos.see_ge(m, Value::new(80)), "X-ray rook should make the capture unfavorable");
    }

    /// 斜めラインのX-ray攻撃テスト(角)
    #[test]
    fn test_see_xray_attack_diagonal() {
        let mut pos = Position::new();
        let from = Square::new(File::File3, Rank::Rank3);
        let to = Square::new(File::File4, Rank::Rank4);
        let bishop_sq = Square::new(File::File7, Rank::Rank7);
        let b_king = Square::new(File::File1, Rank::Rank9);
        let w_king = Square::new(File::File9, Rank::Rank1);

        pos.put_piece(Piece::B_PAWN, from);
        pos.put_piece(Piece::W_PAWN, to);
        pos.put_piece(Piece::W_BISHOP, bishop_sq);
        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;

        let m = Move::new_move(from, to, false);

        assert!(
            !pos.see_ge(m, Value::new(80)),
            "Diagonal x-ray should make the capture unfavorable"
        );
    }

    /// 成りフラグ検証テスト: 成れない駒(金)に成りフラグが立っている手は pseudo_legal で弾く
    #[test]
    fn test_pseudo_legal_rejects_invalid_promote_on_gold() {
        let mut pos = Position::new();
        let from = Square::new(File::File5, Rank::Rank9);
        let to = Square::new(File::File5, Rank::Rank8);
        let king_sq = Square::new(File::File1, Rank::Rank9);
        let enemy_king = Square::new(File::File1, Rank::Rank1);

        pos.put_piece(Piece::B_GOLD, from);
        pos.put_piece(Piece::B_KING, king_sq);
        pos.put_piece(Piece::W_KING, enemy_king);
        pos.king_square[Color::Black.index()] = king_sq;
        pos.king_square[Color::White.index()] = enemy_king;

        // 金に成りフラグを付けた不正な手
        let invalid_promote = Move::new_move(from, to, true);
        assert!(!pos.pseudo_legal(invalid_promote), "Gold with promote flag should be rejected");

        // 金の通常移動は許可
        let valid_move = Move::new_move(from, to, false);
        assert!(pos.pseudo_legal(valid_move), "Gold normal move should be allowed");
    }

    /// 成りフラグ検証テスト: 既に成駒(龍)に成りフラグが立っている手は pseudo_legal で弾く
    #[test]
    fn test_pseudo_legal_rejects_invalid_promote_on_promoted_piece() {
        let mut pos = Position::new();
        let from = Square::new(File::File5, Rank::Rank5);
        let to = Square::new(File::File5, Rank::Rank4);
        let king_sq = Square::new(File::File1, Rank::Rank9);
        let enemy_king = Square::new(File::File1, Rank::Rank1);

        pos.put_piece(Piece::B_DRAGON, from);
        pos.put_piece(Piece::B_KING, king_sq);
        pos.put_piece(Piece::W_KING, enemy_king);
        pos.king_square[Color::Black.index()] = king_sq;
        pos.king_square[Color::White.index()] = enemy_king;

        // 龍に成りフラグを付けた不正な手
        let invalid_promote = Move::new_move(from, to, true);
        assert!(
            !pos.pseudo_legal(invalid_promote),
            "Dragon with promote flag should be rejected"
        );
    }

    /// 成りフラグ検証テスト: 敵陣外での成りは pseudo_legal で弾く
    #[test]
    fn test_pseudo_legal_rejects_promote_outside_enemy_zone() {
        let mut pos = Position::new();
        // 先手の銀を5五に置く(敵陣外)
        let from = Square::new(File::File5, Rank::Rank5);
        let to = Square::new(File::File5, Rank::Rank4); // 移動先も敵陣外
        let king_sq = Square::new(File::File1, Rank::Rank9);
        let enemy_king = Square::new(File::File1, Rank::Rank1);

        pos.put_piece(Piece::B_SILVER, from);
        pos.put_piece(Piece::B_KING, king_sq);
        pos.put_piece(Piece::W_KING, enemy_king);
        pos.king_square[Color::Black.index()] = king_sq;
        pos.king_square[Color::White.index()] = enemy_king;

        // 敵陣外での成りは不正
        let invalid_promote = Move::new_move(from, to, true);
        assert!(
            !pos.pseudo_legal(invalid_promote),
            "Promote outside enemy zone should be rejected"
        );
    }

    /// 成りフラグ検証テスト: 敵陣内での成りは許可
    #[test]
    fn test_pseudo_legal_allows_promote_in_enemy_zone() {
        let mut pos = Position::new();
        // 先手の銀を3四に置く(敵陣外だが移動先が敵陣内)
        let from = Square::new(File::File3, Rank::Rank4);
        let to = Square::new(File::File3, Rank::Rank3); // 移動先が敵陣
        let king_sq = Square::new(File::File1, Rank::Rank9);
        let enemy_king = Square::new(File::File1, Rank::Rank1);

        pos.put_piece(Piece::B_SILVER, from);
        pos.put_piece(Piece::B_KING, king_sq);
        pos.put_piece(Piece::W_KING, enemy_king);
        pos.king_square[Color::Black.index()] = king_sq;
        pos.king_square[Color::White.index()] = enemy_king;

        // 敵陣内への成りは正当
        let valid_promote = Move::new_move(from, to, true);
        assert!(pos.pseudo_legal(valid_promote), "Promote into enemy zone should be allowed");
    }

    // =========================================================================
    // 王手中の pseudo_legal テスト
    // =========================================================================

    /// 両王手時は駒打ち不可
    #[test]
    fn test_pseudo_legal_drop_double_check() {
        let mut pos = Position::new();

        // 配置: 先手玉59、後手玉51、後手飛55(縦の王手)、後手角77(斜めの王手)
        // → 両王手なので合駒不可
        let b_king = Square::new(File::File5, Rank::Rank9);
        let w_king = Square::new(File::File5, Rank::Rank1);
        let w_rook = Square::new(File::File5, Rank::Rank5);
        let w_bishop = Square::new(File::File7, Rank::Rank7);

        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.put_piece(Piece::W_ROOK, w_rook);
        pos.put_piece(Piece::W_BISHOP, w_bishop);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;
        // checkers を手動で設定(テスト用)
        let king_sq = pos.king_square(Color::Black);
        let checkers = pos.attackers_to(king_sq) & pos.pieces_c(Color::White);
        pos.state_stack.last_mut().unwrap().checkers = checkers;

        // 手駒に金を追加
        pos.hand[Color::Black.index()] = pos.hand[Color::Black.index()].add(PieceType::Gold);

        // 両王手なので、どこに打っても不可
        let drop_56 = Move::new_drop(PieceType::Gold, Square::new(File::File5, Rank::Rank6));
        let drop_68 = Move::new_drop(PieceType::Gold, Square::new(File::File6, Rank::Rank8));
        assert!(!pos.pseudo_legal(drop_56), "Drop should be illegal during double check");
        assert!(!pos.pseudo_legal(drop_68), "Drop should be illegal during double check");
    }

    /// 飛車による王手で合駒可能(王と王手駒の間に打つ)
    #[test]
    fn test_pseudo_legal_drop_interpose_rook() {
        let mut pos = Position::new();

        // 配置: 先手玉59、後手玉51、後手飛55(縦の王手)
        let b_king = Square::new(File::File5, Rank::Rank9);
        let w_king = Square::new(File::File5, Rank::Rank1);
        let w_rook = Square::new(File::File5, Rank::Rank5);

        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.put_piece(Piece::W_ROOK, w_rook);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;
        // checkers を手動で設定(テスト用)
        let king_sq = pos.king_square(Color::Black);
        let checkers = pos.attackers_to(king_sq) & pos.pieces_c(Color::White);
        pos.state_stack.last_mut().unwrap().checkers = checkers;

        // 手駒に金を追加
        pos.hand[Color::Black.index()] = pos.hand[Color::Black.index()].add(PieceType::Gold);

        // 王と飛車の間(56, 57, 58)に打つのは合法
        let drop_56 = Move::new_drop(PieceType::Gold, Square::new(File::File5, Rank::Rank6));
        let drop_57 = Move::new_drop(PieceType::Gold, Square::new(File::File5, Rank::Rank7));
        let drop_58 = Move::new_drop(PieceType::Gold, Square::new(File::File5, Rank::Rank8));
        assert!(pos.pseudo_legal(drop_56), "Drop at 56 should be legal (interpose)");
        assert!(pos.pseudo_legal(drop_57), "Drop at 57 should be legal (interpose)");
        assert!(pos.pseudo_legal(drop_58), "Drop at 58 should be legal (interpose)");

        // 王と飛車の間以外(例: 45)に打つのは不可
        let drop_45 = Move::new_drop(PieceType::Gold, Square::new(File::File4, Rank::Rank5));
        assert!(!pos.pseudo_legal(drop_45), "Drop at 45 should be illegal (not interposing)");
    }

    /// 桂馬による王手では合駒不可(between_bb が空)
    #[test]
    fn test_pseudo_legal_drop_knight_check() {
        let mut pos = Position::new();

        // 配置: 先手玉59、後手玉51、後手桂47(桂馬の王手)
        let b_king = Square::new(File::File5, Rank::Rank9);
        let w_king = Square::new(File::File5, Rank::Rank1);
        let w_knight = Square::new(File::File4, Rank::Rank7);

        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.put_piece(Piece::W_KNIGHT, w_knight);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;
        // checkers を手動で設定(テスト用)
        let king_sq = pos.king_square(Color::Black);
        let checkers = pos.attackers_to(king_sq) & pos.pieces_c(Color::White);
        pos.state_stack.last_mut().unwrap().checkers = checkers;

        // 手駒に金を追加
        pos.hand[Color::Black.index()] = pos.hand[Color::Black.index()].add(PieceType::Gold);

        // 桂馬の王手は合駒不可(between_bb が空)
        let drop_48 = Move::new_drop(PieceType::Gold, Square::new(File::File4, Rank::Rank8));
        let drop_58 = Move::new_drop(PieceType::Gold, Square::new(File::File5, Rank::Rank8));
        assert!(
            !pos.pseudo_legal(drop_48),
            "Drop should be illegal (knight check, no interpose)"
        );
        assert!(
            !pos.pseudo_legal(drop_58),
            "Drop should be illegal (knight check, no interpose)"
        );
    }

    /// 両王手時は玉以外の駒移動不可
    #[test]
    fn test_pseudo_legal_move_double_check() {
        let mut pos = Position::new();

        // 配置: 先手玉59、後手玉51、後手飛55(縦の王手)、後手角68(斜めの王手)、先手金78
        // 角68は59の玉に対して斜め方向から王手
        let b_king = Square::new(File::File5, Rank::Rank9);
        let w_king = Square::new(File::File5, Rank::Rank1);
        let w_rook = Square::new(File::File5, Rank::Rank5);
        let w_bishop = Square::new(File::File6, Rank::Rank8); // 59に対して斜め王手
        let b_gold = Square::new(File::File7, Rank::Rank8);

        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.put_piece(Piece::W_ROOK, w_rook);
        pos.put_piece(Piece::W_BISHOP, w_bishop);
        pos.put_piece(Piece::B_GOLD, b_gold);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;
        // checkers を手動で設定(テスト用)
        let king_sq = pos.king_square(Color::Black);
        let checkers = pos.attackers_to(king_sq) & pos.pieces_c(Color::White);
        pos.state_stack.last_mut().unwrap().checkers = checkers;

        // 両王手であることを確認
        assert!(
            checkers.count() >= 2,
            "Should be double check: checkers count = {}",
            checkers.count()
        );

        // 両王手なので金を動かしても不可(王手を遮断しても両王手は回避できない)
        let gold_move = Move::new_move(b_gold, Square::new(File::File6, Rank::Rank9), false);
        assert!(
            !pos.pseudo_legal(gold_move),
            "Non-king move should be illegal during double check"
        );
    }

    /// 王手中の駒移動(遮断)
    #[test]
    fn test_pseudo_legal_move_interpose() {
        let mut pos = Position::new();

        // 配置: 先手玉59、後手玉51、後手飛55、先手金68
        let b_king = Square::new(File::File5, Rank::Rank9);
        let w_king = Square::new(File::File5, Rank::Rank1);
        let w_rook = Square::new(File::File5, Rank::Rank5);
        let b_gold = Square::new(File::File6, Rank::Rank8);

        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.put_piece(Piece::W_ROOK, w_rook);
        pos.put_piece(Piece::B_GOLD, b_gold);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;
        // checkers を手動で設定(テスト用)
        let king_sq = pos.king_square(Color::Black);
        let checkers = pos.attackers_to(king_sq) & pos.pieces_c(Color::White);
        pos.state_stack.last_mut().unwrap().checkers = checkers;

        // 金を58に動かして遮断(合法)
        let gold_interpose = Move::new_move(b_gold, Square::new(File::File5, Rank::Rank8), false);
        assert!(pos.pseudo_legal(gold_interpose), "Gold move to interpose should be legal");

        // 金を67に動かす(遮断にならない、不合法)
        let gold_not_interpose =
            Move::new_move(b_gold, Square::new(File::File6, Rank::Rank7), false);
        assert!(
            !pos.pseudo_legal(gold_not_interpose),
            "Gold move not interposing should be illegal"
        );
    }

    /// 王手中の駒移動(王手駒を取る)
    #[test]
    fn test_pseudo_legal_move_capture_checker() {
        let mut pos = Position::new();

        // 配置: 先手玉59、後手玉51、後手飛55、先手金56
        let b_king = Square::new(File::File5, Rank::Rank9);
        let w_king = Square::new(File::File5, Rank::Rank1);
        let w_rook = Square::new(File::File5, Rank::Rank5);
        let b_gold = Square::new(File::File5, Rank::Rank6);

        pos.put_piece(Piece::B_KING, b_king);
        pos.put_piece(Piece::W_KING, w_king);
        pos.put_piece(Piece::W_ROOK, w_rook);
        pos.put_piece(Piece::B_GOLD, b_gold);
        pos.king_square[Color::Black.index()] = b_king;
        pos.king_square[Color::White.index()] = w_king;
        pos.side_to_move = Color::Black;
        // checkers を手動で設定(テスト用)
        let king_sq = pos.king_square(Color::Black);
        let checkers = pos.attackers_to(king_sq) & pos.pieces_c(Color::White);
        pos.state_stack.last_mut().unwrap().checkers = checkers;

        // 金で飛車を取る(合法)
        let gold_capture = Move::new_move(b_gold, w_rook, false);
        assert!(pos.pseudo_legal(gold_capture), "Gold capturing the checker should be legal");
    }
}