在python中的ConnectFour:在for循环下嵌入while循环

时间:2014-03-30 10:56:40

标签: python

所以我正在尝试在python中实现一个ConnectFour游戏,并且我在计算连续排成一行的棋子(来自单个玩家)时遇到了一些麻烦。我的代码:

    class ConnectFour(object):
def __init__(self):
    self.row=6
    self.col=7
    self.board = []

    #initialize the board
    for arow in range(self.row):
        row = []
        for acol in range(self.col):
            row.append(None)
        self.board.append(row)

    #function for counting the number of the same pieces in a row

    def count_it(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
    counter1 = 0
    counter2 = 0
    if self.board[row][column] == None:
        return 0
    elif self.board[row][column] == 1:
        for i in range(6):
            while self.board[row + (i*step_row)][column + (i*step_col)] == 1:
                counter1 += 1
        return counter1
    else:
        for i in range(6):
            while self.board[row + (i * step_row)][column + (i*step_col)] == 2:
                counter2 += 1
        return counter2

当我在我的功能中输入一个位置和“步骤”时,我想获得玩家1或玩家2排队的数量,但是当我输入时:

    x= ConnectFour()
    x.board[5][6] = 1  
    x.board[4][6] = 1 

    x.count_it(5,6,-1,0)

我没有输出。

1 个答案:

答案 0 :(得分:0)

whilefor不需要whiletrue条件为while时,它将成为无限循环,因为该循环的主体不会影响条件,它只是永远地增加一个计数器。

一种方法是单个while self.board[row + (counter1*step_row)][column + (counter1*step_col)] == 1: counter1 += 1 循环:

for

另一种方法是离开i循环,但counter1for i in range(6): if self.board[row + (i*step_row)][column + (i*step_col)] != 1: break counter1 += 1 实际上用于同一目的:

if

在这两种情况下,请通过某些{{1}}来处理数组边界,或者将标记放在数组的边界处。