SI_projekt_smieciarka/bfs.py

60 lines
1.9 KiB
Python
Raw Normal View History

2021-06-15 19:48:34 +02:00
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
2021-06-15 19:59:23 +02:00
def __eq__(self, other):
if isinstance(other, Node):
return self.pos[0] == other.pos[0] and self.pos[1] == other.pos[1] and self.direction == other.direction
return False
2021-06-15 19:48:34 +02:00
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)
2021-06-15 19:59:23 +02:00
2021-06-15 19:48:34 +02:00
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
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