View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# tic tac toe AI

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

13 replies to this topic

### #1phil67rpg  Members

Posted 12 November 2012 - 10:19 PM

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.

### #2JTippetts  Moderators

Posted 12 November 2012 - 11:16 PM

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.

Edited by JTippetts, 12 November 2012 - 11:17 PM.

### #3phil67rpg  Members

Posted 12 November 2012 - 11:37 PM

I am going to study up on vectors.

### #4ashish123  Members

Posted 24 December 2012 - 09:54 PM

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

### #5m3rlino  Members

Posted 29 December 2012 - 12:19 PM

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)

My new italian Website! - Web site

### #6Álvaro  Members

Posted 29 December 2012 - 02:53 PM

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, 29 December 2012 - 10:41 PM.

### #7Dan Mayor  Members

Posted 30 December 2012 - 07:30 PM

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

### #8Khatharr  Members

Posted 30 December 2012 - 10:39 PM

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.

Edited by Khatharr, 30 December 2012 - 10:46 PM.

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.

### #9Álvaro  Members

Posted 31 December 2012 - 12:00 AM

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.

### #10Khatharr  Members

Posted 31 December 2012 - 08:35 AM

So each node or branch represents a potential action and the leaves are end conditions?

Edited by Khatharr, 31 December 2012 - 08:36 AM.

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.

### #11Álvaro  Members

Posted 31 December 2012 - 08:58 AM

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).

### #12cagdassalur  Members

Posted 07 March 2013 - 06:22 AM

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, 07 March 2013 - 06:23 AM.

### #13Álvaro  Members

Posted 07 March 2013 - 08:29 AM

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 endgame tablebases.

### #14Poigahn  Members

Posted 14 March 2013 - 06:25 PM

If anyone cares,  There is a chapter for Tic-Tac-Toe in the book called "Begining C++ through Game Programming. That solves the problem

Your Brain contains the Best Program Ever Written : Manage Your Data Wisely !!

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.