Ошибка поиска пути: координаты указаны за пределами индекса массива

Ниже приведен простой алгоритм поиска пути, который я закодировал после разработки. Он предназначен для того, чтобы занять положение точки или «единицы», и, учитывая положение компьютера, вычислит разницу в значениях X и Y и сначала пройдет самую короткую разницу (из-за игры, которая является поворотом сверху вниз). игра, в которой юниты должны выстраиваться в линию для атаки).

boardArray = [[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,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0]]


# 0 shows an empty space, G is the goal, and C is the computer


boardArray[3][6] = "G"
boardArray[7][7] = "C"


def printBoard():
    for r in boardArray:
        for c in r:
            print(c,end = " ")
        print()


printBoard()

row = 0
for i in boardArray:
    column = 0
    for k in i:
        if k == "G":
            print(row, column)
            goalpos = [row, column]
        if k == "C":
            print(row, column)
            computerpos = [row, column]
        column = column + 1
    row = row + 1


def updatePositions(currentx, currenty, valrow, valcolumn):
    print(currentx)
    print(currenty)
    boardArray[valrow][valcolumn] = 0
    boardArray[currentx][currenty] = "C"
    valrow = currentx
    valcolumn = currenty
    printBoard()
    return valrow, valcolumn


def findPath(outscoperow, outscopecolumn):
    DifferenceX = computerpos[0] - goalpos[0]
    DifferenceY = computerpos[1] - goalpos[1]
    CurrentCompX = computerpos[0]
    CurrentCompY = computerpos[1] + 1
    TemporaryX = DifferenceX
    TemporaryY = DifferenceY
    if DifferenceX < 0:
        DifferenceX = DifferenceX *(-1)
    if DifferenceY < 0:
        DifferenceY = DifferenceY *(-1)
    pathfinding = True
    while pathfinding:
        if DifferenceX < DifferenceY:
            if TemporaryX > 0:
                CurrentCompX = CurrentCompX - 1
                outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
                DifferenceX = DifferenceX - 1
            elif TemporaryX < 0:
                CurrentCompX = CurrentCompX + 1
                outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
                DifferenceX = DifferenceX - 1
        elif DifferenceX > DifferenceY:
            if TemporaryY > 0:
                CurrentCompY = CurrentCompY - 1
                outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
                DifferenceY = DifferenceY - 1
            elif TemporaryY < 0:
                CurrentCompY = CurrentCompY + 1
                outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
                DifferenceY = DifferenceY - 1
        if DifferenceX == 0 and DifferenceY == 0:
            pathfinding = False



findPath(row, column)

По мере выполнения кода предполагается фактически перемещать позицию компьютера в режиме реального времени, распечатывая 2D-массив по мере его продвижения, однако при изменении позиций интерпретатор также будет указывать, что текущие координаты находятся за пределами индекса массива (или список, потому что Python странный).

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 G 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 C 
3 6
7 7
7
7
Traceback (most recent call last):
  File "C:/Users/Cameron/Desktop/Basic RPG/pathfindingTest.py", line 88, in <module>
    findPath(row, column)
  File "C:/Users/Cameron/Desktop/Basic RPG/pathfindingTest.py", line 77, in findPath
    outscoperow, outscopecolumn = updatePositions(CurrentCompX, CurrentCompY, outscoperow, outscopecolumn)
  File "C:/Users/Cameron/Desktop/Basic RPG/pathfindingTest.py", line 44, in updatePositions
    boardArray[valrow][valcolumn] = 0
IndexError: list index out of range

Если бы кто-нибудь мог протянуть руку помощи, это было бы очень полезно.


person Cameron Shirley    schedule 10.11.2020    source источник


Ответы (1)


findPath получает 8 и 8 в качестве аргументов, а в python массивы начинаются с 0.

Возможно, вам придется переосмыслить логику генерации row и column или просто выполнить -1 при их получении.

person Ramon Medeiros    schedule 10.11.2020