Как работают эти две строки x2 = x + delta [i] [0], y2 = y + delta [i] [1]? - PullRequest
0 голосов
/ 29 июня 2019

Я читаю код ниже о программе First Search - искусственном интеллекте для робототехники, и я немного застрял с работой этих двух строк ниже:

x2 = x+delta[i][0]
y2 = y+delta[i][1]

Я знаю о дельте для схемы перемещения от узла к соседям, но я не мог понять, как эти две линии работают здесь. Кто-нибудь может мне их объяснить, пожалуйста?

Код ниже:

#grid format
# 0 = navigable space
# 1 = occupied space

grid=[[0,0,1,0,0,0],
      [0,0,1,0,0,0],
      [0,0,0,0,1,0],
      [0,0,1,1,1,0],
      [0,0,0,0,1,0]]

init = [0,0]                           
goal = [len(grid)-1,len(grid[0])-1]   

#Below the four potential actions to the single field
delta=[[-1, 0],      #up 
       [ 0,-1],      #left
       [ 1, 0],      #down
       [ 0, 1]]      #right

delta_name = ['^','<','V','>']        
cost = 1

def search():
    #open list elements are of the type [g,x,y] 

    closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
    #We initialize the starting location as checked
    closed[init[0]][init[1]] = 1

    # we assigned the cordinates and g value
    x = init[0]
    y = init[1]
    g = 0
    #our open list will contain our initial value
    open = [[g,x,y]]


    found = False #flag that is set when search complete
    resign= False #Flag set if we can't find expand

    #print('initial open list:')
    #for i in range(len(open)):
            #print('  ', open[i])
    #print('----')


    while found is False and resign is False:
        #Check if we still have elements in the open list
        if len(open)==0: #If our open list is empty
            resign=True
            print('Fail')
            print('############# Search terminated without success')
        else: 
            #if there is still elements on our list
            #remove node from list
            open.sort()      
            open.reverse()    #reverse the list
            next = open.pop() 

            #print('list item')
            #print('next')

            #Then we assign the three values to x,y and g. 
            x = next[1]
            y = next[2]
            g = next[0]

            #Check if we are done

            if x == goal[0] and y == goal[1]:
                found = True
                print(next) #The three elements above this if
                print('############## Search is success')
            else:
                #expand winning element and add to new open list
                for i in range(len(delta)): 

                    x2 = x+delta[i][0]
                    y2 = y+delta[i][1]
                    #if x2 and y2 falls into the grid
                    if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 <= len(grid[0])-1:
                        #if x2 and y2 not checked yet and there is not obstacles
                        if closed[x2][y2] == 0 and grid[x2][y2] == 0:
                            g2 = g+cost #we increment the cose
                            open.append([g2,x2,y2])#we add them to our open list
                            #print('append list item')
                            #print([g2,x2,y2])
                            #Then we check them to never expand again
                            closed[x2][y2] = 1

search()

1 Ответ

0 голосов
/ 29 июня 2019

x2 и y2 - это позиция после выполнения i-го потенциального действия в дельте.

delta[i][0] означает первый элемент i-го действия в дельте (изменениеx, вызванный i-м действием)

delta[i][1] означает второй элемент i-го действия в дельте (изменение y, вызванное i-м действием)

Итакx2=x+delta[i][0] и y2=y+delta[i][1] применяют это потенциальное действие и сохраняют полученные новые значения x и y в x2 и y2.

В контексте этой программы эти значения создаютсядля каждого потенциального действия (for i in range(len(delta)) и если полученная позиция попадает в сетку, еще не проверена и не имеет препятствий, то позиция добавляется в список open.

...