summaryrefslogtreecommitdiff
path: root/gui/pathfind.py
blob: 2c870e1e87f0c0ca57231cec23dd00d05d723932 (plain) (blame)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
import collections


class Queue:
    def __init__(self):
        self.elements = collections.deque()

    def empty(self):
        return len(self.elements) == 0

    def put(self, x):
        self.elements.append(x)

    def get(self):
        return self.elements.popleft()


class Graph:
    def __init__(self, collisions):
        self.collisions = collisions
        self.width = len(collisions[0])
        self.height = len(collisions)

    def walkable(self, coor):
        x, y = coor
        if x < 0 or x > self.width - 1:
            return False
        if y < 0 or y > self.height - 1:
            return False
        if self.collisions[self.height - y - 1][x] > 0:
            return False
        return True

    def neighbors(self, coor):
        n = []
        x, y = coor

        for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            nx = x + dx
            ny = y + dy
            if self.walkable((nx, ny)):
                n.append((nx, ny))

        for dx, dy in ((-1, -1), (-1, 1), (1, -1), (1, 1)):
            nx = x + dx
            ny = y + dy
            if (self.walkable((nx, ny)) and
                    self.walkable((nx, y)) and
                    self.walkable((x, ny))):
                n.append((nx, ny))

        return n


def breadth_first_search(collisions, start, goal):
    graph = Graph(collisions)
    frontier = Queue()
    frontier.put(start)
    came_from = {}
    came_from[start] = None

    while not frontier.empty():
        current = frontier.get()

        if current == goal:
            break

        for next in graph.neighbors(current):
            if next not in came_from:
                frontier.put(next)
                came_from[next] = current

    current = goal
    path = [current]
    while current != start:
        current = came_from[current]
        path.append(current)
    path.reverse()

    # simplify path
    spath = path[:1]
    for i in range(1, len(path) - 1):
        px, py = path[i - 1]
        cx, cy = path[i]
        nx, ny = path[i + 1]
        if nx - cx == cx - px and ny - cy == cy - py:
            continue
        spath.append(path[i])
    spath.append(path[-1])

    return spath