diff --git a/Chess/MoveGenerator.cpp b/Chess/MoveGenerator.cpp index 327acd5..50bf874 100644 --- a/Chess/MoveGenerator.cpp +++ b/Chess/MoveGenerator.cpp @@ -9,7 +9,7 @@ namespace SimpleChessEngine { template <> void MoveGenerator::GenerateMovesForPiece( - Move*& moves, Position& position, Bitboard target) const; + PseudoLegalMove*& moves, Position& position, Bitboard target) const; template MoveGenerator::Moves MoveGenerator::GenerateMoves< MoveGenerator::Type::kAll>(Position& position) const; @@ -18,7 +18,8 @@ template MoveGenerator::Moves MoveGenerator::GenerateMoves< MoveGenerator::~MoveGenerator() = default; -void MoveGenerator::GenerateCastling(Move*& moves, const Position& position) { +void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, + const Position& position) { if (position.IsUnderCheck()) { return; } @@ -32,13 +33,14 @@ void MoveGenerator::GenerateCastling(Move*& moves, const Position& position) { const auto side_idx = static_cast(castling_side); const auto king_to = kKingCastlingDestination[color_idx][side_idx]; - *moves++ = Move::Make(king_square, king_to); + *moves++ = PseudoLegalMove( + Move::Make(king_square, king_to)); } } } template -void MoveGenerator::GenerateMovesForPiece(Move*& moves, Position& position, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, const Bitboard target) const { static_assert(piece != Piece::kPawn && piece != Piece::kKing); @@ -53,7 +55,7 @@ void MoveGenerator::GenerateMovesForPiece(Move*& moves, Position& position, template <> void MoveGenerator::GenerateMovesForPiece( - Move*& moves, Position& position, const Bitboard target) const { + PseudoLegalMove*& moves, Position& position, const Bitboard target) const { const auto us = position.GetSideToMove(); const auto us_idx = static_cast(us); const auto them = Flip(us); @@ -78,7 +80,7 @@ void MoveGenerator::GenerateMovesForPiece( while (push.Any()) { const auto to = push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } auto double_push = Shift(double_push_pawns, direction) & valid_squares; @@ -87,7 +89,7 @@ void MoveGenerator::GenerateMovesForPiece( while (double_push.Any()) { const auto to = double_push.PopFirstBit(); const auto from = Shift(Shift(to, opposite_direction), opposite_direction); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } const auto attacks = @@ -114,7 +116,7 @@ void MoveGenerator::GenerateMovesForPiece( while (attack_squares.Any()) { const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } } @@ -127,7 +129,7 @@ void MoveGenerator::GenerateMovesForPiece( if (attack_to.Any()) { const auto to = en_croissant_square.value(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = Move::Make(from, to); + *moves++ = PseudoLegalMove(Move::Make(from, to)); } } } @@ -141,10 +143,14 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = promotion_push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = Move::Make(from, to, Piece::kQueen); - *moves++ = Move::Make(from, to, Piece::kKnight); - *moves++ = Move::Make(from, to, Piece::kRook); - *moves++ = Move::Make(from, to, Piece::kBishop); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kQueen)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kKnight)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kRook)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kBishop)); } for (size_t attack_direction = 0; attack_direction < attacks.size(); @@ -156,17 +162,21 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = Move::Make(from, to, Piece::kQueen); - *moves++ = Move::Make(from, to, Piece::kKnight); - *moves++ = Move::Make(from, to, Piece::kRook); - *moves++ = Move::Make(from, to, Piece::kBishop); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kQueen)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kKnight)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kRook)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kBishop)); } } } template -Move* MoveGenerator::GeneratePseudoLegal(Position& position, - Move* moves) const { +PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, + PseudoLegalMove* moves) const { const auto us = position.GetSideToMove(); const auto them = Flip(us); auto target = ~position.GetPieces(us); @@ -227,37 +237,39 @@ Move* MoveGenerator::GeneratePseudoLegal(Position& position, template MoveGenerator::Moves MoveGenerator::GenerateMoves(Position& position) const { - std::array moves; + std::array moves; auto* end = GeneratePseudoLegal(position, moves.data()); position.ComputePins(position.GetSideToMove()); Moves legal; legal.reserve(end - moves.data()); for (auto* p = moves.data(); p != end; ++p) { - if (position.IsLegal(*p)) legal.push_back(*p); + if (position.IsLegal(*p)) legal.push_back(LegalMove(static_cast(*p))); } return legal; } bool MoveGenerator::HasLegalMove(Position& position) const { - std::array moves; + std::array moves; auto* end = GeneratePseudoLegal(position, moves.data()); position.ComputePins(position.GetSideToMove()); return std::any_of(moves.data(), end, - [&position](Move move) { return position.IsLegal(move); }); + [&position](Move move) { + return position.IsLegal(move); + }); } -template Move* MoveGenerator::GeneratePseudoLegal( - Position&, Move*) const; -template Move* +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( + Position&, PseudoLegalMove*) const; +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position&, - Move*) const; -template Move* MoveGenerator::GeneratePseudoLegal( - Position&, Move*) const; -template Move* MoveGenerator::GeneratePseudoLegal< - MoveGenerator::Type::kQuiescence>(Position&, Move*) const; + PseudoLegalMove*) const; +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( + Position&, PseudoLegalMove*) const; +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal< + MoveGenerator::Type::kQuiescence>(Position&, PseudoLegalMove*) const; template <> -void MoveGenerator::GenerateMovesForPiece(Move*& moves, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, Bitboard target) const { GenerateMovesFromSquare( @@ -266,7 +278,7 @@ void MoveGenerator::GenerateMovesForPiece(Move*& moves, } template -void MoveGenerator::GenerateMovesFromSquare(Move*& moves, Position& position, +void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, const BitIndex from, Bitboard target) const { assert(position.GetPieceAt(from) == piece); @@ -280,7 +292,7 @@ void MoveGenerator::GenerateMovesFromSquare(Move*& moves, Position& position, while (valid_moves.Any()) { const auto to = valid_moves.PopFirstBit(); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } } } // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.h b/Chess/MoveGenerator.h index 8738a66..8092ac1 100644 --- a/Chess/MoveGenerator.h +++ b/Chess/MoveGenerator.h @@ -25,7 +25,7 @@ class MoveGenerator { MoveGenerator() = default; ~MoveGenerator(); - using Moves = std::vector; + using Moves = std::vector; /** * \brief Generates all possible moves for a given position. @@ -38,8 +38,13 @@ class MoveGenerator { [[nodiscard]] Moves GenerateMoves(Position& position) const; template - [[nodiscard]] Move* GeneratePseudoLegal(Position& position, - Move* moves) const; + [[nodiscard, gnu::always_inline]] Moves GenerateLegalMoves(Position& position) const { + return GenerateMoves(position); + } + + template + [[nodiscard]] PseudoLegalMove* GeneratePseudoLegal(Position& position, + PseudoLegalMove* moves) const; [[nodiscard]] bool HasLegalMove(Position& position) const; @@ -54,7 +59,7 @@ class MoveGenerator { * \return All possible moves for the given square. */ template - void GenerateMovesForPiece(Move*& moves, Position& position, + void GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, Bitboard target) const; /** @@ -69,10 +74,10 @@ class MoveGenerator { * \return All possible moves for the given square and piece. */ template - void GenerateMovesFromSquare(Move*& moves, Position& position, BitIndex from, + void GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, BitIndex from, Bitboard target) const; - static void GenerateCastling(Move*& moves, const Position& position); + static void GenerateCastling(PseudoLegalMove*& moves, const Position& position); }; } // namespace SimpleChessEngine diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index 8741456..fa320f3 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -61,9 +61,9 @@ void MovePicker::InitPicker(Position& position, const Searcher* searcher, } void MovePicker::Generate(bool quiet) { - std::array generated; + std::array generated; auto* begin = generated.data(); - Move* end; + PseudoLegalMove* end; const MoveGenerator generator; if (quiet) { end = generator.GeneratePseudoLegal( @@ -114,29 +114,29 @@ void MovePicker::InitProbCut(Position& position, const Searcher* searcher, Generate(false); } -Move MovePicker::SelectProbCutMove(Eval see_threshold) { +MaybeLegalMove MovePicker::SelectProbCutMove(Eval see_threshold) { while (current_ < end_) { const auto move = moves_[current_++].move; if (move.IsPromotion() && move.PromotionPiece() != Piece::kQueen) continue; if (position_->IsLegal(move, blockers_) && position_->StaticExchangeEvaluation(move, see_threshold)) - return Emit(move); + return Emit(Position::AssumeLegal(move)); } - return Move::None(); + return MaybeLegalMove::None(); } -Move MovePicker::Emit(Move move) { +LegalMove MovePicker::Emit(LegalMove move) { ++move_count_; return move; } -Move MovePicker::SelectNextMove() { +MaybeLegalMove MovePicker::SelectNextMove() { for (;;) { switch (stage_) { case Stage::kTT: stage_ = Stage::kCaptureInit; if (tt_move_.IsValid() && position_->IsLegal(tt_move_, blockers_)) - return Emit(tt_move_); + return Emit(Position::AssumeLegal(tt_move_)); break; case Stage::kCaptureInit: Generate(false); @@ -146,14 +146,14 @@ Move MovePicker::SelectNextMove() { while (current_ < end_) { const auto candidate = moves_[current_++]; if (!position_->IsLegal(candidate.move, blockers_)) continue; - if (!searcher_) return Emit(candidate.move); + if (!searcher_) return Emit(Position::AssumeLegal(candidate.move)); const auto promotion = candidate.move.IsPromotion() ? candidate.move.PromotionPiece() : Piece::kNone; if (!IsUnderpromotion(promotion) && position_->StaticExchangeEvaluation(candidate.move, kGoodCaptureThreshold)) - return Emit(candidate.move); + return Emit(Position::AssumeLegal(candidate.move)); moves_[bad_end_++] = candidate; } stage_ = searcher_ ? Stage::kKillers : Stage::kEnd; @@ -175,7 +175,7 @@ Move MovePicker::SelectNextMove() { found->move = Move::None(); } killers_[index] = move; - return Emit(move); + return Emit(Position::AssumeLegal(move)); } stage_ = Stage::kQuietInit; break; @@ -187,7 +187,8 @@ Move MovePicker::SelectNextMove() { case Stage::kQuiet: while (current_ < end_) { const auto move = moves_[current_++].move; - if (position_->IsLegal(move, blockers_)) return Emit(move); + if (position_->IsLegal(move, blockers_)) + return Emit(Position::AssumeLegal(move)); } current_ = 0; end_ = bad_end_; @@ -196,12 +197,12 @@ Move MovePicker::SelectNextMove() { case Stage::kBadCaptures: while (current_ < end_) { const auto move = moves_[current_++].move; - if (move.IsValid()) return Emit(move); + if (move.IsValid()) return Emit(Position::AssumeLegal(move)); } stage_ = Stage::kEnd; break; case Stage::kEnd: - return Move::None(); + return MaybeLegalMove::None(); } } } diff --git a/Chess/MovePicker.h b/Chess/MovePicker.h index 8451342..55cd295 100644 --- a/Chess/MovePicker.h +++ b/Chess/MovePicker.h @@ -28,8 +28,8 @@ class MovePicker { Move tt_move = Move::None(), Move excluded_move = Move::None()); void InitProbCut(Position& position, const Searcher* searcher, Depth ply); - [[nodiscard]] Move SelectProbCutMove(Eval see_threshold); - [[nodiscard]] Move SelectNextMove(); + [[nodiscard]] MaybeLegalMove SelectProbCutMove(Eval see_threshold); + [[nodiscard]] MaybeLegalMove SelectNextMove(); [[nodiscard]] Stage GetCurrentStage() const { return stage_; } [[nodiscard]] std::ptrdiff_t MoveCount() const { return move_count_; } @@ -43,7 +43,7 @@ class MovePicker { static void PartialInsertionSort(ScoredMove* begin, ScoredMove* end, std::int64_t limit); void Generate(bool quiet); - [[nodiscard]] Move Emit(Move move); + [[nodiscard]] LegalMove Emit(LegalMove move); std::array moves_; std::array killers_{}; diff --git a/Chess/Perft.cpp b/Chess/Perft.cpp index 5c95aa5..60de08a 100644 --- a/Chess/Perft.cpp +++ b/Chess/Perft.cpp @@ -13,7 +13,7 @@ size_t Perft(std::ostream& o_stream, Position& position, const Depth depth) { static auto move_generator = MoveGenerator{}; const auto moves = - move_generator.GenerateMoves(position); + move_generator.GenerateLegalMoves(position); size_t answer{}; diff --git a/Chess/Position.cpp b/Chess/Position.cpp index 8fba398..e6d7100 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -204,7 +204,7 @@ bool Position::VerifyIncrementalState() const { incremental.positional == scratch.positional; } -void Position::DoMove(const Move &move) { +void Position::DoMove(const LegalMove &move) { irreversible_data_.pins_valid = {}; if (const auto &ep_square = irreversible_data_.en_croissant_square; ep_square.has_value()) { @@ -401,7 +401,7 @@ void SimpleChessEngine::Position::DoMove(NullMove) { } -void Position::UndoMove(const Move &move, const IrreversibleData &data) { +void Position::UndoMove(const LegalMove &move, const IrreversibleData &data) { const auto &ep_square = irreversible_data_.en_croissant_square; for (const auto color : {Player::kWhite, Player::kBlack}) { hash_ ^= hasher_.cr_hash[static_cast( @@ -509,11 +509,11 @@ bool Position::IsPseudoLegal(const Move &move) { const auto to = move.To(); if (!GetPieces(side_to_move_).Test(from)) return false; if (!move.IsNormal()) { - std::array moves; + std::array moves; const auto *end = MoveGenerator{}.GeneratePseudoLegal( *this, moves.data()); - return std::find(static_cast(moves.data()), end, move) != end; + return std::find(static_cast(moves.data()), end, move) != end; } if ((move.Raw() & 0x3000) || from == to || GetPieces(side_to_move_).Test(to)) return false; diff --git a/Chess/Position.h b/Chess/Position.h index a3641b5..f76e0c2 100644 --- a/Chess/Position.h +++ b/Chess/Position.h @@ -7,7 +7,7 @@ #include "BitBoard.h" #include "Evaluation.h" #include "Hasher.h" -#include "Move.h" +#include "TypedMove.h" #include "Nnue/Accumulator.h" #include "Nnue/Nnue.h" #include "Piece.h" @@ -129,18 +129,35 @@ class Position { * * \param move Move to do. */ - void DoMove(const Move &move); + void DoMove(const LegalMove &move); /** * \brief Undoes given move. * * \param move Move to undo. */ - void UndoMove(const Move &move, const IrreversibleData &data); + void UndoMove(const LegalMove &move, const IrreversibleData &data); void DoMove(NullMove); void UndoMove(NullMove, const IrreversibleData &data); + [[nodiscard, gnu::always_inline]] MaybePseudoLegalMove TryPseudoLegal(const Move& move) { + return IsPseudoLegal(move) ? MaybePseudoLegalMove(PseudoLegalMove(move)) + : MaybePseudoLegalMove::None(); + } + + [[nodiscard, gnu::always_inline]] std::optional TryLegal(const PseudoLegalMove& move) { + ComputePins(GetSideToMove()); + if (!IsLegal(move)) return std::nullopt; + return LegalMove(move); + } + + [[nodiscard, gnu::always_inline]] std::optional TryLegal( + const PseudoLegalMove& move, Bitboard blockers) const { + if (!IsLegal(move, blockers)) return std::nullopt; + return LegalMove(move); + } + [[nodiscard]] bool CanPseudoCastle(CastlingSide side) const; [[nodiscard]] bool IsPseudoLegal(const Move &move); [[nodiscard]] bool IsLegal(const Move &move) const; @@ -288,6 +305,9 @@ class Position { } private: + friend class MovePicker; + static constexpr LegalMove AssumeLegal(Move move) { return LegalMove(move); } + /** * \brief Places a piece with a color on a chosen square. * diff --git a/Chess/Quiescence.cpp b/Chess/Quiescence.cpp index 0f9edae..886ccb1 100644 --- a/Chess/Quiescence.cpp +++ b/Chess/Quiescence.cpp @@ -78,8 +78,8 @@ SearchResult Quiescence::Search(Position& current_position, : Move::None(); MovePicker picker; picker.InitPicker(current_position, nullptr, current_depth, tt_move); - auto move = picker.SelectNextMove(); - if (!move.IsValid() && !move_generator_.HasLegalMove(current_position)) { + auto next = picker.SelectNextMove(); + if (!next.IsValid() && !move_generator_.HasLegalMove(current_position)) { return kDrawValue; } @@ -105,7 +105,8 @@ SearchResult Quiescence::Search(Position& current_position, alpha = std::max(alpha, best_value); - for (; move.IsValid(); move = picker.SelectNextMove()) { + for (; next.IsValid(); next = picker.SelectNextMove()) { + const auto& move = *next; if (!current_position.StaticExchangeEvaluation( move, std::max(1, alpha - stand_pat - kSEEMargin))) { continue; @@ -149,14 +150,15 @@ SearchResult Quiescence::SearchUnderCheck( Move& best_move) { MovePicker picker; picker.InitPicker(current_position, nullptr, current_depth, tt_move); - auto move = picker.SelectNextMove(); - if (!move.IsValid()) { + auto next = picker.SelectNextMove(); + if (!next.IsValid()) { return Score::MatedIn( static_cast(std::min(current_depth, kMaxSearchPly))); } Eval best_value = -Score::kMate; - for (; move.IsValid(); move = picker.SelectNextMove()) { + for (; next.IsValid(); next = picker.SelectNextMove()) { + const auto& move = *next; const auto irreversible_data = current_position.GetIrreversibleData(); // make the move and search the tree diff --git a/Chess/SearchImplementation.h b/Chess/SearchImplementation.h index abfb2dc..9b56206 100644 --- a/Chess/SearchImplementation.h +++ b/Chess/SearchImplementation.h @@ -100,9 +100,9 @@ struct SearchNode { template SearchResult SearchChild(const PlayedMove &move, SearchState child_state); template - SearchResult ProbeMove(const Move &move); + SearchResult ProbeMove(const LegalMove &move); template - NodeExit SearchFirstMove(const Move &move); + NodeExit SearchFirstMove(const LegalMove &move); [[nodiscard]] bool CanRFP() const; [[nodiscard]] bool CanLateMovePrune() const; @@ -110,13 +110,14 @@ struct SearchNode { [[nodiscard]] bool PassesSEEPruning(const Move &move, bool is_quiet) const; NodeExit TryProbCut(); - SearchResult SearchProbCutMove(const Move &move, Eval probcut_beta, + SearchResult SearchProbCutMove(const LegalMove &move, Eval probcut_beta, Depth child_depth); bool ProbeTranspositionTable(); NodeExit TrySingularExtension(); SearchResult PVSearch(); - SearchResult SearchLateMove(int reduction); + SearchResult SearchLateMove(const LegalMove &move, bool is_quiet, + int reduction); [[nodiscard]] bool CanNullMove() const requires(node_type == NodeType::kCut); @@ -299,7 +300,7 @@ SearchResult SearchNode::operator()() { return GetEndGameScore(); } if (const auto exit = - SearchFirstMove(first_move)) { + SearchFirstMove(*first_move)) { return exit.Result(); } @@ -336,8 +337,9 @@ NodeExit SearchNode::TryProbCut() { ++searcher_.debug_info_.probcut_tries; move_picker_.InitProbCut(GetCurrentPosition(), &searcher_, state_.ply); const Eval see_threshold = probcut_beta - GetStaticEval(); - for (auto move = move_picker_.SelectProbCutMove(see_threshold); - move.IsValid(); move = move_picker_.SelectProbCutMove(see_threshold)) { + for (auto next = move_picker_.SelectProbCutMove(see_threshold); next; + next = move_picker_.SelectProbCutMove(see_threshold)) { + const auto& move = *next; ++searcher_.debug_info_.probcut_candidates; const auto value = SearchProbCutMove(move, probcut_beta, child_depth); if (!value || IsTimeToExit()) return NodeExit::Abort(); @@ -352,7 +354,7 @@ NodeExit SearchNode::TryProbCut() { template requires StopSearchCondition SearchResult SearchNode::SearchProbCutMove( - const Move &move, const Eval probcut_beta, const Depth child_depth) { + const LegalMove &move, const Eval probcut_beta, const Depth child_depth) { searcher_.SetPlayedMove(state_.ply, move, position_info_.static_eval); auto &position = GetCurrentPosition(); const ScopedMove made_move{position, move, position_info_.irreversible_data}; @@ -460,7 +462,7 @@ SearchResult SearchNode::SearchChild( template requires StopSearchCondition template -SearchResult SearchNode::ProbeMove(const Move &move) { +SearchResult SearchNode::ProbeMove(const LegalMove &move) { auto ¤t_position = GetCurrentPosition(); auto &[max_depth, remaining_depth, alpha, beta, ply, _] = state_; @@ -493,7 +495,7 @@ template requires StopSearchCondition template NodeExit SearchNode::SearchFirstMove( - const Move &move) { + const LegalMove &move) { static_assert(expected_node_type == kFirstChildNodeExpectedType); static_assert(expected_node_type != NodeType::kPV || expected_node_type == node_type); @@ -544,8 +546,9 @@ SearchResult SearchNode::PVSearch() { const bool move_pruning_allowed = ply != 0 && !position_info_.is_under_check; - for (auto move = move_picker_.SelectNextMove(); move.IsValid(); - move = move_picker_.SelectNextMove()) { + for (auto next = move_picker_.SelectNextMove(); next; + next = move_picker_.SelectNextMove()) { + const auto& move = *next; const bool is_quiet = move.IsQuiet(current_position); const bool can_prune = move_pruning_allowed && !Score::IsLoss(iteration_status_.best_eval); @@ -579,10 +582,6 @@ SearchResult SearchNode::PVSearch() { continue; } - if (is_quiet) { - RecordSearchedQuiet(move); - } - // Late Move Reduction int R = 0; if (lmr_conditions_met && @@ -613,7 +612,7 @@ SearchResult SearchNode::PVSearch() { static_cast(remaining_depth - 1)); } - late_move_eval = SearchLateMove(R); + late_move_eval = SearchLateMove(move, is_quiet, R); } // undo the move if (!late_move_eval) return std::nullopt; @@ -658,8 +657,11 @@ SearchResult SearchNode::PVSearch() { template requires StopSearchCondition SearchResult SearchNode::SearchLateMove( - const int reduction) { + const LegalMove &move, const bool is_quiet, const int reduction) { auto &[max_depth, remaining_depth, alpha, beta, ply, _] = state_; + if (is_quiet) { + RecordSearchedQuiet(move); + } auto temp_eval_optional = StartSubsearch( {max_depth, static_cast(remaining_depth - 1 - reduction), diff --git a/Chess/Searcher.h b/Chess/Searcher.h index b8ca016..6b25369 100644 --- a/Chess/Searcher.h +++ b/Chess/Searcher.h @@ -223,11 +223,12 @@ inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, const auto hashed_node = best_moves_->GetNode(position); if (!hashed_node.IsOccupied()) break; const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); - if (std::ranges::find(legal_moves, hashed_node.move) == legal_moves.end()) + MoveGenerator{}.GenerateLegalMoves(position); + const auto found = std::ranges::find(legal_moves, hashed_node.move); + if (found == legal_moves.end()) break; - position.DoMove(hashed_node.move); - answer.push_back(hashed_node.move); + position.DoMove(*found); + answer.push_back(*found); } return answer; } diff --git a/Chess/SimpleChessEngine.h b/Chess/SimpleChessEngine.h index 629fb1b..8884d6a 100644 --- a/Chess/SimpleChessEngine.h +++ b/Chess/SimpleChessEngine.h @@ -38,7 +38,7 @@ struct NodePerSecondInfo { struct PrincipalVariationInfo { size_t current_depth = 0; - std::span moves; + std::span moves; }; struct BestMoveInfo { @@ -282,7 +282,8 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( finish(BestMoveInfo{Move::None(), std::nullopt}); return; } - best_move_ = legal_moves.front(); + auto legal_best_move = legal_moves.front(); + best_move_ = legal_best_move; ponder_move_.reset(); if (!condition.ShouldContinueIteration()) { finish(BestMoveInfo{best_move_, std::nullopt}); @@ -300,7 +301,7 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( DebugInfo info; Eval eval = position_.Evaluate(); EBFsInfo ebfs; - MoveGenerator::Moves principal_variation{best_move_}; + MoveGenerator::Moves principal_variation{legal_best_move}; Depth trusted_depth = 0; Depth current_depth = initial_depth_; Depth last_best_move_depth = 0; @@ -340,16 +341,18 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( } const auto move = searcher_.GetCurrentBestMove(); - if (std::ranges::find(legal_moves, move) != legal_moves.end()) { - best_move_ = move; + if (const auto found = std::ranges::find(legal_moves, move); + found != legal_moves.end()) { + legal_best_move = *found; + best_move_ = legal_best_move; } eval = value; trusted_depth = searched_depth; Position pv_position = position_; - pv_position.DoMove(best_move_); + pv_position.DoMove(legal_best_move); principal_variation = searcher_.GetPrincipalVariation( static_cast(searched_depth - 1), std::move(pv_position)); - principal_variation.insert(principal_variation.begin(), best_move_); + principal_variation.insert(principal_variation.begin(), legal_best_move); ponder_move_ = principal_variation.size() > 1 ? std::optional{principal_variation[1]} : std::nullopt; diff --git a/Chess/SyzygyTablebase.cpp b/Chess/SyzygyTablebase.cpp index b55b7c4..7217718 100644 --- a/Chess/SyzygyTablebase.cpp +++ b/Chess/SyzygyTablebase.cpp @@ -165,11 +165,15 @@ std::optional Syzygy::ProbeWdl(const Position& position) const { return result == TB_RESULT_FAILED ? std::nullopt : DecodeWdl(result); } -std::optional Syzygy::RootMove(const Position& position) const { +std::optional Syzygy::RootMove(const Position& position) const { if (!CanProbe(position)) return std::nullopt; const auto encoded = Encode(position); std::lock_guard lock(root_probe_mutex_); - return DecodeMove(ProbeRoot(encoded)); + const auto move = DecodeMove(ProbeRoot(encoded)); + if (!move) return std::nullopt; + auto validation = position; + const auto pseudo = validation.TryPseudoLegal(*move); + return pseudo ? validation.TryLegal(*pseudo) : std::nullopt; } } // namespace SimpleChessEngine::Tablebase diff --git a/Chess/SyzygyTablebase.h b/Chess/SyzygyTablebase.h index 6ee2721..46296a5 100644 --- a/Chess/SyzygyTablebase.h +++ b/Chess/SyzygyTablebase.h @@ -6,7 +6,7 @@ #include #include -#include "Move.h" +#include "TypedMove.h" #include "Tablebase.h" namespace SimpleChessEngine { @@ -23,7 +23,7 @@ class Syzygy { [[nodiscard]] std::optional Probe( const Position& position) const; [[nodiscard]] std::optional ProbeWdl(const Position& position) const; - [[nodiscard]] std::optional RootMove(const Position& position) const; + [[nodiscard]] std::optional RootMove(const Position& position) const; [[nodiscard]] std::size_t MaxPieces() const { return max_pieces_; } private: diff --git a/Chess/TypedMove.h b/Chess/TypedMove.h new file mode 100644 index 0000000..7a51409 --- /dev/null +++ b/Chess/TypedMove.h @@ -0,0 +1,124 @@ +#pragma once + +#include +#include +#include + +#include "Move.h" + +namespace SimpleChessEngine { + +class Position; +class MoveGenerator; +template class MaybeMove; +struct PseudoLegalTag {}; +struct LegalTag {}; + +template +class TypedMove { + public: + TypedMove() = default; + + template + requires (std::is_same_v && + std::is_same_v) + [[gnu::always_inline]] constexpr TypedMove(TypedMove move) : move_(move) {} + + [[gnu::always_inline]] constexpr operator const Move&() const { return move_; } + [[gnu::always_inline]] constexpr BitIndex From() const { return move_.From(); } + [[gnu::always_inline]] constexpr BitIndex To() const { return move_.To(); } + [[gnu::always_inline]] constexpr MoveType Type() const { return move_.Type(); } + [[gnu::always_inline]] constexpr Piece PromotionPiece() const { return move_.PromotionPiece(); } + [[gnu::always_inline]] constexpr bool IsValid() const { return move_.IsValid(); } + [[gnu::always_inline]] constexpr bool IsPromotion() const { return move_.IsPromotion(); } + [[gnu::always_inline]] constexpr bool IsEnPassant() const { return move_.IsEnPassant(); } + [[gnu::always_inline]] constexpr bool IsCastling() const { return move_.IsCastling(); } + [[gnu::always_inline]] constexpr bool IsNormal() const { return move_.IsNormal(); } + [[gnu::always_inline]] constexpr std::uint16_t Raw() const { return move_.Raw(); } + [[gnu::always_inline]] constexpr explicit operator bool() const { return static_cast(move_); } + + template + [[gnu::always_inline]] constexpr bool IsQuiet(const PositionType& position) const { + return move_.IsQuiet(position); + } + + [[gnu::always_inline]] constexpr bool operator==(const TypedMove&) const = default; + [[gnu::always_inline]] constexpr bool operator==(const Move& move) const { return move_ == move; } + + template + [[gnu::always_inline]] constexpr bool operator==(const TypedMove& move) const { + return move_ == static_cast(move); + } + + private: + friend class MaybeMove; + friend class Position; + friend class MoveGenerator; + + [[gnu::always_inline]] constexpr explicit TypedMove(Move move) : move_(move) {} + + Move move_; +}; + +using PseudoLegalMove = TypedMove; +using LegalMove = TypedMove; + +static_assert(sizeof(PseudoLegalMove) == sizeof(Move)); +static_assert(sizeof(LegalMove) == sizeof(Move)); +static_assert(alignof(PseudoLegalMove) == alignof(Move)); +static_assert(alignof(LegalMove) == alignof(Move)); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_convertible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); + +template +class MaybeMove { + public: + MaybeMove() = default; + [[gnu::always_inline]] constexpr MaybeMove(TypedMove move) : move_(move) {} + [[gnu::always_inline]] constexpr operator const Move&() const { return move_; } + [[gnu::always_inline]] constexpr explicit operator bool() const { return static_cast(move_).IsValid(); } + template + [[gnu::always_inline]] constexpr bool IsQuiet(const PositionType& position) const { + return static_cast(move_).IsQuiet(position); + } + [[gnu::always_inline]] constexpr bool IsValid() const { return static_cast(move_).IsValid(); } + [[gnu::always_inline]] constexpr const TypedMove& operator*() const { + assert(IsValid()); + return move_; + } + static constexpr MaybeMove None() { return MaybeMove(Move::None()); } + [[gnu::always_inline]] constexpr bool operator==(const MaybeMove&) const = default; + template + [[gnu::always_inline]] constexpr bool operator==(const TypedMove& move) const { + return move_ == static_cast(move); + } + [[gnu::always_inline]] constexpr bool operator==(const Move& move) const { return move_ == move; } + + private: + [[gnu::always_inline]] constexpr explicit MaybeMove(Move move) : move_(move) {} + TypedMove move_; +}; + +using MaybePseudoLegalMove = MaybeMove; +using MaybeLegalMove = MaybeMove; + +static_assert(sizeof(MaybePseudoLegalMove) == sizeof(Move)); +static_assert(sizeof(MaybeLegalMove) == sizeof(Move)); +static_assert(alignof(MaybePseudoLegalMove) == alignof(Move)); +static_assert(alignof(MaybeLegalMove) == alignof(Move)); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_standard_layout_v); + +} diff --git a/Chess/UciCommunicator.h b/Chess/UciCommunicator.h index dcb6261..51e2b96 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -694,6 +694,7 @@ class UciChessEngine { void ParseUciNewGame(std::stringstream command); void ParseFen(const std::string& fen); void ParseStartPos(); + [[nodiscard]] std::optional ParseLegalMove(const std::string& text); void ParseMoves(std::stringstream command); void ParsePosition(std::stringstream command); void ParsePerft(std::stringstream command); @@ -872,10 +873,34 @@ inline void UciChessEngine::ParseStartPos() { info_.position = PositionFactory{}(); } +inline bool IsUciMoveText(std::string_view text) { + const auto is_file = [](char c) { return c >= 'a' && c <= 'h'; }; + const auto is_rank = [](char c) { return c >= '1' && c <= '8'; }; + const auto is_promotion = [](char c) { + return std::string_view{"qrbnQRBN"}.contains(c); + }; + return (text.size() == 4 || (text.size() == 5 && is_promotion(text[4]))) && + is_file(text[0]) && is_rank(text[1]) && is_file(text[2]) && + is_rank(text[3]); +} + +inline std::optional UciChessEngine::ParseLegalMove( + const std::string& text) { + if (!IsUciMoveText(text)) return std::nullopt; + auto& position = info_.position; + const auto pseudo_legal = position.TryPseudoLegal(MoveFactory{}(position, text)); + return pseudo_legal ? position.TryLegal(*pseudo_legal) : std::nullopt; +} + inline void UciChessEngine::ParseMoves(std::stringstream command) { - std::string move; - while (command >> move) { - info_.position.DoMove(MoveFactory{}(info_.position, move)); + std::string text; + while (command >> text) { + const auto move = ParseLegalMove(text); + if (!move) { + Send("info string illegal move " + text); + break; + } + info_.position.DoMove(*move); } } diff --git a/Tests/AspirationWindowTests.cpp b/Tests/AspirationWindowTests.cpp index 2986c0f..5fbf204 100644 --- a/Tests/AspirationWindowTests.cpp +++ b/Tests/AspirationWindowTests.cpp @@ -10,6 +10,7 @@ #include #include "AspirationWindow.h" +#include "CheckedMove.h" #include "MoveFactory.h" #include "SimpleChessEngine.h" @@ -280,9 +281,9 @@ TEST(AspirationSearch, FindsQueenSacrificeMateAtCompletedDepthEight) { TEST(AspirationSearch, PrintsCompletedDepthWhenPvIsShorter) { auto position = PositionFactory{}(); - MoveGenerator::Moves moves{MoveFactory{}(position, "e2e4")}; + MoveGenerator::Moves moves{CheckedMove(position, "e2e4")}; position.DoMove(moves.front()); - moves.push_back(MoveFactory{}(position, "e7e5")); + moves.push_back(CheckedMove(position, "e7e5")); std::ostringstream output; output << PrincipalVariationInfo{18, moves}; EXPECT_EQ(output.str(), "info depth 18 pv e2e4 e7e5\n"); diff --git a/Tests/CheckedMove.h b/Tests/CheckedMove.h new file mode 100644 index 0000000..26b4ec6 --- /dev/null +++ b/Tests/CheckedMove.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include + +#include "MoveFactory.h" +#include "Position.h" + +namespace SimpleChessEngine { + +inline LegalMove CheckedMove(Position& position, const Move& move) { + const auto pseudo = position.TryPseudoLegal(move); + if (!pseudo) std::abort(); + const auto legal = position.TryLegal(*pseudo); + if (!legal) std::abort(); + return *legal; +} + +inline LegalMove CheckedMove(Position& position, const std::string& text) { + return CheckedMove(position, MoveFactory{}(position, text)); +} + +} diff --git a/Tests/ChessEngineTests.cpp b/Tests/ChessEngineTests.cpp index 567cfb5..9ac7908 100644 --- a/Tests/ChessEngineTests.cpp +++ b/Tests/ChessEngineTests.cpp @@ -14,6 +14,7 @@ #include "ExitCondition.h" #include "Move.h" #include "MoveFactory.h" +#include "CheckedMove.h" #include "MoveGenerator.h" #include "SimpleChessEngine.h" @@ -48,14 +49,14 @@ TEST(RootRepetition, SearchStillReturnsLegalMove) { auto position = PositionFactory{}(); for (const auto *move : {"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8"}) { - position.DoMove(MoveFactory{}(position, move)); + position.DoMove(CheckedMove(position, move)); } std::stringstream ss; ChessEngine engine(position, ss); DepthCondition condition{2}; engine.ComputeBestMove(condition); const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal_moves, engine.GetCurrentBestMove()), legal_moves.end()); } @@ -92,7 +93,7 @@ TEST(TimeManagement, ReturnsLegalMoveWithoutTime) { TimeCondition condition{std::chrono::milliseconds{0}}; engine.ComputeBestMove(condition); const auto legal = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal, engine.GetCurrentBestMove()), legal.end()); EXPECT_EQ(ss.str().find("info depth "), std::string::npos); } diff --git a/Tests/MoveGeneratorTests.cpp b/Tests/MoveGeneratorTests.cpp index a0c1e08..621a2ca 100644 --- a/Tests/MoveGeneratorTests.cpp +++ b/Tests/MoveGeneratorTests.cpp @@ -35,7 +35,7 @@ struct GameInfo { static auto move_generator = MoveGenerator{}; const auto moves = - move_generator.GenerateMoves(position); + move_generator.GenerateLegalMoves(position); if (depth == 1) { for (const auto &move : moves) { diff --git a/Tests/NnueTests.cpp b/Tests/NnueTests.cpp index 4f6719c..483c1f9 100644 --- a/Tests/NnueTests.cpp +++ b/Tests/NnueTests.cpp @@ -12,7 +12,7 @@ #include #include -#include "MoveFactory.h" +#include "CheckedMove.h" #include "MoveGenerator.h" #include "Nnue/Nnue.h" #include "Position.h" @@ -59,12 +59,12 @@ TEST_P(NnueIncremental, RandomGamesMatchFullRefresh) { for (const auto& fen : fens) { for (int game = 0; game < 16; ++game) { Position position = PositionFactory{}(fen); - std::vector> history; + std::vector> history; for (int ply = 0; ply < 160; ++ply) { ASSERT_TRUE(MatchesFullRefresh(position)) << fen << " ply " << ply; ++checked; const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); if (moves.empty()) break; const auto roll = random() % 12; if (roll == 0 && !history.empty()) { @@ -143,7 +143,7 @@ TEST_P(NnueIncremental, SpecialMovesMatchFullRefresh) { for (const auto& [fen, coordinate] : cases) { Position position = PositionFactory{}(fen); ASSERT_TRUE(MatchesFullRefresh(position)) << fen; - const auto move = MoveFactory{}(position, coordinate); + const auto move = CheckedMove(position, coordinate); ASSERT_TRUE(position.IsLegal(move)) << fen << " " << coordinate; const auto data = position.GetIrreversibleData(); position.DoMove(move); @@ -182,13 +182,13 @@ TEST_P(NnueIncremental, MatchesStockfish19Oracle) { TEST_P(NnueIncremental, LazyUpdatesReloadAndFailedLoad) { Position position = PositionFactory{}(); std::mt19937_64 random(20261111); - std::vector> history; + std::vector> history; for (int ply = 0; ply < 120; ++ply) { if (ply % 11 == 0) { ASSERT_TRUE(MatchesFullRefresh(position)); } const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); if (moves.empty()) break; const auto move = moves[random() % moves.size()]; history.emplace_back(move, position.GetIrreversibleData()); @@ -210,7 +210,7 @@ TEST_P(NnueIncremental, LazyUpdatesReloadAndFailedLoad) { Nnue::Unload(); for (int ply = 0; ply < 8; ++ply) { const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); const auto move = moves[random() % moves.size()]; history.emplace_back(move, position.GetIrreversibleData()); position.DoMove(move); diff --git a/Tests/PositionStateTests.cpp b/Tests/PositionStateTests.cpp index 58c062f..0a2c472 100644 --- a/Tests/PositionStateTests.cpp +++ b/Tests/PositionStateTests.cpp @@ -1,6 +1,6 @@ #include -#include "MoveFactory.h" +#include "CheckedMove.h" #include "PositionFactory.h" namespace SimpleChessEngine { @@ -33,7 +33,7 @@ TEST(PositionState, VerifiesPinCacheAcrossMoveAndNullMoveUndo) { position.ComputePins(Player::kBlack); ExpectPinCacheUnchanged(position); const auto before = position.GetIrreversibleData(); - const auto move = MoveFactory{}(position, "e8f8"); + const auto move = CheckedMove(position, "e8f8"); position.DoMove(move); ExpectPinCacheUnchanged(position); position.ComputePins(Player::kWhite); diff --git a/Tests/PositionTests.cpp b/Tests/PositionTests.cpp index 9ffdcdd..e8044fa 100644 --- a/Tests/PositionTests.cpp +++ b/Tests/PositionTests.cpp @@ -3,6 +3,7 @@ #include #include "MoveFactory.h" +#include "CheckedMove.h" #include "MoveGenerator.h" #include "ExitCondition.h" #include "NodeType.h" @@ -43,7 +44,7 @@ TEST(DoMove, DoAndUndoEqualZero) { Position pos = start_pos; for (const auto moves = - MoveGenerator{}.GenerateMoves(pos); + MoveGenerator{}.GenerateLegalMoves(pos); const auto &move : moves) { const auto irreversible_data = pos.GetIrreversibleData(); pos.DoMove(move); @@ -59,7 +60,7 @@ TEST(SomeMoves, DifferentHash) { std::vector moves = {"b1c3", "d7d5", "a1b1"}; std::set hashes = {pos.GetHash()}; for (const auto &move_str : moves) { - auto move = MoveFactory{}(pos, move_str); + auto move = CheckedMove(pos, move_str); pos.DoMove(move); ASSERT_TRUE(hashes.insert(pos.GetHash()).second); } @@ -67,7 +68,7 @@ TEST(SomeMoves, DifferentHash) { Position DoMoves(Position pos, const std::vector &moves) { for (const auto &move_str : moves) { - auto move = MoveFactory{}(pos, move_str); + auto move = CheckedMove(pos, move_str); pos.DoMove(move); } @@ -101,10 +102,10 @@ TEST(FenFactory, PreservesEnPassantSquare) { TEST(FenFactory, UpdatesCountersFromInitialFenState) { auto position = PositionFactory{}( "7k/8/8/8/8/8/8/K7 b - - 37 42"); - position.DoMove(MoveFactory{}(position, "h8g7")); + position.DoMove(CheckedMove(position, "h8g7")); EXPECT_EQ(position.GetHalfMoveClock(), 38); EXPECT_EQ(position.GetFullMoveNumber(), 43); - position.DoMove(MoveFactory{}(position, "a1b1")); + position.DoMove(CheckedMove(position, "a1b1")); EXPECT_EQ(position.GetHalfMoveClock(), 39); EXPECT_EQ(position.GetFullMoveNumber(), 43); } @@ -112,17 +113,17 @@ TEST(FenFactory, UpdatesCountersFromInitialFenState) { TEST(FenFactory, CastlingIgnoresRooksOffTheBackRank) { auto position = PositionFactory{}("3qk2r/prp1pppp/1p1p4/8/8/8/1R2PPPP/4K2R w Kk - 0 1"); - position.DoMove(MoveFactory{}(position, "e1g1")); - position.DoMove(MoveFactory{}(position, "e8g8")); + position.DoMove(CheckedMove(position, "e1g1")); + position.DoMove(CheckedMove(position, "e8g8")); EXPECT_EQ(FenFactory{}(position), "3q1rk1/prp1pppp/1p1p4/8/8/8/1R2PPPP/5RK1 w - - 2 2"); } TEST(FenFactory, CastlingUsesCornerRookWhenAnotherRookShares) { auto position = PositionFactory{}("r1r1k2r/8/8/8/8/8/8/R3K2R b Kq - 0 1"); - position.DoMove(MoveFactory{}(position, "c8c7")); - position.DoMove(MoveFactory{}(position, "e1g1")); - position.DoMove(MoveFactory{}(position, "e8c8")); + position.DoMove(CheckedMove(position, "c8c7")); + position.DoMove(CheckedMove(position, "e1g1")); + position.DoMove(CheckedMove(position, "e8c8")); EXPECT_EQ(FenFactory{}(position), "2kr3r/2r5/8/8/8/8/8/R4RK1 w - - 3 3"); } @@ -136,10 +137,10 @@ TEST(Hash, IncludesCastlingRightsFromFen) { TEST(Hash, LostCastlingRightsMatchFenWithoutThem) { auto position = PositionFactory{}("4k3/8/8/8/8/8/8/4K2R w K - 0 1"); - position.DoMove(MoveFactory{}(position, "h1g1")); - position.DoMove(MoveFactory{}(position, "e8d8")); - position.DoMove(MoveFactory{}(position, "g1h1")); - position.DoMove(MoveFactory{}(position, "d8e8")); + position.DoMove(CheckedMove(position, "h1g1")); + position.DoMove(CheckedMove(position, "e8d8")); + position.DoMove(CheckedMove(position, "g1h1")); + position.DoMove(CheckedMove(position, "d8e8")); const auto expected = PositionFactory{}("4k3/8/8/8/8/8/8/4K2R w - - 4 3"); EXPECT_EQ(position.GetHash(), expected.GetHash()); } @@ -148,14 +149,14 @@ TEST(Repetition, IgnoresEnPassantSquareNobodyCanCapture) { auto position = PositionFactory{}(); for (const auto *move : {"e2e4", "g8f6", "g1f3", "f6g8", "f3g1", "g8f6", "g1f3", "f6g8", "f3g1"}) { - position.DoMove(MoveFactory{}(position, move)); + position.DoMove(CheckedMove(position, move)); } EXPECT_TRUE(position.DetectRepetition(0)); } TEST(Hash, KeepsCapturableEnPassantSquare) { auto position = PositionFactory{}("4k3/8/8/8/3p4/8/4P3/4K3 w - - 0 1"); - position.DoMove(MoveFactory{}(position, "e2e4")); + position.DoMove(CheckedMove(position, "e2e4")); const auto with_square = PositionFactory{}("4k3/8/8/8/3pP3/8/8/4K3 b - e3 0 1"); const auto without_square = @@ -167,10 +168,10 @@ TEST(Hash, KeepsCapturableEnPassantSquare) { TEST(FiftyMoveClock, QuietPromotionResetsCounter) { auto position = PositionFactory{}( "7k/P7/8/8/8/8/8/K7 w - - 99 42"); - position.DoMove(MoveFactory{}(position, "a7a8q")); + position.DoMove(CheckedMove(position, "a7a8q")); EXPECT_EQ(position.GetHalfMoveClock(), 0); EXPECT_EQ(position.GetFullMoveNumber(), 42); - position.DoMove(MoveFactory{}(position, "h8g7")); + position.DoMove(CheckedMove(position, "h8g7")); EXPECT_EQ(position.GetHalfMoveClock(), 1); EXPECT_EQ(position.GetFullMoveNumber(), 43); } @@ -218,7 +219,7 @@ TEST(InsufficientMaterial, SearchReturnsDrawAndLegalRootMove) { ASSERT_TRUE(result.has_value()); EXPECT_EQ(*result, kDrawValue); const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal_moves, searcher.GetCurrentBestMove()), legal_moves.end()); } @@ -285,7 +286,7 @@ TEST(TranspositionTable, IllegalStoredMoveIsIgnored) { ASSERT_TRUE(result.has_value()); const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal_moves, searcher.GetCurrentBestMove()), legal_moves.end()); } diff --git a/Tests/QuiescenceTTTests.cpp b/Tests/QuiescenceTTTests.cpp index eed89fc..abb9b03 100644 --- a/Tests/QuiescenceTTTests.cpp +++ b/Tests/QuiescenceTTTests.cpp @@ -5,6 +5,7 @@ #include #include "ExitCondition.h" +#include "CheckedMove.h" #include "MoveFactory.h" #include "Nnue/Nnue.h" #include "PositionFactory.h" @@ -256,7 +257,7 @@ TEST(QuiescenceTT, StoresPlyAdjustedMateAndTablebaseCaptureScores) { DepthCondition condition{4}; for (const Eval child_value : {-Score::kMate, -Score::kTbWin}) { auto position = PositionFactory{}("k7/8/8/3p4/3R3p/8/8/K7 w - - 0 1"); - const auto tt_move = MoveFactory{}(position, "d4h4"); + const auto tt_move = CheckedMove(position, "d4h4"); const Eval beta = position.Evaluate() + 1; QTable table; table.SetEntry(position, tt_move, ToTT(-20000, 0), 0, Bound::kLower, 1); diff --git a/Tests/SearchCorrectnessTests.cpp b/Tests/SearchCorrectnessTests.cpp index 205653b..e0cfc2a 100644 --- a/Tests/SearchCorrectnessTests.cpp +++ b/Tests/SearchCorrectnessTests.cpp @@ -11,6 +11,7 @@ #include "ExitCondition.h" #include "MoveFactory.h" +#include "CheckedMove.h" #include "Nnue/Nnue.h" #include "PositionFactory.h" #include "Quiescence.h" @@ -30,7 +31,7 @@ TEST(QuiescenceDraws, RepetitionInGameHistory) { auto position = PositionFactory{}("7k/8/6K1/8/8/8/8/1Q6 w - - 0 1"); for (const auto* move : {"b1b2", "h8g8", "b2b1", "g8h8", "b1b2", "h8g8", "b2b1", "g8h8"}) { - position.DoMove(MoveFactory{}(position, move)); + position.DoMove(CheckedMove(position, move)); } ASSERT_TRUE(position.DetectRepetition(0)); DepthCondition condition{4}; @@ -42,7 +43,7 @@ TEST(QuiescenceDraws, RepetitionInGameHistory) { TEST(QuiescenceDraws, StalemateWithPinnedBishop) { auto position = PositionFactory{}("7k/5K1b/7Q/8/8/8/8/8 b - - 0 1"); ASSERT_FALSE(position.IsUnderCheck()); - ASSERT_TRUE(MoveGenerator{}.GenerateMoves(position) + ASSERT_TRUE(MoveGenerator{}.GenerateLegalMoves(position) .empty()); DepthCondition condition{4}; Quiescence search{condition}; @@ -104,7 +105,7 @@ TEST(SingularExtensions, ExclusionIgnoresBoundsAndPreservesFullNodeEntry) { TEST(SingularExtensions, ExcludingOnlyEvasionReturnsFailLow) { auto position = PositionFactory{}("r7/8/8/8/8/2k5/8/K7 w - - 0 1"); const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); ASSERT_EQ(moves.size(), 1u); ASSERT_TRUE(position.IsUnderCheck()); Searcher searcher(position); @@ -416,12 +417,19 @@ TEST(ProbCut, TacticalPickerOrdersCapturesAndOmitsQuietsAndUnderpromotions) { Searcher searcher(position); MovePicker picker; picker.InitProbCut(position, &searcher, 1); - std::vector moves; - for (auto move = picker.SelectProbCutMove(-2000); move.IsValid(); - move = picker.SelectProbCutMove(-2000)) { + std::vector moves; + for (auto next = picker.SelectProbCutMove(-2000); next; + next = picker.SelectProbCutMove(-2000)) { + const auto& move = *next; moves.push_back(move); EXPECT_FALSE(move.IsQuiet(position)); EXPECT_TRUE(!move.IsPromotion() || move.PromotionPiece() == Piece::kQueen); + const auto before = position; + const auto irreversible_data = position.GetIrreversibleData(); + position.DoMove(move); + EXPECT_FALSE(position.IsUnderCheck(Flip(position.GetSideToMove()))); + position.UndoMove(move, irreversible_data); + ExpectProbCutPositionRestored(position, before); } ASSERT_EQ(moves.size(), 3u); EXPECT_EQ(moves[0], MoveFactory{}(position, "d4d5")); diff --git a/Tests/SearchEvaluationTests.cpp b/Tests/SearchEvaluationTests.cpp index 317d4d8..7d43d24 100644 --- a/Tests/SearchEvaluationTests.cpp +++ b/Tests/SearchEvaluationTests.cpp @@ -3,6 +3,7 @@ #include #include +#include "CheckedMove.h" #include "ExitCondition.h" #include "MoveFactory.h" #include "PositionFactory.h" @@ -236,7 +237,7 @@ TEST(StaticEvalPolicy, UpdatesSavedMoverOnlyAndLeavesContinuationUnchanged) { const auto position = PositionFactory{}(); const auto move = MoveFactory{}(position, "e2e4"); auto child = position; - child.DoMove(move); + child.DoMove(CheckedMove(child, move)); Searcher searcher(position); PolicyAccess::Play(searcher, 0, move, 20); PolicyAccess::Play(searcher, 1, move, 20); @@ -288,7 +289,7 @@ TEST(StaticEvalPolicy, ChildTrainsBeforeCutoffAndRestoresBoard) { const auto parent = PositionFactory{}(); const auto move = MoveFactory{}(parent, "e2e4"); auto child = parent; - child.DoMove(move); + child.DoMove(CheckedMove(child, move)); const auto parent_eval = parent.Evaluate(); const auto child_eval = child.Evaluate(); Searcher searcher(parent); @@ -309,7 +310,7 @@ TEST(StaticEvalPolicy, SuppressesNullMissingParentRootAndExclusion) { const auto parent = PositionFactory{}(); const auto move = MoveFactory{}(parent, "e2e4"); auto child = parent; - child.DoMove(move); + child.DoMove(CheckedMove(child, move)); for (int test = 0; test < 4; ++test) { SCOPED_TRACE(test); Searcher searcher(parent); @@ -340,7 +341,7 @@ TEST(StaticEvalPolicy, Searcher searcher(parent); PolicyAccess::Play(searcher, 0, move, parent.Evaluate()); auto child = parent; - child.DoMove(move); + child.DoMove(CheckedMove(child, move)); searcher.SetPosition(child); ProbePolicyNode(searcher); EXPECT_EQ(PolicyAccess::Entry(searcher, Player::kWhite, move), 0); @@ -374,7 +375,7 @@ TEST(StaticEvalPolicy, TtCutoffSkipsEvaluationAndPolicyTraining) { const auto parent = PositionFactory{}(); const auto move = MoveFactory{}(parent, "e2e4"); auto child = parent; - child.DoMove(move); + child.DoMove(CheckedMove(child, move)); auto table = std::make_shared(); table->SetEntry(child, MoveFactory{}(child, "e7e5"), ToTT(-1, 0), 3, Bound::kUpper, 0); @@ -448,7 +449,7 @@ TEST(StaticEvalPolicy, SearchReplacesContextForLaterQuietSibling) { const auto parent_eval = parent.Evaluate(); auto table = std::make_shared(); for (const auto &move : - MoveGenerator{}.GenerateMoves(parent)) { + MoveGenerator{}.GenerateLegalMoves(parent)) { auto child = parent; child.DoMove(move); table->SetEntry(child, MoveFactory{}(child, "e7e5"), ToTT(-9999, 0), 6, @@ -469,7 +470,7 @@ TEST(StaticEvalPolicy, SearchReplacesContextForLaterQuietSibling) { EXPECT_TRUE(context.quiet); EXPECT_EQ(context.parent_eval, parent_eval); auto expected_child = parent; - expected_child.DoMove(context.move); + expected_child.DoMove(CheckedMove(expected_child, context.move)); EXPECT_EQ(searcher.GetPosition().GetHash(), expected_child.GetHash()); return true; }}; diff --git a/Tests/StagedMovePickerTests.cpp b/Tests/StagedMovePickerTests.cpp index 8c184ea..404f526 100644 --- a/Tests/StagedMovePickerTests.cpp +++ b/Tests/StagedMovePickerTests.cpp @@ -30,7 +30,7 @@ constexpr std::array kPositions = { std::set LegalSet(Position& position) { std::set result; for (auto move : - MoveGenerator{}.GenerateMoves(position)) { + MoveGenerator{}.GenerateLegalMoves(position)) { result.insert(move.Raw()); } return result; @@ -41,7 +41,7 @@ TEST(StagedMovePicker, PseudoLegalValidationMatchesGenerator) { for (const auto* fen : kPositions) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); - std::array generated; + std::array generated; auto* end = MoveGenerator{}.GeneratePseudoLegal( position, generated.data()); std::set expected; @@ -59,7 +59,7 @@ TEST(StagedMovePicker, CaptureAndQuietStagesPartitionLegalMoves) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); const auto expected = LegalSet(position); - std::array generated; + std::array generated; auto* middle = MoveGenerator{}.GeneratePseudoLegal( position, generated.data()); @@ -92,14 +92,15 @@ TEST(StagedMovePicker, MainSearchEmitsLegalMovesOnceWithTtFirst) { std::set actual; auto move = picker.SelectNextMove(); if (expected.contains(tt.Raw())) { - EXPECT_EQ(move, tt); + ASSERT_TRUE(move); + EXPECT_EQ(*move, tt); } - for (; move.IsValid(); move = picker.SelectNextMove()) { - ASSERT_TRUE(expected.contains(move.Raw())); - EXPECT_TRUE(actual.insert(move.Raw()).second); - position.DoMove(move); + for (; move; move = picker.SelectNextMove()) { + ASSERT_TRUE(expected.contains((*move).Raw())); + EXPECT_TRUE(actual.insert((*move).Raw()).second); + position.DoMove(*move); position.ComputePins(position.GetSideToMove()); - position.UndoMove(move, uncomputed_data); + position.UndoMove(*move, uncomputed_data); } EXPECT_EQ(actual, expected); EXPECT_EQ(picker.MoveCount(), expected.size()); @@ -113,13 +114,17 @@ TEST(StagedMovePicker, QuiescencePreservesGeneratorOrderAndEvasions) { auto position = PositionFactory{}(fen); const auto expected = position.IsUnderCheck() - ? MoveGenerator{}.GenerateMoves(position) - : MoveGenerator{}.GenerateMoves( + ? MoveGenerator{}.GenerateLegalMoves(position) + : MoveGenerator{}.GenerateLegalMoves( position); MovePicker picker; picker.InitPicker(position, nullptr, 0); - for (auto move : expected) EXPECT_EQ(picker.SelectNextMove(), move); - EXPECT_EQ(picker.SelectNextMove(), Move::None()); + for (auto move : expected) { + const auto selected = picker.SelectNextMove(); + ASSERT_TRUE(selected); + EXPECT_EQ(*selected, move); + } + EXPECT_FALSE(picker.SelectNextMove()); } } diff --git a/Tests/StaticExchangeEvaluationTests.cpp b/Tests/StaticExchangeEvaluationTests.cpp index 983ba5f..38fa29d 100644 --- a/Tests/StaticExchangeEvaluationTests.cpp +++ b/Tests/StaticExchangeEvaluationTests.cpp @@ -1,5 +1,6 @@ #include +#include "CheckedMove.h" #include "MoveFactory.h" #include "PositionFactory.h" @@ -95,7 +96,7 @@ TEST(StaticExchangeEvaluation, RefreshesPinsAfterMoveAndRestoresOnUndo) { position.ComputePins(Player::kWhite); position.ComputePins(Player::kBlack); const auto pins = position.GetIrreversibleData(); - const auto move = MoveFactory{}(position, "e8f8"); + const auto move = CheckedMove(position, "e8f8"); position.DoMove(move); ExpectSeeValue(position, "d1d5", -870); position.UndoMove(move, pins); diff --git a/Tests/TypedMoveTests.cpp b/Tests/TypedMoveTests.cpp new file mode 100644 index 0000000..085d7e1 --- /dev/null +++ b/Tests/TypedMoveTests.cpp @@ -0,0 +1,117 @@ +#include + +#include +#include + +#include "MoveFactory.h" +#include "MoveGenerator.h" +#include "MovePicker.h" +#include "PositionFactory.h" +#include "ScopedMove.h" +#include "TypedMove.h" + +using namespace SimpleChessEngine; + +template +concept CanDoMove = requires(Position& position, M move) { + position.DoMove(move); +}; + +template +concept CanUndoMove = requires(Position& position, M move) { + position.UndoMove(move, position.GetIrreversibleData()); +}; + +template +concept CanConstructLegalMove = requires(M move) { + LegalMove(move); +}; + +static_assert(ReversibleMove); +static_assert(ReversibleMove); +static_assert(!ReversibleMove); +static_assert(!ReversibleMove); +static_assert(!ReversibleMove); +static_assert(!ReversibleMove); +static_assert(CanDoMove); +static_assert(CanUndoMove); +static_assert(!CanDoMove); +static_assert(!CanDoMove); +static_assert(!CanDoMove); +static_assert(!CanUndoMove); +static_assert(!CanUndoMove); +static_assert(!CanUndoMove); +static_assert(std::is_same_v().SelectNextMove()), MaybeLegalMove>); +static_assert(std::is_same_v< + decltype(std::declval().SelectProbCutMove(Eval{})), + MaybeLegalMove>); +static_assert(!CanConstructLegalMove); +static_assert(!CanConstructLegalMove); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); +static_assert(!static_cast(MaybeLegalMove::None())); +static_assert(!static_cast(MaybePseudoLegalMove::None())); +static_assert(sizeof(PseudoLegalMove) == sizeof(Move)); +static_assert(sizeof(LegalMove) == sizeof(Move)); +static_assert(alignof(PseudoLegalMove) == alignof(Move)); +static_assert(alignof(LegalMove) == alignof(Move)); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_convertible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); + +TEST(TypedMoves, RejectsGarbage) { + auto position = PositionFactory{}(); + EXPECT_FALSE(position.TryPseudoLegal(Move(0xffff))); + EXPECT_FALSE(position.TryPseudoLegal(Move::None())); + EXPECT_FALSE(position.TryPseudoLegal(Move::Null())); + EXPECT_FALSE(position.TryPseudoLegal(MoveFactory{}(position, "a1a8"))); +} + +TEST(TypedMoves, RejectsExposingKing) { + auto position = PositionFactory{}("4r1k1/8/8/8/8/8/4R3/4K3 w - - 0 1"); + const auto pseudo = position.TryPseudoLegal(MoveFactory{}(position, "e2f2")); + ASSERT_TRUE(pseudo); + EXPECT_FALSE(position.TryLegal(*pseudo)); + EXPECT_FALSE(position.TryLegal(*pseudo, position.GetIrreversibleData().blockers[0])); +} + +TEST(TypedMoves, AcceptsEveryGeneratedLegalMove) { + for (const auto* fen : { + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", + "4k3/8/8/r4pPK/8/8/8/8 w - f6 0 1", + "4k3/P7/8/8/8/8/7p/4K3 w - - 0 1", + "4k3/8/8/8/8/8/8/6KR w H - 0 1"}) { + auto position = PositionFactory{}(fen); + const auto moves = MoveGenerator{}.GenerateLegalMoves(position); + const auto raw_moves = MoveGenerator{}.GenerateMoves(position); + ASSERT_EQ(moves.size(), raw_moves.size()); + for (size_t i = 0; i < moves.size(); ++i) EXPECT_EQ(moves[i], raw_moves[i]); + for (const auto move : moves) { + const Move raw = move; + const PseudoLegalMove degraded = move; + EXPECT_EQ(degraded, raw); + EXPECT_EQ(raw, degraded); + EXPECT_EQ(move, raw); + EXPECT_EQ(raw, move); + EXPECT_EQ(move, degraded); + const auto pseudo = position.TryPseudoLegal(raw); + ASSERT_TRUE(pseudo); + EXPECT_EQ(*pseudo, degraded); + const auto legal = position.TryLegal(*pseudo); + ASSERT_TRUE(legal); + EXPECT_EQ(*legal, move); + const auto explicit_blockers = position.TryLegal( + *pseudo, position.GetIrreversibleData().blockers[static_cast(position.GetSideToMove())]); + ASSERT_TRUE(explicit_blockers); + EXPECT_EQ(*explicit_blockers, move); + } + } +} diff --git a/Tests/UciInfoTests.cpp b/Tests/UciInfoTests.cpp index 3134e8f..9014560 100644 --- a/Tests/UciInfoTests.cpp +++ b/Tests/UciInfoTests.cpp @@ -6,12 +6,17 @@ #include #include +#include "CheckedMove.h" #include "SimpleChessEngine.h" namespace SimpleChessEngine::UciInfoTests { TEST(PrincipalVariationInfo, ReportsIterationDepthForShortPV) { std::ostringstream output; - output << PrincipalVariationInfo{14, {Move{12, 28}, Move{52, 36}}}; + auto position = PositionFactory{}(); + const auto first = CheckedMove(position, "e2e4"); + position.DoMove(first); + const auto second = CheckedMove(position, "e7e5"); + output << PrincipalVariationInfo{14, {first, second}}; EXPECT_EQ(output.str(), "info depth 14 pv e2e4 e7e5\n"); } diff --git a/Tests/uci_input_test.py b/Tests/uci_input_test.py index 2fed407..9c73239 100644 --- a/Tests/uci_input_test.py +++ b/Tests/uci_input_test.py @@ -5,6 +5,8 @@ import sys CASES = [ + ("reject short castling notation", ["position startpos moves O-O"], "info string illegal move O-O"), + ("reject long castling notation", ["position startpos moves O-O-O"], "info string illegal move O-O-O"), ("disable NNUE", ["setoption name EvalFile value none"], "info string NNUE disabled"), ("NNUE option is case insensitive", ["setoption name evalfile value none"], "info string NNUE disabled"), ("unknown option", ["setoption name Hash value 64"], "info string unknown option or invalid value"),