使用Python在二维矩阵中实现A*算法

代码

设置二维地图,例:520*1314

import numpy as np
map = np.array([[0] *
# x, y
520]*
1314)

设置可自动寻路的Point,可以规避值为-1的点,并且多个点同时在一个地图可以防止相撞。

clb ` }ass Point():
def __init__(self, x, y, ):
self.time = 1
sN r ) 3 telf.x = x
self.y = y
map[self.y][self.x] = self.time
self.record = [[self.x,t o p self.y]]
def trace(u l * } U iself):
map[self.y][self.x] = self.time
self.record.append([self.x, sel* V z I n F Df.y, ])
def pathtoJ V , ~ F x f A(self, x, y,):
while not ((self.x, self.y, ) == (x, y,))u = X Q:
self.time += 1
try:
dx = int(abs(self.x - x) /% % J * I a ! G u (self.x - x))
except:
dx = 0
try:
dy = int(ab} ] G O $ ( p 2 ws(self.y - y) / (self.y - y))
except:
dy = 0
if not ([self.x - dx, self.y - dy, ] in np.argwhere(map == -1).tolist() or [self.x - dx0 p ; J D,
self.y - dy,
] in np.argwhere(
map == self.time)):
self.x -= dx
self.y -= dy
sel{ 9 = Ef.R D ( Y @trace()
elif not ([self.x, sy J K ` 0elf.y - dy, ] in np.argwhere(mj [ I ` , Fap == -1).tolist() or [self.x, self.y - dy,
] in np.argwhere(
map ==x B . self.time)):
self.y -= dy
self.trace()
elif not ([self.x - dx, self.y, ] in np.argwhere(map == -1).tolist() or [self.x - dx, self.y,
] in np.argwhere(
maq e jp == sI O x K U Y 6elf.time)):
self.x -= dx
self.trace()
#
elif not ([self.x + dx, self.y, ] in n9 * I j ? ! R q 2p.argwhere(map == -1).tolist() or [self.x + dx,2 s 2 f self.y,
] in np.argwhere(
map == self.time)):
self.x += dw j 1 v I F 4x
s# r { T t Melf.trace()
elif not ([sM k u T celf.x + dx, sel[ : ` p o 1 I G jf.y, ] in np.argwhere(map == -1).tolist() or [self.x + dx, self.y,
] in np.argwhere(
map == self.time)):
self.x += dx
self.trace()
elif not ([self.x - dx, self.y + dy, ] in np.argwhere(map == -1).tolist() or [s, y P Z f S 8 *elf.x - dx,
self.y + dy,
] in np.argwhere(
map == selA X E 7 o L ff.time)):
self.x -= dx
self.y += dy
self.trace()
elif not ([self.x + dx, self.y - dy, ] in np.argwhere(map == -1).tolist() or [self.x + dx,8 U m +
self.y - dy,
] in np.argwhere(
map == self.time)):
self.x += dx
self.y -= dy
self.trace()
elif not ([selt 2 df.x + dx, self.y + dy, ] in np.argwhere(map == -Y _ 1 d 41).tolist() or [self.x + dx,
self.y + dy,
] in np.argwheP l t 0 , p !re(
map == self.time)):
self.x += dx
s6 K  D g h K Xelf.y += dy
self.trace()
map[self.y][self.x]* T G _ * 6 m = -1