这是主要课程:
class GameStateNode:
'''
A tree of possible states for a two-player, sequential move, zero-sum,
perfect-information game.
value: GameState -- the game state at the root of this tree
children: list -- all possible game states that can be reached from this
game state via one legal move in the game. children is None until grow
is called.
'''
def __init__(self, game_state):
''' (GameStateNode, GameState) -> NoneType
Initialize a new game state tree consisting of a single root node
that contains game_state.
'''
self.value = game_state
self.children = []
以下是我目前正在处理的功能:
def game_descriptions(root):
''' (GameStateNode) -> list of str
Return a list containing a str describing each complete game that is
possible from the game stored at root.
Assume root is the root of a game state tree specifically for the game
Subtract Square.
>>> s = SubtractSquareState('p1', current_total = 6)
>>> root = GameStateNode(s)
>>> root.grow()
>>> game_descriptions(root)
['p1:6 -> p2:2 -> p1:1 -> p2:0 = p1 wins!', 'p1:6 -> p2:5 -> p1:1 -> p2:0 = p1 wins!', 'p1:6 -> p2:5 -> p1:4 -> p2:0 = p1 wins!', 'p1:6 -> p2:5 -> p1:4 -> p2:3 -> p1:2 -> p2:1 -> p1:0 = p2 wins!']
'''
def _build_paths(root, L = []):
''' (GameStateNode) -> list of str '''
if root.children:
for child in root.children:
a = abbreviated(root.value)
a += ' -> {}'.format(abbreviated(child.value))
L.append(a)
_build_paths(child, L)
else:
pass
return L
def abbreviated(s):
'''(GameState) -> str
Return an abbreviated str representation of SubtractSquareState s.
'''
return "{}:{}".format(s.next_player, s.current_total)
正如你在fcn game_descriptions中看到的那样,我需要返回一个游戏状态列表,以便最后获胜者。我目前的问题是fcn _build_paths。我希望它返回一个没有获胜者的游戏描述列表,因为我将实现谁赢得了fcn game_descriptions。 我想要这个,例如:
>>> root = GameStateNode(SubtractSquareState('p1', current_total = 4))
>>> root.grow()
>>> _build_paths(root)
['p1:4 -> p2:0', 'p1:4 -> p2:3 -> p1:2 -> p2:1 -> p1:0']
相反,我得到了这个:
['p1:4 -> p2:0', 'p1:4 -> p2:3', 'p2:3 -> p1:2', 'p1:2 -> p2:1', 'p2:1 -> p1:0']
答案 0 :(得分:0)
因为您需要一个字符串列表,所以需要建立一个字符串,指示当前路径与所有字符串列表分开。您也可以使用它来指示起点,这样就可以避免在每个路径中列出每个节点两次。
如果没有您的所有代码,我无法对此进行测试,但我认为这种通用形式的某些方法可行:
def _build_paths(root, currentpath, L = []):
''' (GameStateNode) -> list of str '''
if root.children:
for child in root.children:
a = ' -> {}'.format(abbreviated(child.value))
currentpath += a
_build_paths(child, currentpath, L)
else:
L.append(currentpath)
return L
你可以这样称呼:
_build_paths(root, abbreviated(root.value))