2016-07-18 184 views
0

我创建了连接4;它是一个7乘6格。以下是测试对角线连接4是否赢得的算法。尽管当芯片位于图像中所示的位置时,会发生索引错误。我该如何解决这个问题,以及如何获得对角线算法?索引错误,超出范围Python

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 
+1

'range(7 - 3)'与'range(4)'是一样的,它将从0到3计数。这是你想要的吗? –

+0

那么它的唯一方法,我认为这将允许我检测对角线连接4,但我可能混淆了这个数学。这可能是没有被发现对角线胜利的原因。 –

回答

1

由于板具有6行(0 - > 5),并从第3行开始x(0为基础的索引),以便board[x+3][y-3]将给list index out of range,因为x + 3 = 6> 5.

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 

此外,你将需要一个更一般的算法检查对角线。你需要使用变量,而不是数字。作为提示,我只检查最后一块放置在哪个位置的垂直/水平/对角线。

+0

似乎没有工作,当我改变它时仍然会出现索引错误 –

+0

你能发布你的新代码吗? – Yaelle