繁体   English   中英

索引错误,超出Python范围

[英]Index Error, out of range Python

我已经创建了connect 4; 这是一个7 x 6的网格。 以下是测试对角线连接4是否获胜的算法。 虽然,当切屑位于图像中所示的位置时,会发生索引错误。 如何解决此问题,如何使对角线算法起作用?

在此处输入图片说明

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

由于板具有6行(0 - > 5),并且在启动x从行3(基于0的索引),所以board[x+3][y-3]将给出list index out of range ,因为X + 3 = 6> 5。

您正在将行从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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM