Esempio n. 1
0
        public void OnInit(InitContext context)
        {
            if (context == InitContext.Loaded)
            {
                _path = new Stack <Point2>();

                _playerMonsterTiles = GameObj.GetComponent <Tilemap>();

                //TODO: get player position from player controll component
                _playerController = GameObj.GetComponent <PlayerController>();

                _monsterPosition = new Point2(_playerMonsterTiles.Size.X - 1, _playerMonsterTiles.Size.Y - 1);
                Tile monsterInitTile = _playerMonsterTiles.Tiles[_monsterPosition.X, _monsterPosition.Y];
                monsterInitTile.Index = 1;
                _playerMonsterTiles.SetTile(_monsterPosition.X, _monsterPosition.Y, monsterInitTile);

                //Do pathfinding
                _mazeTiles = GameObj.Parent.ChildByName("BordersTilemap").GetComponent <Tilemap>();
                _path      = MazeSolver.SolveMaze(_mazeTiles, _playerController.PlayerPosition, _monsterPosition);
            }
        }
Esempio n. 2
0
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            bool             failed = false;

            MazeSolver solver = CreateSolver();

            solver.Stage += SolverOnStage;
            solver.SolveMaze(Maze.Value, SourceCell.Value, TargetCell.Value);
            solver.Stage -= SolverOnStage;

            if (!failed)
            {
                e.Result = solver;
            }

            void SolverOnStage(ProgressStage stage, Maze maze, float percentage)
            {
                if (worker.CancellationPending && (stage == ProgressStage.Started || stage == ProgressStage.Ongoing))
                {
                    e.Cancel = true;
                    solver.Cancel();
                }

                switch (stage)
                {
                case ProgressStage.Failed:
                    failed = true;
                    break;

                case ProgressStage.Ongoing:
                    worker.ReportProgress((int)percentage);
                    break;
                }
            }
        }
