我的战舰战略中的IndexError在python中

时间:2014-09-29 22:29:12

标签: python

在战舰计划中运行我的策略时,我收到一个IndexError:list index超出范围。该代码适用于地图上的大多数正方形,但在靠近地图轮廓的正方形上,例如当行= 0时,错误出现。 我的战舰战略在地图上选择随机移动,将每个猜测存储在函数外的lastHit列表中。如果猜测命中了一艘船,那么下一轮,row和col将获取lastHit列表中的最后两个值,然后使用if语句中设置的条件检查它周围的相邻方块。错误代码出现在第10行,其中第一个if语句是。

lastHit = [1, 1]

def chooseMove():

    global playerBoard, opponentBoard

    row = lastHit[0]
    col = lastHit[1]

    if (opponentBoard[row][col] == const.HIT) and (opponentBoard[row - 1][col] != opponentBoard[5:][:5]) and (row - 1 != -1):
    row -= 1
    if ((opponentBoard[row][col] == const.MISSED) or (opponentBoard[row][col] == const.HIT)) and (opponentBoard[row + 2][col] != opponentBoard[5:][:5]) and (row + 2 != 12):
        row += 2
        if ((opponentBoard[row][col] == const.MISSED) or (opponentBoard[row][col] == const.HIT)) and (opponentBoard[row - 1][col - 1] != opponentBoard[5:][:5]) and (col - 1 != -1):
        row -= 1
        col -= 1
            if ((opponentBoard[row][col] == const.MISSED) or (opponentBoard[row][col] == const.HIT)) and (opponentBoard[row][col + 2] != opponentBoard[5:][:5]) and (col + 2 != 12):
            col += 2
            if ((opponentBoard[row][col] == const.MISSED) or (opponentBoard[row][col] == const.HIT)) and (opponentBoard[row][col] != opponentBoard[5:][:5]):
                while (opponentBoard[row][col] == const.MISSED):
                        row = randint(0,len(opponentBoard)-1)
                        col = randint(0,len(opponentBoard[row])-1)
                else:
                    lastHit[0] = row;
                    lastHit[1] = col;
                    return row, col
            else:
                lastHit[0] = row;
            lastHit[1] = col;
            return row, col 
        else:
            lastHit[0] = row;
            lastHit[1] = col;
            return row, col
        else:
        lastHit[0] = row;
        lastHit[1] = col;
        return row, col
        else:
        lastHit[0] = row;
        lastHit[1] = col;
        return row, col
    else: 
        while (opponentBoard[row][col] == const.HIT) or (opponentBoard[row][col] == const.MISSED):
            row = randint(0,len(opponentBoard)-1)
            col = randint(0,len(opponentBoard[row])-1)
        else:
        lastHit[0] = row;
        lastHit[1] = col;
        return row, col

0 个答案:

没有答案