Monte Carlo
Monte Carlo
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <utility>
#include <ctime>
#include <iterator>
#include <algorithm>
class BoardGraph
{
public:
BoardGraph() {}
BoardGraph(int size):
size(size), board(size, vector<char>(size, '.'))
{
edges = "\\";
for (int i=1; i<size; i++)
{
edges += " / \\";
}
}
//copy constructor
BoardGraph(const BoardGraph &board2)
{
board = board2.board;
edges = board2.edges;
size = board2.size;
}
private:
bool ValidMove(int x, int y);
void checkBorders(int x, int y,
vector<bool> &flags, char side);
void BoardGraph::printBoardGraph()
{
//first line
cout << board[0][0];
for (int j=1; j<size; j++)
cout << " - " << board[0][j];
cout << endl;
if (p == player::BLUE)
board[x][y] = Blue;
else if (p == player::RED)
board[x][y] = Red;
return true;
}
board[x][y] = Blank;
return true;
}
while (!traces.empty())
{
auto top = traces.front();
checkBorders(top.first, top.second, flags, side);
traces.pop();
pair<int,int> BoardGraph::AIalgorithm()
{
//vectors for shuffling and counting the empty spots
vector<int> emptySpots, emptySpotsCounter(size*size);
int main()
{
const int SIZE = 5;
BoardGraph board1(SIZE); //create the board to play
int turn = 0;
int steps = 0;
int x, y;
char comma;
srand(time(0));
while (true)
{
steps++;
turn = !turn;
if (turn == 1)
{
BoardGraph board2 = board1; //copy of the board for testing the
best play
AImove = board2.AIalgorithm(); //the AI method outputs a pair of
ints
x = AImove.first;
y = AImove.second;
board1.makeMove(x, y, player::BLUE); //
cout << "Computer: (" << x << "," << y << ")" << endl;
board1.printBoardGraph();
}
else
{
while (true)
{
cout << "Input coordinates (write \"x,y\" and then press enter): ";
cin >> x >> comma >> y;
if (board1.makeMove(x, y, player::RED)==true)
break;
else
cout << "Invalid values! Try again!\n";
}
cout << "Human: (" << x << "," << y << ")" << endl;
}
if (board1.win(x, y))
{
if (turn==0)
board1.printBoardGraph();
cout << (turn ? "Computer" : "Human") << " wins!" << endl;
cout << "Total steps = " << steps << endl;
break;
}
}
return 0;
}