# Thread: Tic Tac Toe AI help please...

1. ## Tic Tac Toe AI help please...

I got a nice tic tac toe game started but I don't know were to start on the computer AI. I have read all about the minimax tree and other stuff but notin told me how to do it! So does anyone know a good tic tac toe AI tutorial?

Thanks

(This is my first game, besides my never finished text based rpg game...)

2. This Gooooooooooooogle search I did on tic tac toe AI has some good examples of AI code in the first few links, look at those.

3. Just keep this in mind. Priotrity.

Here is my tic tac toe game from AGES ago, The code is messy and very unefficent.
Keep in mind I had just started out.

My TicTacToe game

4. What you want to use the min-max algorithm, in the guise of negamax. The idea is that your score of position is the opponent's minimum score, and vice versa. For example, if you are attempting to find your score for specific position after a given move, look at the opponents scores for each possible move the opponent could make from the position, say his moves are m1, m2, m3, and m4 and his scores are, respectively, 50, 60, 40, and 30. Then the optimal move the opponent minimizes the score of the oponent. That move is m4, because 30 is less than all other moves. Obtaining the score of each move from a given position, the move with the max score is the one which top-level player will make.

Taking this idea a step further, you can build a game tree.
For instance,
Code:
```                      5
/       \                              max
/                 \
5                  4                       min
/               |             \
5               8              4                   max
/  |  | \        /  |  | \      /  |  | \
4 3 4 5       6 7 7 8     1 2 3 4```
the negamax uses this information but instead of switching between min and max, the score is multiplied by negative. min(45, 3, 2, 6) = -max(-45, -3, -2, -6)

Code:
```int negamax(int depth)
{
Moves moves;
int best = -INF;

if (depth == 0)
return board.eval();

board.generate_moves(moves);

while(still moves left) {
move =  moves[i];
board.make_move(move);
best = max(-negamax(depth - 1), best);
board.undo_move(move);
moves.next_move();
i++;
}

return best;
}```
Because it's possible to search the complete tree in tick-tac-toe, it's not necessary to individual values representing the score. Instead, a position is either lost, winning or tied, so a given position's score can represented -1, 1, and 0.

5. omg I downloaded your ttt game and saw the sorce code...

that is to long for so little! That would take me years to finish....ok nto years but a long time!

