Esempio n. 1
0
        private void ViewPort_Loaded(object sender, RoutedEventArgs e)
        {
            width           = (int)this.ViewPortContainer.ActualWidth;
            height          = (int)this.ViewPortContainer.ActualHeight;
            writeableBitmap = BitmapFactory.New(width, height);
            ViewPort.Source = writeableBitmap;
            PrintTheMap();



            CompositionTarget.Rendering += CompositionTarget_Rendering;
            MazeState state = new MazeState();

            if (ALGORITHM_CHOOSER == 0)
            {
                var dfs = new DeepFirstSearcher(state);
                new Thread(() => dfs.Search()).Start();
            }
            if (ALGORITHM_CHOOSER == 1)
            {
                var bfs = new BreadthFirstSearcher(state);
                new Thread(() => bfs.Search()).Start();
            }
            if (ALGORITHM_CHOOSER == 2)
            {
                var ast = new AStarSearcher(state);
                new Thread(() => ast.Search()).Start();
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public WallMaze()
        {
            pen = new Pen(Brushes.Black);
            pen.Width = 3.0f;

            font = new Font("Arial", 8);
            brush = new SolidBrush(Color.Red);

            Width = 800;
            Height = 800;
            random = new Random();

            startNode = -1;
            endNode = -1;
            currentNode = -1;

            mazeState = MazeState.NOT_START;

            addingSquareFlag = true;

            directions = new List<Square.Direction>();
            sizeDialog = new MazeInfoDialog();

            DoubleBuffered = true;

            SetupPopupMenu();
            SetupMenu();
        }
Esempio n. 3
0
 public MazeState(int x, int y, MazeState previous)
 {
     X            = x;
     Y            = y;
     Depth        = previous?.Depth + 1 ?? 0;
     PreviousStep = previous;
 }
        public void InitializeMazeSolverTests()
        {
            var width    = 5;
            var heigth   = 5;
            var mazeData = new string[][]
            {
                new[] { "north", "west" }, new[] { "north", "west" }, new[] { "north" }, new[] { "north" }, new[] { "north" },
                new[] { "west" }, new[] { "north" }, new[] { "north", "west" }, new string[0], new[] { "west" },
                new[] { "north", "west" }, new string[0], new[] { "west" }, new[] { "north" }, new[] { "west" },
                new[] { "west" }, new[] { "north", "west" }, new[] { "north" }, new[] { "west" }, new[] { "west" },
                new[] { "west" }, new string[0], new[] { "west" }, new string[0], new[] { "west" }
            };

            var mazeState = new MazeState()
            {
                Id              = "TestMaze1234",
                Difficulty      = 1,
                PlayerName      = "moi",
                Dimensions      = new[] { width, heigth },
                Data            = mazeData,
                PonyPosition    = new[] { ponyPosition },
                DomokunPosition = new[] { domokunPosition },
                ExitPosition    = new[] { exitPosition },
                GameState       = new GameState()
                {
                    MazeState = "Active", MoveStatus = "Successfully created"
                }
            };

            mazeSolver = new MazeSolver(mazeState);
        }
Esempio n. 5
0
        /// <summary>
        /// 根据初始参数提供ICellObj
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public GameObject GetCellObj(Vector2Int pos, MazeState state)
        {
            GameObject temp = null;

            switch (state)
            {
            case MazeState.Wall:
                temp = GetWallObj(pos);
                break;

            case MazeState.Route:
                temp = GetRouteObj(pos);
                break;
                ;

            case MazeState.Entry:
                temp = EntryMarker;
                break;

            case MazeState.Exit:
                temp = ExitMarker;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(state), state, null);
            }

            temp.GetComponent <ICell>().CellPosition = pos;
            return(temp);
        }
Esempio n. 6
0
        public int MinimumDistanceBetween(int startX, int startY, int destX, int destY)
        {
            if (startX == destX && startY == destY)
            {
                return(0);
            }
            var start = new MazeState(startX, startY, null);

            var toExplore = new HashSet <MazeState> {
                start
            };

            while (!toExplore.Any(square => square.X == destX && square.Y == destY))
            {
                toExplore = new HashSet <MazeState>(toExplore.SelectMany(GetNextStates));
                if (toExplore.Any(square => square.X == destX && square.Y == destY))
                {
                    var finalState = toExplore.Where(square => square.X == destX && square.Y == destY)
                                     .OrderBy(x => x.Depth)
                                     .First();

                    MazeState startState = finalState;
                    while (startState != null)
                    {
                        _maze[startState.X, startState.Y] = 'B';
                        startState = startState.PreviousStep;
                    }
                    return(finalState.Depth);
                }
            }
            return(1);
        }
Esempio n. 7
0
        public override void Execute()
        {
            // assumes x,y and x2,y2 have been normalized so that x,y is top-left
            Tools.PrepareUndo(x, y, x2, y2, plr);

            switch (algorithm)
            {
            case 0:
                TShock.Players[plr].SendMessage(String.Format("0: Recursive Backtracker maze creation initiated!"), Color.Green);
                this.maze = new Mazes.Maze(new Mazes.Point(x, y), new Mazes.Point(x2 - x, y2 - y), new Mazes.Point(TShock.Players[plr].TileX, TShock.Players[plr].TileY),
                                           tunnelWidth, wallWidth, algorithm, 0, this.PeekBlock, this.NukeTiles);
                //RecursiveBacktracker();
                break;

            case 1:
                // TShock.Players[plr].SendMessage(String.Format("1: Growing Tree maze creation initiated!"), Color.Green);
                //  GrowingTree();
                break;

            default:
                TShock.Players[plr].SendMessage(String.Format("Invalid algorithm specified."), Color.Red);
                break;
            }
            MazeState ms = new MazeState();

            while (ms.status < 8)
            {
                ms = maze.Step();
            }



            TShock.Players[plr].SendMessage(String.Format("Maze creation complete."), Color.LimeGreen);
            ResetSection();
        } //Execute()
Esempio n. 8
0
        private async Task <bool> UpdateMazeState(MazeState state = null)
        {
            var waitBmp = MazePainter.MazePainter.GetWaitBmp();

            pictureBox1.Image = waitBmp;

            if (state == null)
            {
                try
                {
                    state = await _client.GetMazeCurrentState(_mazeId);
                }
                catch (PonyClientException ex)
                {
                    DoLog(ex.Message);
                    return(false);
                }
                catch (Exception ex)
                {
                    DoLog("CRITICAL: " + ex.Message);
                    return(false);
                }
            }

            if (!string.IsNullOrEmpty(state.HiddenImageUrl))
            {
                try
                {
                    var imgData = await _client.LoadImage(state.HiddenImageUrl);

                    var ms = new MemoryStream(imgData);
                    pictureBox1.Image = Image.FromStream(ms);
                }
                catch (Exception ex)
                {
                    DoLog(ex.Message);
                }
            }
            else
            {
                _solver = MazeSolver.Load(state);
                // paint a maze
                var bmp = MazePainter.MazePainter.RepresentMaze(_solver.Field,
                                                                state.MazeWidth, state.MazeHeight,
                                                                _solver.PonyLocation.x, _solver.PonyLocation.y,
                                                                _solver.ExitLocation.x, _solver.ExitLocation.y,
                                                                _solver.DomokunLocation.x, _solver.DomokunLocation.y);
                pictureBox1.Image = bmp;
            }

            if (state.State == "over" || state.State == "won")
            {
                return(false);
            }
            return(true);
        }
Esempio n. 9
0
    void ResetLevel()
    {
        ClearLevel();
        // When resetting the level, levelIndex will be set to the next level.
        int       currentLevel = levelIndex == 0 ? LevelCollection.levels.Count - 1 : levelIndex - 1;
        MazeLevel level        = LevelCollection.levels[currentLevel];

        visibilityController.SetupLevel(level);
        mazeState = MazeState.Starting;
    }
Esempio n. 10
0
        /// <summary>
        /// display the solution to the screen
        /// </summary>
        /// <param name="solution">position of the solution</param>
        public void DisplaySolution(Solution solution)
        {
            string final_solution = "";

            foreach (AState state in solution.GetSolutionPath())
            {
                MazeState m_state = state as MazeState;
                final_solution += m_state.Position.ToString() + "\n"; // add the position to the list
            }
            Output(final_solution);
        }
Esempio n. 11
0
 public static void RegisterMazeStateWorker(MazeState state, Component component)
 {
     if (Instance == null)
     {
         return;
     }
     if (!Instance.workerFlags[(int)state].ContainsKey(component))
     {
         Instance.workerFlags[(int)state][component] = false;
     }
 }
Esempio n. 12
0
 bool AreAllWorkersComplete(MazeState state)
 {
     foreach (var pair in Instance.workerFlags[(int)state])
     {
         if (!pair.Value)
         {
             return(false);
         }
     }
     return(true);
 }
Esempio n. 13
0
        /// <summary>
        /// change solution to string
        /// </summary>
        /// <param name="solution">solution s</param>
        /// <returns>string of solution</returns>
        private string solutionTostring(Solution solution)
        {
            string s = "";

            foreach (AState state in solution.GetSolutionPath())
            {
                MazeState Ms = state as MazeState;

                s = s + (Ms.State);
            }
            return(s);
        }
        public MazeHandler(Maze aMaze)
        {
            _maze       = aMaze;
            _curState   = aMaze.StartState;
            _traversing = false;
            index       = 0;

            VariableMoveCost = false;
            IterationMode    = false;
            PlaySound        = true;
            ShowCoords       = false;
        }
Esempio n. 15
0
        /// <summary>
        /// get the solution
        /// </summary>
        /// <param name="maze">maze m</param>
        /// <param name="s">solution s</param>
        /// <returns></returns>
        private ArrayList getSolution(Maze maze, Solution s)
        {
            ArrayList positions_sol = new ArrayList();
            ArrayList states        = s.GetSolutionPath();

            foreach (AState state in states)
            {
                MazeState ms = state as MazeState;
                Position  p  = ms.Position;
                positions_sol.Add(p);
            }
            return(positions_sol);
        }
Esempio n. 16
0
        /// <summary>
        ///  gets a state and looks for possible moves
        /// </summary>
        /// <param name="state"> current state</param>
        /// <returns> list of all the possible moves from this state</returns>
        public IEnumerable <AState> GetAllSuccessors(AState state)
        {
            List <AState> successors = new List <AState>();
            MazeState     mazeState  = (MazeState)state;

            if (maze.isAvailable(mazeState.GetPosition().X + 1, mazeState.GetPosition().Y, mazeState.GetPosition().Z))
            {
                maze.changeToVisited(mazeState.GetPosition());
                Position newPos = new Position(mazeState.GetPosition().X + 1, mazeState.GetPosition().Y, mazeState.GetPosition().Z);
                successors.Add(new MazeState(newPos, mazeState));
            }

            if (maze.isAvailable(mazeState.GetPosition().X - 1, mazeState.GetPosition().Y, mazeState.GetPosition().Z))
            {
                maze.changeToVisited(mazeState.GetPosition());
                Position newPos = new Position(mazeState.GetPosition().X - 1, mazeState.GetPosition().Y, mazeState.GetPosition().Z);
                successors.Add(new MazeState(newPos, mazeState));
            }

            if (maze.isAvailable(mazeState.GetPosition().X, mazeState.GetPosition().Y + 1, mazeState.GetPosition().Z))
            {
                maze.changeToVisited(mazeState.GetPosition());
                Position newPos = new Position(mazeState.GetPosition().X, mazeState.GetPosition().Y + 1, mazeState.GetPosition().Z);
                successors.Add(new MazeState(newPos, mazeState));
            }

            if (maze.isAvailable(mazeState.GetPosition().X, mazeState.GetPosition().Y - 1, mazeState.GetPosition().Z))
            {
                maze.changeToVisited(mazeState.GetPosition());
                Position newPos = new Position(mazeState.GetPosition().X, mazeState.GetPosition().Y - 1, mazeState.GetPosition().Z);
                successors.Add(new MazeState(newPos, mazeState));
            }

            if (maze.isAvailable(mazeState.GetPosition().X, mazeState.GetPosition().Y, mazeState.GetPosition().Z + 1))
            {
                maze.changeToVisited(mazeState.GetPosition());
                Position newPos = new Position(mazeState.GetPosition().X, mazeState.GetPosition().Y, mazeState.GetPosition().Z + 1);
                successors.Add(new MazeState(newPos, mazeState));
            }

            if (maze.isAvailable(mazeState.GetPosition().X, mazeState.GetPosition().Y, mazeState.GetPosition().Z - 1))
            {
                maze.changeToVisited(mazeState.GetPosition());
                Position newPos = new Position(mazeState.GetPosition().X, mazeState.GetPosition().Y, mazeState.GetPosition().Z - 1);
                successors.Add(new MazeState(newPos, mazeState));
            }

            return(successors);
        }
Esempio n. 17
0
        public static void RenderDay18(int part)
        {
            Console.WriteLine($"Processing day 18 - part {part}...");
            PathResult <MazeState> mazeStatePathResult;

            if (part == 1)
            {
                mazeStatePathResult = Day18.GetDay18Part1AnswerPath();
            }
            else
            {
                mazeStatePathResult = Day18.GetDay18Part2AnswerPath();
            }
            int imageNumber = 0;

            for (int i = 0; i < mazeStatePathResult.Path.Count - 1; i++)
            {
                var startState = mazeStatePathResult.Path[i];
                var endState   = mazeStatePathResult.Path[i + 1];

                // Get intermediate maze states going from the initial to final state
                int positionIndex          = MazeState.GetPositionThatChangedIndex(startState, endState);
                var robotPathBetweenStates = MazeState.GetRobotPathBetweenMazeStates(startState, endState);
                for (int robotMovementIndex = 0; robotMovementIndex < robotPathBetweenStates.Count; robotMovementIndex++)
                {
                    if (i > 0 && robotMovementIndex == 0)
                    {
                        continue;
                    }
                    var currentPositions = startState.CurrentPositions.ToList();
                    currentPositions[positionIndex] = robotPathBetweenStates[robotMovementIndex];
                    var intermediateState = new MazeState(
                        maze: startState.Maze,
                        currentPositions: currentPositions,
                        keysCollected: startState.KeysCollected);
                    var stateFrame = new Frame(intermediateState.GetMazeStateRenderingData());
                    var renderer   = new ConsoleStreamRenderer();
                    renderer.Render(stateFrame);
                    imageNumber++;
                    IntPtr consoleWindowHandle = GetConsoleWindow();
                    var    consoleWindowBitmap = ScreenCapture.CaptureWindow(consoleWindowHandle);
                    var    imageFilePath       = Path.Combine(Directory.GetCurrentDirectory(), "Images", $"Part1_{imageNumber.ToString("0000")}.png");
                    consoleWindowBitmap.Save(imageFilePath, ImageFormat.Png);
                }
            }
        }
Esempio n. 18
0
    void LoadNextLevel()
    {
        ClearLevel();
        if (UDLRCameraController.Instance != null)
        {
            UDLRCameraController.Instance.ResetCameraPositions();
        }
        if (levelIndex < LevelCollection.levels.Count)
        {
            MazeLevel level = LevelCollection.levels[levelIndex];
            visibilityController.SetupLevel(level);
            levelIndex = (levelIndex + 1) % LevelCollection.levels.Count;

            // This happens before Start() is called on some components, so we have to force their
            // MazeStateChanged callback whenever they register themselves. Which isn't ideal.
            mazeState = MazeState.Starting;
        }
    }
Esempio n. 19
0
    public static void MazeStateWorkerComplete(MazeState state, Component component)
    {
        if (Instance == null)
        {
            return;
        }
        Assert.IsTrue(state == Instance.mazeState);
        Instance.workerFlags[(int)state][component] = true;

        if (state == MazeState.Revealing && Instance.visibilityController.AreObjectsRevealed())
        {
            return;
        }

        if (Instance.AreAllWorkersComplete(state))
        {
            Instance.IncrementMazeState();
        }
    }
Esempio n. 20
0
        public int ExploreAllPaths()
        {
            var start     = new MazeState(1, 1, null);
            var toExplore = new HashSet <MazeState> {
                start
            };

            for (int i = 0; i < 51; i++) //51
            {
                toExplore = new HashSet <MazeState>(toExplore.SelectMany(GetNextStates));
            }

            foreach (var location in _visited)
            {
                Maze[location.X, location.Y] = MazeSquare.Visited;
            }
            Print();
            return(_visited.Count);
        }
Esempio n. 21
0
        public static MazeSolver Load(MazeState state)
        {
            var instance = new MazeSolver();
            var newField = new MazeCell[state.MazeWidth, state.MazeHeight];

            instance._solverField = new SolverMazeCell[state.MazeWidth, state.MazeHeight];

            for (var i = 0; i < state.Cells.Count; i++)
            {
                var x = i % state.MazeWidth;
                var y = i / state.MazeWidth;
                newField[x, y] = state.Cells[i];
                instance._solverField[x, y] = new SolverMazeCell {
                    Walls = newField[x, y]
                };

                if (x == state.MazeWidth - 1 || state.Cells[i + 1].HasFlag(MazeCell.West))
                {
                    instance._solverField[x, y].Walls |= MazeCell.East;
                }

                if (y == state.MazeHeight - 1 || state.Cells[i + state.MazeWidth].HasFlag(MazeCell.North))
                {
                    instance._solverField[x, y].Walls |= MazeCell.South;
                }

                if (i == state.Domokun)
                {
                    instance.DomokunLocation = new Point(x, y);
                }
                if (i == state.Exit)
                {
                    instance.ExitLocation = new Point(x, y);
                }
                if (i == state.Pony)
                {
                    instance.PonyLocation = new Point(x, y);
                }
            }

            instance.Field = newField;
            return(instance);
        }
Esempio n. 22
0
        public List <MazeState> GetNextStates(MazeState currentSquare)
        {
            _visited.Add(currentSquare);

            var states = new List <MazeState>();

            if (currentSquare.Y > 0 && _maze[currentSquare.X, currentSquare.Y - 1] != '#')
            {
                states.Add(new MazeState(currentSquare.X, currentSquare.Y - 1, currentSquare));
            }
            if (currentSquare.X < _maxX && _maze[currentSquare.X + 1, currentSquare.Y] != '#')
            {
                states.Add(new MazeState(currentSquare.X + 1, currentSquare.Y, currentSquare));
            }
            if (currentSquare.Y < _maxY && _maze[currentSquare.X, currentSquare.Y + 1] != '#')
            {
                states.Add(new MazeState(currentSquare.X, currentSquare.Y + 1, currentSquare));
            }
            if (currentSquare.X > 0 && _maze[currentSquare.X - 1, currentSquare.Y] != '#')
            {
                states.Add(new MazeState(currentSquare.X - 1, currentSquare.Y, currentSquare));
            }
            return(states);
        }
Esempio n. 23
0
        public List <MazeState> GetNextStates(MazeState currentSquare)
        {
            _visited.Add(currentSquare);
            var results = new []
            {
                new { X = 0, Y = -1 },
                new { X = 1, Y = 0 },
                new { X = 0, Y = 1 },
                new { X = -1, Y = 0 }
            };

            //0,1 & 1,2 should be open
            var states = new List <MazeState>();

            //North - if I'm greater than y - x is irrelevant
            if (currentSquare.Y > 0 && Maze[currentSquare.X, currentSquare.Y - 1] != MazeSquare.Wall)
            {
                states.Add(new MazeState(currentSquare.X, currentSquare.Y - 1, currentSquare));
            }
            if (currentSquare.X < MaxSize && Maze[currentSquare.X + 1, currentSquare.Y] != MazeSquare.Wall)
            {
                //east
                states.Add(new MazeState(currentSquare.X + 1, currentSquare.Y, currentSquare));
            }
            if (currentSquare.Y < MaxSize && Maze[currentSquare.X, currentSquare.Y + 1] != MazeSquare.Wall)
            {
                //south
                states.Add(new MazeState(currentSquare.X, currentSquare.Y + 1, currentSquare));
            }
            if (currentSquare.X > 0 && Maze[currentSquare.X - 1, currentSquare.Y] != MazeSquare.Wall)
            {
                //west
                states.Add(new MazeState(currentSquare.X - 1, currentSquare.Y, currentSquare));
            }
            return(states);
        }
        private void SetupMenu()
        {
            MainMenu menu = new MainMenu();
            this.Menu = menu;

            MenuItem buildMenu = new MenuItem();
            menu.MenuItems.Add(buildMenu);
            buildMenu.Text = "Build";

            runItem = new MenuItem();
            runItem.Enabled = false;
            buildMenu.MenuItems.Add(runItem);
            runItem.Text = "Run";
            runItem.Click += delegate(object sender, EventArgs args) {
                Thread thread = new Thread(new ThreadStart(BuildMaze));
                mazeState = MazeState.BUILDING;
                thread.Start();
            };

            solveItem = new MenuItem();
            solveItem.Enabled = false;
            buildMenu.MenuItems.Add(solveItem);
            solveItem.Text = "Solve";
            solveItem.Click += delegate(object sender, EventArgs args) {
                Thread thread = new Thread(new ThreadStart(SolveMaze));
                mazeState = MazeState.SOLVING;
                thread.Start();
            };

            resetItem = new MenuItem();
            resetItem.Enabled = false;
            buildMenu.MenuItems.Add(resetItem);
            resetItem.Text = "Reset";
            resetItem.Click += delegate(object sender, EventArgs args) {
                mazeState = MazeState.NOT_START;
                runItem.Enabled = false;
                solveItem.Enabled = false;
                /*
                 * Reset data
                 */
                currentNode = -1;
                startNode = -1;
                endNode = -1;

                Invalidate();
            };

            setSizeItem = new MenuItem();
            buildMenu.MenuItems.Add(setSizeItem);
            setSizeItem.Text = "Set Size";
            setSizeItem.Click += delegate(object sender, EventArgs args) {
                sizeDialog.ShowDialog();
                if (sizeDialog.DialogResult == DialogResult.OK) {
                    maze = new Maze(sizeDialog.Width, sizeDialog.Height, sizeDialog.Spacing);
                    runItem.Enabled = true;
                    resetItem.Enabled = true;

                    mazeState = MazeState.BUILT;

                    InitializeGraph();

                    Invalidate();
                }
            };
        }
Esempio n. 25
0
/////
//////////////////////////////////////////////////
/////

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (createInProgress)
            {
                // update maze here
                MazeState ms = this.maze.Step();
                //toolbarLabel1.Text = ms.status.ToString() + "     " + ms.message;

                if (ms.status == 1)
                {
                    this.firstCell = maze.mazeData.tunnelling.First();
                    SetRect(new Rect(this.firstCell, maze.mazeData.tunnelWidthP()), Color.Orange);
                }

                if (ms.status >= 2 && ms.status <= 4)
                {
                    int c = maze.mazeData.tunnelling.Count();
                    if (c > 0)
                    {
                        SetRect(new Rect(maze.mazeData.lastCell, maze.mazeData.tunnelWidthP()), Color.Red);
                    }
                    if (c > 1)
                    {
                        SetRect(new Rect(this.prevCell, maze.mazeData.tunnelWidthP()), pathColor);
                        toolbarLabel1.Text = maze.mazeData.lastCell.ToString() + " / " + this.prevCell.ToString();
                    }
                    this.prevCell = maze.mazeData.lastCell;
                    mazePanel.Invalidate();
                }
                if (ms.status == 8)
                {
                    createInProgress = false;
                    timer1.Stop();
                }

                this.lastMazeState = ms;
            }


            if (solveInProgress)
            {
                int prevExp = solver.exploredPoints.Count;

                //  Stopwatch stopwatch = Stopwatch.StartNew();
                this.solver.SolveStep();
                //   stopwatch.Stop();
                //   Debug.WriteLine(stopwatch.ElapsedMilliseconds);

                // for (int i = prevExp;  i < solver.exploredPoints.Count; i++)
                foreach (ExploredPoint ep in solver.exploredPoints)
                {
                    //mazeBmp.SetPixel(solver.exploredPoints[i].p.X, solver.exploredPoints[i].p.Y, solvePathColor);
                    // bug here - exception if edge of map is reached.
                    mazeBmp.SetPixel(ep.p.X, ep.p.Y, solvePathColor);
                }

                if (solver.state == 4)
                {
                    //solver.
                }
                else if (solver.state >= 8)
                {
                    solveInProgress = false;
                    timer1.Stop();
                }
                if (solver.state >= 12)
                {
                    foreach (Mazes.Point s in solver.solution)
                    {
                        SetPixel(s, solutionColor);
                    }
                }
                this.toolbarLabel1.Text = "alivePoints.Count: " + solver.alivePoints.Count();
                mazePanel.Invalidate();
            }
        }
