ここに実用的なソリューションがあります。Pythonで実装されていますが、役立つと思います。
ゲーム ツリーはbuild_tree
関数によって再帰的に構築され、リストのリストとして実装されます。
このbuild_tree
関数は、ボード (ツリーのノード) と、順番にプレイする駒を入力パラメーターとして受け取り、その駒をボードに適用した結果として考えられるすべての新しいボードを作成します。次に、これらの新しいボードごとにbuild_tree
関数を再度呼び出しますが、今度はプレイする番の駒を変更します。ボードが終了する (空の四角がない) 場合、再帰は終了します。
これは、1x3 ボードの結果のツリーです。
[(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')]]]]]]
空の四角は「0」で示されます。
三目並べゲームの場合は、3x3 ボードにするために に変更blank_board = (0,0,0)
してください。blank_board = (0,0,0,0,0,0,0,0,0)
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)