本文使用 Python 语言实现 A* 算法。
算法流程和原理不赘述。
代码文件结构:
point.py
import sys
class Point(object):
def __init__(self, x: int, y: int):
self.x = x
self.y = y
self.cost = sys.maxsize
self.parent = None
map.py
from typing import Tuple, List
from point import Point
class Map(object):
def __init__(self, width: int, height: int, obstacles: List[Tuple[int, int]] = []):
self.width = width
self.height = height
self.obstacles = [Point(x=osc[0], y=osc[1]) for osc in obstacles]
def is_obstacle(self, i: int, j: int):
for p in self.obstacles:
if i==p.x and j==p.y:
return True
return False
a_star.py
有可视化的代码,最终生成视频,生成后可将中间生成的图片删除。
import os
import sys
import time
from typing import Tuple, List
from matplotlib.patches import Rectangle
import cv2
import glob
from point import Point
from map import Map
class AStar(object):
"""
A* algorithm
"""
def __init__(self, map: Map, origin: Tuple[int, int], target: Tuple[int, int]):
"""
initialise
:param map: map
:param origin: starting point coordinates
:param target: ending point coordinates
"""
self.map = map
self.origin = Point(x=origin[0], y=origin[1])
self.target = Point(x=target[0], y=target[1])
self.open_points = []
self.close_points = []
def _basic_cost(self, point: Point):
"""
basic cost from origin
"""
return abs(point.x - self.origin.x) + abs(point.y - self.origin