0

我有一个正确运行的连接四程序,但我想将我的 match_in_direction() 方法打印到屏幕上...我的代码如下

class ConnectFour(object):

这将初始化板:

    def __init__(self):
        self.board = [[None for i in range(7)] for j in range(8)]

这得到每个播放点的位置:

    def get_position(self, row, column):
        assert row >= 0 and row < 6 and column >= 0 and column < 7
        return self.board[row][column]

这应该检查所玩的筹码是否匹配:

    def match_in_direction(self, row, column, step_row, step_col):

    assert row >= 0 and row < 6 and column >= 0 and column < 7
    assert step_row != 0 or step_col != 0 # (0,0) gives an infinite loop

    match = 1

    while True:
        nrow = row + step_row
        ncolumn = column + step_col
        if nrow >=0 and nrow <6 and ncolumn >=0 and ncolumn <7:
            if self.board[row][column] == self.board[nrow][ncolumn]:
                match == match+1
                row = nrow
                column = ncolumn
            else:
                return match
        else:
            return match
    print match

这将是一个基于用户输入的游戏

    def play_turn(self, player, column):
    """ Updates the board so that player plays in the given column.

    player: either 1 or 2
    column: an integer between 0 and 6
    """
    assert player == 1 or player == 2
    assert column >= 0 and column < 7

    for row in xrange(6):
        if self.board[row][column] == None:
            self.board[row][column] = player
            return

打印板:

    def print_board(self):
        print "-" * 29
        print "| 0 | 1 | 2 | 3 | 4 | 5 | 6 |"
        print "-" * 29
        for row in range(5,-1,-1):
            s = "|"
            for col in range(7):
                p = self.get_position(row, col)
                if p == None:
                    s += "   |"
                elif p == 1:
                    s += " x |"
                elif p == 2:
                    s += " o |"
                else:
                    # This is impossible if the code is correct, should never occur.
                    s += " ! |"
            print s
        print "-" * 29

而我的用法:

b = ConnectFour()

b.play_turn(1, 3)

b.play_turn(1, 3)

b.play_turn(1, 4)

b.match_in_direction(0,3,0,2)

b.print_board()

我当前的输出给了我很好的位置......但是它没有打印应该是 2 的 match_in_direction(0,3,0,2) 因为那是匹配的筹码数量......任何帮助都会很大赞赏。

4

3 回答 3

1

快速浏览一下 match_in_direction 看起来你有match == match+1而不是match = match + 1(或“更好” match += 1

于 2013-03-12T20:18:00.547 回答
1

将此添加到您的测试代码中:

f = b.match_in_direction(0,3,0,2) 
print(m)

由于返回语句,您不需要在 match_in_direction 函数中“打印匹配”,并且打印板不使用(因为没有更好的词)方向函数的匹配,因此您必须单独打印出来。

于 2013-03-19T16:22:18.700 回答
0

match_in_direction 函数的格式有点混乱,但我认为这是因为这里的错字:

if self.board[row][column] == self.board[nrow][ncolumn]:
    match == match+1

它应该是

match += 1
于 2013-03-12T20:24:39.170 回答