-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.cpp
348 lines (281 loc) · 10.9 KB
/
core.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#include <iostream>
#include <algorithm>
#include <string>
#include <list>
#include <array>
#include <limits>
#include <thread>
#include <chrono>
#define INF numeric_limits<int>::max()
#define EMPTY ' '
#define BLACK 'B'
#define WHITE 'W'
using namespace std;
// Struct for a position on the board
struct TilePosition {
int x = -1;
int y = -1;
bool operator==(const TilePosition& other) const {
return x == other.x && y == other.y;
}
string toString() {
return "(" + to_string(x) + ":" + to_string(y) + ")";
}
};
// Struct for a move
struct Move {
TilePosition placedTile;
list<TilePosition> flippedTiles;
bool operator==(const Move& other) const {
return placedTile.x == other.placedTile.x && placedTile.y == other.placedTile.y;
}
string toString() {
return "Placed tile " + placedTile.toString() + " and rotating " + to_string(flippedTiles.size()) + " tiles.";
}
};
// Struct for the game board
struct Board {
// 2D array for the board
array<array<char, 8>, 8> array = {{
{EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY, BLACK, WHITE, EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY, WHITE, BLACK, EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY}
}};
bool isBlackTurn = false;
// Update the flipped tiles for a move
void setFlippedTiles(Move* move) {
// Get adjacent tiles
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (x == 0 && y == 0) continue;
int newX = move->placedTile.x + x;
int newY = move->placedTile.y + y;
if (newX < 0 || newX >= 8 || newY < 0 || newY >= 8) continue; // Out of bounds
if (array[newY][newX] == (isBlackTurn ? BLACK : WHITE) || array[newY][newX] == EMPTY) continue; // Not a tile to flip
/* DEBUG
Board newBoard(*this);
newBoard.array[move->placedTile.x][move->placedTile.y] = 'H';
cout << newBoard.toString() << endl;
*/
// While the tile is not empty and not the same color as the placed tile
list<TilePosition> tilesToFlip;
while (true) {
if (array[newY][newX] == (isBlackTurn ? WHITE : BLACK)) {
tilesToFlip.push_back({newX, newY});
} else if (array[newY][newX] == (isBlackTurn ? BLACK : WHITE)) {
// Tiles are sourrounded by the same color -> Valid move
move->flippedTiles.splice(move->flippedTiles.end(), tilesToFlip);
break;
} else break; // Invalid move
// Check next tile in the same direction
newX += x;
newY += y;
if (newX < 0 || newX >= 8 || newY < 0 || newY >= 8) break;
}
}
}
// Remove duplicates
move->flippedTiles.unique();
}
bool hasAdjacent(int x, int y, char tile) {
// TODO: fix
// Get adjacent tiles
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int newX = x + i;
int newY = y + j;
if (newX < 0 || newX >= 8 || newY < 0 || newY >= 8) continue;
if (array[newY][newX] == tile) return true;
}
}
return false;
}
list<Move> getPossibleMoves() {
list<Move> moves;
// For each field
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
if (array[y][x] != EMPTY) continue; // Not empty
if (!hasAdjacent(x, y, isBlackTurn ? WHITE : BLACK)) continue; // No adjacent opponent tiles
// DEBUG
// cout << "Possible move: " << x << ":" << y << endl;
moves.push_back({{x, y}, {}});
}
}
// Remove duplicates
moves.sort([](Move move1, Move move2){
return move1.placedTile.x * 10 + move1.placedTile.y < move2.placedTile.x * 10 + move2.placedTile.y;
});
moves.unique();
/* DEBUG
Board newBoard(*this);
for (Move move : moves) {
if (newBoard.array[move.placedTile.y][move.placedTile.x] == '-') cout << "WARNING: Duplicate found!";
newBoard.array[move.placedTile.y][move.placedTile.x] = '-';
}
cout << newBoard.toString() << endl;
*/
// Remove tiles that don't flip any tiles
for (auto it = moves.begin(); it != moves.end();) {
// Update flipped tiles
setFlippedTiles(&*it);
if (it->flippedTiles.size() == 0) it = moves.erase(it);
else it++;
}
return moves;
}
// Make a move
void makeMove(Move* move) {
if (move->placedTile.x != -1 && move->placedTile.y != -1) {
// Place new tile
array[move->placedTile.y][move->placedTile.x] = isBlackTurn ? BLACK : WHITE;
// Flip tiles
for (TilePosition tilePosition : move->flippedTiles) {
array[tilePosition.y][tilePosition.x] = isBlackTurn ? BLACK : WHITE;
}
}
// Switch turn
isBlackTurn = !isBlackTurn;
}
// Evaluate the score for the current board
// White is maximizing player
int evaluateScore() {
int score = 0;
bool onlyBlack = true;
bool onlyWhite = true;
// For each field
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
// If the tile is the same color as the player, add to score (positive), else subtract (negative)
if (array[i][j] == BLACK) {
score--;
onlyWhite = false;
} else if (array[i][j] == WHITE) {
score++;
onlyBlack = false;
}
}
}
// Amplify win score
if (onlyBlack) score = -INF;
else if (onlyWhite) score = INF;
return score;
}
string toString() {
string result;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
result += "|";
result += array[i][j];
}
result += "|\n";
}
return result;
}
};
// Minimax algorithm based on https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-4-alpha-beta-pruning/
int _minimax(Board* board, int depth, int alpha = -INF, int beta = INF) {
// If depth is reached return the score
if (depth == 0) return board->evaluateScore();
list<Move> moves = board->getPossibleMoves();
// If no moves are possible, game is over and return the score
if (moves.size() == 0) {
board->isBlackTurn = !board->isBlackTurn;
moves = board->getPossibleMoves();
if (moves.size() == 0) return board->evaluateScore();
}
if (!board->isBlackTurn) {
int maxEval = -INF;
for (Move move : moves) {
Board newBoard(*board);
newBoard.makeMove(&move);
// Recursively call minimax and get the best possible score
int eval = _minimax(&newBoard, depth - 1, alpha, beta);
// Alpha-beta pruning
maxEval = max(maxEval, eval);
alpha = max(alpha, maxEval);
if (beta <= alpha) break;
}
return maxEval;
} else {
int maxEval = INF;
for (Move move : moves) {
Board newBoard(*board);
newBoard.makeMove(&move);
// Recursively call minimax and get the best possible score
int eval = _minimax(&newBoard, depth - 1, alpha, beta);
// Alpha-beta pruning
maxEval = min(maxEval, eval);
beta = min(beta, maxEval);
if (beta <= alpha) break;
}
return maxEval;
}
}
void _launchMinimax(Board board, Move move, int depth, bool isMaximizingPlayer, int &bestEval, Move &bestMove, int &progress, int total) {
chrono::steady_clock::time_point start = chrono::steady_clock::now();
// Make move
Board newBoard(board);
newBoard.makeMove(&move);
// Minimax and if best move yet, update best move
int eval = _minimax(&newBoard, depth);
if ((isMaximizingPlayer && eval > bestEval) || (!isMaximizingPlayer && eval < bestEval)) {
bestEval = eval;
bestMove = move;
}
// Update debug info
progress++;
long duration = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count();
cout << "Processed " << progress << "/" << total << " solutions (" << duration << "ms" << "). \r";
}
// Function to get the best move using minimax
Move getBestMove(Board* board, int depth) {
list<Move> possibleMoves = board->getPossibleMoves();
list<thread> threads;
bool isMaximizingPlayer = !board->isBlackTurn;
int progress = 0;
int bestEval = isMaximizingPlayer ? -INF : INF;
Move bestMove;
// Launch thread for each possible move
for (Move move : possibleMoves) {
threads.push_back(thread(_launchMinimax, *board, move, depth, isMaximizingPlayer, ref(bestEval), ref(bestMove), ref(progress), possibleMoves.size()));
}
// Wait for all threads to finish
for (thread &thread : threads) thread.join();
cout << endl << "Best eval: " << bestEval << endl;
return bestMove;
}
// For testing
int main() {
Board board;
Move move;
long total = 0;
long max = 0;
int count = 0;
int no_possible_move_count = 0;
while (no_possible_move_count < 2) {
chrono::steady_clock::time_point start = chrono::steady_clock::now();
move = getBestMove(&board, 6);
cout << move.toString() << endl;
long duration = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count();
if (duration > max) max = duration;
total += duration;
count++;
board.makeMove(&move);
cout << board.toString() << endl;
if (move.placedTile.x == -1) no_possible_move_count++;
else no_possible_move_count = 0;
}
cout << "Average: " << to_string(total / count) << "ms" << endl;
cout << "Max: " << to_string(max) << "ms" << endl;
int score = board.evaluateScore();
if (score > 0) cout << "White wins! (" + to_string(score) + ")" << endl;
else if (score < 0) cout << "Black wins! (" + to_string(score) + ")" << endl;
else cout << "Draw!" << endl;
return 0;
}