Search code examples
c++treeartificial-intelligencetic-tac-toe

Tic-Tac-Toe AI: How to Make the Tree?


I'm having a huge block trying to understand "trees" while making a Tic-Tac-Toe bot. I understand the concept, but I can't figure out to implement them.

Can someone show me an example of how a tree should be generated for such a case? Or a good tutorial on generating trees? I guess the hard part is generating partial trees. I know how to implement generating a whole tree, but not parts of it.


Solution

  • Imagine that at any point in a tic-tac-toe board, every single possible move is a branch. The current state of the board is the root. One move is a branch. Now pretend (one at a time), that each branch becomes the current state. Each possible move becomes a new branch. The leaf of the tree is when the last move is made and the board is full.

    The reason you need to have a tree, is that once it is built, you need to figure out which branch has the most leaves that are 'WIN' scenarios. You build the branch of all possible outcomes, add up the total number of WINs, and then make the move that has the chance to end up with the most wins.

    Make the tree something like this:

    class Node {
    public:
       std::list< Node > m_branches;
       BoardState m_board;
       int m_winCount;
    }
    
    std::list< Node > tree;
    

    Now, you iterate through the list of branches in the tree, and for each branch, iterate through its branches. This can be done with a recursive function:

    int recursiveTreeWalk( std::list< Node >& partialTree)
    {
    
       for each branch in tree
           if node has no branches
               calculate win 1/0;
           else
               recursiveTreeWalk( branch );
    
       partialTree.m_winCount = sum of branch wins;
    }
    
    // initial call
    recursiveTreeWalk( tree )
    

    Very pseudo-code.