36#include <gtest/gtest.h>
46struct ArtificialGameState
53struct ArtificialGameMove
59class ArtificialGameDomain
62 using State = ArtificialGameState;
63 using Move = ArtificialGameMove;
65 using State_Key = std::uint64_t;
67 bool is_terminal(
const State &state)
const
69 return state.depth == 2;
72 Score evaluate(
const State &state)
const
74 return root_score(state.code)*state.player;
77 [[nodiscard]] State_Key state_key(
const State &state)
const noexcept
79 return (
static_cast<State_Key
>(state.code) << 1) |
80 static_cast<State_Key
>(state.player > 0 ? 1 : 0);
83 void apply(State &state,
const Move &move)
const
85 state.code = move.next_code;
86 state.player = -state.player;
90 void undo(State &state,
const Move&)
const
93 state.player = -state.player;
97 template <
typename Visitor>
98 bool for_each_successor(
const State &state, Visitor visit)
const
100 if (state.depth >= 2)
106 if (not visit(Move{2,
'A'}))
108 return visit(Move{3,
'B'});
111 if (not visit(Move{4,
'a'}))
113 return visit(Move{5,
'b'});
116 if (not visit(Move{6,
'a'}))
118 return visit(Move{7,
'b'});
126 [[nodiscard]]
static Score root_score(
const size_t code)
noexcept
145 size_t moves_played = 0;
147 TicTacToeState() : board(size_t(9), 0)
160 [[nodiscard]]
bool operator == (
const Move &)
const noexcept =
default;
163 using State = TicTacToeState;
165 using State_Key = std::uint64_t;
166 using Move_Key = size_t;
168 bool is_terminal(
const State &state)
const
170 return winner(state) != 0 or state.moves_played == 9;
173 Score evaluate(
const State &state)
const
175 const int win = winner(state);
177 return win == state.player ? 100 : -100;
179 if (state.moves_played == 9)
182 return heuristic(state, state.player) - heuristic(state, -state.player);
185 [[nodiscard]] State_Key state_key(
const State &state)
const noexcept
187 State_Key key =
static_cast<State_Key
>(state.player > 0 ? 1 : 2);
188 for (
size_t i = 0; i < state.board.size(); ++i)
191 if (state.board[i] == 1)
193 else if (state.board[i] == -1)
200 [[nodiscard]] Move_Key move_key(
const Move &move)
const noexcept
205 void apply(State &state,
const Move &move)
const
207 state.board[move.cell] = state.player;
208 state.player = -state.player;
209 ++state.moves_played;
212 void undo(State &state,
const Move &move)
const
214 --state.moves_played;
215 state.player = -state.player;
216 state.board[move.cell] = 0;
219 template <
typename Visitor>
220 bool for_each_successor(
const State &state, Visitor visit)
const
222 static constexpr size_t order[] = {1, 3, 5, 7, 0, 2, 6, 8, 4};
224 for (
const size_t cell : order)
225 if (state.board[
cell] == 0
and not visit(Move{
cell}))
232 [[nodiscard]]
static int winner(
const State &state)
noexcept
234 static constexpr size_t lines[8][3] = {
235 {0, 1, 2}, {3, 4, 5}, {6, 7, 8},
236 {0, 3, 6}, {1, 4, 7}, {2, 5, 8},
240 for (
const auto &line : lines)
242 const int a = state.board[line[0]];
243 if (a != 0
and a == state.board[line[1]]
and a == state.board[line[2]])
250 [[nodiscard]]
static Score heuristic(
const State &state,
const int player)
noexcept
252 static constexpr size_t lines[8][3] = {
253 {0, 1, 2}, {3, 4, 5}, {6, 7, 8},
254 {0, 3, 6}, {1, 4, 7}, {2, 5, 8},
259 for (
const auto &line : lines)
263 bool blocked =
false;
265 for (
const size_t cell : line)
266 if (state.board[
cell] == player)
268 else if (state.board[
cell] == 0)
279 if (mine == 2
and empty == 1)
281 else if (mine == 1
and empty == 2)
289static_assert(AdversarialGameDomain<ArtificialGameDomain>);
290static_assert(AdversarialGameDomain<TicTacToeDomain>);
295 for (
const auto &move : path)
296 out.push_back(move.label);
300template <
typename Move,
typename Score>
308 if (event.
kind == kind)
314TicTacToeState make_tictactoe_state(
const char *layout,
const int player)
316 TicTacToeState state;
317 state.player = player;
319 for (
size_t i = 0; i < 9; ++i)
324 ++state.moves_played;
329 ++state.moves_played;
349template <
typename Domain>
350[[nodiscard]]
typename Domain::Score
352 typename Domain::State state,
355 for (
const auto &move : pv)
356 domain.apply(state, move);
358 const auto leaf_value =
domain.evaluate(state);
359 return (pv.
size() % 2 == 0) ? leaf_value : -leaf_value;
364TEST(AdversarialSearchFramework, ArtificialGameNegamaxFindsKnownValueAndPath)
366 auto result =
negamax_search(ArtificialGameDomain{}, ArtificialGameState{});
368 EXPECT_TRUE(result.exhausted());
369 EXPECT_EQ(result.value, 3);
370 EXPECT_EQ(path_signature(result.principal_variation),
"Aa");
371 EXPECT_EQ(result.stats.visited_states, 7u);
372 EXPECT_EQ(result.stats.expanded_states, 3u);
375TEST(AdversarialSearchFramework, ArtificialGameAlphaBetaMatchesNegamaxAndPrunes)
377 auto negamax =
negamax_search(ArtificialGameDomain{}, ArtificialGameState{});
378 auto alpha_beta =
alpha_beta_search(ArtificialGameDomain{}, ArtificialGameState{});
380 EXPECT_EQ(alpha_beta.value, negamax.value);
381 EXPECT_EQ(path_signature(alpha_beta.principal_variation),
"Aa");
382 EXPECT_LT(alpha_beta.stats.visited_states, negamax.stats.visited_states);
383 EXPECT_GT(alpha_beta.stats.alpha_beta_cutoffs, 0u);
386TEST(AdversarialSearchFramework, ArtificialGameDepthLimitUsesHeuristicEvaluation)
391 auto result =
negamax_search(ArtificialGameDomain{}, ArtificialGameState{}, {}, limits);
393 EXPECT_TRUE(result.exhausted());
394 EXPECT_EQ(result.value, 6);
395 EXPECT_EQ(path_signature(result.principal_variation),
"A");
396 EXPECT_EQ(result.stats.pruned_by_depth, 2u);
399TEST(AdversarialSearchFramework, TicTacToeFindsImmediateWinningMove)
401 const TicTacToeState state = make_tictactoe_state(
"XX.OO....", 1);
406 EXPECT_EQ(negamax.value, 100);
407 EXPECT_EQ(alpha_beta.value, 100);
408 ASSERT_TRUE(alpha_beta.has_principal_variation());
409 EXPECT_EQ(alpha_beta.first_move().cell, 2u);
410 EXPECT_EQ(negamax.first_move().cell, alpha_beta.first_move().cell);
413TEST(AdversarialSearchFramework, TicTacToeAlphaBetaMatchesNegamaxAndVisitsFewerNodes)
415 TicTacToeState state;
420 EXPECT_EQ(negamax.value, 0);
421 EXPECT_EQ(alpha_beta.value, negamax.value);
422 ASSERT_TRUE(negamax.has_principal_variation());
423 ASSERT_TRUE(alpha_beta.has_principal_variation());
424 EXPECT_EQ(alpha_beta.first_move().cell, negamax.first_move().cell);
425 EXPECT_LT(alpha_beta.stats.visited_states, negamax.stats.visited_states);
426 EXPECT_GT(alpha_beta.stats.alpha_beta_cutoffs, 0u);
429TEST(AdversarialSearchFramework, InvalidBestFirstPolicyIsRejected)
432 policy.
strategy = ExplorationPolicy::Strategy::Best_First;
437 EXPECT_THROW((
void) negamax.search(ArtificialGameState{}), std::invalid_argument);
438 EXPECT_THROW((
void) alpha_beta.search(ArtificialGameState{}), std::invalid_argument);
441TEST(AdversarialSearchFramework, AlphaBetaHeuristicMoveOrderingReducesNodes)
443 TicTacToeState state;
446 auto plain = plain_engine.
search(state);
449 ordered_policy.
move_ordering = MoveOrderingMode::Estimated_Score;
454 auto ordered = ordered_engine.
search(state);
456 EXPECT_EQ(ordered.value, plain.value);
457 ASSERT_TRUE(plain.has_principal_variation());
458 ASSERT_TRUE(ordered.has_principal_variation());
459 EXPECT_LT(ordered.stats.visited_states, plain.stats.visited_states);
460 EXPECT_EQ(ordered.first_move().cell, 4u);
461 EXPECT_GT(ordered.stats.alpha_beta_cutoffs, 0u);
462 EXPECT_GT(ordered.stats.move_ordering.ordered_batches, 0u);
463 EXPECT_GT(ordered.stats.move_ordering.ordered_moves, 0u);
464 EXPECT_GT(ordered.stats.move_ordering.priority_estimates, 0u);
467TEST(AdversarialSearchFramework, NegamaxTranspositionTablePreservesResultAndReducesNodes)
469 TicTacToeState state;
475 TicTacToeDomain::Move,
476 TicTacToeDomain::Score>;
478 auto with_tt =
engine.search(state, table);
480 EXPECT_EQ(with_tt.value, without_tt.value);
481 ASSERT_TRUE(with_tt.has_principal_variation());
482 ASSERT_TRUE(without_tt.has_principal_variation());
483 EXPECT_EQ(with_tt.first_move().cell, without_tt.first_move().cell);
484 EXPECT_LT(with_tt.stats.visited_states, without_tt.stats.visited_states);
485 EXPECT_GT(with_tt.stats.transpositions.hits, 0u);
486 EXPECT_GT(with_tt.stats.transpositions.cutoffs, 0u);
487 EXPECT_GT(table.stats().stores, 0u);
490TEST(AdversarialSearchFramework, AlphaBetaTranspositionTablePreservesResultAndReducesNodes)
492 TicTacToeState state;
498 TicTacToeDomain::Move,
499 TicTacToeDomain::Score>;
501 auto with_tt =
engine.search(state, table);
503 EXPECT_EQ(with_tt.value, without_tt.value);
504 ASSERT_TRUE(with_tt.has_principal_variation());
505 ASSERT_TRUE(without_tt.has_principal_variation());
506 EXPECT_EQ(with_tt.first_move().cell, without_tt.first_move().cell);
507 EXPECT_LT(with_tt.stats.visited_states, without_tt.stats.visited_states);
508 EXPECT_GT(with_tt.stats.transpositions.hits, 0u);
509 EXPECT_GT(with_tt.stats.transpositions.cutoffs, 0u);
510 EXPECT_GT(table.stats().stores, 0u);
513TEST(AdversarialSearchFramework, NegamaxIterativeDeepeningCollectsPerDepthPV)
518 auto fixed =
negamax_search(ArtificialGameDomain{}, ArtificialGameState{}, {}, limits);
520 ArtificialGameState{},
524 ASSERT_TRUE(iterative.has_iterations());
525 ASSERT_EQ(iterative.iterations.size(), 2u);
526 EXPECT_EQ(iterative.completed_iterations, 2u);
528 EXPECT_EQ(iterative.iterations[0].depth, 1u);
529 EXPECT_EQ(iterative.iterations[0].result.value, 6);
530 EXPECT_EQ(path_signature(iterative.iterations[0].result.principal_variation),
"A");
532 EXPECT_EQ(iterative.iterations[1].depth, 2u);
533 EXPECT_EQ(iterative.iterations[1].result.value, fixed.value);
534 EXPECT_EQ(path_signature(iterative.iterations[1].result.principal_variation),
"Aa");
536 EXPECT_EQ(iterative.result.value, fixed.value);
537 EXPECT_EQ(path_signature(iterative.result.principal_variation),
"Aa");
538 EXPECT_GT(iterative.total_stats.visited_states, fixed.stats.visited_states);
541TEST(AdversarialSearchFramework, AlphaBetaIterativeDeepeningAspirationPreservesValue)
549 options.aspiration.half_window = 1;
552 auto fixed =
alpha_beta_search(ArtificialGameDomain{}, ArtificialGameState{}, {}, limits);
554 ArtificialGameState{},
559 ASSERT_EQ(iterative.iterations.size(), 2u);
560 EXPECT_EQ(iterative.result.value, fixed.value);
561 EXPECT_EQ(path_signature(iterative.result.principal_variation),
"Aa");
562 EXPECT_TRUE(iterative.iterations[1].used_aspiration_window);
563 EXPECT_GT(iterative.iterations[1].aspiration_researches, 0u);
564 EXPECT_GT(iterative.aspiration_researches, 0u);
567TEST(AdversarialSearchFramework, AlphaBetaTracingRecordsIterationsAndCutoffs)
575 options.aspiration.half_window = 1;
580 ArtificialGameState{},
586 EXPECT_EQ(iterative.result.value, 3);
587 EXPECT_GT(trace.size(), 0u);
588 EXPECT_EQ(count_trace_events(trace, AdversarialTraceEventKind::Iteration_Begin), 2u);
589 EXPECT_EQ(count_trace_events(trace, AdversarialTraceEventKind::Iteration_End), 2u);
590 EXPECT_GT(count_trace_events(trace, AdversarialTraceEventKind::Alpha_Beta_Cutoff), 0u);
591 EXPECT_GT(count_trace_events(trace, AdversarialTraceEventKind::Aspiration_Retry), 0u);
594TEST(AdversarialSearchFramework, AlphaBetaIterativeDeepeningTTPreservesValueAndReducesNodes)
596 TicTacToeState state;
602 ordered_policy.
move_ordering = MoveOrderingMode::Estimated_Score;
609 options.aspiration.half_window = 4;
619 TicTacToeDomain::Move,
620 TicTacToeDomain::Score>;
629 EXPECT_EQ(with_tt.result.value, without_tt.result.value);
630 ASSERT_TRUE(with_tt.result.has_principal_variation());
631 ASSERT_TRUE(without_tt.result.has_principal_variation());
632 EXPECT_EQ(with_tt.result.first_move().cell, without_tt.result.first_move().cell);
633 EXPECT_LT(with_tt.total_stats.visited_states, without_tt.total_stats.visited_states);
634 EXPECT_GT(table.stats().stores, 0u);
639TEST(AdversarialSearchFramework, SearchWithWindowWideWindowMatchesFullSearch)
644 auto windowed =
engine.search_with_window(ArtificialGameState{}, -1000, 1000);
646 EXPECT_EQ(windowed.value, full.value);
647 EXPECT_EQ(path_signature(windowed.principal_variation),
648 path_signature(full.principal_variation));
651TEST(AdversarialSearchFramework, SearchWithWindowExactWindowReturnsCorrectValue)
656 auto windowed =
engine.search_with_window(ArtificialGameState{},
657 full.value - 1, full.value + 1);
659 EXPECT_EQ(windowed.value, full.value);
660 ASSERT_TRUE(windowed.has_principal_variation());
663TEST(AdversarialSearchFramework, SearchWithWindowFailLowReturnsUpperBound)
668 auto windowed =
engine.search_with_window(ArtificialGameState{},
669 full.value + 5, full.value + 10);
671 EXPECT_LE(windowed.value, full.value + 5);
674TEST(AdversarialSearchFramework, SearchWithWindowFailHighReturnsLowerBound)
679 auto windowed =
engine.search_with_window(ArtificialGameState{},
680 full.value - 10, full.value - 5);
682 EXPECT_GE(windowed.value, full.value - 5);
685TEST(AdversarialSearchFramework, SearchWithWindowTicTacToeMatchesFullSearch)
687 const TicTacToeState state = make_tictactoe_state(
"XX.OO....", 1);
691 auto windowed =
engine.search_with_window(state, -200, 200);
693 EXPECT_EQ(windowed.value, full.value);
694 ASSERT_TRUE(windowed.has_principal_variation());
695 EXPECT_EQ(windowed.first_move().cell, full.first_move().cell);
698TEST(AdversarialSearchFramework, SearchWithWindowTTPreservesResult)
700 const TicTacToeState state = make_tictactoe_state(
"XX.OO....", 1);
706 TicTacToeDomain::Move,
707 TicTacToeDomain::Score>;
709 auto windowed =
engine.search_with_window(state, table, -200, 200);
711 EXPECT_EQ(windowed.value, full.value);
712 ASSERT_TRUE(windowed.has_principal_variation());
713 EXPECT_EQ(windowed.first_move().cell, full.first_move().cell);
714 EXPECT_GT(table.stats().stores, 0u);
717TEST(AdversarialSearchFramework, SearchWithWindowNarrowPrunesMoreNodes)
719 TicTacToeState state;
723 auto narrow =
engine.search_with_window(state, -1, 1);
725 EXPECT_LE(narrow.stats.visited_states, wide.stats.visited_states);
732TEST(AdversarialSearchFramework, NegamaxPVReplayMatchesReportedValue)
734 ArtificialGameDomain domain;
737 ASSERT_TRUE(result.has_principal_variation());
738 const auto replayed = replay_pv(domain, ArtificialGameState{},
739 result.principal_variation);
740 EXPECT_EQ(replayed, result.value);
743TEST(AdversarialSearchFramework, AlphaBetaPVReplayMatchesReportedValue)
745 ArtificialGameDomain domain;
748 ASSERT_TRUE(result.has_principal_variation());
749 const auto replayed = replay_pv(domain, ArtificialGameState{},
750 result.principal_variation);
751 EXPECT_EQ(replayed, result.value);
754TEST(AdversarialSearchFramework, DepthLimitedNegamaxPVReplayMatchesReportedValue)
756 ArtificialGameDomain domain;
760 auto result =
negamax_search(domain, ArtificialGameState{}, {}, limits);
762 ASSERT_TRUE(result.has_principal_variation());
763 const auto replayed = replay_pv(domain, ArtificialGameState{},
764 result.principal_variation);
765 EXPECT_EQ(replayed, result.value);
768TEST(AdversarialSearchFramework, TicTacToeNegamaxPVReplayMatchesValue)
770 TicTacToeDomain domain;
771 TicTacToeState state;
775 ASSERT_TRUE(result.has_principal_variation());
776 const auto replayed = replay_pv(domain, state, result.principal_variation);
777 EXPECT_EQ(replayed, result.value);
780TEST(AdversarialSearchFramework, TicTacToeAlphaBetaPVReplayMatchesValue)
782 TicTacToeDomain domain;
783 TicTacToeState state;
787 ASSERT_TRUE(result.has_principal_variation());
788 const auto replayed = replay_pv(domain, state, result.principal_variation);
789 EXPECT_EQ(replayed, result.value);
792TEST(AdversarialSearchFramework, TicTacToeWinningPositionPVReplay)
794 TicTacToeDomain domain;
795 const TicTacToeState state = make_tictactoe_state(
"XX.OO....", 1);
800 ASSERT_TRUE(negamax.has_principal_variation());
801 ASSERT_TRUE(alpha_beta.has_principal_variation());
802 EXPECT_EQ(replay_pv(domain, state, negamax.principal_variation), negamax.value);
803 EXPECT_EQ(replay_pv(domain, state, alpha_beta.principal_variation), alpha_beta.value);
806TEST(AdversarialSearchFramework, TicTacToeWithTTPVReplayMatchesValue)
808 TicTacToeDomain domain;
809 TicTacToeState state;
812 TicTacToeDomain::Move,
813 TicTacToeDomain::Score>;
816 auto result =
engine.search(state, table);
818 ASSERT_TRUE(result.has_principal_variation());
819 const auto replayed = replay_pv(domain, state, result.principal_variation);
820 EXPECT_EQ(replayed, result.value);
823TEST(AdversarialSearchFramework, IterativeDeepeningPVReplayMatchesValueAtEachDepth)
825 ArtificialGameDomain domain;
830 ArtificialGameState{},
834 ASSERT_TRUE(iterative.has_iterations());
835 for (
size_t i = 0; i < iterative.iterations.size(); ++i)
837 const auto &iter = iterative.iterations[i];
838 ASSERT_TRUE(iter.result.has_principal_variation())
839 <<
"Iteration " << i <<
" has no PV";
840 const auto replayed = replay_pv(domain, ArtificialGameState{},
841 iter.result.principal_variation);
842 EXPECT_EQ(replayed, iter.result.value)
843 <<
"PV replay mismatch at iteration " << i
844 <<
" (depth " << iter.depth <<
")";
847 ASSERT_TRUE(iterative.result.has_principal_variation());
848 const auto final_replayed = replay_pv(domain, ArtificialGameState{},
849 iterative.result.principal_variation);
850 EXPECT_EQ(final_replayed, iterative.result.value);
853TEST(AdversarialSearchFramework, AlphaBetaIterativeDeepeningPVReplayMatchesValue)
855 ArtificialGameDomain domain;
862 options.aspiration.half_window = 1;
866 ArtificialGameState{},
871 ASSERT_TRUE(iterative.result.has_principal_variation());
872 const auto replayed = replay_pv(domain, ArtificialGameState{},
873 iterative.result.principal_variation);
874 EXPECT_EQ(replayed, iterative.result.value);
876 for (
size_t i = 0; i < iterative.iterations.size(); ++i)
878 const auto &iter = iterative.iterations[i];
879 ASSERT_TRUE(iter.result.has_principal_variation())
880 <<
"Iteration " << i <<
" has no PV";
881 const auto r = replay_pv(domain, ArtificialGameState{},
882 iter.result.principal_variation);
883 EXPECT_EQ(
r, iter.result.value)
884 <<
"PV replay mismatch at iteration " << i;
888TEST(AdversarialSearchFramework, SearchWithWindowPVReplayMatchesValue)
890 TicTacToeDomain domain;
891 const TicTacToeState state = make_tictactoe_state(
"XX.OO....", 1);
894 auto result =
engine.search_with_window(state, -200, 200);
896 ASSERT_TRUE(result.has_principal_variation());
897 const auto replayed = replay_pv(domain, state, result.principal_variation);
898 EXPECT_EQ(replayed, result.value);
908struct AdversarialThrowState
910 std::shared_ptr<bool> undo_called;
914struct AdversarialThrowMove
916 bool throw_on_apply =
false;
920struct ThrowingApplyGameDomain
922 using State = AdversarialThrowState;
923 using Move = AdversarialThrowMove;
926 bool is_terminal(
const State &state)
const
928 return state.node >= 1;
931 Score evaluate(
const State &)
const
936 void apply(State &state,
const Move &move)
const
938 if (move.throw_on_apply)
943 void undo(State &state,
const Move &)
const
945 *state.undo_called =
true;
949 template <
typename Visitor>
950 bool for_each_successor(
const State &state, Visitor visit)
const
954 return visit(Move{
true});
960struct ThrowingPostApplyGameDomain
962 using State = AdversarialThrowState;
963 using Move = AdversarialThrowMove;
966 bool is_terminal(
const State &state)
const
973 Score evaluate(
const State &)
const
978 void apply(State &state,
const Move &)
const
983 void undo(State &state,
const Move &)
const
985 *state.undo_called =
true;
989 template <
typename Visitor>
990 bool for_each_successor(
const State &state, Visitor visit)
const
994 return visit(Move{
false});
999struct ForcedDrawGameDomain
1001 using State = ArtificialGameState;
1002 using Move = ArtificialGameMove;
1005 bool is_terminal(
const State &state)
const
1007 return state.depth == 2;
1010 Score evaluate(
const State &)
const
1015 void apply(State &state,
const Move &move)
const
1017 state.code = move.next_code;
1018 state.player = -state.player;
1022 void undo(State &state,
const Move &)
const
1025 state.player = -state.player;
1029 template <
typename Visitor>
1030 bool for_each_successor(
const State &state, Visitor visit)
const
1032 if (state.depth >= 2)
1034 if (not visit(ArtificialGameMove{2,
'L'}))
1036 return visit(ArtificialGameMove{3,
'R'});
1043struct EmptySuccessorGameDomain
1045 using State = ArtificialGameState;
1046 using Move = ArtificialGameMove;
1049 bool is_terminal(
const State &)
const
1054 Score evaluate(
const State &)
const
1059 void apply(State &,
const Move &)
const
1064 void undo(State &,
const Move &)
const
1069 template <
typename Visitor>
1070 bool for_each_successor(
const State &, Visitor)
const
1078struct ExtremeScoreGameDomain
1080 using State = ArtificialGameState;
1081 using Move = ArtificialGameMove;
1084 bool is_terminal(
const State &state)
const
1086 return state.depth >= 1;
1089 Score evaluate(
const State &state)
const
1092 return adversarial_search_detail::score_ceiling<Score>() * state.player;
1095 void apply(State &state,
const Move &move)
const
1097 state.code = move.next_code;
1098 state.player = -state.player;
1102 void undo(State &state,
const Move &)
const
1105 state.player = -state.player;
1109 template <
typename Visitor>
1110 bool for_each_successor(
const State &state, Visitor visit)
const
1112 if (state.depth >= 1)
1114 return visit(ArtificialGameMove{2,
'A'});
1123class IncrementalEvalGameDomain
1126 using State = ArtificialGameState;
1127 using Move = ArtificialGameMove;
1130 mutable size_t evaluate_after_calls = 0;
1132 bool is_terminal(
const State &state)
const
1134 return state.depth == 2;
1137 Score evaluate(
const State &state)
const
1139 return root_score(state.code) * state.player;
1142 Score evaluate_after(
const State &state,
const Move &move)
const
1144 ++evaluate_after_calls;
1146 const int child_player = -state.player;
1147 return root_score(move.next_code) * child_player;
1150 void apply(State &state,
const Move &move)
const
1152 state.code = move.next_code;
1153 state.player = -state.player;
1157 void undo(State &state,
const Move &)
const
1160 state.player = -state.player;
1164 template <
typename Visitor>
1165 bool for_each_successor(
const State &state, Visitor visit)
const
1167 if (state.depth >= 2)
1173 if (not visit(Move{2,
'A'}))
1175 return visit(Move{3,
'B'});
1178 if (not visit(Move{4,
'a'}))
1180 return visit(Move{5,
'b'});
1183 if (not visit(Move{6,
'a'}))
1185 return visit(Move{7,
'b'});
1193 [[nodiscard]]
static Score root_score(
const size_t code)
noexcept
1214TEST(AdversarialSearchFramework, NegamaxApplyExceptionDoesNotCallUndo)
1216 auto undo_called = std::make_shared<bool>(
false);
1217 ThrowingApplyGameDomain domain;
1222 EXPECT_THROW((
void)
engine.search(AdversarialThrowState{undo_called, 0}),
1223 std::runtime_error);
1224 EXPECT_FALSE(*undo_called);
1227TEST(AdversarialSearchFramework, AlphaBetaApplyExceptionDoesNotCallUndo)
1229 auto undo_called = std::make_shared<bool>(
false);
1230 ThrowingApplyGameDomain domain;
1235 EXPECT_THROW((
void)
engine.search(AdversarialThrowState{undo_called, 0}),
1236 std::runtime_error);
1237 EXPECT_FALSE(*undo_called);
1244TEST(AdversarialSearchFramework, NegamaxPostApplyExceptionCallsUndo)
1246 auto undo_called = std::make_shared<bool>(
false);
1247 ThrowingPostApplyGameDomain domain;
1252 EXPECT_THROW((
void)
engine.search(AdversarialThrowState{undo_called, 0}),
1253 std::runtime_error);
1254 EXPECT_TRUE(*undo_called);
1257TEST(AdversarialSearchFramework, AlphaBetaPostApplyExceptionCallsUndo)
1259 auto undo_called = std::make_shared<bool>(
false);
1260 ThrowingPostApplyGameDomain domain;
1265 EXPECT_THROW((
void)
engine.search(AdversarialThrowState{undo_called, 0}),
1266 std::runtime_error);
1267 EXPECT_TRUE(*undo_called);
1274TEST(AdversarialSearchFramework, ForcedDrawReturnZeroScore)
1276 ForcedDrawGameDomain domain;
1280 auto negamax =
negamax_search(domain, ArtificialGameState{}, {}, limits);
1283 EXPECT_EQ(negamax.value, 0);
1284 EXPECT_EQ(ab.value, 0);
1285 EXPECT_TRUE(negamax.exhausted());
1286 EXPECT_TRUE(ab.exhausted());
1293TEST(AdversarialSearchFramework, EmptySuccessorsInNonTerminalTreatedAsLeaf)
1295 EmptySuccessorGameDomain domain;
1299 auto negamax =
negamax_search(domain, ArtificialGameState{}, {}, limits);
1305 EXPECT_EQ(negamax.value, 42);
1306 EXPECT_EQ(ab.value, 42);
1307 EXPECT_GT(negamax.stats.terminal_states, 0u);
1308 EXPECT_GT(ab.stats.terminal_states, 0u);
1315TEST(AdversarialSearchFramework, ExtremePositiveScoreDoesNotOverflow)
1317 ExtremeScoreGameDomain domain;
1321 auto negamax =
negamax_search(domain, ArtificialGameState{}, {}, limits);
1326 const int ceiling = adversarial_search_detail::score_ceiling<int>();
1327 EXPECT_GT(negamax.value, 0);
1328 EXPECT_LE(negamax.value, ceiling);
1329 EXPECT_EQ(ab.value, negamax.value);
1330 EXPECT_TRUE(negamax.has_principal_variation());
1337TEST(AdversarialSearchFramework, AlphaBetaIncrementalEvaluatorUsesEvaluateAfter)
1339 IncrementalEvalGameDomain domain;
1346 auto result =
engine.search(ArtificialGameState{});
1350 EXPECT_EQ(result.value, 3);
1351 EXPECT_TRUE(result.exhausted());
1354 EXPECT_GT(
engine.domain().evaluate_after_calls, 0u);
1357 EXPECT_GT(result.stats.move_ordering.priority_estimates, 0u);
1360TEST(AdversarialSearchFramework, AlphaBetaIncrementalEvaluatorMatchesLegacy)
1364 ArtificialGameDomain legacy_domain;
1365 IncrementalEvalGameDomain incr_domain;
1372 auto legacy =
alpha_beta_search(legacy_domain, ArtificialGameState{}, policy, limits);
1373 auto incr =
alpha_beta_search(incr_domain, ArtificialGameState{}, policy, limits);
1375 EXPECT_EQ(legacy.value, incr.value);
1376 EXPECT_EQ(legacy.stats.terminal_states, incr.stats.terminal_states);
Umbrella header for the implicit state-space search framework.
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error()
Throws std::runtime_error unconditionally.
static int cell(const aleph_ca_engine_t *e, size_t r, size_t c)
size_t size_t int32_t * out
Collector that stores trace events in an Aleph list.
const Container_Type & events() const noexcept
Read-only access to the recorded event list.
Adversarial search engine with Alpha-Beta pruning.
Result search_with_window(State initial_state, const Score alpha, const Score beta)
Execute Alpha-Beta with an explicit root window.
static ExplorationPolicy default_policy() noexcept
Return the default exploration policy for Alpha-Beta.
Result search(State initial_state)
Execute Alpha-Beta from initial_state.
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Pure Negamax search over an implicit game tree.
static ExplorationPolicy default_policy() noexcept
Return the default exploration policy for adversarial search.
Result search(State initial_state)
Execute Negamax from initial_state.
Transposition-table container built on top of Aleph hash maps.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
auto iterative_deepening_alpha_beta_search(Domain domain, typename Domain::State initial_state, Tracer &tracer, ExplorationPolicy policy=Alpha_Beta< Domain >::default_policy(), SearchLimits limits={}, AdversarialIterativeDeepeningOptions< typename Domain::Score > options={})
Iterative deepening over Alpha-Beta with optional aspiration windows.
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
auto iterative_deepening_negamax_search(Domain domain, typename Domain::State initial_state, ExplorationPolicy policy=Negamax< Domain >::default_policy(), SearchLimits limits={}, AdversarialIterativeDeepeningOptions< typename Domain::Score > options={})
Iterative deepening over Negamax without transposition table.
and
Check uniqueness with explicit hash + equality functors.
auto alpha_beta_search(Domain domain, typename Domain::State initial_state, ExplorationPolicy policy=Alpha_Beta< Domain >::default_policy(), SearchLimits limits={})
Convenience wrapper for one-shot Alpha-Beta search.
AdversarialTraceEventKind
Trace event kinds emitted by adversarial search engines.
@ Domain
Preserve the order emitted by for_each_successor().
auto negamax_search(Domain domain, typename Domain::State initial_state, ExplorationPolicy policy=Negamax< Domain >::default_policy(), SearchLimits limits={})
Convenience wrapper for one-shot Negamax search.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
std::string next_code(const Aleph::Adaptive_Huffman_Encoder &encoder, const unsigned char byte)
Probe a byte's code without changing the source encoder.
Domain domain(int max_nodes, int max_arcs)
The domain of max_nodes nodes and max_arcs arcs, of one more of each in heavy mode,...
static struct argp_option options[]
Controls for adversarial iterative deepening.
size_t initial_depth
First horizon to search.
One trace event produced by an adversarial search.
AdversarialTraceEventKind kind
Exploration controls shared across engines.
Strategy strategy
Traversal strategy.
MoveOrderingMode move_ordering
Successor-ordering mode.
bool use_history_heuristic
Enable experimental history heuristic where supported.
bool use_killer_moves
Enable experimental killer heuristic where supported.
Hard bounds applied by the search engine.
size_t max_depth
Maximum expansion depth.