在这里,您有一个可行的解决方案。它是用 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”表示。
对于井字游戏,请更改blank_board = (0,0,0)
为blank_board = (0,0,0,0,0,0,0,0,0)
以获得 3x3 棋盘。
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)