tic tac toe AI

Started by
12 comments, last by Poigahn 11 years, 1 month ago
I am working on a very simple AI and tic tac toe. my problem is that the O's overwrite the X's. I have tried various routines but I am still stuck. I am convinced that all I need is a couple of lines of code to finish. Please keep the help as simple as possible. Here is the code I am using. void Computer::move_player_O()
{
player_O = rand()%9+1;
if(player_X==player_O)
{
repeat[player_O]=true;
}
else
{
repeat[player_O]=false;
}
}
void Computer::check_player_O()
{
if(repeat[player_O]==true)
{
board[player_O]='O';
}
else
{
move_player_O();
board[player_O]='O';
}
}
I am using a Boolean to keep track of what mark is being placed where and what mark it is.
Advertisement
Pretty tough to say what's going on without seeing the rest of the code (such as how the variable player_X is set and when, etc...) But still, it seems as if you are kind of going about this oddly.

You have a board that can hold 'X', 'O' or ' ' (space for empty). To find a randomly selected space for player O, you could do something similar to this:


int Computer::findRandomSpace()
{
int move=-1;
do
{
space=rand()%9;
}
while (board[move]!=' '
return move;
}



Of course, this method will hang if the board is full, so ensure that you test the board first for a win/loss/draw condition. Essentially, you loop until you find an empty space, generating a new random board index each time.

Another way would be to iterate through the board and find all the empty spaces, and add the empties to a vector:


std::vector<int> Computer::getValidMoves()
{
std::vector<int> moves;
for(int c=0; c<9; ++c)
{
if (board[c]==' ') moves.push_back(c);
}
return moves;
}


After calling getValidMoves(), you will have a vector that is either empty (if the board is full), or holds the indices of all empty spaces in the board. Now, you can choose one at random:


int Computer::chooseMove()
{
std::vector<int> moves=getValidMoves();
if(moves.size()==0) return -1; // Board is full
int length=moves.size();
return moves[rand() % length];
}


Another benefit of constructing a vector of all valid moves is that when you move on to a smarter AI, you can change the getValidMoves() method to prioritize spaces by how much closer they get you to a win condition. For example, if a space will generate a win condition for the player, it receives the highest priority; if a space will block the other player from a win condition, it gets the next highest priority. And so forth. You can sort the vector based on priority, then in the chooseMove() method, instead of grabbing a random space you grab the space at the back of the list (assuming you sort from lowest priority to highest). That way, you always choose the best move you can make.
I am going to study up on vectors.

Since you say that pieces override each other, you can keep a track of board state and play there only where its empty.

something like this.



for(int i=0;i<9;i++)
{
if(board[i]==EMPTY)
{
int sq_move=board[i];
......
}
}

Hello, but speaking of wiser AI. Is there a good AI system to make tic tac toe forecast other person move?

As I know if you play second you can only draw.

If you play first you can win, but if the other player is good enough he can also draw.

So priority to the center, then the corners and then it depends on the other person's moves.

I tried to create some schema based on weights of cells, but sometimes i managed to deceive my AI, so I'm asking

Evil bay - Our new game at FourLeafGames! (Link to the game)
Link to our web site! Leave a message if you like it! - Web site

My new italian Website! - Web site

You can make an interesting AI by implementing minimax search and assigning +1000 to winning, -1000 to losing and a random number R (with abs( R ) < 1000) for draws. The program will play optimally (never lose, win if it can), and it will also play in ways that reduce the options of the opponent, most of the time.

It would actually be very easy to build a smarter AI for Tic Tac Toe, such as trying to block wins and what not. First start by scanning the board for opponent boxes, when you find one start checking adjacent boxes, if they have the opponent's mark then check for the next box in the series and place your mark there. If you scan through the entire board and don't find any potential wins you would do the process again in your favor. Look for potential wins. If you cant find a potential win look for a path that you can go that isn't blocked yet (eg find 2 empty boxes in a direction from one of your marks). Here's a little mock up of the idea I'm thinking of (not real code)...


// we assume that gameBoard is a 2d array of ints
// gameBoard[row][col] = 0 for empty, -1 for x, +1 for o)

// we assume that the "Player" is X and the PC is O

bool defenseCheck()
{
    for(int r=0; r<3; r++)
    {
        for(int c=0; c<3; c++)
        {
            if(gameBoard[r][c] == -1)
            {
                // You would have to play with this but basically...
                if(gameBoard[r][c+1] == -1 && gameBoard[r][c+2] == 0)
                {
                    gameBoard[r][c+2] = 1;
                    return true;
                }
            }
        }
    }
}

bool winCheck()
{
    // Same as defense check but looking for +1's in a row that we can complete
}

bool moveCheck()
{
    // This assumes defenseCheck and winCheck both failed.  In this case we want to do the same thing but we're looking for +1 and then 2 empty 0's in a row
}

void npcMover()
{
    if(winCheck())
    {
        Say("I just beat you at Tic Tac Toe so ha!");
    }
    else if(defenseCheck())
    {
        Say("Ha, blocked your puny attempt to beat me!");
    }
    else if(moveCheck())
    {
        Say("Let's see what you do now mr tic");
    }
    else
    {
        Say("I don't know what to do!!!");
        ThrowTemperTantrum();
    }
}

Dan Mayor

Professional Programmer & Hobbyist Game Developer

Seeking team for indie development opportunities, see my classifieds post

You can make an interesting AI by implementing minimax search and assigning +1000 to winning, -1000 to losing and a random number R (with abs( R ) < 1000) for draws. The program will play optimally (never lose, win if it can), and it will also play in ways that reduce the options of the opponent, most of the time.

So you'd enumerate the open cells, then assign each one a score based on how valuable a play there would be, considering wins, then blocks, then moves that would lead toward wins, right? (I've never implemented a minimax.) That would be easily extensible to larger board sizes too.



        ThrowTemperTantrum();

Oi, don't give away my secret move. happy.png

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

You can make an interesting AI by implementing minimax search and assigning +1000 to winning, -1000 to losing and a random number R (with abs( R ) < 1000) for draws. The program will play optimally (never lose, win if it can), and it will also play in ways that reduce the options of the opponent, most of the time.

So you'd enumerate the open cells, then assign each one a score based on how valuable a play there would be, considering wins, then blocks, then moves that would lead toward wins, right? (I've never implemented a minimax.) That would be easily extensible to larger board sizes too.



No, that's not how minimax works. Minimax examines the tree of moves available from the current position and, given desirability values for the leaves of the tree, it propagates these values to the interior nodes.
So each node or branch represents a potential action and the leaves are end conditions?
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement