-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimax.cpp
125 lines (110 loc) · 2.65 KB
/
minimax.cpp
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
#include "minimax.h"
#include <QList>
#include <QCoreApplication>
#include <QtDebug>
/**
* Constructor
*
* @param rootNode
* @param maxDepth
*/
Minimax::Minimax(QSharedPointer<Board> rootNode,int maxDepth) :
rootNode(rootNode), maxDepth(maxDepth)
{
BoardPosition bestMove = {0,0};
this->bestMove = bestMove;
}
/**
* Desctructor
*
*/
Minimax::~Minimax()
{
}
/**
* Search the tree
* Begins at the root node
*
* @return int
*/
int Minimax::search()
{
return calculate(this->rootNode,0,-10000,10000, 0);
}
/**
* Evaluates all possible moves and returns best move
* http://de.wikipedia.org/wiki/Minimax-Algorithmus
*
* @param board
* @param depth
* @param alpha
* @param beta
* @param level
* @return int
*/
int Minimax::calculate(QSharedPointer<Board> board, int depth, int alpha, int beta, int level=1)
{
if (++depth > this->maxDepth || board->isGameOver()) {
return board->getScore();
}
const CELL_STATE whoseNext = board->getWhoIsNext();
const QList<BoardPosition> moves = board->getValidMoves(whoseNext);
BoardPosition bestMove = {0,0};
foreach(const BoardPosition move, moves)
{
QSharedPointer<Board> simBoard(new Board(*board));
simBoard->makeMove(move,whoseNext);
int score = this->calculate(simBoard,depth,alpha,beta,level++);
if (whoseNext == WHITE)
{
if (score > alpha)
{
alpha = score;
bestMove = move;
}
else if (score == alpha && qrand() % 2) {
bestMove = move;
}
if (beta <= alpha) {
break;
}
}
else if (whoseNext == BLACK)
{
if (score < beta)
{
beta = score;
bestMove = move;
}
else if (score == beta && qrand() % 2) {
bestMove = move;
}
if (beta <= alpha) {
break;
}
}
}
if (depth == 1) {
this->bestMove = bestMove;
}
/*
Return the score of the board configuration created by optimal-play by both players if the
so-called best move is taken
*/
if (whoseNext == WHITE) {
return alpha;
}
else {
return beta;
}
}
/**
* Just a getter to get the last calculated best move
* because the algorithm is too heavy to recalculate every single time
*
* @return BoardPosition
*/
BoardPosition Minimax::getBestMove() const
{
return this->bestMove;
}