-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_finder.py
79 lines (71 loc) · 2.57 KB
/
path_finder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from heapq import heappop, heappush
from structs import Point, TileContent
from actions import create_move_action
def dist(p1, p2):
return abs(p1.X - p2.X) + abs(p1.Y - p2.Y)
def free(tiles, p, player):
"""
p has absolute coordinates
"""
# Change start and stop to relative coordinates
x = p.X - 10 + player.X
y = p.Y - 10 + player.Y
if x < 0:
return False
if y < 0:
return False
if x >= 19:
return False
if y >= 19:
return False
# TODO: prevent overflows
if tiles[x][y].Content != TileContent.Empty:
return False
return True
def find_path(tiles, start, goal, player):
"""
Search for the minimal path from start to an adjacent cell of goal
start and stop are absolute coordinates in the full map.
"""
def heuristic(cell, goal):
return dist(cell, goal) - 1
pr_queue = []
#heappush(pr_queue, (0 + heuristic(start, goal), 0, start, start))
right = Point(start.X - 1, start.Y)
if free(tiles, right, player):
heappush(pr_queue, (0 + heuristic(right, goal), 0, right, right))
left = Point(start.X + 1, start.Y)
if free(tiles, left, player):
heappush(pr_queue, (0 + heuristic(left, goal), 0, left, left))
up = Point(start.X , start.Y - 1)
if free(tiles, up, player):
heappush(pr_queue, (0 + heuristic(up, goal), 0, up, up))
down = Point(start.X , start.Y + 1)
if free(tiles, down, player):
heappush(pr_queue, (0 + heuristic(down, goal), 0, down, down))
visited = {start}
while pr_queue:
_, cost, path, current = heappop(pr_queue)
if current == goal:
return path
if current in visited:
continue
visited.add(current)
right = Point(current.X - 1, current.Y)
if free(tiles, right, player):
heappush(pr_queue, (cost + heuristic(right, goal), cost + 1, path, right))
left = Point(current.X + 1, current.Y)
if free(tiles, left, player):
heappush(pr_queue, (cost + heuristic(left, goal), cost + 1, path, left))
up = Point(current.X , current.Y - 1)
if free(tiles, up, player):
heappush(pr_queue, (cost + heuristic(up, goal), cost + 1, path, up))
down = Point(current.X , current.Y + 1)
if free(tiles, down, player):
heappush(pr_queue, (cost + heuristic(down, goal), cost + 1, path, down))
return None
def move_to(tiles, start, goal, player):
p = find_path(tiles, start, goal, player)
if p != None:
return create_move_action(p)
return None