TTT Competitor

Here's a guide for one way of creating a perfect TTT competitor...

We'll be creating a class called BoardNode, which will contain all the information about one node in the game's game-tree.

Here's the new BoardNode's __init__():

class BoardNode:
    def __init__(self,layout):
        self.layout = layout
        self.endState = None # if this is a terminal board, endState == 'x' or 'o' for wins, or 'd' for draw, else None if this board is not final
        self.children = [] # all nodes that can be reached with a single move

        self.best_move  # cell position (0-8) of the best move from this layout, or -1 if this is a final layout
        self.moves_to_end  # how many moves until the end of the game, if played perfectly.  0 if this is a final layout
        self.final_state   # expected final state ('x' if 'x' wins, 'o' if 'o' wins, else 'd' for a draw)


 

6
best move is lower-left
x wins in 1 move

The first output line contains the position for the next move and the other two are for human eyes.

Basic recursive loop:

Best move choice:

Timing:  You are allowed to cheat if given an empty board and you have to make the first move (any first move will lead to a draw in 9 moves, if played perfectly by both sides).  Ther are only 3 distinctly different moves: corner, edge and center.  Choose one of the 3 types, and if choosing corner or edge, choose a random one of those. After that, however, your program should deliver an answer in under 2 seconds.

Testing: Now you can really play with tictactoe against your creation.  It should never lose.  Make it so.