|
1 | 1 | import heapq # used for the so colled "open list" that stores known nodes |
2 | 2 | import time # for time limitation |
| 3 | +from ..core.grid import Grid |
3 | 4 | from ..core.diagonal_movement import DiagonalMovement |
4 | 5 | from ..core.heap import SimpleHeap |
5 | 6 |
|
@@ -56,15 +57,24 @@ def __init__(self, heuristic=None, weight=1, |
56 | 57 | self.start_time = 0 # execution time limitation |
57 | 58 | self.runs = 0 # count number of iterations |
58 | 59 |
|
59 | | - def apply_heuristic(self, node_a, node_b, heuristic=None): |
| 60 | + def apply_heuristic(self, node_a, node_b, heuristic=None, graph=None): |
60 | 61 | """ |
61 | 62 | helper function to apply heuristic |
62 | 63 | """ |
63 | 64 | if not heuristic: |
64 | 65 | heuristic = self.heuristic |
65 | | - return heuristic( |
66 | | - abs(node_a.x - node_b.x), |
67 | | - abs(node_a.y - node_b.y)) |
| 66 | + |
| 67 | + dx = abs(node_a.x - node_b.x) |
| 68 | + dy = abs(node_a.y - node_b.y) |
| 69 | + |
| 70 | + if isinstance(graph, Grid): |
| 71 | + if graph.passable_left_right_border and dx > graph.width / 2: |
| 72 | + dx = graph.width - dx |
| 73 | + |
| 74 | + if graph.passable_up_down_border and dy > graph.height / 2: |
| 75 | + dy = graph.height - dy |
| 76 | + |
| 77 | + return heuristic(dx, dy) |
68 | 78 |
|
69 | 79 | def find_neighbors(self, grid, node, diagonal_movement=None): |
70 | 80 | ''' |
@@ -110,7 +120,7 @@ def process_node( |
110 | 120 | if not node.opened or ng < node.g: |
111 | 121 | old_f = node.f |
112 | 122 | node.g = ng |
113 | | - node.h = node.h or self.apply_heuristic(node, end) |
| 123 | + node.h = node.h or self.apply_heuristic(node, end, graph=graph) |
114 | 124 | # f is the estimated total cost from start to goal |
115 | 125 | node.f = node.g + node.h |
116 | 126 | node.parent = parent |
|
0 commit comments