0

適切に実行されるConnectFourプログラムがありますが、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()

私の現在の出力では、位置は問題なく表示されます...ただし、match_in_direction(0,3,0,2)は出力されません。これは、一致するチップの数であるため、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)

returnステートメントがあるため、match_in_direction関数に「printmatch」は必要ありません。また、print boardは(より適切な単語がないために)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 に答える