Example #1
0
    public List <GridSection> FindPath(int startX, int startY, int endX, int endY)
    {
        GridSection startGridSection = grid[startX, startY];
        GridSection endGridSection   = grid[endX, endY];

        openList = new List <GridSection> {
            startGridSection
        };
        closedList = new List <GridSection>();

        for (int x = 0; x < grid.GetLength(0); x++)
        {
            for (int y = 0; y < grid.GetLength(1); y++)
            {
                GridSection GridSection = grid[x, y];
                GridSection.gCost = int.MaxValue;
                GridSection.CalculateFCost();
                GridSection.lastSection = null;
            }
        }

        startGridSection.gCost = 0;
        startGridSection.hCost = CalculateDistance(startGridSection, endGridSection);
        startGridSection.CalculateFCost();

        //-------------------------------------------------------------------//

        while (openList.Count > 0)
        {
            GridSection currentGridSection = GetLowestFCostGridSection(openList);

            if (currentGridSection == endGridSection)  //
            {
                return(CalculatePath(endGridSection)); //
            }

            openList.Remove(currentGridSection);
            closedList.Add(currentGridSection);

            foreach (GridSection neighbourGridSection in GetNeighbourGridSections(currentGridSection)) //
            {
                if (closedList.Contains(neighbourGridSection))
                {
                    continue;
                }

                if (neighbourGridSection.wall)
                {
                    closedList.Add(neighbourGridSection);
                    continue;
                }

                int tempGCost = currentGridSection.gCost + CalculateDistance(currentGridSection, neighbourGridSection); //

                if (tempGCost < neighbourGridSection.gCost)                                                             //
                {
                    neighbourGridSection.lastSection = currentGridSection;                                              //
                    neighbourGridSection.gCost       = tempGCost;                                                       //
                    neighbourGridSection.hCost       = CalculateDistance(neighbourGridSection, endGridSection);         //
                    neighbourGridSection.CalculateFCost();                                                              //

                    if (!openList.Contains(neighbourGridSection))                                                       //
                    {
                        openList.Add(neighbourGridSection);
                    }
                }
            }
        }
        //
        return(null);
    }