-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.cpp
More file actions
143 lines (115 loc) · 2.14 KB
/
Tree.cpp
File metadata and controls
143 lines (115 loc) · 2.14 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include "Tree.h"
#include "heuristics.h"
#include <iostream>
#include <time.h>
Tree::Tree(const TBoard& brd) :
state(brd),
move(-10),
parent(0),
depth(0),
min(false),
value_definite(0),
value(0)
{
}
Tree::Tree(Tree* prnt, const TBoard& brd, int dpth, bool mn, int mv) :
state(brd),
move(mv),
parent(prnt),
depth(dpth),
min(mn),
value_definite(0),
value(0)
{
}
//-------------------------------------------------------------------------
void Tree::expand()
{
children.clear();
for (unsigned int i = 0; i < state.size(); i++)
{
for (unsigned int j = 0; j < state.size(); j++)
{
if (state[i][j] == '_')
{
if (min)
{
state[i][j] = 'O';
}
else
{
state[i][j] = 'X';
}
children.push_back(Tree(this, state, depth+1, !min, 10*i + j));
state[i][j] = '_';
}
}
}
}
int Tree::minimax(int maxdpth)
{
int best = -10;
int n=0;
int rresult;
// initialize a random number generator
srand(time(NULL));
minimax_propag(maxdpth);
int collect;
if (min)
{
collect = 1000 * 1000;
}
else
{
collect = - 1000 * 1000;
}
for (std::list<Tree>::const_iterator it = children.begin(); it != children.end(); ++it)
{
if (it->Value() == value)
{
n++;
rresult=rand() % n;
if (rresult == 0) {best = it->Move();}
}
}
return best;
}
//-------------------------------------------------------------------------
void Tree::minimax_propag(int maxdpth)
{
// at maximum depth, use heuristics
if (depth >= maxdpth)
{
eval();
return;
}
expand();
int collect;
if (min)
{
collect = 1000 * 1000;
}
else
{
collect = - 1000 * 1000;
}
// go thru the chilren
for (std::list<Tree>::iterator it = children.begin(); it != children.end(); ++it)
{
it->minimax_propag(maxdpth);
int childval = it->Value();
if (min)
{
collect = (collect < childval) ? collect : childval;
}
else
{
collect = (collect > childval) ? collect : childval;
}
}
value = collect;
}
void Tree::eval()
{
value = ::eval(state);
}