Esempio n. 1
0
        static void Main(string[] args)
        {
            int duration = 2200000;

            duration = 5000;
            string file    = @"Data\Tasks.xml";
            string config  = @"Data\Config.xml";
            string outFile = @"Data\Results";


            (Workload work, Configuration cfg)scheme = DataLoader.Load(file, config);
            Simulation s = HeuristicFactory.Load(scheme.work, scheme.cfg);

            Console.WriteLine(s);
            //Simulation s2 = RunSimulatedAnnealing(s, 1500000);
            List <Simulation> bestSolutions = RunSimulatedAnnealing(s, duration);

            DataLoader.Unload(outFile, bestSolutions);
            //Schedule schedule = s2.GetSchedule();
            //schedule.Run();
            //schedule.Build("schedule.txt", "test.svg");
            //Console.Write(schedule.Output);
            //Console.WriteLine(s2);
            //Console.WriteLine(s2.Fitness.Score);
            Console.WriteLine("Hit a key to Exit");
            Console.ReadKey();
        }
Esempio n. 2
0
        static List <Simulation> RunSimulatedAnnealing(Simulation s, int duration)
        {
            SimulatedAnnealing SA = HeuristicFactory.CreateSA(s, duration, SimulatedAnnealingBase.DebugLevel.All);

            SA.Run();
            return(SA.BestSolutions);
        }
Esempio n. 3
0
        private Dictionary <string, object> GetSetHeuristicsAndOptions(string gameName)
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            #region RecursionDepth
            Logger.LogInfo("Setting recursion depth.");
            uint recursionDepth = (uint)recursionDepthCounter.Value;
            parameters.Add("recursionDepth", recursionDepth);
            Logger.LogInfo("Recursion depth set to " + recursionDepth + ".");
            #endregion

            #region SetHeuristics
            Logger.LogInfo("Setting heuristics.");
            string[] names   = new string[0];
            double[] weights = new double[0];
            switch (gameName)
            {
            case "ConnectFour":
                names   = new string[] { "connectFourHeuristic" };
                weights = new double[] { 1 };
                break;

            case "TicTacToe":
                names   = new string[] { "ticTacToeHeuristic" };
                weights = new double[] { 1 };
                break;

            case "2048":
            {
                CheckBox[]    selectedHeuristics = GetSelectedCheckBoxesInGroup(setHeuristicsGroupBox);
                List <string> namesList          = selectedHeuristics.OrderBy(checkBox => checkBox.Name)
                                                   .Select(checkBox => checkBox.Name.Substring(0, checkBox.Name.IndexOf("CheckBox")))
                                                   .ToList();
                namesList.Add("2048Heuristic");
                names = namesList.ToArray();
                NumericUpDown[] selectedWeights = GetSelectedNumericUpDownsInGroup(setHeuristicsGroupBox);
                List <double>   weightsList     = selectedWeights.OrderBy(numericUpDown => numericUpDown.Name)
                                                  .Select(numericUpDown => (double)numericUpDown.Value)
                                                  .ToList();
                weightsList.Add(1);
                weights = weightsList.ToArray();
            }
            break;
            }


            Heuristic[] setHeuristics = HeuristicFactory.GetHeuristicsByNames(names, weights);
            for (int i = 0; i < names.Length; ++i)
            {
                Logger.LogInfo("Heuristic " + names[i] + " with weight " + weights[i]);
            }
            parameters.Add("setHeuristics", setHeuristics);
            #endregion

            return(parameters);
        }
