├── .gitignore ├── A(star)_pygame.py ├── A(star)_pygame_control.py ├── LICENSE ├── README.md ├── bfs.py ├── bfs_pygame.py ├── bfs_pygame_control.py ├── dijkstra.py ├── dijkstra_pygame.py ├── img ├── 1.png └── 2.png └── screenshot └── 1.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /A(star)_pygame.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | from heapq import * 3 | 4 | 5 | def get_circle(x, y): 6 | return (x * TILE + TILE // 2, y * TILE + TILE // 2), TILE // 4 7 | 8 | 9 | def get_rect(x, y): 10 | return x * TILE + 1, y * TILE + 1, TILE - 2, TILE - 2 11 | 12 | 13 | def get_next_nodes(x, y): 14 | check_next_node = lambda x, y: True if 0 <= x < cols and 0 <= y < rows else False 15 | ways = [-1, 0], [0, -1], [1, 0], [0, 1] 16 | return [(grid[y + dy][x + dx], (x + dx, y + dy)) for dx, dy in ways if check_next_node(x + dx, y + dy)] 17 | 18 | 19 | def heuristic(a, b): 20 | return abs(a[0] - b[0]) + abs(a[1] - b[1]) 21 | 22 | 23 | cols, rows = 23, 13 24 | TILE = 70 25 | 26 | pg.init() 27 | sc = pg.display.set_mode([cols * TILE, rows * TILE]) 28 | clock = pg.time.Clock() 29 | # grid 30 | grid = ['22222222222222222222212', 31 | '22222292222911112244412', 32 | '22444422211112911444412', 33 | '24444444212777771444912', 34 | '24444444219777771244112', 35 | '92444444212777791192144', 36 | '22229444212777779111144', 37 | '11111112212777772771122', 38 | '27722211112777772771244', 39 | '27722777712222772221244', 40 | '22292777711144429221244', 41 | '22922777222144422211944', 42 | '22222777229111111119222'] 43 | grid = [[int(char) for char in string ] for string in grid] 44 | # dict of adjacency lists 45 | graph = {} 46 | for y, row in enumerate(grid): 47 | for x, col in enumerate(row): 48 | graph[(x, y)] = graph.get((x, y), []) + get_next_nodes(x, y) 49 | 50 | # BFS settings 51 | start = (0, 7) 52 | goal = (22, 7) 53 | queue = [] 54 | heappush(queue, (0, start)) 55 | cost_visited = {start: 0} 56 | visited = {start: None} 57 | 58 | bg = pg.image.load('img/2.png').convert() 59 | bg = pg.transform.scale(bg, (cols * TILE, rows * TILE)) 60 | 61 | while True: 62 | # fill screen 63 | sc.blit(bg, (0, 0)) 64 | # draw BFS work 65 | [pg.draw.rect(sc, pg.Color('forestgreen'), get_rect(x, y), 1) for x, y in visited] 66 | [pg.draw.rect(sc, pg.Color('darkslategray'), get_rect(*xy)) for _, xy in queue] 67 | pg.draw.circle(sc, pg.Color('purple'), *get_circle(*goal)) 68 | 69 | # Dijkstra logic 70 | if queue: 71 | cur_cost, cur_node = heappop(queue) 72 | if cur_node == goal: 73 | queue = [] 74 | continue 75 | 76 | next_nodes = graph[cur_node] 77 | for next_node in next_nodes: 78 | neigh_cost, neigh_node = next_node 79 | new_cost = cost_visited[cur_node] + neigh_cost 80 | 81 | if neigh_node not in cost_visited or new_cost < cost_visited[neigh_node]: 82 | priority = new_cost + heuristic(neigh_node, goal) 83 | heappush(queue, (priority, neigh_node)) 84 | cost_visited[neigh_node] = new_cost 85 | visited[neigh_node] = cur_node 86 | 87 | # draw path 88 | path_head, path_segment = cur_node, cur_node 89 | while path_segment: 90 | pg.draw.circle(sc, pg.Color('brown'), *get_circle(*path_segment)) 91 | path_segment = visited[path_segment] 92 | pg.draw.circle(sc, pg.Color('blue'), *get_circle(*start)) 93 | pg.draw.circle(sc, pg.Color('magenta'), *get_circle(*path_head)) 94 | # pygame necessary lines 95 | [exit() for event in pg.event.get() if event.type == pg.QUIT] 96 | pg.display.flip() 97 | clock.tick(7) -------------------------------------------------------------------------------- /A(star)_pygame_control.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | from heapq import * 3 | 4 | 5 | def get_circle(x, y): 6 | return (x * TILE + TILE // 2, y * TILE + TILE // 2), TILE // 4 7 | 8 | 9 | def get_neighbours(x, y): 10 | check_neighbour = lambda x, y: True if 0 <= x < cols and 0 <= y < rows else False 11 | ways = [-1, 0], [0, -1], [1, 0], [0, 1]#, [-1, -1], [1, -1], [1, 1], [-1, 1] 12 | return [(grid[y + dy][x + dx], (x + dx, y + dy)) for dx, dy in ways if check_neighbour(x + dx, y + dy)] 13 | 14 | 15 | def get_click_mouse_pos(): 16 | x, y = pg.mouse.get_pos() 17 | grid_x, grid_y = x // TILE, y // TILE 18 | pg.draw.circle(sc, pg.Color('red'), *get_circle(grid_x, grid_y)) 19 | click = pg.mouse.get_pressed() 20 | return (grid_x, grid_y) if click[0] else False 21 | 22 | 23 | def heuristic(a, b): 24 | return abs(a[0] - b[0]) + abs(a[1] - b[1]) 25 | 26 | 27 | # def heuristic(a, b): 28 | # return max(abs(a[0] - b[0]), abs(a[1] - b[1])) 29 | 30 | 31 | def dijkstra(start, goal, graph): 32 | queue = [] 33 | heappush(queue, (0, start)) 34 | cost_visited = {start: 0} 35 | visited = {start: None} 36 | 37 | while queue: 38 | cur_cost, cur_node = heappop(queue) 39 | if cur_node == goal: 40 | break 41 | 42 | neighbours = graph[cur_node] 43 | for neighbour in neighbours: 44 | neigh_cost, neigh_node = neighbour 45 | new_cost = cost_visited[cur_node] + neigh_cost 46 | 47 | if neigh_node not in cost_visited or new_cost < cost_visited[neigh_node]: 48 | priority = new_cost + heuristic(neigh_node, goal) 49 | heappush(queue, (priority, neigh_node)) 50 | cost_visited[neigh_node] = new_cost 51 | visited[neigh_node] = cur_node 52 | return visited 53 | 54 | 55 | cols, rows = 23, 13 56 | TILE = 70 57 | 58 | pg.init() 59 | sc = pg.display.set_mode([cols * TILE, rows * TILE]) 60 | clock = pg.time.Clock() 61 | # set grid 62 | grid = ['22222222222222222222212', 63 | '22222292222911112244412', 64 | '22444422211112911444412', 65 | '24444444212777771444912', 66 | '24444444219777771244112', 67 | '92444444212777791192144', 68 | '22229444212777779111144', 69 | '11111112212777772771122', 70 | '27722211112777772771244', 71 | '27722777712222772221244', 72 | '22292777711144429221244', 73 | '22922777222144422211944', 74 | '22222777229111111119222'] 75 | grid = [[int(char) for char in string ] for string in grid] 76 | # adjacency dict 77 | graph = {} 78 | for y, row in enumerate(grid): 79 | for x, col in enumerate(row): 80 | graph[(x, y)] = graph.get((x, y), []) + get_neighbours(x, y) 81 | 82 | start = (0, 7) 83 | goal = start 84 | queue = [] 85 | heappush(queue, (0, start)) 86 | visited = {start: None} 87 | 88 | bg = pg.image.load('img/2.png').convert() 89 | bg = pg.transform.scale(bg, (cols * TILE, rows * TILE)) 90 | while True: 91 | # fill screen 92 | sc.blit(bg, (0, 0)) 93 | 94 | # bfs, get path to mouse click 95 | mouse_pos = get_click_mouse_pos() 96 | if mouse_pos: 97 | visited = dijkstra(start, mouse_pos, graph) 98 | goal = mouse_pos 99 | 100 | # draw path 101 | path_head, path_segment = goal, goal 102 | while path_segment and path_segment in visited: 103 | pg.draw.circle(sc, pg.Color('blue'), *get_circle(*path_segment)) 104 | path_segment = visited[path_segment] 105 | pg.draw.circle(sc, pg.Color('green'), *get_circle(*start)) 106 | pg.draw.circle(sc, pg.Color('magenta'), *get_circle(*path_head)) 107 | 108 | # pygame necessary lines 109 | [exit() for event in pg.event.get() if event.type == pg.QUIT] 110 | pg.display.flip() 111 | clock.tick(30) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 StanislavPetrovV 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Dijkstra-BFS-A-star 2 | examples of applying Dijkstra, BFS, A* in Pygame 3 | 4 | ![bfs](screenshot/1.png "bfs") 5 | -------------------------------------------------------------------------------- /bfs.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | graph = {'A': ['M', 'P'], 4 | 'M': ['A', 'N'], 5 | 'N': ['M', 'B'], 6 | 'P': ['A', 'B'], 7 | 'B': ['P', 'N']} 8 | 9 | def bfs(start, goal, graph): 10 | queue = deque([start]) 11 | visited = {start: None} 12 | 13 | while queue: 14 | cur_node = queue.popleft() 15 | if cur_node == goal: 16 | break 17 | 18 | next_nodes = graph[cur_node] 19 | for next_node in next_nodes: 20 | if next_node not in visited: 21 | queue.append(next_node) 22 | visited[next_node] = cur_node 23 | return visited 24 | 25 | start = 'A' 26 | goal = 'B' 27 | visited = bfs(start, goal, graph) 28 | 29 | cur_node = goal 30 | print(f'\npath from {goal} to {start}: \n {goal} ', end='') 31 | while cur_node != start: 32 | cur_node = visited[cur_node] 33 | print(f'---> {cur_node} ', end='') -------------------------------------------------------------------------------- /bfs_pygame.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | from random import random 3 | from collections import deque 4 | 5 | 6 | def get_rect(x, y): 7 | return x * TILE + 1, y * TILE + 1, TILE - 2, TILE - 2 8 | 9 | 10 | def get_next_nodes(x, y): 11 | check_next_node = lambda x, y: True if 0 <= x < cols and 0 <= y < rows and not grid[y][x] else False 12 | ways = [-1, 0], [0, -1], [1, 0], [0, 1] 13 | return [(x + dx, y + dy) for dx, dy in ways if check_next_node(x + dx, y + dy)] 14 | 15 | 16 | cols, rows = 25, 15 17 | TILE = 60 18 | 19 | pg.init() 20 | sc = pg.display.set_mode([cols * TILE, rows * TILE]) 21 | clock = pg.time.Clock() 22 | # grid 23 | grid = [[1 if random() < 0.2 else 0 for col in range(cols)] for row in range(rows)] 24 | # dict of adjacency lists 25 | graph = {} 26 | for y, row in enumerate(grid): 27 | for x, col in enumerate(row): 28 | if not col: 29 | graph[(x, y)] = graph.get((x, y), []) + get_next_nodes(x, y) 30 | 31 | # BFS settings 32 | start = (0, 0) 33 | queue = deque([start]) 34 | visited = {start: None} 35 | cur_node = start 36 | 37 | while True: 38 | # fill screen 39 | sc.fill(pg.Color('black')) 40 | # draw grid 41 | [[pg.draw.rect(sc, pg.Color('darkorange'), get_rect(x, y), border_radius=TILE // 5) 42 | for x, col in enumerate(row) if col] for y, row in enumerate(grid)] 43 | # draw BFS work 44 | [pg.draw.rect(sc, pg.Color('forestgreen'), get_rect(x, y)) for x, y in visited] 45 | [pg.draw.rect(sc, pg.Color('darkslategray'), get_rect(x, y)) for x, y in queue] 46 | 47 | # BFS logic 48 | if queue: 49 | cur_node = queue.popleft() 50 | next_nodes = graph[cur_node] 51 | for next_node in next_nodes: 52 | if next_node not in visited: 53 | queue.append(next_node) 54 | visited[next_node] = cur_node 55 | 56 | # draw path 57 | path_head, path_segment = cur_node, cur_node 58 | while path_segment: 59 | pg.draw.rect(sc, pg.Color('white'), get_rect(*path_segment), TILE, border_radius=TILE // 3) 60 | path_segment = visited[path_segment] 61 | pg.draw.rect(sc, pg.Color('blue'), get_rect(*start), border_radius=TILE // 3) 62 | pg.draw.rect(sc, pg.Color('magenta'), get_rect(*path_head), border_radius=TILE // 3) 63 | # pygame necessary lines 64 | [exit() for event in pg.event.get() if event.type == pg.QUIT] 65 | pg.display.flip() 66 | clock.tick(7) -------------------------------------------------------------------------------- /bfs_pygame_control.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | from random import random 3 | from collections import deque 4 | 5 | 6 | def get_rect(x, y): 7 | return x * TILE + 1, y * TILE + 1, TILE - 2, TILE - 2 8 | 9 | 10 | def get_next_nodes(x, y): 11 | check_next_node = lambda x, y: True if 0 <= x < cols and 0 <= y < rows and not grid[y][x] else False 12 | ways = [-1, 0], [0, -1], [1, 0], [0, 1], [-1, -1], [1, -1], [1, 1], [-1, 1] 13 | return [(x + dx, y + dy) for dx, dy in ways if check_next_node(x + dx, y + dy)] 14 | 15 | 16 | def get_click_mouse_pos(): 17 | x, y = pg.mouse.get_pos() 18 | grid_x, grid_y = x // TILE, y // TILE 19 | pg.draw.rect(sc, pg.Color('red'), get_rect(grid_x, grid_y)) 20 | click = pg.mouse.get_pressed() 21 | return (grid_x, grid_y) if click[0] else False 22 | 23 | 24 | def bfs(start, goal, graph): 25 | queue = deque([start]) 26 | visited = {start: None} 27 | 28 | while queue: 29 | cur_node = queue.popleft() 30 | if cur_node == goal: 31 | break 32 | 33 | next_nodes = graph[cur_node] 34 | for next_node in next_nodes: 35 | if next_node not in visited: 36 | queue.append(next_node) 37 | visited[next_node] = cur_node 38 | return queue, visited 39 | 40 | 41 | cols, rows = 35, 20 42 | TILE = 50 43 | 44 | pg.init() 45 | sc = pg.display.set_mode([cols * TILE, rows * TILE]) 46 | clock = pg.time.Clock() 47 | # grid 48 | grid = [[1 if random() < 0.2 else 0 for col in range(cols)] for row in range(rows)] 49 | # dict of adjacency lists 50 | graph = {} 51 | for y, row in enumerate(grid): 52 | for x, col in enumerate(row): 53 | if not col: 54 | graph[(x, y)] = graph.get((x, y), []) + get_next_nodes(x, y) 55 | 56 | # BFS settings 57 | start = (0, 0) 58 | goal = start 59 | queue = deque([start]) 60 | visited = {start: None} 61 | 62 | while True: 63 | # fill screen 64 | sc.fill(pg.Color('black')) 65 | # draw grid 66 | [[pg.draw.rect(sc, pg.Color('darkorange'), get_rect(x, y), border_radius=TILE // 5) 67 | for x, col in enumerate(row) if col] for y, row in enumerate(grid)] 68 | # draw BFS work 69 | [pg.draw.rect(sc, pg.Color('forestgreen'), get_rect(x, y)) for x, y in visited] 70 | [pg.draw.rect(sc, pg.Color('darkslategray'), get_rect(x, y)) for x, y in queue] 71 | 72 | # bfs, get path to mouse click 73 | mouse_pos = get_click_mouse_pos() 74 | if mouse_pos and not grid[mouse_pos[1]][mouse_pos[0]]: 75 | queue, visited = bfs(start, mouse_pos, graph) 76 | goal = mouse_pos 77 | 78 | # draw path 79 | path_head, path_segment = goal, goal 80 | while path_segment and path_segment in visited: 81 | pg.draw.rect(sc, pg.Color('white'), get_rect(*path_segment), TILE, border_radius=TILE // 3) 82 | path_segment = visited[path_segment] 83 | pg.draw.rect(sc, pg.Color('blue'), get_rect(*start), border_radius=TILE // 3) 84 | pg.draw.rect(sc, pg.Color('magenta'), get_rect(*path_head), border_radius=TILE // 3) 85 | # pygame necessary lines 86 | [exit() for event in pg.event.get() if event.type == pg.QUIT] 87 | pg.display.flip() 88 | clock.tick(30) -------------------------------------------------------------------------------- /dijkstra.py: -------------------------------------------------------------------------------- 1 | from heapq import * 2 | 3 | graph = {'A': [(2, 'M'), (3, 'P')], 4 | 'M': [(2, 'A'), (2, 'N')], 5 | 'N': [(2, 'M'), (2, 'B')], 6 | 'P': [(3, 'A'), (4, 'B')], 7 | 'B': [(4, 'P'), (2, 'N')]} 8 | 9 | def dijkstra(start, goal, graph): 10 | queue = [] 11 | heappush(queue, (0, start)) 12 | cost_visited = {start: 0} 13 | visited = {start: None} 14 | 15 | while queue: 16 | cur_cost, cur_node = heappop(queue) 17 | if cur_node == goal: 18 | break 19 | 20 | next_nodes = graph[cur_node] 21 | for next_node in next_nodes: 22 | neigh_cost, neigh_node = next_node 23 | new_cost = cost_visited[cur_node] + neigh_cost 24 | 25 | if neigh_node not in cost_visited or new_cost < cost_visited[neigh_node]: 26 | heappush(queue, (new_cost, neigh_node)) 27 | cost_visited[neigh_node] = new_cost 28 | visited[neigh_node] = cur_node 29 | return visited 30 | 31 | start = 'A' 32 | goal = 'B' 33 | visited = dijkstra(start, goal, graph) 34 | 35 | cur_node = goal 36 | print(f'\npath from {goal} to {start}: \n {goal} ', end='') 37 | while cur_node != start: 38 | cur_node = visited[cur_node] 39 | print(f'---> {cur_node} ', end='') -------------------------------------------------------------------------------- /dijkstra_pygame.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | from heapq import * 3 | 4 | 5 | def get_circle(x, y): 6 | return (x * TILE + TILE // 2, y * TILE + TILE // 2), TILE // 4 7 | 8 | 9 | def get_rect(x, y): 10 | return x * TILE + 1, y * TILE + 1, TILE - 2, TILE - 2 11 | 12 | 13 | def get_next_nodes(x, y): 14 | check_next_node = lambda x, y: True if 0 <= x < cols and 0 <= y < rows else False 15 | ways = [-1, 0], [0, -1], [1, 0], [0, 1] 16 | return [(grid[y + dy][x + dx], (x + dx, y + dy)) for dx, dy in ways if check_next_node(x + dx, y + dy)] 17 | 18 | 19 | cols, rows = 23, 13 20 | TILE = 70 21 | 22 | pg.init() 23 | sc = pg.display.set_mode([cols * TILE, rows * TILE]) 24 | clock = pg.time.Clock() 25 | # grid 26 | grid = ['22222222222222222222212', 27 | '22222292222911112244412', 28 | '22444422211112911444412', 29 | '24444444212777771444912', 30 | '24444444219777771244112', 31 | '92444444212777791192144', 32 | '22229444212777779111144', 33 | '11111112212777772771122', 34 | '27722211112777772771244', 35 | '27722777712222772221244', 36 | '22292777711144429221244', 37 | '22922777222144422211944', 38 | '22222777229111111119222'] 39 | grid = [[int(char) for char in string ] for string in grid] 40 | # dict of adjacency lists 41 | graph = {} 42 | for y, row in enumerate(grid): 43 | for x, col in enumerate(row): 44 | graph[(x, y)] = graph.get((x, y), []) + get_next_nodes(x, y) 45 | 46 | # BFS settings 47 | start = (0, 7) 48 | goal = (22, 7) 49 | queue = [] 50 | heappush(queue, (0, start)) 51 | cost_visited = {start: 0} 52 | visited = {start: None} 53 | 54 | bg = pg.image.load('img/2.png').convert() 55 | bg = pg.transform.scale(bg, (cols * TILE, rows * TILE)) 56 | 57 | while True: 58 | # fill screen 59 | sc.blit(bg, (0, 0)) 60 | # draw BFS work 61 | [pg.draw.rect(sc, pg.Color('forestgreen'), get_rect(x, y), 1) for x, y in visited] 62 | [pg.draw.rect(sc, pg.Color('darkslategray'), get_rect(*xy)) for _, xy in queue] 63 | pg.draw.circle(sc, pg.Color('purple'), *get_circle(*goal)) 64 | 65 | # Dijkstra logic 66 | if queue: 67 | cur_cost, cur_node = heappop(queue) 68 | if cur_node == goal: 69 | queue = [] 70 | continue 71 | 72 | next_nodes = graph[cur_node] 73 | for next_node in next_nodes: 74 | neigh_cost, neigh_node = next_node 75 | new_cost = cost_visited[cur_node] + neigh_cost 76 | 77 | if neigh_node not in cost_visited or new_cost < cost_visited[neigh_node]: 78 | heappush(queue, (new_cost, neigh_node)) 79 | cost_visited[neigh_node] = new_cost 80 | visited[neigh_node] = cur_node 81 | 82 | # draw path 83 | path_head, path_segment = cur_node, cur_node 84 | while path_segment: 85 | pg.draw.circle(sc, pg.Color('brown'), *get_circle(*path_segment)) 86 | path_segment = visited[path_segment] 87 | pg.draw.circle(sc, pg.Color('blue'), *get_circle(*start)) 88 | pg.draw.circle(sc, pg.Color('magenta'), *get_circle(*path_head)) 89 | # pygame necessary lines 90 | [exit() for event in pg.event.get() if event.type == pg.QUIT] 91 | pg.display.flip() 92 | clock.tick(7) -------------------------------------------------------------------------------- /img/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StanislavPetrovV/Python-Dijkstra-BFS-A-star/db39f6f113f457d9658fb47a43bb86c2b6be999a/img/1.png -------------------------------------------------------------------------------- /img/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StanislavPetrovV/Python-Dijkstra-BFS-A-star/db39f6f113f457d9658fb47a43bb86c2b6be999a/img/2.png -------------------------------------------------------------------------------- /screenshot/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StanislavPetrovV/Python-Dijkstra-BFS-A-star/db39f6f113f457d9658fb47a43bb86c2b6be999a/screenshot/1.png --------------------------------------------------------------------------------