Projekt_AI-Automatyczny_saper/Engine/BfsPathFinder.py

65 lines
2.1 KiB
Python
Raw Normal View History

2021-04-13 21:27:51 +02:00
from queue import Queue
2021-04-26 20:24:52 +02:00
from Engine.Point import Point
from Engine.State import State
from Constants import RIGHT, LEFT, DOWN, UP, DEFUSE, REST
class BfsPathFinder:
2021-04-13 21:27:51 +02:00
def __init__(self, board):
self.board = board
self.goal = None
2021-04-26 20:24:52 +02:00
def findBomb(self,startState):
2021-04-13 21:27:51 +02:00
frontier = Queue()
2021-04-26 20:24:52 +02:00
frontier.put(startState)
2021-04-13 21:27:51 +02:00
cameFrom = dict()
2021-04-26 20:24:52 +02:00
cameFrom[startState] = None
2021-04-13 21:27:51 +02:00
while not frontier.empty():
current = frontier.get()
if self.checkGoal(current):
2021-04-26 20:24:52 +02:00
return self.constructPath(cameFrom,startState)
2021-04-13 21:27:51 +02:00
for next in self.getNeighbour(current):
if next not in cameFrom:
frontier.put(next)
cameFrom[next] = current
return []
2021-04-26 20:24:52 +02:00
def constructPath(self,cameFrom,startState):
2021-04-13 21:27:51 +02:00
current = cameFrom[self.goal]
path = []
path.append(self.goal)
2021-04-26 20:24:52 +02:00
while current.getAction != startState:
2021-04-13 21:27:51 +02:00
path.append(current)
current = cameFrom[current]
2021-04-26 20:24:52 +02:00
path.append(startState)
2021-04-13 21:27:51 +02:00
path.reverse()
return path
2021-04-26 20:24:52 +02:00
def getNeighbour(self, current):
neighbourlist = []
state1 = State(LEFT,Point(current.getX() + 1, current.getY()))
state2 = State(RIGHT,Point(current.getX(), current.getY() + 1))
state3 = State(UP,Point(current.getX(), current.getY() - 1))
state4 = State(DOWN,Point(current.getX() - 1, current.getY()))
if self.checkField(current.getPoint(),state1.getPoint()):
neighbourlist.append(state1.getPoint())
if self.checkField(current.getPoint(), state2.getPoint()):
neighbourlist.append(state2.getPoint())
if self.checkField(current.getPoint(),state3.getPoint()):
neighbourlist.append(state3)
if self.checkField(current.getPoint(),state4.getPoint()):
neighbourlist.append(state4)
return neighbourlist
2021-04-13 21:27:51 +02:00
def checkGoal(self, current):
2021-04-26 20:24:52 +02:00
if current.getPoint() in self.board.bombMap:
2021-04-13 21:27:51 +02:00
self.goal = current
return True
return False
2021-04-26 20:24:52 +02:00