Esempio n. 4
0
        public IMap DefineMap(DiagonalMovement diagonal, int width, int height, int seed, int minPathLength)
        {
            var  IsAGoodMap = false;
            IMap ret        = null;

            var        aStar = FinderFactory.GetAStarImplementation();
            IHeuristic heuristic;

            heuristic = diagonal == DiagonalMovement.Never ?
                        HeuristicFactory.GetManhattamImplementation() :
                        HeuristicFactory.GetOctileImplementation();


            while (!IsAGoodMap)
            {
                var nodes = new List <Node>();
                var _map  = new Map(diagonal, width, height);

                var size = Convert.ToInt32((width * height) * (seed / 100M));
                var rand = new Random();

                while (size > 0)
                {
                    var p = RandNode(rand, width, height, true);
                    GridMap.Add(p);
                    size--;
                }
                _map.DefineAllNodes(GridMap);
                _map.StartNode = RandNode(rand, width, height, false);
                _map.EndNode   = RandNode(rand, width, height, false);
                if (!_map.ValidMap())
                {
                    throw new Exception("Invalid map configuration");
                }
                if (aStar.Find(_map, heuristic)) // verifica se o mapa possui um caminho
                {
                    var path = _map.GetPath();
                    if (path.Max(e => e.G) >= minPathLength) // verifica se o caminho sastifaz o tamanho minimo
                    {
                        IsAGoodMap = true;
                        ret        = _map;
                    }
                }
                GridMap = new List <Node>();
            }
            ret.Clear();
            ret.MapType = MapGeneratorEnum.Random;
            return(ret);
        }
    public void StratPathFindinAlgorithm()
    {
        pathFind.interactable         = false;
        resetCurrentPath.interactable = true;
        clearAll.interactable         = true;
        gridController.PathGridState  = PathGridState.PathFind;
        gridController.InitGraf();
        Vector2Int goalPosition  = new Vector2Int(gridController.GoalPos.x, gridController.GoalPos.y);
        Vector2Int startPosition = new Vector2Int(gridController.StartPos.x, gridController.StartPos.y);

        IHeuristicEstimate heuristic = HeuristicFactory.СreateHeuristic(heuristicType, breakerType, startPosition, float.Parse(heuristicCoeffField.text));
        float          timeDelay     = float.Parse(delayBeforeSteps.text);
        AStarAlgorithm algorithm     = new AStarAlgorithm(gridMarkerController, heuristic, timeDelay);

        pathFindingAlgorithmCoroutine = StartCoroutine(algorithm.FindPath(gridController.GetStartVertex(), gridController.GetGoalVertex()));
    }
    public void StratPathFindinAlgorithm()
    {
        OnPathSearchState();
        gridController.InitGraf();
        Vector2Int goalPosition  = new Vector2Int(gridController.GoalPos.x, gridController.GoalPos.y);
        Vector2Int startPosition = new Vector2Int(gridController.StartPos.x, gridController.StartPos.y);

        IHeuristicEstimate heuristic = HeuristicFactory.СreateHeuristic(HeuristicType.Manhattan, TieBreakerType.None, startPosition, 1);
        float timeDelay     = float.Parse(delayBeforeSteps.text);
        float moveTimeDelay = float.Parse(delayBeforeMove.text);

        DStarLiteAlgorithm algorithm = new DStarLiteAlgorithm(gridMarkerController, gridController.Graph, heuristic, timeDelay);

        gridController.OnVerteciesUpdate = (vertecies) => { vertecies.ForEach(v => algorithm.UpdatePath(v)); };

        pathFindingAlgorithmCoroutine = StartCoroutine(algorithm.MoveByPath(gridController.GetStartVertex(), gridController.GetGoalVertex(), OnPathSearchState, OnStartMove));
    }
Esempio n. 7
0
        private Dictionary <string, object> GetDynamicHeuristicOptions(string dynamicHeuristicName)
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            Logger.LogInfo("Setting recursion depth.");
            uint recursionDepth = (uint)recursionDepthCounter.Value;

            parameters.Add("recursionDepth", recursionDepth);
            Logger.LogInfo("Recursion depth set to " + recursionDepth + ".");
            Logger.LogInfo("Setting dynamic heuristic.");
            string filename = dynamicHeuristicsFilePath + GetGameName() + "\\" + dynamicHeuristicName +
                              "\\" + recursionDepth;
            int       numberOfInputs = GetNumberOfInputs();
            Heuristic heuristic      = HeuristicFactory.GetHeuristicByName(dynamicHeuristicName, 1,
                                                                           new Dictionary <string, object>()
            {
                { "filename", filename },
                { "numberOfInputs", numberOfInputs },
                { "gameName", GetGameName() }
            });

            parameters.Add("dynamicHeuristic", heuristic);
            return(parameters);
        }
