2015-04-03 49 views
0

这里的具体名单是主类:构建海峡

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'] 

相反,我得到这个:

​​
+0

什么是'SubtractSquareState:

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 

你将与调用此('p1',current_total = 4))'? – 2015-04-03 21:44:37

+0

SubtractSquareState是游戏SubtractSquare的当前状态,其中玩家从当前总数中减去数字的平方以试图达到0(即1,4,9,16)。在这种情况下,在current_total = 4时,可以减去4或1,导致下一个状态为'p2:0'或'p2:3'。等等。 – FistLauncher 2015-04-03 21:47:07

+0

我有不到4个小时的时间来完成这项任务,所以任何帮助/想法都是值得欢迎的! – FistLauncher 2015-04-03 22:11:34

回答

0

因为你想要的字符串列表,您需要从列表中单独建立一个字符串,表示当前路径的所有字符串。您也可以使用它来指示起始点,这样可以避免在每个路径中列出每个节点两次。

没有所有的代码,我不能对此进行测试,但我认为这种一般形式的东西会工作:

_build_paths(root, abbreviated(root.value))