Here you have a working solution. It is implemented in Python but I think it may help you.
The game tree is build recursively by the build_tree
function, and is implemented as a list of lists.
The build_tree
function takes a board (a node of the tree) and the piece that has the turn to play as input parameters, and builds all the possible new boards resulting of applying the piece to the board. Then, for each of these new boards, it calls the build_tree
function again, but this time changing the piece that has the turn to play. When the board is terminal (no empty squares) the recursion ends.
This is the resulting tree for a 1x3 board:
[(0, 0, 0), [[('x', 0, 0), [[('x', 'o', 0), [('x', 'o', 'x')]], [('x', 0, 'o'), [('x', 'x', 'o')]]]], [(0, 'x', 0), [[('o', 'x', 0), [('o', 'x', 'x')]], [(0, 'x', 'o'), [('x', 'x', 'o')]]]], [(0, 0, 'x'), [[('o', 0, 'x'), [('o', 'x', 'x')]], [(0, 'o', 'x'), [('x', 'o', 'x')]]]]]]
Empty squares are denoted by '0'.
For the tic tac toe game, please change blank_board = (0,0,0)
to blank_board = (0,0,0,0,0,0,0,0,0)
in order to have a 3x3 board.
def change_piece(piece):
if piece == 'x': return 'o'
return 'x'
def is_terminal(board):
"""Check if there are any empty square in the board"""
for square in board:
if square == 0:
return False
return True
def build_tree(node, piece):
"""Build the game tree recursively.
The tree is implemented as a list of lists.
"""
child_nodes = []
for index, value in enumerate(node):
if value == 0:
new_node = list(node)
new_node[index] = piece
new_node = tuple(new_node)
if not is_terminal(new_node):
child_nodes.append(build_tree(new_node,change_piece(piece)))
else:
child_nodes.append(new_node)
if child_nodes:
return [node,child_nodes]
return
if __name__ == "__main__":
blank_board = (0,0,0)
game_tree = build_tree(blank_board,'x')
print(game_tree)