-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinMaxplayer.cc
More file actions
79 lines (71 loc) · 1.96 KB
/
MinMaxplayer.cc
File metadata and controls
79 lines (71 loc) · 1.96 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
#include "MinMaxplayer.h"
namespace Othello{
pair<int, bool> MinMaxPlayer::calcMinMax(const ChessBoard &board, Color color){
ull pos = board.getPossibleUll(color);
if (pos == 0)
return make_pair(-1, true);
ChessBoard tb;
int res = color == BLACK ? -2 : 2, ret, loc = -1;
// test all possible steps
for (int i = 0; pos; ++i, pos >>= 1)
if (pos & 1){
tb = board, tb.play(color, i);
if (color == BLACK){
if (res < (ret = minValue(tb, res, 1)))
res = ret, loc = i;
}
else{
if (res > (ret = maxValue(tb, -1, res)))
res = ret, loc = i;
}
}
fprintf(stderr, "+++++++++++++ MinMaxPlayer: color: %s\nresult check = %d, %d\n", color == BLACK ? "BLACK" : "WHITE", res, loc);
return make_pair(loc, color == BLACK ? res != -1 : res != 1);
}
int MinMaxPlayer::minValue(const ChessBoard &board, int a, int b){
if (board.isFull())
return board.getResult();
vector<int> pos = board.getPossible(WHITE);
// no possible steps
if (pos.size() == 0){
if (!board.haveStep(BLACK)) // is a terminal state
return board.getResult();
else
return maxValue(board, a, b);
}
// randomly expand
random_shuffle(pos.begin(), pos.end());
ChessBoard tb;
int ret = 1;
for (size_t i = 0; i < pos.size(); ++i){
tb = board, tb.play(WHITE, pos[i]);
ret = min(ret, maxValue(tb, a, b));
if (ret <= a)
return ret;
b = min(b, ret);
}
return ret;
}
int MinMaxPlayer::maxValue(const ChessBoard &board, int a, int b){
if (board.isFull())
return board.getResult();
vector<int> pos = board.getPossible(BLACK);
if (pos.size() == 0){
if (!board.haveStep(WHITE))
return board.getResult();
else
return minValue(board, a, b);
}
random_shuffle(pos.begin(), pos.end());
ChessBoard tb;
int ret = -1;
for (size_t i = 0; i < pos.size(); ++i){
tb = board, tb.play(BLACK, pos[i]);
ret = max(ret, minValue(tb, a, b));
if (ret >= b)
return ret;
a = max(a, ret);
}
return ret;
}
}