To much if(board....

WOW!

6. Lol, I had just started programming and I hard coded the AI. I didnt know any better.
Thats what the majority of the code is, AI.

7. Here's an example of a minmax-AI, but in connect-four instead.
Connect four AI demo

8. My tic-tac-toe AI was pretty good. It picked random positions, and won 1/5 of the time. But no matter how good it works, I guess I should still read up minmax... just to see what the competitors are doing

9. Here's an example of a minmax-AI, but in connect-four instead.
Connect four AI demo
is that all it is? I looked at the ai.cpp only but that is all? Not as bad as I thought it was going to be but I don't understand any of it but still it was pretty short. Confusing but short...

10. http://www.ocf.berkeley.edu/~yosenl/...alphabeta.html

Did you go there. That explains it quite thouroughly.

11. I looked. But I am thinking maybe games arn't for me yet. Because that doesn't explain much because it doesn't give a complete ttt game. If it gave all the sorce code it could help me but I think that is hard to come by.

12. Rune Hunter, the site posted covers alpha-beta, which is not too useful for ticktack toe games. The functions you need to create a tick-tack-toe AI are a movegeneration function, which adds possible moves from a given position, and a negamax search. For instance, if you have

Code:
```0X0
X0
0X```
and then possible moves are the empty spaces, (row2, column 1) and (row3, column1). Hence, represent a move by something like
Code:
```struct Move {
int row;
int col;
};```
and then write the move generation function: generate_moves(Board* board, Move* moves).

Then, you need an evaluation function that returns whether the position is winning, lost, and tied. To write this, simply determine whose turn it's to move and whether there's 3 of a given color. For example, if you have a row like XXX and it's X to move, then return 10. But if you detect a stalemate, then return 0, and so on.

Write these two functions, along with a board datastructure that stores the board and the current turn to move, and then write the AI. Test everything before writing the AI function.

13. Take A look at this....hope it helps
Code:
```// Tic-Tac-Toe
// Plays the game of tic-tac-toe against a human opponent

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

// global constants
const char X = 'X';
const char O = 'O';
const char EMPTY = ' ';
const char TIE = 'T';
const char NO_ONE = 'N';

// function prototypes
void instructions();
char askYesNo(string question);
int askNumber(string question, int high, int low = 0);
char humanPiece();
char opponent(char piece);
void displayBoard(const vector<char>& board);
char winner(const vector<char>& board);
bool isLegal(const vector<char>& board, int move);
int humanMove(const vector<char>& board, char human);
int computerMove(vector<char> board, char computer);
void announceWinner(char winner, char computer, char human);

// main function
int main()
{
int move;
const int NUM_SQUARES = 9;
vector<char> board(NUM_SQUARES, EMPTY);

instructions();
char human = humanPiece();
char computer = opponent(human);
char turn = X;
displayBoard(board);

while (winner(board) == NO_ONE)
{
if (turn == human)
{
move = humanMove(board, human);
board[move] = human;
}
else
{
move = computerMove(board, computer);
board[move] = computer;
}
displayBoard(board);
turn = opponent(turn);
}

announceWinner(winner(board), computer, human);

return 0;
}

// functions
void instructions()
{
cout << "Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.\n";
cout << "--where human brain is pit against silicon processor\n\n";

cout << "Make your move known by entering a number, 0 - 8.  The number\n";
cout << "corresponds to the desired board position, as illustrated:\n\n";

cout << "       0 | 1 | 2\n";
cout << "       ---------\n";
cout << "       3 | 4 | 5\n";
cout << "       ---------\n";
cout << "       6 | 7 | 8\n\n";

cout << "Prepare yourself, human.  The battle is about to begin.\n\n";
}

char askYesNo(string question)
{
char response;
do
{
cout << question << " (y/n): ";
cin >> response;
} while (response != 'y' && response != 'n');

return response;
}

int askNumber(string question, int high, int low)
{
int number;
do
{
cout << question << " (" << low << " - " << high << "): ";
cin >> number;
} while (number > high || number < low);

return number;
}

char humanPiece()
{
char go_first = askYesNo("Do you require the first move?");
if (go_first == 'y')
{
cout << "\nThen take the first move.  You will need it.\n";
return X;
}
else
{
cout << "\nYour bravery will be your undoing... I will go first.\n";
return O;
}
}

char opponent(char piece)
{
if (piece == X)
return O;
else
return X;
}

void displayBoard(const vector<char>& board)
{
cout << "\n\t" << board[0] << " | " << board[1] << " | " << board[2];
cout << "\n\t" << "---------";
cout << "\n\t" << board[3] << " | " << board[4] << " | " << board[5];
cout << "\n\t" << "---------";
cout << "\n\t" << board[6] << " | " << board[7] << " | " << board[8];
cout << "\n\n";
}

char winner(const vector<char>& board)
{
// all possible winning rows
const int WINNING_ROWS[8][3] = { {0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{2, 4, 6} };
const int TOTAL_ROWS = 8;

// if any winning row has three values that are the same (and not EMPTY),
// then we have a winner
for(int row = 0; row < TOTAL_ROWS; ++row)
{
if ( (board[WINNING_ROWS[row][0]] != EMPTY) &&
(board[WINNING_ROWS[row][0]] == board[WINNING_ROWS[row][1]]) &&
(board[WINNING_ROWS[row][1]] == board[WINNING_ROWS[row][2]]) )
{
return board[WINNING_ROWS[row][0]];
}
}

// since nobody has won, check for a tie (no empty squares left)
if (count(board.begin(), board.end(), EMPTY) == 0)
return TIE;

// since nobody has won and it isn't a tie, the game ain't over
return NO_ONE;
}

inline bool isLegal(int move, const vector<char>& board)
{
return (board[move] == EMPTY);
}

int humanMove(const vector<char>& board, char human)
{
int move = askNumber("Where will you move?", (board.size() - 1));
while (!isLegal(move, board))
{
cout << "\nThat square is already occupied, foolish human.\n";
move = askNumber("Where will you move?", (board.size() - 1));
}
cout << "Fine...\n";
return move;
}

int computerMove(vector<char> board, char computer)
{
cout << "I shall take square number ";

// if computer can win on next move, make that move
for(int move = 0; move < board.size(); ++move)
{
if (isLegal(move, board))
{
board[move] = computer;
if (winner(board) == computer)
{
cout << move << endl;
return move;
}
// done checking this move, undo it
board[move] = EMPTY;
}
}

// if human can win on next move, block that move
char human = opponent(computer);
for(int move = 0; move < board.size(); ++move)
{
if (isLegal(move, board))
{
board[move] = human;
if (winner(board) == human)
{
cout << move << endl;
return move;
}
// done checking this move, undo it
board[move] = EMPTY;
}
}

// the best moves to make, in order
const int BEST_MOVES[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
// since no one can win on next move, pick best open square
for(int i = 0; i < board.size(); ++i)
{
int move = BEST_MOVES[i];
if (isLegal(move, board))
{
cout << move << endl;
return move;
}
}
}

void announceWinner(char winner, char computer, char human)
{
if (winner == computer)
{
cout << winner << "'s won!\n";
cout << "As I predicted, human, I am triumphant once more -- proof\n";
cout << "that computers are superior to humans in all regards.\n";
}

else if (winner == human)
{
cout << winner << "'s won!\n";
cout << "No, no!  It cannot be!  Somehow you tricked me, human.\n";
cout << "But never again!  I, the computer, so swear it!\n";
}

else
{
cout << "It's a tie.\n";
cout << "You were most lucky, human, and somehow managed to tie me.\n";
cout << "Celebrate... for this is the best you will ever achieve.\n";
}
}```

Popular pages Recent additions