Esempio n. 8
0
        /// <summary>
        /// Returns an algorithm based on the given string and the given data
        /// fields. This will throw an AlgorithmNotFoundException if the given
        /// key is invalid based on the given implementation of this interface.
        /// </summary>
        /// <param name="Key">A string key of the algorithm which should be
        /// selected.</param>
        /// <param name="Params">object params of additional optional data
        /// to use when fetching the algorithm. What this data means depends
        /// on the implementation.</param>
        /// <returns></returns>
        public Algorithm <SS, DS> GetAlgorithm(string Key,
                                               HeuristicFactory <SS, DS> HeuristicFactory, int offset,
                                               params string[] Data)
        {
            if (RealTimeDataSet)
            {
                int i;
                if ((i = Key.IndexOf("-Weight=")) > 0)
                {
                    string AfterValue = Key.Substring(i + 8);
                    int    j          = AfterValue.IndexOf("-");
                    if (j > 0)
                    {
                        AfterValue = AfterValue.Substring(0, j);
                    }
                    Weight = new Metric(double.Parse(AfterValue));
                    if (j > 0)
                    {
                        AfterValue = Key.Substring(i + 8 + j);
                        Key        = Key.Substring(0, i) + AfterValue;
                    }
                    else
                    {
                        Key = Key.Substring(0, i);
                    }
                }
                else if ((i = Key.IndexOf("-Ratio=")) > 0)
                {
                    string AfterValue = Key.Substring(i + 7);
                    int    j          = AfterValue.IndexOf("-");
                    if (j > 0)
                    {
                        AfterValue = AfterValue.Substring(0, j);
                    }
                    Ratio = double.Parse(AfterValue);
                    if (j > 0)
                    {
                        AfterValue = Key.Substring(i + 7 + j);
                        Key        = Key.Substring(0, i) + AfterValue;
                    }
                    else
                    {
                        Key = Key.Substring(0, i);
                    }
                }
            }

            try {
                if (Key.Equals("Human"))
                {
                    return(new Human(vis as OpenGLStateVisualizer) as Algorithm <SS, DS>);
                }
                else if (Key.Equals("NoOp"))
                {
                    return(new NoOp <SS, DS>( ));
                    // Some Special Algs. for myself.
                }
                else if (Key.Equals("depth-first-closed-list"))
                {
                    return(new DepthFirstSearch <SS, DS>(Metric.Zero, true, vis));
                }
                else if (Key.Equals("depth-first-closed-list-bounded"))
                {
                    return(new DepthFirstSearch <SS, DS>(new Metric(double.Parse(Data[offset])),
                                                         true, vis));
                }
                else if (Key.Equals("depth-first-duplicate-detection"))
                {
                    return(new DepthFirstSearch <SS, DS>(Metric.Zero, false, vis));
                }
                else if (Key.Equals("depth-first-duplicate-detection-bounded"))
                {
                    return(new DepthFirstSearch <SS, DS>(new Metric(double.Parse(Data[offset])),
                                                         false, vis));

                    /*} else if ( Key.Equals( "depth-first-id-closed-list" ) ) {
                     * return new IterativeDeepingSearch<SS, DS>(
                     *       new DepthFirstSearch<SS, DS>( new Metric( 1.0d ), true, vis ) );
                     * } else if ( Key.Equals( "depth-first-id-duplicate-detection" ) ) {
                     * return new IterativeDeepingSearch<SS, DS>(
                     *       new DepthFirstSearch<SS, DS>( new Metric( 1.0d ), false, vis ) );
                     */
                }
                // Start A1 Algs.
                else if (Key.Equals("depth-first"))
                {
                    return(new DepthFirstSearch <SS, DS>(Metric.Zero, true, vis));
                } /*else if ( Key.Equals( "depth-first-id" ) ) {
                   * return new IterativeDeepingSearch<SS, DS>(
                   *     new DepthFirstSearch<SS, DS>( new Metric( 1.0d ), false, vis ) );
                   * } */
                else if (Key.Equals("uniform-cost"))
                {
                    return(new UniformedCostSearch <SS, DS>(true, vis));
                }
                else if (Key.Equals("greedy"))
                {
                    return(new Greedy <SS, DS>(h, true, vis));
                }
                else if (Key.Equals("A*"))
                {
                    return(new Net.Mokon.Edu.Unh.CS.AI.Search.Algorithms.AStar <SS, DS>(
                               h, true, vis));
                }
                else if (Key.Equals("weighted-a-star"))
                {
                    return(new WeightedAStar <SS, DS>(
                               HeuristicFactory.GetHeuristic(Data[offset + 1]), true,
                               new Metric(double.Parse(Data[offset])), vis));
                }
                else if (Key.Equals("weighted-a-star-duplicate-detection"))
                {
                    return(new WeightedAStar <SS, DS>(
                               HeuristicFactory.GetHeuristic(Data[offset + 1]), false,
                               new Metric(double.Parse(Data[offset])), vis));
                } /*else if ( Key.Equals( "ida-star" ) ) {
                   * return new IterativeDeepingSearch<SS, DS>(
                   *     new Net.Mokon.Edu.Unh.CS.AI.Search.Algorithms.AStar<SS, DS>(
                   *       new PathLengthGComputer<SS, DS>( ),
                   *     HeuristicFactory.GetHeuristic( Data[1] ), new Metric( 1.0d ), true, vis ) );
                   * // Real Time Algorithms
                   * } else if ( Key.Equals( "LRTA*" ) ) {
                   * return new LRTAStar<SS, DS>( h, true, vis, Weight, false );
                   * } else if ( Key.Equals( "LRTA*-dyn" ) ) {
                   * return new LRTAStar<SS, DS>( h, false, vis, Weight, false );
                   * } else if ( Key.Equals( "RTA*" ) ) {
                   * return new LRTAStar<SS, DS>( h, true, vis, Weight, true );
                   * } else if ( Key.Equals( "RTA*-dyn" ) ) {
                   * return new LRTAStar<SS, DS>( h, false, vis, Weight, true );
                   * } */
                else if (Key.Equals("D*Lite"))
                {
                    return(new DStarLite <SS, DS>(h, sut, vis));
                }
                else if (Key.Equals("Anytime-D*"))
                {
                    return(new AnytimeDStar <SS, DS>(h, sut, vis));
                }
                else if (Key.Equals("LSS-LRTA*"))
                {
                    return(new LSSLRTAStar <SS, DS>(h, vis, sut));
                }
                else if (Key.Equals("A*-RealTime"))
                {
                    return(new Net.Mokon.Edu.Unh.CS.AI.Search.Algorithms.RealTime.
                           AStar <SS, DS>(h));
                }
                else if (Key.StartsWith("RealTimeD*Lite"))
                {
                    ChooseMethodLandMarkGoal lmg  = ChooseMethodLandMarkGoal.Goal;
                    ChooseMethodFilterSucc   fs   = ChooseMethodFilterSucc.All;
                    ChooseMethodStep         step = ChooseMethodStep.MinHLandmarkGoal;
                    if (Key.Contains("LSS-LRTA*")) // must be b4 lrta*
                    {
                        step = ChooseMethodStep.LSSLRTAStar;
                    }
                    else if (Key.Contains("LRTA*"))
                    {
                        step = ChooseMethodStep.LRTAStar;
                    }
                    else if (Key.Contains("RTA*"))
                    {
                        step = ChooseMethodStep.RTAStar;
                    }
                    else if (Key.Contains("AStar"))
                    {
                        step = ChooseMethodStep.AStar;
                    }
                    else if (Key.Contains("NoOp"))
                    {
                        step = ChooseMethodStep.Null;
                    }
                    else if (Key.Contains("Adjusted"))
                    {
                        step = ChooseMethodStep.MinHAdustedLandmarkGoal;
                    }

                    if (Key.Contains("Goal"))
                    {
                        lmg = ChooseMethodLandMarkGoal.Goal;
                    }
                    else if (Key.Contains("USample"))
                    {
                        lmg = ChooseMethodLandMarkGoal.USample;
                    }
                    else if (Key.Contains("UTop"))
                    {
                        lmg = ChooseMethodLandMarkGoal.UTop;
                    }

                    if (Key.Contains("Lock"))
                    {
                        fs = ChooseMethodFilterSucc.Lock;
                    }

                    return(new RealTimeDStarLite <SS, DS>(h, sut, vis,
                                                          lmg, fs, step, Weight, Ratio));
                }
                else if (Key.StartsWith("RealTimeAnytimeD*"))
                {
                    ChooseMethodStep step = ChooseMethodStep.LSSLRTAStar;
                    if (Key.Contains("LSS-LRTA*")) // must be b4 lrta*
                    {
                        step = ChooseMethodStep.LSSLRTAStar;
                    }
                    else if (Key.Contains("LRTA*"))
                    {
                        step = ChooseMethodStep.LRTAStar;
                    }
                    else if (Key.Contains("RTA*"))
                    {
                        step = ChooseMethodStep.RTAStar;
                    }
                    else if (Key.Contains("NoOp"))
                    {
                        step = ChooseMethodStep.Null;
                    }
                    return(new RealTimeAnytimeDStar <SS, DS>(h, sut, vis, step, Ratio));
                }
                else if (Key.Equals("BRTA*"))
                {
                    return(new BRTSAStar <SS, DS>(h, sut));
                }
                else if (Key.Equals("BRTwA*"))
                {
                    return(new BRTSwAStar <SS, DS>(h, sut, Weight));

                    /*} else if ( Key.Equals( "TBA*-Old" ) ) {
                     * return new TBAStar<SS, DS>( ( SS, DS, G, Os ) => gc.G( SS, DS, G ) + h.H( SS, DS, G, Os ) );
                     * } else if ( Key.Equals( "TBA*" ) ) {
                     * return new TBAStar2<SS, DS>( ( SS, DS, G, Os ) => gc.G( SS, DS, G ) + h.H( SS, DS, G, Os ), 0.9f, 10 );
                     * } else if ( Key.Equals( "TBA*-LPA*" ) ) {
                     * return new TBAStar2<SS, DS>( h, sut, 0.9f, 10, vis );
                     * } else if ( Key.StartsWith( "RealTimeTBA*-LPA*" ) ) {
                     * ReconstructPathStartingPoint rpsp = ReconstructPathStartingPoint.UTop;
                     * ShortcutDetection sd = ShortcutDetection.None;
                     *
                     * if ( Key.Contains( "-UTop" ) ) {
                     *  rpsp = ReconstructPathStartingPoint.UTop;
                     * } else if ( Key.Contains( "-BestH" ) ) {
                     *  rpsp = ReconstructPathStartingPoint.BestH;
                     * } else if ( Key.Contains( "-Alternate" ) ) {
                     *  rpsp = ReconstructPathStartingPoint.Alternate;
                     * }
                     *
                     * if ( Key.Contains( "-ShortcutDetection" ) ) {
                     *  sd = ShortcutDetection.AStar;
                     * }
                     *
                     * return new RealTimeTBAStar<SS, DS>( h, sut, 0.9f, 10, vis, rpsp, sd );*/
                }
                else if (Key.Equals("BRTA*Sorting"))
                {
                    return(new BRTSAStarSorting <SS, DS>(h, sut));
                }
                else if (Key.Equals("LPA*"))
                {
                    return(new LPAStar <SS, DS>(h, sut, vis, ReconstructPathStartingPoint.UTop));
                }
                else if (Key.Equals(""))
                {
                    return(null);
                }
                else
                {
                    throw new AlgorithmNotFoundException(
                              "Algorithm [ " + Key + " ] Not Implemented");
                }
            } catch (FormatException) {
                throw new AlgorithmNotFoundException(
                          "Algorithm [ " + Key + " ] Problem Parsing Arguments");
            }
        }
        static void Process(BatchOption option)
        {
            var ft         = new FileTool();
            var now        = DateTime.Now;
            var folder     = option.Directory;
            var dataFile   = "_data.csv";
            var dataFileGA = "_dataGA.csv";

            var files      = Directory.GetFiles(folder, "*.txt");
            var fileCount  = files.Count();
            var finders    = option.Finder.ToArray();
            var heuristics = option.Heuristic.ToArray();
            var Mutation   = option.Mutate.ToArray();
            var Crossover  = option.Crossover.ToArray();
            var Fitness    = option.Fitness.ToArray();
            var Selection  = option.Selection.Cast <SelectionEnum>().ToArray();

            var newdatafile   = !File.Exists(dataFile);
            var newdatafileGA = !File.Exists(dataFileGA);

            StreamWriter csvFile;
            StreamWriter csvGAFile;

            if (newdatafile)
            {
                csvFile = File.CreateText(dataFile);
            }
            else
            {
                csvFile = File.AppendText(dataFile);
            }

            if (newdatafileGA)
            {
                csvGAFile = File.CreateText(dataFileGA);
            }
            else
            {
                csvGAFile = File.AppendText(dataFileGA);
            }

            //csvFile = new StreamWriter(File.Open(dataFile, FileMode.OpenOrCreate), Encoding.UTF8, 4096, false);
            //csvGAFile = new StreamWriter(File.Open(dataFileGA, FileMode.OpenOrCreate), Encoding.UTF8, 4096, false);

            if (newdatafile)
            {
                csvFile.Write(new TextWrapper().GetHeader());
            }
            if (newdatafileGA)
            {
                csvGAFile.Write(new TextGAWrapper().GetHeader());
            }

            for (int i = 0; i < fileCount; i++)
            {
                var map = FileTool.ReadMapFromFile(files[i]);
                foreach (var _finder in finders)
                {
                    foreach (var _h in heuristics)
                    {
                        var h      = new HeuristicFactory().GetImplementation(_h);
                        var finder = new FinderFactory().GetImplementation(_finder);

                        if (finder is IGeneticAlgorithm)
                        {
                            for (int cross = 0; cross < Crossover.Count(); cross++)
                            {
                                for (int mut = 0; mut < Mutation.Count(); mut++)
                                {
                                    for (int fit = 0; fit < Fitness.Count(); fit++)
                                    {
                                        for (int sel = 0; sel < Selection.Count(); sel++)
                                        {
                                            for (int j = 0; j < option.GaTimes; j++)
                                            {
                                                GC.Collect();
                                                GC.WaitForPendingFinalizers();

                                                var GAFinder = (IGeneticAlgorithm) new FinderFactory().GetImplementation(_finder);
                                                GAFinder.Crossover = new CrossoverFactory().GetImplementation(Crossover[cross]);
                                                GAFinder.Mutate    = new MutateFactory().GetImplementation(Mutation[mut]);
                                                GAFinder.Fitness   = new FitnessFactory().GetImplementation(Fitness[fit]);
                                                GAFinder.Selection = new SelectionFactory().GetImplementation(Selection[sel]);

                                                var helper = $"\n                n:{j},cx:{GAFinder.Crossover.GetType().Name},m:{GAFinder.Mutate.GetType().Name},f:{GAFinder.Fitness.GetType().Name},s:{GAFinder.Selection.GetType().Name}";
                                                var csv    = new TextWrapper();
                                                csv = RunStep(csv, i, fileCount, map, h, GAFinder, option.Directory, Path.GetFileName(files[i]), helper);
                                                csvFile.Write(csv.ToString());
                                                var csvGA = new TextGAWrapper
                                                {
                                                    Alg             = csv.Alg,
                                                    MapNumber       = csv.MapNumber,
                                                    Heuristic       = csv.Heuristic,
                                                    MapTypeGenerate = csv.MapTypeGenerate,
                                                    MapDiagonal     = csv.MapDiagonal,
                                                    MapSize         = csv.MapSize,
                                                    Solution        = csv.Solution,
                                                    Time            = csv.Time,
                                                    MaxNodes        = csv.MaxNodes,
                                                    PathLength      = csv.PathLength,
                                                    Crossover       = GAFinder.Crossover.GetType().Name,
                                                    Mutation        = GAFinder.Mutate.GetType().Name,
                                                    Fitness         = GAFinder.Fitness.GetType().Name,
                                                    Selection       = GAFinder.Selection.GetType().Name,
                                                    Generations     = GAFinder.Generations.ToString(),
                                                };
                                                csvGAFile.Write(csvGA.ToString());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            var csv = new TextWrapper();
                            csv = RunStep(csv, i, fileCount, map, h, finder, option.Directory, Path.GetFileName(files[i]));
                            csvFile.Write(csv.ToString());
                        }
                        csvFile.Flush();
                        csvGAFile.Flush();
                    }
                }
            }
            DrawTextProgressBar(fileCount, fileCount);

            csvFile.Dispose();
            csvGAFile.Dispose();
        }
        public IMap DefineMap(DiagonalMovement diagonal, int width, int height, int seed, int minPathLength)
        {
            int _GDC(int a, int b) => (b == 0 || a == 0) ? a | b : _GDC(Min(a, b), Max(a, b) % Min(a, b));

            var  blocksize  = Blocksize > 0 ? Blocksize : _GDC(width, height);
            var  IsAGoodMap = false;
            IMap ret        = null;

            // finder para valida se o mapa é passavel
            var        aStar = FinderFactory.GetAStarImplementation();
            IHeuristic heuristic;

            heuristic = diagonal == DiagonalMovement.Never ?
                        HeuristicFactory.GetManhattamImplementation() :
                        HeuristicFactory.GetOctileImplementation();

            var subgrid = new List <Node>();

            while (!IsAGoodMap)
            {
                var nodes = new List <Node>();
                var _map  = new Map(diagonal, width, height);

                var size = Convert.ToInt32(blocksize * blocksize * (seed / 100M));
                var rand = new Random();
                while (size > 0)
                {
                    var p = RandNode(rand, blocksize, blocksize, true);
                    subgrid.Add(p);
                    size--;
                }
                for (int i = 0; i < width; i += blocksize)
                {
                    for (int j = 0; j < height; j += blocksize)
                    {
                        foreach (var item in subgrid)
                        {
                            var x = item.X + i;
                            var y = item.Y + j;
                            if (x < width && y < height)
                            {
                                var node = new Node(x, y, false);
                                GridMap.Add(node);
                            }
                        }
                    }
                }
                _map.DefineAllNodes(GridMap);
                _map.StartNode = RandNode(rand, width, height, false);
                _map.EndNode   = RandNode(rand, width, height, false);
                if (!_map.ValidMap())
                {
                    throw new Exception("Invalid map configuration");
                }
                if (aStar.Find(_map, heuristic)) // verifica se o mapa possui um caminho
                {
                    var path = _map.GetPath();
                    if (path.Max(e => e.G) >= minPathLength) // verifica se o caminho sastifaz o tamanho minimo
                    {
                        IsAGoodMap = true;
                        _map.Clear();
                        ret = _map;
                    }
                }
                GridMap = new List <Node>();
                subgrid = new List <Node>();
            }

            ret.Clear();
            ret.MapType = MapGeneratorEnum.WithPattern;
            return(ret);
        }