from a_star_utils import Node
def A_star(map, mapSize, start, end):
'''
A*算法,从start走到end
:param map:地图
:param mapSize:地图大小,例如[10,10]表示地图长10宽10
:param start:表示出发地,类型为列表,如[1,2]表示出发地为地图中的第1行第2列的方块
:param end:表示目的地,类型为列表,如[1,2]表示目的地为地图中的第1行第2列的方块
:return:从出发地到目的地的路径
'''
openedList = []
#********* Begin *********#
# 获得出发地方块的信息,并将信息保存为node变量
node = map[start[0]][start[1]]
#********* End *********#
node.distanceFromOri = 0
node.allDistance = 0
#********* Begin *********#
# 将当前方块存到开启列表中
openedList.append (node)
node.added = True
#********* End *********#
while len(openedList) != 0:
node = openedList.pop(0)
node.closed = True
if node.y == end[0] and node.x == end[1]:
finalListNeedReverse = []
while node != None:
finalListNeedReverse.append(node)
node = node.parent
finalListNeedReverse.reverse()
return finalListNeedReverse
neighboursList = []
y = node.y
x = node.x
parentDistanceFromOri = node.distanceFromOri
for needNodey in (y + 1, y, y - 1):
if needNodey < 0 or needNodey >= mapSize[0]:
continue
for needNodex in (x + 1, x, x - 1):
if needNodex < 0 or needNodex >= mapSize[1]:
continue
needNode = map[needNodey][needNodex]
if needNode.unable == True or needNode.closed == True or needNode.added == True:
continue
yOffset = needNodey - y
xOffset = needNodex - x
allOffset = yOffset + xOffset
if allOffset == 1 or allOffset == -1:
distanceFromOri = parentDistanceFromOri + 1
else:
distanceFromOri = parentDistanceFromOri + 1.4
if needNode in neighboursList:
# 若新的G值比老的G值低,则更新成老的G值
if distanceFromOri < needNode.distanceFromOri:
needNode.distanceFromOri = distanceFromOri
else:
needNode.distanceFromOri = distanceFromOri
neighboursList.append(needNode)
for needNode in neighboursList:
needNode.parent = node
# 更新F值
needNode.allDistance = needNode.distanceFromOri + needNode.distanceFromDes
needNode.added = True
openedList.append(needNode)
openedList.sort(key=lambda x: x.allDistance)
return None