|
1 | | -def a_star(): |
| 1 | +import sys |
| 2 | +import numpy as np |
| 3 | +from config import config |
| 4 | +from collections import deque |
| 5 | +import time |
| 6 | +import pygame |
| 7 | +from queue import PriorityQueue |
| 8 | +import copy |
| 9 | + |
| 10 | + |
| 11 | +def is_valid(mat, row, col): |
| 12 | + M, N = mat.shape |
| 13 | + return (row >= 0) and (row < M) and (col >= 0) and (col < N) \ |
| 14 | + and mat[row][col] == 0 |
| 15 | + |
| 16 | + |
| 17 | +def manhattan_distance(x1, y1, x2, y2): |
| 18 | + return abs(x1 - x2) + abs(y1 - y2) |
| 19 | + |
| 20 | + |
| 21 | +def a_star(win, startEnd, walls): |
| 22 | + start, end = startEnd |
| 23 | + mat = np.zeros([config['board']['w'], config['board']['h']]) |
| 24 | + for i in walls: |
| 25 | + mat[i] = 1 |
| 26 | + |
| 27 | + # explore 4 neighbors |
| 28 | + row = [-1, 0, 0, 1] |
| 29 | + col = [0, -1, 1, 0] |
| 30 | + |
| 31 | + q = PriorityQueue() |
| 32 | + count = 0 |
| 33 | + q.put((0, count, start)) |
| 34 | + g_score = {} |
| 35 | + for i in range(mat.shape[0]): |
| 36 | + for j in range(mat.shape[1]): |
| 37 | + g_score[(i, j)] = float('inf') |
| 38 | + |
| 39 | + f_score = copy.deepcopy(g_score) |
| 40 | + g_score[start] = 0 |
| 41 | + f_score[start] = manhattan_distance(*start, *end) |
| 42 | + q_hash = {start} |
| 43 | + came_from = {} |
| 44 | + while not q.empty(): |
| 45 | + for event in pygame.event.get(): |
| 46 | + if event.type == pygame.QUIT: |
| 47 | + pygame.quit() |
| 48 | + current = q.get()[2] |
| 49 | + q_hash.remove(current) |
| 50 | + |
| 51 | + for k in range(4): |
| 52 | + coordinate = (current[0] + row[k], current[1] + col[k]) |
| 53 | + |
| 54 | + if is_valid(mat, *coordinate): |
| 55 | + temp_g_score = g_score[current] + 1 |
| 56 | + if temp_g_score < g_score[coordinate]: |
| 57 | + came_from[coordinate] = current |
| 58 | + g_score[coordinate] = temp_g_score |
| 59 | + f_score[coordinate] = temp_g_score + manhattan_distance(*coordinate, *end) |
| 60 | + if coordinate not in q_hash: |
| 61 | + count += 1 |
| 62 | + q_hash.add(coordinate) |
| 63 | + q.put((f_score[coordinate], count, coordinate)) |
| 64 | + win.write('*', *coordinate, fgcolor='green') |
| 65 | + pygame.time.wait(5) |
| 66 | + if current == end: |
| 67 | + count = 0 |
| 68 | + win.write('@', *end) |
| 69 | + while current in came_from: |
| 70 | + for event in pygame.event.get(): |
| 71 | + if event.type == pygame.QUIT: |
| 72 | + pygame.quit() |
| 73 | + current = came_from[current] |
| 74 | + win.write('+', *current, fgcolor='red') |
| 75 | + count += 1 |
| 76 | + pygame.time.wait(20) |
| 77 | + win.write('@', *start) |
| 78 | + win.write(f"The shortest path from source to destination has length {count}", 1, 1) |
| 79 | + break |
| 80 | + win.write("Destination can't be reached from a given source", 1, 1) |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | + |
0 commit comments