Projekt_AI-Automatyczny_saper/Engine/PathFinder.py
2021-04-26 20:24:52 +02:00

82 lines
2.7 KiB
Python

from Constants import ROWS, COLS
from Engine.Point import Point
class PathFinder:
def __init__(self, board):
self.board = board
self.openList = []
self.cameFrom = {}
self.gScore = {}
self.fScore = {}
self.current = Point(0,0)
def findPath(self,startPoint, endPoint):
self.openList.append(startPoint)
self.gScore[startPoint] = 0
self.fScore[startPoint] = startPoint.distance(endPoint)
while self.openList:
self.current = self.minKey(self.fScore, self.openList)
if self.current.__eq__(endPoint):
return self.reconstructPath()
self.openList.remove(self.current)
for point in self.getNeighbour(self.current):
tentativeGScore = self.gScore.get(self.current) + self.current.distance(point)
if tentativeGScore < self.gScore.get(point, 10000):
self.cameFrom[point] = self.current
self.gScore[point] = tentativeGScore
self.fScore[point] = point.distance(startPoint)
if(point not in self.openList):
self.openList.append(point)
return []
def reconstructPath(self):
totalPath = []
totalPath.append(self.current)
while self.current in self.cameFrom:
self.current = self.cameFrom[self.current]
totalPath.insert(0,self.current)
return totalPath
def getNeighbour(self, current):
neighbourlist = []
point1 = Point(current.getX() + 1, current.getY())
point2 = Point(current.getX(), current.getY() + 1)
point3 = Point(current.getX(), current.getY() - 1)
point4 = Point(current.getX() - 1, current.getY())
if self.checkField(current,current):
neighbourlist.append(point1)
if self.checkField(current, point2):
neighbourlist.append(point2)
if self.checkField(current,point3):
neighbourlist.append(point3)
if self.checkField(current,point4):
neighbourlist.append(point4)
return neighbourlist
def checkField(self,current, point):
if not (point.getX() < 0 or point.getX() > COLS - 1 or point.getY() < 0 or point.getY() > ROWS - 1 or point.__eq__(current)) and point not in self.board.stoneMap:
return True
return False
def minKey(self, fscore, openlist):
minkey = Point(0,0)
minValue = float('inf')
for point in openlist:
value = fscore.get(point, 10000)
if value < minValue:
minValue = value
minkey = point
return minkey