索引错误,超出范围Python

时间:2016-07-18 01:41:18

标签: python python-3.x multidimensional-array

我创建了connect 4;它是一个7乘6格。下面是一个测试对角连接4是否已赢的算法。尽管,当芯片处于图像中所示的位置时,发生索引错误。我该如何解决这个问题,如何让对角线算法工作?

enter image description here

board[5][1] = 1 # (red chip)

board[4][2] = 1 # (red chip)

board[3][3] = 1 # (red chip) #THIS IS WHEN ERROR OCCURS FOR THE FIRST DIAGONAL ALGORITHM

# check / diagonal spaces
for x in range(7 - 3):
    for y in range(3, 6):
        if board[x][y] == 1  and board[x+1][y-1] == 1 and board[x+2][y-2] == 1 and board[x+3][y-3] == 1:
            return True

# check \ diagonal spaces
for x in range(7 - 3):
    for y in range(6 - 3):
        if board[x][y] == 1 and board[x+1][y+1] == 1 and board[x+2][y+2] == 1 and board[x+3][y+3] == 1:
            return True

错误:

 if board[x][y] == 1  and board[x+1][y-1] == 1 and board[x+2][y-2] == 1 and board[x+3][y-3] == 1:
IndexError: list index out of range

2 个答案:

答案 0 :(得分:1)

由于电路板有6行(0 - > 5),并且您从第3行(从0开始的索引)开始x,因此board[x+3][y-3]会给list index out of range,因为x + 3 = 6> 5。

答案 1 :(得分:0)

您将行编号从1到7而不是0到6.

另外,你正在做的循环应该使用逗号,而不是连字符。

    for x in range (4, 7): # This will count 4, 5, 6

如果使用连字符,计算机将进行减法操作。你最终得到了

    for x in range (7 - 3): # Computer will do subtraction, this will count 0, 1, 2, 3

此外,您将需要更通用的算法来检查对角线。你需要使用变量,而不是数字。作为提示,我只检查每次移动放置最后一块的垂直/水平/对角线。