-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.cpp
More file actions
75 lines (56 loc) · 2.32 KB
/
engine.cpp
File metadata and controls
75 lines (56 loc) · 2.32 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
#include <limits>
#include <thread>
#include <chrono>
#include "utils.hpp"
#include "engine.hpp"
Engine::Engine() {}
int Engine::minimax(Board board, bool isMax, int depth) {
int score = board.evaluate();
// we subract the depth because we want to prioritise the moves that are closest to the top of the tree
if (score == 10) return score - depth;
if (score == -10) return score + depth;
if (!board.isMovesLeft()) return 0;
int bestScore = isMax ? std::numeric_limits<int>::max() : std::numeric_limits<int>::min();
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (board.getCell(row, col) == ' ') {
board.setCell(row, col, isMax ? 'X' : 'O');
int val = minimax(board, !isMax, depth + 1);
board.setCell(row, col, ' ');
if (val <= bestScore && isMax) {
bestScore = val;
}
else if (val >= bestScore && !isMax) {
bestScore = val;
}
}
}
}
return bestScore;
}
std::pair<int, int> Engine::findBestMove(Board board) {
std::chrono::milliseconds time(artificialDelay);
std::this_thread::sleep_for(time);
std::pair<int, int> bestMove = { -1, -1 };
int bestScore = std::numeric_limits<int>::min();
int score{};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (board.getCell(row, col) == ' ') {
board.setCell(row, col, 'O');
score = minimax(board, true, 0);
utils::log("log.txt", board.toString(false), true);
utils::log("log.txt", "score: " + std::to_string(score) + "\n", true);
board.setCell(row, col, ' ');
if (score >= bestScore) {
bestScore = score;
bestMove = { row, col };
}
}
}
}
utils::log("log.txt", "best score: " + std::to_string(bestScore) + "\n", true);
utils::log("log.txt", "best move: " + std::to_string(bestMove.first) + ", " + std::to_string(bestMove.second) + "\n", true);
utils::log("log.txt", "-----------------------------\n", true);
return bestMove;
}