For my Tic Tac Toe AI it is only necessary to generate a random move. I have a class AIPlayer
with a makeAMove
function. It simply generates two random numbers from 0 - 3 (row and column) and checks if the cell is taken. It seems to work okay, but for some reason it will never take a winning move. On the command line when I try to let it win and there are only winning moves left for it to take, it will not take them--it just gets stuck.
Also, I think using a 1-dimesional array would be easier with the AI, but I'm trying to stick with the 2-dimesional array.
I think it would be better to somehow collect the available cells in another array and generate a random move from these cells.
Any suggestions are welcome.
Here is my AI class:
Implementation file:
#include <stdlib.h> // rand, srand
#include <time.h> // time
#include "AIPlayer.h"
AIPlayer::AIPlayer(char token) : Player(token)
{
}
void AIPlayer::makeAMove(Board &myBoard)
{
int row;
int column;
bool done = false;
do
{
srand (time(0));
row = rand() % 3;
column = rand() % 3;
if (myBoard.getCell(row, column) == ' ')
{
myBoard.setCell(row, column, getToken());
done = true;
}
}
while (!done);
std::cout << "\nComputer move (" << getToken() << ")\n"
"row " << row << ", column " << column;
}
Header file:
#pragma once // include guard
#include "Player.h"
class AIPlayer: public Player
{
public:
AIPlayer(char token);
virtual void makeAMove(Board &myBoard);
};