-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecisiontree.cpp
More file actions
72 lines (60 loc) · 2.3 KB
/
decisiontree.cpp
File metadata and controls
72 lines (60 loc) · 2.3 KB
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
#include "decisiontree.h"
DecisionTree::DecisionTree(Board *board, Side maximizer) {
// this is our side
this->maximizer = maximizer;
root = new Node(NULL, maximizer == BLACK ? WHITE : BLACK, maximizer, board);
}
DecisionTree::~DecisionTree() {
// free some stuff
}
Move *DecisionTree::findBestMove(int depth) {
Board *board = root->getBoard();
vector<Move> moves = board->getMoves(maximizer);
Node *best = NULL;
for (int i = 0; i < moves.size(); i++) {
Move *move = new Move(moves[i].getX(), moves[i].getY());
Board *newBoard = board->copy();
newBoard->doMove(move, maximizer);
Node *child = new Node(move, maximizer, maximizer, newBoard);
// pass alpha and beta values down
child->setAlpha(root->getAlpha());
child->setBeta(root->getBeta());
// search child
search(child, depth - 1);
if (best == NULL || child->getBeta() > best->getBeta()) {
best = child;
}
}
return best->getMove();
}
void DecisionTree::search(Node *startingNode, int depth) {
if (depth == 0) {
startingNode->setAlpha(startingNode->getBoard()->getScore(maximizer));
startingNode->setBeta(startingNode->getBoard()->getScore(maximizer));
return;
}
Board *board = startingNode->getBoard();
Side oppositeSide = startingNode->getSide() == BLACK ? WHITE : BLACK;
vector<Move> moves = board->getMoves(oppositeSide);
for (int i = 0; i < moves.size(); i++) {
// create the next child
Move *move = new Move(moves[i].getX(), moves[i].getY());
Board *newBoard = board->copy();
newBoard->doMove(move, oppositeSide);
Node *child = new Node(move, oppositeSide, maximizer, newBoard);
// pass alpha and beta values down
child->setAlpha(startingNode->getAlpha());
child->setBeta(startingNode->getBeta());
// search child
search(child, depth - 1);
if (startingNode->getSide() == maximizer) {
startingNode->setBeta(min(startingNode->getBeta(), child->getAlpha()));
} else {
startingNode->setAlpha(max(startingNode->getAlpha(), child->getBeta()));
}
delete child;
if (startingNode->getAlpha() > startingNode->getBeta()) {
return;
}
}
}