Esempio n. 26
0
 protected bool Equals(MazeState other)
 {
     return(X == other.X && Y == other.Y);
 }
 public void mazeInstantiatedServer()
 {
     estadoConstruccion = MazeState.FIN;
 }
    private void generateMazePrimThread()
    {
        estadoConstruccion = MazeState.THREAD;
        tablero = new Casilla[height, width];

        //inizialization to all walls and no visited
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                tablero[i, j].wallDown = true;
                tablero[i, j].wallUp = true;
                tablero[i, j].wallLeft= true;
                tablero[i, j].wallRight = true;
                tablero[i, j].visited = false;
                tablero[i, j].trampas = false;
            }
        }

        pendientesDeAnalizar = new List<Vector4>();

        pendientesDeAnalizar.Add(new Vector4(casillaComienzo.x-1,casillaComienzo.y,casillaComienzo.x,casillaComienzo.y));

        GestorRandom gr = GestorRandom.getInstance();

        while (pendientesDeAnalizar.Count != 0)
        {
            //we take one randomally
            int index = gr.getNumeroAleatorio(0, pendientesDeAnalizar.Count);
            Vector4 elemSelected = pendientesDeAnalizar[index];
            pendientesDeAnalizar.RemoveAt(index);

            Vector2 origin= new Vector2(elemSelected.x,elemSelected.y);
            Vector2 destiny= new Vector2(elemSelected.z,elemSelected.w);

            if(!tablero[(int)destiny.x, (int)destiny.y].visited)
            {
                tablero[(int)destiny.x, (int)destiny.y].visited = true;
                //if the destiny isn't visited yet
                //remove the wall(carefully with the first case
                //add the destiny 4 wall to the list if they dont go outside the maze
                if(origin.x>=0 &&  origin.y>= 0 && origin.x< height && origin.y< width)
                {
                   if(origin.x == destiny.x)
                   {//left or right
                       if(origin.y> destiny.y)
                       {
                           //left
                           tablero[(int)origin.x, (int)origin.y].wallLeft=false;
                       }
                       else
                       {
                           //right
                           tablero[(int)origin.x, (int)origin.y].wallRight=false;
                       }
                   }
                   else
                   {//up or down
                       if(origin.x> destiny.x)
                       {
                           //up
                           tablero[(int)origin.x, (int)origin.y].wallUp=false;
                       }
                       else
                       {
                           //down
                           tablero[(int)origin.x, (int)origin.y].wallDown=false;
                       }
                   }

                   //remove wall from destiny to origin
                   //caution-> when left-> right, and when up->down
                   if (origin.x == destiny.x)
                   {//left or right
                       if (origin.y > destiny.y)
                       {
                           //right
                           tablero[(int)destiny.x, (int)destiny.y].wallRight = false;
                       }
                       else
                       {
                           //left
                           tablero[(int)destiny.x, (int)destiny.y].wallLeft = false;
                       }
                   }
                   else
                   {//up or down
                       if (origin.x > destiny.x)
                       {
                           //down
                           tablero[(int)destiny.x, (int)destiny.y].wallDown = false;
                       }
                       else
                       {
                           //up
                           tablero[(int)destiny.x, (int)destiny.y].wallUp = false;
                       }
                   }

                }

                //add up
                if(destiny.x-1 >= 0)
                {
                    Vector4 add= new Vector4(destiny.x,destiny.y,destiny.x-1,destiny.y);
                    pendientesDeAnalizar.Add(add);
                }

                //add down
                if(destiny.x+1 < height)
                {
                    Vector4 add= new Vector4(destiny.x,destiny.y,destiny.x+1,destiny.y);
                    pendientesDeAnalizar.Add(add);
                }
                //add left
                if(destiny.y-1 >= 0)
                {
                    Vector4 add= new Vector4(destiny.x,destiny.y,destiny.x,destiny.y-1);
                    pendientesDeAnalizar.Add(add);
                }

                //add right
                if(destiny.y+1 < width)
                {
                    Vector4 add= new Vector4(destiny.x,destiny.y,destiny.x,destiny.y+1);
                    pendientesDeAnalizar.Add(add);
                }

            }

        }
        estadoConstruccion = MazeState.INSTANCIANDO;
    }
    private void generateMazeKruskalThread()
    {
        estadoConstruccion = MazeState.THREAD;
        tablero = new Casilla[height, width];
        List<Vector4> listaParedes = new List<Vector4>();
        List<HashSet<int>> arraySet = new List<HashSet<int>>();
        int cuenta = 0;
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                tablero[i, j].wallDown = true;
                tablero[i, j].wallUp = true;
                tablero[i, j].wallLeft = true;
                tablero[i, j].wallRight = true;
                tablero[i, j].visited = false;
                tablero[i, j].trampas = false;

                HashSet<int> aux = new HashSet<int>();
                aux.Add(cuenta);
                arraySet.Add(aux);
                cuenta++;
                if (i - 1 >= 0)
                {
                    //up
                    listaParedes.Add(new Vector4(i, j, i - 1, j));
                }
                if (j - 1 >= 0)
                {
                    //left
                    listaParedes.Add(new Vector4(i, j, i, j-1));
                }
                if (i + 1 < height)
                {
                    //down
                    listaParedes.Add(new Vector4(i, j, i + 1, j));
                }
                if (j + 1 < width)
                {
                    //right
                    listaParedes.Add(new Vector4(i, j, i,j + 1));
                }

            }
        }
        GestorRandom gr = GestorRandom.getInstance();
        while (listaParedes.Count != 0)
        {
            int paredAEliminarIndex = gr.getNumeroAleatorio(0, listaParedes.Count);
            Vector4 paredAEliminar = listaParedes[paredAEliminarIndex];
            Vector4 popuesta = new Vector4(paredAEliminar.z, paredAEliminar.w, paredAEliminar.x, paredAEliminar.y);
            listaParedes.RemoveAt(paredAEliminarIndex);
            listaParedes.Remove(popuesta);

            int idOrigen = (int)(paredAEliminar.x * width + paredAEliminar.y);
            int idDestino = (int)(paredAEliminar.z * width + paredAEliminar.w);

            int idSetOrigen = findInSet(idOrigen, arraySet);
            int idSetDestino = findInSet(idDestino, arraySet);

            if (idSetDestino!= idSetOrigen)
            {
                HashSet<int> setDestino = arraySet[idSetDestino];
                arraySet[idSetOrigen].UnionWith(setDestino);
                arraySet.RemoveAt(idSetDestino);

                Vector2 origin = new Vector2(paredAEliminar.x , paredAEliminar.y);
                Vector2 destiny = new Vector2(paredAEliminar.z, paredAEliminar.w);

                //eliminar la pared
                if (origin.x == destiny.x)
                {//left or right
                    if (origin.y > destiny.y)
                    {
                        //left
                        tablero[(int)origin.x, (int)origin.y].wallLeft = false;
                    }
                    else
                    {
                        //right
                        tablero[(int)origin.x, (int)origin.y].wallRight = false;
                    }
                }
                else
                {//up or down
                    if (origin.x > destiny.x)
                    {
                        //up
                        tablero[(int)origin.x, (int)origin.y].wallUp = false;
                    }
                    else
                    {
                        //down
                        tablero[(int)origin.x, (int)origin.y].wallDown = false;
                    }
                }

                //remove wall from destiny to origin
                //caution-> when left-> right, and when up->down
                if (origin.x == destiny.x)
                {//left or right
                    if (origin.y > destiny.y)
                    {
                        //right
                        tablero[(int)destiny.x, (int)destiny.y].wallRight = false;
                    }
                    else
                    {
                        //left
                        tablero[(int)destiny.x, (int)destiny.y].wallLeft = false;
                    }
                }
                else
                {//up or down
                    if (origin.x > destiny.x)
                    {
                        //down
                        tablero[(int)destiny.x, (int)destiny.y].wallDown = false;
                    }
                    else
                    {
                        //up
                        tablero[(int)destiny.x, (int)destiny.y].wallUp = false;
                    }
                }

            }
        }

        estadoConstruccion = MazeState.INSTANCIANDO;
    }
    // Update is called once per frame
    void Update()
    {
        switch (estadoConstruccion)
        {
            case MazeState.THREAD: GestorRandom.getInstance().generaNumero(); break;
            case MazeState.INSTANCIANDO: break;
            case MazeState.WAITING_SERVER:
                Debug.Log("Waitig building from server");break;

            case MazeState.FIN:

                if (!networkManager.playerInstanciado)
                {
                    networkManager.instanciaAllPlayers();
                    estadoConstruccion = MazeState.DONOTHING;
                }
                break;

        }
    }
 // Use this for initialization
 void Start()
 {
     networkManager = GameObject.FindGameObjectWithTag("Network").GetComponent<NetworkManager>();
     width = networkManager.Ancho;
     height = networkManager.Alto;
     m_seed = networkManager.Seed;
     Random.seed = Seed;
     porcentajeQuitaVidas = networkManager.PorcentajeQuitaVidas;
     //noWallNoThread();
     generateMazeKruskalNoThread();
     instanciarLaberintoNoNetWork();
     instanciarSueloNoNetWork();
     colocarHuecosPasilloNoNetWork();
     instanciaKillPlane();
     estadoConstruccion = MazeState.FIN;
 }
    private void noWallThread()
    {
        estadoConstruccion = MazeState.THREAD;
        tablero = new Casilla[height, width];

        //inizialization to all walls and no visited
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                tablero[i, j].wallDown = false;
                tablero[i, j].wallUp = false;
                tablero[i, j].wallLeft = false;
                tablero[i, j].wallRight = false;
                tablero[i, j].visited = false;
            }
        }
        estadoConstruccion = MazeState.INSTANCIANDO;
    }
