Search the maze with the python A * algorithm

What is an A * algorithm?

qiita Algorithm.py



import heapq

class CalculationAStarAlgorithm():
    def __init__(self, dungeon, start_charactor, goal_charactor):
        self.dungeon = dungeon
        self.start_charactor_position = self.getCharacotorCoordinates(start_charactor)
        self.goal_charactor_position = self.getCharacotorCoordinates(goal_charactor)

    def getCharacotorCoordinates(self, search_criteria_charactor):
        for index_height, line in enumerate(self.dungeon):
            for index_wedth, charactor in enumerate(line):
                if charactor == search_criteria_charactor:
                    return (index_height, index_wedth)

    def heuristic(self, position):
        return ((position[0] - self.goal_charactor_position[0]) ** 2 + (position[1] - self.goal_charactor_position[1]) ** 2) ** 0.5

    def distance(self, path):
        return len(path)

    def nextCandidatePosition(self, last_passed_position):
        wall = "*"
        vertical_axis, horizontal_axis = last_passed_position
        for next_vertical, next_horizontal in zip((vertical_axis + 1, vertical_axis - 1, vertical_axis, vertical_axis), (horizontal_axis, horizontal_axis, horizontal_axis + 1, horizontal_axis - 1)):
            if self.dungeon[next_vertical][next_horizontal] != wall:
                yield (next_vertical, next_horizontal)

    def aStarAlgorithm(self):
        passed_list = [self.start_charactor_position]
        init_score = self.distance(passed_list) + self.heuristic(self.start_charactor_position)
        checked = {self.start_charactor_position: init_score}
        searching_heap = []
        heapq.heappush(searching_heap, (init_score, passed_list))

        while len(searching_heap) > 0:
            score, passed_list = heapq.heappop(searching_heap)
            last_passed_position = passed_list[-1]
            
            if last_passed_position == self.goal_charactor_position:
                return passed_list
            for position in self.nextCandidatePosition(last_passed_position):
                new_passed_list = passed_list + [position]
                position_score = self.distance(new_passed_list) + self.heuristic(position)
                if position in checked and checked[position] <= position_score:
                    continue
                checked[position] = position_score
                heapq.heappush(searching_heap, (position_score, new_passed_list))
        return []

    def renderPath(self, path):
        structure = [[dungeon_dot for dungeon_dot in element] for element in self.dungeon]
        for dot in path[1:-1]:
            structure[dot[0]][dot[1]] = "$"
        structure[path[0][0]][path[0][1]] = "S"
        structure[path[-1][0]][path[-1][1]] = "G"
        return ["".join(l) for l in structure]

if __name__ == '__main__': 

    dungeon = [
        '**************************',
        '*S* *                    *',
        '* * *  *  *************  *',
        '* *   *    ************  *',
        '*    *                   *',
        '************** ***********',
        '*                        *',
        '** ***********************',
        '*      *              G  *',
        '*  *      *********** *  *',
        '*    *        ******* *  *',
        '*       *                *',
        '**************************',
        ]

    calculation = CalculationAStarAlgorithm(dungeon, "S", "G")
    path = calculation.aStarAlgorithm()

    if len(path) > 0:
        print("\n".join(calculation.renderPath(path)))
    else:
        print('failed')

reference

https://qiita.com/masashi127/items/0c794e28f4b295ad82c6

Recommended Posts

Search the maze with the python A * algorithm
Algorithm learned with Python 12th: Maze search
Algorithm learned with Python 9th: Linear search
Solve the subset sum problem with a full search in Python
A * algorithm (Python edition)
Sequential search with Python
Binary search with python
Binary search with Python3
[Python] Get the files in a folder with Python
[Python] Make a simple maze game with Pyxel
Find the shortest path with the Python Dijkstra's algorithm
Solving the Python knapsack problem with the greedy algorithm
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
The first algorithm to learn with Python: FizzBuzz problem
Make a breakpoint on the c layer with python
Search algorithm using word2vec [python]
Algorithm in Python (binary search)
Fill the background with a single color with OpenCV2 + Python
Full bit search with Python
Make a fortune with Python
[Python3] Dijkstra's algorithm with 14 lines
A memo that I touched the Datastore with python
Call the API with python3.
Search engine work with python
Search twitter tweets with python
Create a directory with python
Streamline web search with python
A note about hitting the Facebook API with the Python SDK
Probably the easiest way to create a pdf with Python3
[Python] Try optimizing FX systole parameters with a genetic algorithm
Try a similar search for Image Search using the Python SDK [Search]
Solve the spiral book (algorithm and data structure) with python!
Create a Twitter BOT with the GoogleAppEngine SDK for Python
[Python] Make a simple maze game with Pyxel-Make enemies appear-
[Python] The first step to making a game with Pyxel
Finding a solution to the N-Queen problem with a genetic algorithm (1)
Algorithm in Python (breadth-first search, bfs)
[Python] What is a with statement?
Write a binary search in Python
Solve ABC163 A ~ C with Python
Extract the xz file with python
Operate a receipt printer with python
A python graphing manual with Matplotlib.
Let's make a GUI with python.
Solve ABC166 A ~ D with Python
Learn search with Python # 2bit search, permutation search
Get the weather with Python requests
Create a virtual environment with Python!
Write A * (A-star) algorithm in Python
Get the weather with Python requests 2
I made a fortune with Python.
Algorithm in Python (depth-first search, dfs)
Find the Levenshtein Distance with python
Explore the maze with reinforcement learning
Building a virtual environment with Python 3
Hit the Etherpad-lite API with Python
Install the Python plugin with Netbeans 8.0.2
Solve ABC168 A ~ C with Python
[Python] Make the function a lambda function
Make a recommender system with python