Esempio n. 3
0
        public string SolveMaze(string mazeAsString)
        {
            MazeSolver solver = new MazeSolver();

            // Set the symbols that may occur in the maze

            solver.GoalSymbol  = 'B';
            solver.OpenSymbol  = '.';
            solver.StartSymbol = 'A';
            solver.WallSymbol  = '#';

            // Set the additional symbol that may occur in a solution
            // to the maze

            solver.PathSymbol = '@';

            string errorMessage = "";

            try
            {
                // Information on the solution attempt may retrieved
                // from properties of the solver object after the
                // SolveMaze() call completes

                solver.SolveMaze(mazeAsString);

                errorMessage = solver.ErrorMessage;
            }
            catch (Exception exception)
            {
                errorMessage = String.Format("Exception: {0} {1}", exception.Message,
                                             exception.StackTrace);
            }

            // Construct the JSON string that is to be returned

            StringBuilder jsonBuilder = new StringBuilder();

            // Since the task specification didn't request any error
            // reporting, I extended the JSON response to include four
            // items related to error reporting.

            jsonBuilder.AppendLine("{");
            jsonBuilder.Append("   \"error message\": \"");
            jsonBuilder.Append(errorMessage);
            jsonBuilder.AppendLine("\"");
            jsonBuilder.Append("   \"symbols are valid\": ");
            jsonBuilder.AppendLine(solver.SymbolsAreValid.ToString());
            jsonBuilder.Append("   \"maze is valid\": ");
            jsonBuilder.AppendLine(solver.MazeIsValid.ToString());
            jsonBuilder.Append("   \"solution found\": ");
            jsonBuilder.AppendLine(solver.SolutionFound.ToString());
            jsonBuilder.Append("   \"steps\": ");
            jsonBuilder.AppendLine(solver.NumSolutionSteps.ToString());
            jsonBuilder.Append("   \"solution\": \"");
            jsonBuilder.Append(solver.Solution);
            jsonBuilder.AppendLine("\"");
            jsonBuilder.AppendLine("}");

            return(jsonBuilder.ToString());
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            // The command line must contain one argument, the full
            // path and name of a file. It is recommended to
            // wrap this argument in double-quotes to avoid misparsing.

            if (args.LongLength == 1)
            {
                try
                {
                    string filePathName = args[0];

                    if (File.Exists(filePathName))
                    {
                        string mazeAsString = File.ReadAllText(filePathName);

                        Console.WriteLine(mazeAsString);

                        MazeSolver solver = new MazeSolver();

                        // Set the symbols that may occur in the maze

                        solver.GoalSymbol  = 'B';
                        solver.OpenSymbol  = '.';
                        solver.StartSymbol = 'A';
                        solver.WallSymbol  = '#';

                        // Set the additional symbol that may occur in a solution
                        // to the maze

                        solver.PathSymbol = '@';

                        Stopwatch stopwatch = new Stopwatch();

                        stopwatch.Start();

                        solver.SolveMaze(mazeAsString);

                        stopwatch.Stop();

                        Console.WriteLine();
                        Console.WriteLine(solver.Solution);
                        Console.WriteLine();

                        if (solver.ErrorMessage.Length > 0)
                        {
                            Console.WriteLine("Error message: {0}", solver.ErrorMessage);
                        }

                        Console.WriteLine("Symbols are {0}", solver.SymbolsAreValid
                                                             ? "valid" : "not valid");

                        if (solver.SymbolsAreValid)
                        {
                            Console.WriteLine("Maze is {0}", solver.MazeIsValid
                                                             ? "valid" : "not valid");

                            if (solver.MazeIsValid)
                            {
                                Console.WriteLine("A solution was {0}", solver.SolutionFound
                                                                        ? "found" : "not found");
                                if (solver.SolutionFound)
                                {
                                    Console.WriteLine("Number of solution steps = {0}",
                                                      solver.NumSolutionSteps);
                                }
                            }
                        }

                        Console.WriteLine("Elapsed time: {0} milliseconds",
                                          stopwatch.ElapsedMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("File '{0}' does not exist", filePathName);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception: {0} {1}",
                                      exception.Message, exception.StackTrace);
                }

                Console.WriteLine();
                Console.Write("Press any key to exit the program... ");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Usage: mazeFilePathName");
            }
        }
    public void CreateBoard()
    {
        DeleteAllBoardNodesWithoutTowers();
        DeleteAllPathTiles();

        MazeArrayGenerator mag = GetComponent <MazeArrayGenerator>();
        List <Position>    currentBlockedPositions = new List <Position>();

        // foreach tower, add it to the blocked list

        foreach (Thing t in towers.Items)
        {
            Position p = new Position(Mathf.RoundToInt(t.gameObject.transform.position.x / NodeScale), Mathf.RoundToInt(t.gameObject.transform.position.z / NodeScale));
            currentBlockedPositions.Add(p);
        }
        // foreach otherblocked position, block that position
        // in the future if we have other blocked sets we can eval them here before
        // generating the maze on the board.

        MazeNode[,] mazeData = mag.GetMaze(currentBlockedPositions);

        // Solve Maze
        MazeSolver       myMazeSolver = GetComponent <MazeSolver>();
        Stack <Position> path         = myMazeSolver.SolveMaze(mazeData);

        // Build Maze
        foreach (MazeNode mn in mazeData)
        {
            if (mn != null)
            {
                GameObject go = Instantiate(BoardNodePrefab, transform);
                go.transform.position = new Vector3(mn.myPos.X * NodeScale.Value, nodeHeight, mn.myPos.Z * NodeScale.Value);
                BoardNode bn = go.GetComponent <BoardNode>();

                bool isOnPath = false;
                foreach (Position p in path)
                {
                    if (mn.myPos.X == p.X && mn.myPos.Z == p.Z)
                    {
                        isOnPath = true;
                    }
                    if (isOnPath)
                    {
                        break;
                    }
                }
                if (isOnPath)
                {
                    if (mn.walls[0] == false)
                    {
                        Destroy(bn.NorthWall);
                    }
                    if (mn.walls[1] == false)
                    {
                        Destroy(bn.EastWall);
                    }
                    if (mn.walls[2] == false)
                    {
                        Destroy(bn.SouthWall);
                    }
                    if (mn.walls[3] == false)
                    {
                        Destroy(bn.WestWall);
                    }
                }
                else
                {
                    Destroy(bn.NorthWall);
                    Destroy(bn.EastWall);
                    Destroy(bn.SouthWall);
                    Destroy(bn.WestWall);
                }
            }
        }

        // lay solved path
        while (path.Count > 0)
        {
            GameObject go = Instantiate(PathTilePrefab, transform);
            Position   p  = path.Pop();
            go.transform.position = new Vector3(p.X * NodeScale, pathHeight, p.Z * NodeScale);
        }

        BoardCreated.Raise();
    }
Esempio n. 6
0
 public void Pathfind()
 {
     //Do pathfinding
     _path = MazeSolver.SolveMaze(_mazeTiles, _playerController.PlayerPosition, _monsterPosition);
 }