-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgame.cpp
388 lines (335 loc) · 11.5 KB
/
game.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*************************
* GAME.CPP
* game class declaration
************************/
#ifndef _GAME_CPP_
#define _GAME_CPP_
#include <iostream>
#include <fstream>
#include <vector>
#include <climits>
#include <time.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include "game.h"
#include "board.h"
#include "const.h"
using namespace std;
//Game::Game()
// empty Game constructor
Game::Game(){}
//void Game::Setup(int gameType)
// game setup method - initialies board and game state
// based on gameType, allowing user to import board
// state from a file in the specified format
// gameType:
// 1: go first (black)
// 2. go second (white)
// 3: computer vs. computer
void Game::Setup(int gameType){
char import;
switch(gameType){
case(1):
humanPlayer[BLACK] = true;
humanPlayer[WHITE] = false;
break;
case(2):
humanPlayer[BLACK] = false;
humanPlayer[WHITE] = true;
break;
case(3):
humanPlayer[BLACK] = false;
humanPlayer[WHITE] = false;
break;
default:
throw;
}
cout << "Import a board state? (Y/N) ";
cin >> import;
//allow user to import a board state
if(tolower(import) == 'y'){
char c, boardState[8][8];
int player, i = 0, j = 0;
string fileName;
fstream boardFile;
cout << "Enter a file name: ";
cin >> fileName;
boardFile.open(fileName.c_str(), fstream::in);
//make sure user enters a valid file path
while(boardFile.fail()){
cout << "Invalid file!" << endl;
cout << "Enter a file name: ";
cin >> fileName;
boardFile.open(fileName.c_str(), fstream::in);
}
//scan the file and generate a board state
while((c = boardFile.get()) != EOF){
if((c == '0') || (c == '1') || (c == '2')){
boardState[i][j++] = c-'0';
if(j == BOARDSIZE){
j = 0;
if(++i == BOARDSIZE)
break;
}
}
}
boardFile >> player;
boardFile >> timeLimit;
board = Board(boardState, player);
boardFile.close();
}
else{
string t;
timeLimit = -1;
while(timeLimit < 0){
cout << "Enter a time limit: ";
cin >> t;
if(isdigit(t.c_str()[0]))
timeLimit = atoi(t.c_str());
}
board = Board();
}
}
//int Game::heuristic(Board b)
// heuristic evaluation of board state
// accounts for number of pieces of each color, corners,
// potential corners (that the opponent can capture),
// frontier pieces, mobility, and edges
//
// reference:
// Kartik Kukreja, New Delhi, India
// {http://kartikkukreja.wordpress.com/2013/03/30/heuristic-function-for-reversiothello/}
int Game::heuristic(Board b){
double piececount, corners, potentialCorners, edges, frontier, mobility;
int mine, opp;
int opponent = (maxPlayer == WHITE)
? BLACK
: WHITE;
//set weights of heuristic parameters
int pW = 2*(b.score[maxPlayer]+b.score[opponent]);
int cW = 5000;
int pcW = 2000;
int fW = 200;
int eW = 50;
int mW = 10*(100-(b.score[maxPlayer]+b.score[opponent]));
//piece count
piececount = (100.0*b.score[maxPlayer])/(b.score[maxPlayer] + b.score[opponent]);
//corners
mine = 0, opp = 0;
if(b.board[0][0] == maxPlayer) mine++;
else if(b.board[0][0] == opponent) opp++;
if(b.board[0][7] == maxPlayer) mine++;
else if(b.board[0][7] == opponent) opp++;
if(b.board[7][0] == maxPlayer) mine++;
else if(b.board[7][0] == opponent) opp++;
if(b.board[7][7] == maxPlayer) mine++;
else if(b.board[7][7] == opponent) opp++;
corners = 25.0*(mine - opp);
//edges and frontier
int myEdges = 0, oppEdges = 0;
int myFrontier = 0, oppFrontier = 0;
for(int i = 0; i < BOARDSIZE; i++){
for(int j = 0; j < BOARDSIZE; j++){
if(i == 0 || i == BOARDSIZE-1 || j == 0 || j == BOARDSIZE-1){
if(b.board[i][j] == maxPlayer) myEdges++;
else if(b.board[i][j] == opponent) oppEdges++;
}
else if(b.board[i][j] != '0'){
if(b.OnFrontier(i, j)){
if(b.board[i][j] == maxPlayer) myFrontier++;
else if(b.board[i][j] == opponent) oppFrontier++;
}
}
}
}
edges = 100.0*myEdges/(myEdges + oppEdges);
frontier = -100*(myFrontier - oppFrontier); //frontier pieces are bad!
//mobility
vector<Board::Move> myLegal = board.LegalMoves(maxPlayer);
vector<Board::Move> oppLegal = board.LegalMoves(opponent);
mobility = 100.0*myLegal.size()/(myLegal.size() + oppLegal.size());
//potential corners (pseudo-expand node)
opp = 0;
for(int i = 0; i < oppLegal.size(); i++){
if(oppLegal[i].square.y == 0 && oppLegal[i].square.x == 0) opp++;
else if(oppLegal[i].square.y == 0 && oppLegal[i].square.x == (BOARDSIZE-1)) opp++;
else if(oppLegal[i].square.y == (BOARDSIZE-1) && oppLegal[i].square.x == 0) opp++;
else if(oppLegal[i].square.y == (BOARDSIZE-1) && oppLegal[i].square.x == (BOARDSIZE-1)) opp++;
}
potentialCorners = -25.0*opp;
return pW*piececount + cW*corners + pcW*potentialCorners+ eW*edges + fW*frontier + mW*mobility;
}
//int Game::alphabeta(Board board, int depth, int alpha, int beta, bool maxPlayer)
// alpha beta search method implementing minimax A* search
// with alpha beta pruning
// reference
// {http://aima.cs.berkeley.edu/python/games.html}
int Game::alphabeta(Board board, int depth, int alpha, int beta, bool maxPlayer){
int a = alpha, b = beta, msize;
//do a quick check on time limit and depth
if((((float)(clock()-startTime))/CLOCKS_PER_SEC) > TIMECUTOFF*timeLimit){
timeout = true;
return heuristic(board);
}
else if(depth == 0)
return heuristic(board);
else
depth--;
vector<Board::Move> m = board.LegalMoves(board.currentPlayer); //expand
msize = m.size();
if(msize == 0){ //no legal moves
if(board.TerminalState(true)){ //check terminal state
Board child = board;
child.NextPlayer(false);
return heuristic(child);
}
else{ //if pass is only move, continue search with pass
Board child = board;
child.NextPlayer(true);
return alphabeta(child, depth, alpha, beta, !maxPlayer);
}
}
if(maxPlayer){ //maximize alpha
int v = INT_MIN;
for(int i = 0; i < msize; i++){
Board child = board;
child.ApplyMove(m[i]);
child.NextPlayer(false);
int eval = alphabeta(child, depth, a, b, false);
v = MAX(v, eval);
//if opponent can make a move that will give max
//a lower score than alpha, this branch is not
//worth exploring
if(v >= beta)
return v;
a = MAX(a, v);
}
return v;
}
else{ //minimize beta
int v = INT_MAX;
for(int i = 0; i < msize; i++){
Board child = board;
child.ApplyMove(m[i]);
child.NextPlayer(false);
int eval = alphabeta(child, depth, a, b, true);
v = MIN(v, eval);
//if opponent can make a move that will give max
//a lower score than alpha, this branch is not
//worth exploring
if(v <= a)
return v;
b = MIN(b, v);
}
return v;
}
}
//bool Game::smartMove()
// intelligent move selection using alpha beta tree search
// returns false if game in terminal state
bool Game::smartMove(){
int depth, eval, moveNum;
int depthLimit = NUMSQUARES - (board.score[BLACK] + board.score[WHITE]);
Board::Move move, bestMove;
startTime = clock();
maxPlayer = board.currentPlayer;
//expand layer 1
vector<Board::Move> legal = board.LegalMoves(board.currentPlayer);
if(legal.size() == 0){ //if no legal moves, pass
cout << "Computer had to pass :(" << endl;
return board.NextPlayer(true);
}
//increment depth of search until time runs out
//look for the move with the MAX evaluation
for(depth = 0; (((float)(clock()-startTime))/CLOCKS_PER_SEC < timeLimit/2.0) && depth < depthLimit; depth++){
int alpha = INT_MIN, beta = INT_MAX, randMove = 1;
timeout = false; //reset timeout
for(int i = 0; i < legal.size(); i++){ //maximize alpha
Board child = board;
child.ApplyMove(legal[i]);
child.NextPlayer(false);
eval = alphabeta(child, depth, alpha, beta, false);
//if this depth timed out, use the best move from the previous depth
if(timeout)
break;
if(eval > alpha){
move = legal[i];
moveNum = i;
alpha = eval;
}
else if(eval == alpha){
//use the new move instead of the existing one with uniform probabilty
if(((rand() % randMove++)-1) == 0){
move = legal[i];
moveNum = i;
}
}
}
bestMove = move;
}
cout << "Searched to depth: " << depth << " in " << ((float)(clock()-startTime))/CLOCKS_PER_SEC << " seconds" << endl;
cout << "Computer chose move " << moveNum << endl;
board.Print(vector<Board::Move>(1,move), true);
board.ApplyMove(move);
return board.NextPlayer(false);
}
//bool Game::randomMove()
// random move method for testing
// returns false if game in terminal state
bool Game::randomMove(){
vector<Board::Move> m = board.LegalMoves(board.currentPlayer);
if(m.size()){
Board::Move randMove = m[rand() % m.size()];
board.Print(vector<Board::Move>(1,randMove), true);
board.ApplyMove(randMove);
return board.NextPlayer(false);
}
else{
cout << "Computer had to pass :(" << endl;
return board.NextPlayer(true);
}
}
//bool Game::humanMove()
// method to apply move to game based on human input
// returns false if game in terminal state
bool Game::humanMove(){
int moveNum = -1;
string in;
vector<Board::Move> m = board.LegalMoves(board.currentPlayer);
if(m.size()){
board.Print(m);
for(int i = 0; i < m.size(); i++)
cout << i << ": [" << (int)m[i].square.y << "," << (int)m[i].square.x << "]" << endl;
//make sure the user inputs a valid move
while(!(moveNum < m.size() && moveNum >= 0)){
cout << "Choose your move wisely: " << endl;
cin >> in;
if(isdigit(in.c_str()[0]))
moveNum = atoi(in.c_str());
}
board.ApplyMove(m[moveNum]);
return board.NextPlayer(false);
}
else{
cout << "Sorry, you have to pass :(" << endl;
return board.NextPlayer(true);
}
}
//void Game::Play()
// main game loop
void Game::Play(){
bool gameOver = false;
srand(time(NULL)); //seed rand
cout << "Let the game begin!" << endl << endl;
board.Print();
while(!gameOver){
if(humanPlayer[board.currentPlayer])
gameOver = humanMove();
else
gameOver = smartMove();
}
board.Print();
board.GameOver();
}
#endif //_GAME_CPP_