// this stucture simply defines the characteristic of each player
typedef struct {
std::string name;
char symbol;
int move;
int game_win;
int draw_num;
bool selected;
bool win;
} player;
evaluate_position(char _board[9], player _player);
// the three functions below implements the MiniMax algorithm
int MiniMax(char _board[9], player _player); // main function for MiniMax algorithm
int MinMove(char _board[9], player _player); // Min Move MiniMax algorithm
int MaxMove(char _board[9], player _player); // Max Move function for MiniMax algorithm
// returns best move for the current computer player
int MiniMax(char _board[9], player _player) {
int best_val = -INFINITY, index = 0;
std::list<int> move_list;
char best_moves[9] = {0};
generate_moves(_board, move_list);
while(!move_list.empty()) {
_board[move_list.front()] = _player.symbol;
cSymbol = _player.symbol;
int val = MinMove(_board, _player);
if(val > best_val) {
best_val = val;
index = 0;
best_moves[index] = move_list.front() + 1;
} else if(val == best_val) {
best_moves[++index] = move_list.front() + 1;
}
_board[move_list.front()] = 0;
move_list.pop_front();
}
if(index > 0) {
index = rand() % index;
}
return best_moves[index];
}
// finds best move for 'min player'
int MinMove(char _board[9], player _player) {
int pos_value = evaluate_position(_board, _player);
if(pos_value != -1) {
return pos_value;
}
int best_val = +INFINITY;
std::list<int> move_list;
generate_moves(_board, move_list);
while(!move_list.empty()) {
_player.symbol == 'X' ? cSymbol = 'O' : cSymbol = 'X';
_board[move_list.front()] = cSymbol;
int val = MaxMove(_board, _player);
if(val < best_val) {
best_val = val;
}
_board[move_list.front()] = 0;
move_list.pop_front();
}
return best_val;
}
// finds best move for 'max player'
int MaxMove(char _board[9], player _player) {
int pos_value = evaluate_position(_board, _player);
if(pos_value != -1) {
return pos_value;
}
int best_val = -INFINITY;
std::list<int> move_list;
generate_moves(_board, move_list);
while(!move_list.empty()) {
_player.symbol == 'X' ? cSymbol = 'X' : cSymbol = 'O';
_board[move_list.front()] = cSymbol;
int val = MinMove(_board, _player);
if(val > best_val) {
best_val = val;
}
_board[move_list.front()] = 0;
move_list.pop_front();
}
return best_val;
}