Esempio n. 33
0
 void IncrementMazeState()
 {
     mazeState = (MazeState)(((int)mazeState + 1) % (int)MazeState.NumStates);
 }
        private void DepthFirstSearch(int u)
        {
            currentNode = u;
            if (u == endNode) {
                mazeState = MazeState.SOLVED;
                Invalidate();
                return;
            }

            if (AreAllNodesVisited()) {
                return;
            }

            visited[u] = true;

            // for each neighbor of u make a move
            List<int> neighbors = GetNeighbors(u);
            for (int i = 0; i < neighbors.Count; ++i) {
                int v = neighbors[i];
                if (adjacentMatrix[u, v] == true || adjacentMatrix[v, u] == true) {
                    path[v] = u;
                    DepthFirstSearch(v);
                    Thread.Sleep(10);
                    Invalidate();
                }
            }
        }
        public void BuildMaze()
        {
            // pick a random square
            int c = 0;
            int r = random.Next(maze.Height);
            Square startingSquare = maze.SquareAt(r, c);

            // set current square to starting square
            currentSquare = startingSquare;

            // remove LEFT wall of current square
            currentSquare.RemoveSide(Square.Direction.LEFT);

            // set last side to left
            lastSide = Square.Direction.LEFT;

            // while there remains any blocked square in the grid
            while (maze.IsAnyBlocked()) {
                // set bool addingSquare to false
                addingSquareFlag = false;

                // create a random sequence of the 0, 1, 2, or 3 remaining walls for currentSquare
                // exclude sides that lead to unblocked squares (squares that are already in the maze)
                directions.Clear();
                if (currentSquare.HasSide(Square.Direction.LEFT)) {
                    if (currentSquare.AdjacentSquare(Square.Direction.LEFT) != null &&
                        currentSquare.AdjacentSquare(Square.Direction.LEFT).IsBlocked()) {
                        directions.Add(Square.Direction.LEFT);
                    }
                }

                if (currentSquare.HasSide(Square.Direction.RIGHT)) {
                    if (currentSquare.AdjacentSquare(Square.Direction.RIGHT) != null &&
                        currentSquare.AdjacentSquare(Square.Direction.RIGHT).IsBlocked()) {
                        directions.Add(Square.Direction.RIGHT);
                    }
                }

                if (currentSquare.HasSide(Square.Direction.TOP)) {
                    if (currentSquare.AdjacentSquare(Square.Direction.TOP) != null &&
                        currentSquare.AdjacentSquare(Square.Direction.TOP).IsBlocked()) {
                        directions.Add(Square.Direction.TOP);
                    }
                }

                if (currentSquare.HasSide(Square.Direction.BOTTOM)) {
                    if (currentSquare.AdjacentSquare(Square.Direction.BOTTOM) != null &&
                        currentSquare.AdjacentSquare(Square.Direction.BOTTOM).IsBlocked()) {
                        directions.Add(Square.Direction.BOTTOM);
                    }
                }

                // exclude lastSide
                directions.Remove(lastSide);

                // shuffle them
                Shuffle(directions);

                foreach (Square.Direction dir in directions) {
                    // let nextSide be the current element in this sequence
                    Square.Direction nextSide = dir;

                    // if square adjacent to the current square on side nextSide exists and is blocked
                    if (currentSquare.AdjacentSquare(nextSide) != null && currentSquare.AdjacentSquare(nextSide).IsBlocked()) {
                        // remove walls that separate currentSquare and adjacentSquare
                        Square adjacent = currentSquare.AdjacentSquare(nextSide);
                        currentSquare.RemoveSide(nextSide);
                        adjacent.RemoveSide(Square.OppositeSide(nextSide));

                        // add path to adjacency matrix
                        int u = ConvertToNode(currentSquare.Row, currentSquare.Column);
                        int v = ConvertToNode(adjacent.Row, adjacent.Column);
                        adjacentMatrix[u, v] = true;
                        adjacentMatrix[v, u] = true;

                        // adjacentSquare becomes currentSquare
                        currentSquare = adjacent;

                        // set boolean addingSquareFlag to true
                        addingSquareFlag = true;

                        // set lastSide to the opposite of nextSide
                        lastSide = Square.OppositeSide(nextSide);
                        break;
                    }
                }

                // this means we couldn't find any adjacent square to move to in the for loop above
                // we now have to backtrack by picking a random unblocked square elsewhere in the maze
                // and try to build a path from that point
                if (!addingSquareFlag) {
                    // pick an unblocked square (already in the maze) from the grid at
                    // random, optionally ensuring that it is adjacent to at least one
                    // blocked square (not already in the maze)
                    // this becomes the current square
                    currentSquare = maze.SelectRandomUnblockedSquare();
                    if (currentSquare == null)
                        break;

                    // randomly pick an open side (one with wall already removed) of the
                    // current square, this becomes lastSide
                    lastSide = currentSquare.SelectOpenSide();
                }

                // redraw
                UpdateDrawing();
            }

            // update state
            mazeState = MazeState.BUILT;
        }