移动时列出索引超出范围

时间:2017-12-01 15:02:36

标签: python-3.x

这是我十五岁游戏的代码,不包括'won'功能:

导入sys

d = int(sys.argv[1])

dimension = (d * d) - 1

board = [[0 for x in range(d)] for y in range(d)]

def main():

    global d
    if len(sys.argv) != 2 or 0 > d or d > 9:
        print("usage: python fifteen.py size")
        exit()

def init():

    global d

    global dimension

    global board

    for row in range(d):
        for col in range(d):
            board[row][col] = dimension
            dimension -= 1
    if d % 2 == 0:
        board[d-1][d-3] = 1
        board[d-1][d-2] = 2

def draw():

    global d

    global dimension

    global board

    for row in range(d):
        for col in range(d):
            if board[row][col] == 0:
                print("__", end="")
            else:
                print("{:0=2d} ".format(board[row][col]), end="")
        print("")

def move():

    global d

    global dimension

    global board

    while True:
        tile = int(input("Tile to move: "))
        if tile > 0:
            break

    for row in range(d):
        for col in range(d):
            if board[row][col] == tile:
                colleft = col - 1
                colright = col + 1
                rowup = row - 1
                rowdown = row + 1

                if board[row][colleft] == 0 and colleft >= 0:
                    board[row][colleft] = tile
                    board[row][col] = 0
                    return True

                elif board[row][colright] == 0 and colright < d:
                    board[row][colright] = tile
                    board[row][col] = 0
                    return True

                elif board[rowup][col] == 0 and rowup >= 0:
                    board[rowup][col] = tile
                    board[row][col] = 0
                    return True

                elif board[rowdown][col] == 0 and rowdown < d:
                    board[rowdown][col] = tile
                    board[row][col] = 0
                    return True
                return False
    return True


main()

init()

draw()

move()

draw()

例如,当我想移动2或3时,我不断收到“IndexError:list index out of range”:

Erorr留言:

python3 fifteen.py 3

追踪(最近一次呼叫最后一次):

File "fifteen.py", line 83, in <module>

    move()

File "fifteen.py", line 72, in move

    elif board[rowdown][col] == 0 and rowdown < d:

IndexError:列表索引超出范围

我需要做些什么才能使其正常工作?

1 个答案:

答案 0 :(得分:0)

因为rowdown和colright可能比你的电路板的最大索引大。

例如,

,d = 3。 当row = 2时,rowdown = 3,这超出了董事会的索引。