Beispiel #1
0
 public PathFinder(MapContext context)
 {
     _context = context;
     _param   = new AStarParam(context.MovementGrid, DiagonalMovement.Never);
 }
        public static List <Point> FindPath(AStarParam iParam)
        {
            object lo = new object();
            //var openList = new IntervalHeap<Node>(new NodeComparer());
            var openList         = new IntervalHeap <Node>();
            var startNode        = iParam.StartNode;
            var endNode          = iParam.EndNode;
            var grid             = iParam.SearchGrid;
            var diagonalMovement = iParam.DiagonalMovement;
            var weight           = iParam.Weight;


            startNode.startToCurNodeLen      = 0;
            startNode.heuristicStartToEndLen = 0;

            openList.Add(startNode);
            startNode.isOpened = true;

            while (openList.Count != 0)
            {
                var node = openList.DeleteMin();
                node.isClosed = true;

                if (node == endNode)
                {
                    return(Node.Backtrace(endNode));
                }

                var neighbors = grid.GetNeighbors(node);

                foreach (var neighbor in neighbors)
                {
                    if (neighbor == endNode)
                    {
                        neighbor.parent = node;
                        return(Node.Backtrace(neighbor));
                    }
                    if (neighbor.isClosed || neighbor.value < 0)
                    {
                        continue;
                    }
                    var   X  = neighbor.x;
                    var   Y  = neighbor.y;
                    float ng = node.startToCurNodeLen + (float)((X - node.x == 0 || Y - node.y == 0) ? 1 : Math.Sqrt(2));

                    if (!neighbor.isOpened || ng < neighbor.startToCurNodeLen)
                    {
                        neighbor.startToCurNodeLen = ng;
                        if (neighbor.heuristicCurNodeToEndLen == null)
                        {
                            neighbor.heuristicCurNodeToEndLen = neighbor.value + Heuristic.Manhattan(Math.Abs(X - endNode.x), Math.Abs(Y - endNode.y));
                        }
                        neighbor.heuristicStartToEndLen = neighbor.startToCurNodeLen + neighbor.heuristicCurNodeToEndLen.Value;
                        neighbor.parent = node;
                        if (!neighbor.isOpened)
                        {
                            lock (lo)
                            {
                                openList.Add(neighbor);
                            }
                            neighbor.isOpened = true;
                        }
                        else
                        {
                        }
                    }
                }
            }
            return(new List <Point>());
        }