我得到一个列表索引超出范围错误

时间:2015-04-14 18:25:06

标签: python-3.x

我正在开发一个“Connect 4”应用程序,但是当我运行一个函数来查看连续四个时我得到错误:list index out of range

如果有人可以向我解释如何修复此错误,但也解释了为什么在我的代码的这一部分发生了这样的错误,我将不胜感激。

我只包含模块中的代码,因为我认为应该足以弥补错误。

编辑我正在添加main方法的代码,以显示列表的构造方式。还添加了确切的错误。感谢您的所有意见。

追踪(最近一次通话):   文件“connect4AlphaUpdate1.py”,第164行,in     主要()   在main中输入“connect4AlphaUpdate1.py”,第30行     winner = checkWinnerOne(boardStatus)   在checkWinnerOne中的文件“connect4AlphaUpdate1.py”,第106行     如果board [x] [y]为1且board [x] [y + 1]为1且board [x] [y + 2]为1且board [x] [y + 3]为1: IndexError:列表索引超出范围

def main():
# local variables
playerMove = 0
winner = False

# list to show board status
boardStatus = [[0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0]]
# while loop to run until there is a winner
while winner is False:
    displayBoard(boardStatus)
    playerMove = playerOneMove()
    boardStatus = checkMoveOne(boardStatus, playerMove)
    winner = checkWinnerOne(boardStatus)
    if winner is True:
        print('player one wins')
        sys.exit()
    displayBoard(boardStatus)
    playerMove = playerTwoMove()
    boardStatus = checkMoveTwo(boardStatus, playerMove)
    winner = checkWinnerTwo(boardStatus)
    if winner is True:
        print('Player 2 wins')
        sys.exit()


def checkWinnerOne(board):
# check across
for y in range(0, ROWS):
    for x in range (0, COLS -3):
        if board[x][y] is 1 and board[x+1][y] is 1 and board[x+2][y] is 1 and board[x+3][y] is 1:

            return True


# check down
for x in range (COLS):
    for y in range (ROWS -3):
        if board[x][y] is 1 and board[x][y+1] is 1 and board[x][y+2] is 1 and board[x][y+3] is 1:
            print('b')
            return True


# check diagnol 1
for x in range (COLS - 3):
    for y in range(ROWS -3):
        if board[x][y] is 1 and board[x+1][y-1] is 1 and board[x+2][y-2] is 1 and board[x+3][y-3] is 1:
            return True

# check diagnol 2
for x in range (ROWS - 3):
    for y in range(COLS -3):
        if board[x][y] is 1 and board[x+1][y+1] is 1 and board[x+2][y+2] is 1 and board[x+3][y+3] is 1:
            return True

return False

1 个答案:

答案 0 :(得分:0)

看起来你的diagnol1部分函数有错误。您正在从0迭代到ROWS-3,但是您尝试访问y-1位置的元素,-1在第一次迭代中y = 0。显然,访问列表的-1索引会给您list index out of range错误。 (同样的事情发生在y-2y-3

解决方案:

for循环应该从3转到ROWS