Sign in to follow this  
phil67rpg

tic tac toe AI

Recommended Posts

phil67rpg    443
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. [code] 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';
}
}[/code] I am using a Boolean to keep track of what mark is being placed where and what mark it is.

Share this post


Link to post
Share on other sites
JTippetts    12950
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:

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

[/code]

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:

[code]
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;
}
[/code]

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:

[code]
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];
}
[/code]

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. Edited by JTippetts

Share this post


Link to post
Share on other sites
ashish123    166

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];
......
}
}

Share this post


Link to post
Share on other sites
m3rlino    254

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

Share this post


Link to post
Share on other sites
alvaro    21246

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.

Edited by Álvaro

Share this post


Link to post
Share on other sites
Digivance    1724

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();
    }
}

Share this post


Link to post
Share on other sites
Khatharr    8812
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

Edited by Khatharr

Share this post


Link to post
Share on other sites
alvaro    21246

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.

Share this post


Link to post
Share on other sites
alvaro    21246
So each node or branch represents a potential action and the leaves are end conditions?

Yes. You should search the web for the term "minimax". Since it is the basis of computer chess, there is a lot of information about it out there. The algorithm has been around since around 1950, but it is so natural that a lot of people have rediscovered it (including myself).

Share this post


Link to post
Share on other sites
cagdassalur    118

You dont necessarily need to use Minimax. Here's the xkcd's optimal tic-tac-toe moves for each player.

 

And this is the list of rules you need to check if you choose to implement this kind of method(from tic-tac-toe page on wikipedia);

  1. Win: If the player has two in a row, they can place a third to get three in a row.
  2. Block: If the [opponent] has two in a row, the player must play the third themself to block the opponent.
  3. Fork: Creation of an opportunity where the player has two threats to win (two non-blocked lines of 2).
  4. Blocking an opponent's fork:
    • Option 1: The player should create two in a row to force the opponent into defending, as long as it doesn't result in them creating a fork. For example, if "X" has a corner, "O" has the center, and "X" has the opposite corner as well, "O" must not play a corner in order to win. (Playing a corner in this scenario creates a fork for "X" to win.)
    • Option 2: If there is a configuration where the opponent can fork, the player should block that fork.
  5. Center: A player marks the center. (If it is the first move of the game, playing on a corner gives "O" more opportunities to make a mistake and may therefore be the better choice; however, it makes no difference between perfect players.)
  6. Opposite corner: If the opponent is in the corner, the player plays the opposite corner.
  7. Empty corner: The player plays in a corner square.
  8. Empty side: The player plays in a middle square on any of the 4 sides
Edited by cagdassalur

Share this post


Link to post
Share on other sites
alvaro    21246

You dont necessarily need to use Minimax. [...]

 

While that's true, using a game-specific recipe doesn't teach you anything you can apply in another game, and the whole point is to use tic-tac-toe as a learning tool.

 

You can also make a graph with all the positions in the game and use retrograde analysis to assign values to every node. This will also solve the game, and it will teach you how to create [url="http://en.wikipedia.org/wiki/Endgame_tablebase"]endgame tablebases[/url].

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this