56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
from house import is_house
|
|
import pygame
|
|
|
|
|
|
class Node:
|
|
def __init__(self, pos, direction, parent=None, action=None):
|
|
self.pos = pos
|
|
self.direction = direction
|
|
self.parent = parent
|
|
self.action = action
|
|
|
|
|
|
def successor(pos, direction, houses):
|
|
neighbours = []
|
|
axis = 0 if direction in [0, 2] else 1
|
|
move = 1 if direction in [0, 1] else -1
|
|
|
|
neighbours.append([pos, (direction - 1) % 4, pygame.K_a])
|
|
neighbours.append([pos, (direction + 1) % 4, pygame.K_d])
|
|
|
|
if not axis: # x
|
|
new_pos = [pos[0] + (move * 40), pos[1]]
|
|
if not is_house(new_pos, houses):
|
|
neighbours.append([new_pos, direction, pygame.K_w])
|
|
|
|
else: # y
|
|
new_pos = [pos[0], pos[1] + (move * 40)]
|
|
if not is_house(new_pos, houses):
|
|
neighbours.append([new_pos, direction, pygame.K_w])
|
|
return neighbours
|
|
|
|
|
|
def bfs(pos, direction, end_pos, houses):
|
|
visited = []
|
|
queue = []
|
|
actions = []
|
|
queue.append(Node(pos, direction))
|
|
|
|
while queue:
|
|
curr_node = queue.pop(0)
|
|
print(curr_node.pos, curr_node.direction)
|
|
if not is_house(curr_node.pos, houses) and curr_node.pos == end_pos:
|
|
while curr_node.parent:
|
|
print(curr_node.pos, end_pos)
|
|
actions.append(curr_node.action)
|
|
curr_node = curr_node.parent
|
|
actions.append(curr_node.action)
|
|
return actions
|
|
|
|
visited.append(curr_node)
|
|
for n_pos, n_direction, action in successor(curr_node.pos, curr_node.direction, houses):
|
|
neighbour_node = Node(n_pos, n_direction, curr_node, action)
|
|
if neighbour_node not in visited and neighbour_node not in queue:
|
|
queue.append(neighbour_node)
|
|
return actions
|