-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeSearch.h
58 lines (46 loc) · 1.77 KB
/
TreeSearch.h
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
// treesearch.h
// Jeffrey Drost
#ifndef TREESEARCH_H
#define TREESEARCH_H
#include <vector>
class TreeSearch {
public:
template <class O>
static int MiniMaxAB(O branch, int (*evaluate)(const O &, const Player &), std::vector<O> (*findChildNodes)(const O &), int depth, bool maximize, Player p, int worstVal, int bestVal, bool *isFullTreeEvaluated);
};
#endif //TREESEARCH_H
// treesearch.cpp
template<class O>
int TreeSearch::MiniMaxAB(O branch, int (*evaluate)(const O &, const Player &), std::vector<O> (*findChildNodes)(const O &), int depth, bool maximize, Player p, int worstVal, int bestVal, bool *isFullTreeEvaluated)
{
// Get all child nodes with function passed as argument
auto children = findChildNodes(branch);
// This branch has no children, all we can do is evaluate it now
if(children.empty()) {
return evaluate(branch, p);
}
// Depth limit has been reached, return value of current node
if(depth == 0) {
*isFullTreeEvaluated = false;
return evaluate(branch, p);
}
int value;
if(maximize) {
value = worstVal;
for(O child:children) {
int childVal = MiniMaxAB(child, evaluate, findChildNodes, depth-1, false, p, worstVal, bestVal, isFullTreeEvaluated);
if(childVal > value) value = childVal;
if(value > worstVal) worstVal = value;
if(worstVal >= bestVal) break;
}
} else {
value = bestVal;
for(O child:children) {
int childVal = MiniMaxAB(child, evaluate, findChildNodes, depth-1, true, p, worstVal, bestVal, isFullTreeEvaluated);
if(childVal < value) value = childVal;
if(value < bestVal) bestVal = value;
if(worstVal >= bestVal) break;
}
}
return value;
}