Exemple #1
0
    private void GoToGoal()
    {
        IEnumerable <Node> pathList = Astar.FindPath(startTilePos, endTilePos);

        pathLength = pathList.Count();
        pathIndex  = 0;
    }
    public void Update()
    {
        /*if (player != null)
         * {
         *  if (player.position.x + weapon.range < transform.position.x)
         *      Move(4);
         *  else if (player.position.x - weapon.range > transform.position.x)
         *      Move(0);
         *  if (player.position.y + 0.1f < transform.position.y)
         *      Move(6);
         *  else if (player.position.y - 0.1f > transform.position.y)
         *      Move(2);
         * }*/

        if (Input.GetKeyDown(KeyCode.J))
        {
            List <Vector2> path = Astar.FindPath(transform.position, player.position, ref ground);

            foreach (Vector2 v in path)
            {
                Instantiate(beacon, new Vector3(v.x, v.y, 0), Quaternion.identity);
                //Debug.Log(v);
            }
        }
    }
 public void OnMapChange()
 {
     if (_targetRoom != null)
     {
         _roomPath = Astar.FindPath(_currentRoom, _targetRoom);
     }
 }
Exemple #4
0
    public void Run()
    {
        message.gameObject.SetActive(false);
        Vector2Int start  = new Vector2Int(1, size - 2);
        Vector2Int finish = new Vector2Int(size - 2, 1);

        if (!Astar.FindPath(labGrid, start, finish))
        {
            message.gameObject.SetActive(true);
            message.text  = "NO PATH AVAILABLE";
            message.color = Color.red;
            return;
        }
        IsAlgorithmRunning = true;
        bool         isTimeout;
        List <Child> bestOfGeneration = GAController.GeneticAlgorithm(labGrid.grid, size, start, finish, out isTimeout);

        if (bestOfGeneration != null)
        {
            message.gameObject.SetActive(true);
            message.text  = "PATH FOUND";
            message.color = Color.blue;

            StartCoroutine(ShowGenerations(bestOfGeneration, start, finish));
        }
        else if (isTimeout)
        {
            message.gameObject.SetActive(true);
            message.text  = "TIMEOUT";
            message.color = Color.blue;
        }
    }
Exemple #5
0
    protected List <Point> UseAstar(Vector3 origin, Vector3 destination, int range)
    {
        int[,] array = new int[BattleFieldManager.GetInstance().GridX, BattleFieldManager.GetInstance().GridY];     //可优化为更小的地图。
        path.Clear();
        for (int i = 0; i < BattleFieldManager.GetInstance().GridX; i++)
        {
            for (int j = 0; j < BattleFieldManager.GetInstance().GridY; j++)
            {
                array[i, j] = 1;
            }
        }

        var minX = origin.x - range;
        var minY = origin.z - range;
        var maxX = origin.x + range;
        var maxY = origin.z + range;

        minX = minX > 0 ? minX : 0.5f;
        minY = minY > 0 ? minY : 0.5f;
        maxX = maxX < BattleFieldManager.GetInstance().GridX ? maxX : BattleFieldManager.GetInstance().GridX - 0.5f;
        maxY = maxY < BattleFieldManager.GetInstance().GridY ? maxY : BattleFieldManager.GetInstance().GridY - 0.5f;

        //检测整张地图的地板块激活情况,判断障碍物,存入数组。

        for (int i = (int)minX; i <= (int)maxX; i++)
        {
            for (int j = (int)minY; j <= (int)maxY; j++)
            {
                floorPosition    = Vector3.zero;
                floorPosition.x += (i + anchorPoint);
                floorPosition.z += (j + anchorPoint);
                GameObject floor = BFM.GetFloor(floorPosition);
                //AI做预判时会有限制,不能用activeSelf,基于哈希表的Dictionary,ContainsKey比ContainsValue的效率高很多100ms <---> 400ms
                if (floor && rangeDic.ContainsKey(floor.transform.position) /* floor.activeSelf */ && (floor.transform.position == destination || !floorAroundEnemy.Contains(floor.transform.position)))   //地板是激活的且不在敌人周围,可用作寻路路径。如果是目的地且在激活的状态下,一定可以作为寻路路径。
                {
                    array[i, j] = 0;
                }
                else
                {
                    array[i, j] = 1;
                }
            }
        }
        //调用A*。
        Astar astar = new Astar(array);
        Point start = new Point((int)origin.x, (int)origin.z);
        Point end   = new Point((int)destination.x, (int)destination.z);

        var parent = astar.FindPath(start, end, false);

        while (parent != null)
        {
            path.Add(parent);
            parent = parent.ParentPoint;
        }
        path.Reverse();     //里面的元素顺序是反的,即从目的指向起点,这里变为由起点指向目的。
        return(path);
    }
        public override void OnEventReceived(Events.Event e, object o)
        {
            if (e == Events.Event.PleaseDoSomething)
            {
                if (_actions.Count == 0)
                {
                    StartCoroutine(DoNextThing(Random.Range(0.1f, 1f)));
                }
                else
                {
                    DoNextAction();
                }
            }
            // Debug.Log("Event Received");
            if (e == Events.Event.RoomCreated)
            {
                // If already doing something, just redo the paths
                if (_actions != null && _actions.Count > 0)
                {
                    List <(List <ARoom> path, Action action)> newactions = new List <(List <ARoom> path, Action action)>();

                    // do not forget to start from the current room and not from the next one !!
                    _actions[0].path.Insert(0, _currentRoom);
                    foreach (var action in _actions)
                    {
                        newactions.Add((
                                           Astar.FindPath(action.path[0], action.path[action.path.Count - 1]),
                                           action.action
                                           ));
                    }
                    _actions = newactions;
                }
                // else {
                //     ChooseAction();
                // }
            }
            if (e == Events.Event.RoomDestroyed)
            {
                // oups
            }
            if (e == Events.Event.BlueprintDrawn || e == Events.Event.RoomCreated)
            {
                // Debug.Log("Blueprint Drawn event received for warehouseman");
                if (_actions.Count == 0)
                {
                    // Debug.Log("I'm available");
                    StartCoroutine(DoNextThing(Random.Range(0.1f, 1f)));
                }
            }
            if (e == Events.Event.ResourceMined)
            {
                if (_actions.Count == 0)
                {
                    StartCoroutine(DoNextThing(Random.Range(0.1f, 1f)));
                }
            }
        }
Exemple #7
0
        private void FindPath()
        {
            Grid grid = new Grid(width, length);

            Astar.FindPath(grid, transform.position, player.transform.position);
            smartPath = ConvertToPosition(grid.path);
            Moving    = true;
            if (Moving)
            {
                StartCoroutine(onCoroutine());
            }
        }
Exemple #8
0
 private void GetPath()
 {
     if (player != null && gameObject != null)
     {
         Grid grid = new Grid(width, length);
         Astar.FindPath(grid, transform.position, player.transform.position);
         smartPath = ConvertToPosition(grid.path);
     }
     else
     {
         smartPath.Clear();
     }
 }
Exemple #9
0
    protected List <Point> UseAstar(Vector3 origin, Vector3 destination, int range)
    {
        path.Clear();
        for (int i = 0; i < BattleFieldManager.GridX; i++)
        {
            for (int j = 0; j < BattleFieldManager.GridY; j++)
            {
                array[i, j] = 1;
            }
        }

        var minX = origin.x - range;
        var minY = origin.z - range;
        var maxX = origin.x + range;
        var maxY = origin.z + range;

        //检测整张地图的地板块激活情况,判断障碍物,存入数组。

        for (int i = (int)minX; i <= (int)maxX; i++)
        {
            for (int j = (int)minY; j <= (int)maxY; j++)
            {
                floorPosition    = Vector3.zero;
                floorPosition.x += (i + anchorPoint);
                floorPosition.z += (j + anchorPoint);
                GameObject floor = BFM.GetFloor(floorPosition);
                if (floor && floor.activeSelf && (floor.transform.position == destination || !floorAroundEnemy.Contains(floor.transform.position)))   //地板是激活的且不在敌人周围,可用作寻路路径。如果是目的地且在激活的状态下,一定可以作为寻路路径。
                {
                    array[i, j] = 0;
                }
                else
                {
                    array[i, j] = 1;
                }
            }
        }
        //调用A*。
        Astar astar = new Astar(array);
        Point start = new Point((int)origin.x, (int)origin.z);
        Point end   = new Point((int)destination.x, (int)destination.z);

        var parent = astar.FindPath(start, end, false);

        while (parent != null)
        {
            path.Add(parent);
            parent = parent.ParentPoint;
        }
        path.Reverse();     //里面的元素顺序是反的,即从目的指向起点,这里变为由起点指向目的。
        return(path);
    }
Exemple #10
0
        public void MoveTo(string username, Point destination)
        {
            var actor = _state.Actors.Single(act => act.Id == username);
            var level = _state.Maps.Single(map => map.Id == actor.MapId).Level;
            var path  = Astar.FindPath(level, actor.Position, destination);

            if (actor.CurrentAction != null && actor.CurrentAction is Movement movement)
            {
                movement.UpdateMovement(path, actor.Position);
            }
            else if (path.Count != 0)
            {
                actor.CurrentAction = new Movement(path, actor.Position);
            }
        }
Exemple #11
0
    void FixedUpdate()
    {
        if (Target._new)
        {
            Target._new  = false;
            int[,] field = new int[CellGenerator.levelGrid.Length, CellGenerator.levelGrid[0].Length];
            for (int i = 0; i < field.GetLength(0); i++)
            {
                for (int j = 0; j < field.GetLength(1); j++)
                {
                    if (CellGenerator.levelGrid[i][j].GetComponent <Cube>()._color == 0)
                    {
                        field[i, j] = 0;
                    }
                    else
                    {
                        field[i, j] = 1;
                    }
                }
            }

            Point current_position = new Point((int)Mathf.Round(transform.position.x / 10.0f), (int)Mathf.Round(transform.position.z / 10.0f));
            Debug.Log(Target._target.X);
            path        = Astar.FindPath(field, current_position, Target._target);
            Target._new = false;
            current_position_in_path = 1;
        }
        if (path != null && Target._target != new Point(-1, -1) && current_position_in_path <= path.Count - 1)
        {
            var heading = new Vector2((int)Mathf.Round(path[current_position_in_path].X * 10.0f - transform.position.x), (int)Mathf.Round(path[current_position_in_path].Y * 10.0f - transform.position.z));
            if (heading.magnitude >= 0.01f)
            {
                transform.position = transform.position + new Vector3(normalize((int)Mathf.Round(heading.x)), 0, normalize((int)Mathf.Round(heading.y))) * Time.deltaTime * 40;
                if (path != null && current_position_in_path == path.Count - 1 && heading.magnitude <= 0.1f)
                {
                    path = null;
                    current_position_in_path = 1;
                }
            }
            else
            {
                transform.position = new Vector3(path[current_position_in_path].X * 10.0f, 0, path[current_position_in_path].Y * 10.0f);
                current_position_in_path++;
            }

            //transform.position = Vector3.Lerp(path[current_position_in_path-1], path[current_position_in_path], Time.deltaTime * 40.0f);
        }
    }
Exemple #12
0
        public void SolvePuzzle()
        {
            DateTime StartTime = DateTime.Now;
            Astar    aStar     = new Astar(PuzzlePiecesAsInt, PuzzleSize);

            Directions = aStar.FindPath();
            DateTime EndingTime = DateTime.Now;
            var      diff       = EndingTime.Subtract(StartTime);
            var      res        = String.Format("Hours: {0} Minutes: {1} Seconds: {2} Milliseconds: {3}", diff.Hours, diff.Minutes, diff.Seconds, diff.Milliseconds);

            Debug.WriteLine(res);
            Debug.WriteLine("Puzzle solved. Moves: " + Directions.Count);
            foreach (Direction Direction in Directions)
            {
                Debug.WriteLine(Direction);
            }
        }
    private void updatePath(GameObject go)
    {
        Transform tr = go.GetComponent <Transform>();
        Move      mv = go.GetComponent <Move>();

        mv.path = new List <Vector3>();

        if (myMaps != null)
        {
            List <MyTilemap> maps = new List <MyTilemap>();

            foreach (Tilemap tm in myMaps.myTileMaps)
            {
                maps.Add(new MyTilemap(tm, tm.GetComponent <MapLayer>()));
            }

            Astar a = new Astar(maps);
            Stack <Vector3Int> path = a.FindPath(tr.position, mv.targetPosition);

            Vector3 lastCellWorldPos = tr.position;
            //string s = "[" + myMaps.myTileMaps[0].WorldToCell(lastCellWorldPos).ToString() + "]";

            int i = 0;
            foreach (Vector3Int cell in path)
            {
                Vector3 cellWorldPos = myMaps.myTileMaps[0].CellToWorld(cell);
                mv.path.Add(cellWorldPos);
                //Debug.DrawLine(lastCellWorldPos, cellWorldPos, (i%2==0) ? Color.green : Color.white);

                lastCellWorldPos = cellWorldPos;
                //s += " -> " + cell.ToString();
                i++;
            }

            if (mv.path.Count > 0)
            {
                mv.path.RemoveAt(mv.path.Count - 1);
            }

            //s += " | [" + myMaps.myTileMaps[0].WorldToCell(mv.targetPosition).ToString() + "]";

            //Debug.Log(s);
        }

        mv.path.Add(mv.targetPosition);
    }
Exemple #14
0
 private void Update()
 {
     // if mouse press -> send co-ordinates to A-star pathfinding agent
     if (Input.GetMouseButtonDown(0))
     {
         world.Tile target = MouseRead.MouseRaycast();
         if (target != null)
         {
             if (!target.isWall)
             {
                 Vector2Int        destination = target.index;
                 List <Vector2Int> path        = astar.FindPath(destination, new Vector2Int((int)character.itemRep.transform.position.x, (int)character.itemRep.transform.position.y), map, 0.2f);
                 collorPath(path);
                 character.traversePath(path, map);
             }
         }
     }
 }
    private void UpdatePath(CharacterObjectController target, Chunk chunk)
    {
        Vector3 startPosition = (path != null && path.Count > pathIterator + 1) ? (Vector3)path[pathIterator].position : transform.position;

        path = pathfinding.FindPath(chunk, target.currentChunk,
                                    startPosition, target.transform.position);
        pathIterator = 0;
        if (path != null)
        {
            Vector2 centerPosition = Vector2.zero;
            for (int i = 0; i < path.Count - 1; i++)
            {
                //Debug.DrawLine(new Vector3(path[i].position.x, path[i].position.y),
                //    new Vector3(path[i + 1].position.x, path[i + 1].position.y), Color.green, 10.0f);
                centerPosition    = path[i].position;
                centerPosition.x += 0.5f;                               // przesunięcie z wierzchołka płytki do jej środka
                centerPosition.y += 0.5f;                               //
                path[i].position  = centerPosition;
            }
        }
    }
Exemple #16
0
 void Update()
 {
     chunk = player.currentChunk;
     if (Input.GetMouseButtonDown(0))
     {
         //Profiler.BeginSample("FindPath");
         List <Node> path = pathFinding.FindPath(chunk, GetChunkOnMouse(), new Vector2(-4, 6), GetMousePosToCell());
         //Profiler.EndSample();
         if (path != null)
         {
             for (int i = 0; i < path.Count - 1; i++)
             {
                 Debug.DrawLine(new Vector3(path[i].position.x, path[i].position.y),
                                new Vector3(path[i + 1].position.x, path[i + 1].position.y), Color.green, 10.0f);
             }
         }
         else
         {
             Debug.Log("elsexd");
         }
     }
 }
Exemple #17
0
        public void MapAstarTest()
        {
            var mapData = new MapFromImageParser(new MapModel {
                FileName = "1_map.png", Cols = 55, Rows = 55
            }).ParseImage();
            var erg = new List <List <Node> >();

            mapData.Data.OrderBy(p => p.Y).ThenBy(p => p.X).ToList().ForEach(e =>
            {
                if (erg.Count - 1 != e.Y)
                {
                    erg.Add(new List <Node>());
                }
                var node = new Node(new Vector2(e.X, e.Y), !e.Block && e.TowerId == null);
                erg[e.Y].Add(node);
                // Console.WriteLine("Walkable: " + (node.Walkable ? "ja" : "nein"));
            });

            var bm = new Bitmap(55, 55);

            erg.ForEach(l =>
            {
                l.ForEach(n =>
                {
                    bm.SetPixel(n.Position.X, n.Position.Y, n.Walkable?Color.White:Color.Black);
                });
            });

            var astar = new Astar(erg);
            var path  = astar.FindPath(new Vector2(21, 26), new Vector2(25, 22));

            path.ForEach(pa =>
            {
                bm.SetPixel(pa.Position.X, pa.Position.Y, Color.Red);
                output.WriteLine("X: " + pa.Position.X + "Y: " + pa.Position.Y);
            });

            bm.Save("TESTMAP.png", ImageFormat.Png);
        }
Exemple #18
0
        private async Task <List <Vector> > PathThroughRoom(BasePathable room, Vector from, Vector to, List <BaseRoom> notPassableList)
        {
            var grid = new List <List <Node> >();

            for (int i = 0; i < room.Size.Height; i++)
            {
                var row = new List <Node>();
                grid.Add(row);
                for (int j = 0; j < room.Size.Width; j++)
                {
                    bool isNotPassable = notPassableList.Any(x => x.Position.X <room.Position.X + j &&
                                                                                x.Position.X + x.Size.Width> room.Position.X + j &&
                                                             x.Position.Y <room.Position.Y + i &&
                                                                           x.Position.Y + x.Size.Height> room.Position.Y + i);
                    var node = new Node(new Vector(j, i), !isNotPassable);
                    row.Add(node);
                }
            }

            var astar = new Astar(grid);
            var path  = astar.FindPath(from - room.Position, to - room.Position);

            return(path.Select(x => new Vector(x.Position.X, x.Position.Y)).ToList());
        }
Exemple #19
0
        private void StartRobot()
        {
            var    position       = filter.getPosition();
            var    dontDoAnything = false;
            double tmpSensorRead  = 0;

            motionControle.RotationScan(Sensors, filter, OriginalBitmap);
            motionControle.RotationScan(Sensors, filter, OriginalBitmap);

            while ((position.X - Astar._goalX) > 10 || (position.Y - Astar._goalY) > 10)
            {
                tmpSensorRead = Sensors.Read();
                if (tmpSensorRead > 5 && tmpSensorRead < 185)
                {
                    filter.Resample(tmpSensorRead); // Complete run
                    position = filter.getPosition();

                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        BitmapClone = (Bitmap)OriginalBitmap.Clone();
                        BitmapClone.Drawparticles(filter.ParticleSet);

                        Image.Source = BitmapClone.DrawRobotPos(position);
                    }
                                                      ));

                    var movement = Astar.FindPath((int)position.X, (int)position.Y);


                    if (dontDoAnything)
                    {
                        dontDoAnything = false;
                    }
                    else
                    {
                        var turnThisMuch = motionControle.TurnCommand(movement, filter.RadToDeg(position.theta));

                        if (turnThisMuch < 0)
                        {
                            filter.TurnParticlesRight(Math.Abs(turnThisMuch));
                        }
                        else
                        {
                            filter.TurnParticlesLeft(turnThisMuch);
                        }
                        motionControle.PIDMove(10);
                        filter.MoveParticles(10);

                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            BitmapClone = (Bitmap)OriginalBitmap.Clone();
                            BitmapClone.Drawparticles(filter.ParticleSet);

                            Image.Source = BitmapClone.DrawRobotPos(position);
                        }
                                                          ));
                    }
                }
            }
            brick.DirectCommand.PlayToneAsync(100, 440, 500);
        }
Exemple #20
0
    private void FixedUpdate()
    {
        // make sure the game has a speed limit so it wont run to fast
        if (gameTick > 1 / gameSpeedMultiplier)
        {
            // make sure to reset the gametick
            gameTick = 0;

            // stuff related to the Astar pathfinding
            if (usePathfinding)
            {
                // if the pathfinding is null, assign a new Astar instance
                if (pathfinding == null)
                {
                    pathfinding = new Astar();
                }
                // generate a new path to the fruit
                hasPath = pathfinding.FindPath(GameManager.instance.grid, transform.position, GameManager.instance.fruit.transform.position);
                // if a path is found the snake will find its way to the fruit
                if (hasPath)
                {
                    PathfindSnake();
                }
                else
                {
                    // if there is no path to the fruit, the snake will try to find a way to its tail. Or just take a random path depending on if its neighbour is walkable
                    bool tailPath = false;
                    //GameManager.instance.grid[(int)linkedList.getLast().transform.position.x, (int)linkedList.getLast().transform.position.y].isWalkable = true;
                    //tailPath = pathfinding.FindPath(GameManager.instance.grid, transform.position, linkedList.getLast().transform.position);
                    // uncomment the 2 above lines if you want the snake to try to find its way to the tail
                    if (tailPath)
                    {
                        PathfindSnake();
                    }
                    else
                    {
                        // try to find the first walkable tile if there is no path to the fruit or tail
                        snakeDirection = Direction.Up;              // firt we set the move direction to up
                        Tile[,] grid   = GameManager.instance.grid; // get a grid to compare if the tiles are walkable or not
                        //check if the direction is walkable else it will try the next direction
                        for (int i = 0; i < 3; i++)
                        {
                            if (grid[(int)GetNewHeadPosition().x, (int)GetNewHeadPosition().y].isWalkable)
                            {
                                // if the direction is walkable, there is no need to check an other one just break out
                                break;
                            }
                            else
                            {
                                //just increment the direction by 1 (available directions are 0, 1, 2, 3)
                                snakeDirection++;
                            }
                        }
                    }
                }
            }
            MoveSnake();
            GrowSnake();
            RotateSnake(snakeDirection);    // set the rotation of the snake head. Mainly for the graphic of the head
        }

        gameTick += Time.fixedDeltaTime;    // increase the tick timer to manipulate the game speed/ movement speed
    }
 public Vector3[] GetPath()
 {
     return(astar.FindPath(transform.position + transform.forward * 50 + transform.up * 20, target.position));
 }
Exemple #22
0
        private void AddPath()
        {
            // Create map for A* lib
            List <List <Node> > temp_map = new List <List <Node> >();

            generator.Map.lines.ForEach((line) =>
            {
                int y = generator.Map.lines.IndexOf(line);
                temp_map.Add(new List <Node>());
                line.tiles.ForEach((tile) =>
                {
                    int x = line.tiles.IndexOf(tile);
                    //if it's a cliff side :
                    if (GetTileId(x, y) == 55 && GetTileId(x - 1, y) == 55 && GetTileId(x + 1, y) == 55)
                    {
                        temp_map[y].Add(new Node(new System.Numerics.Vector2(x, y), true, 5));
                    }
                    else if (GetTileId(x, y) == 33 && GetTileId(x, y - 1) == 33 && GetTileId(x, y + 1) == 33)
                    {
                        temp_map[y].Add(new Node(new System.Numerics.Vector2(x, y), true, 5));
                    }
                    else if (GetTileId(x, y) == 35 && GetTileId(x, y - 1) == 35 && GetTileId(x, y + 1) == 35)
                    {
                        temp_map[y].Add(new Node(new System.Numerics.Vector2(x, y), true, 5));
                    }

                    //if it's grass or path :
                    else if (GetTileId(x, y) == 89 || GetTileId(x, y) == 34)
                    {
                        if ((GetTileId(x - 1, y) == 89 || GetTileId(x - 1, y) == 34) && (GetTileId(x + 1, y) == 89 || GetTileId(x + 1, y) == 34) ||
                            (GetTileId(x, y - 1) == 89 || GetTileId(x, y - 1) == 34) && (GetTileId(x, y + 1) == 89 || GetTileId(x, y + 1) == 34))
                        {
                            temp_map[y].Add(new Node(new System.Numerics.Vector2(x, y), true, 3));
                        }

                        else
                        {
                            temp_map[y].Add(new Node(new System.Numerics.Vector2(x, y), true, 20));
                        }
                    }
                    //if it's sand :
                    else if (GetTileId(x, y) == 72 || GetTileId(x, y) == 73 || GetTileId(x, y) == 74 || GetTileId(x, y) == 93 || GetTileId(x, y) == 94 ||
                             GetTileId(x, y) == 95 || GetTileId(x, y) == 114 || GetTileId(x, y) == 114 || GetTileId(x, y) == 115)
                    {
                        temp_map[y].Add(new Node(new System.Numerics.Vector2(x, y), true, 4));
                    }
                    else
                    {
                        temp_map[y].Add(new Node(new System.Numerics.Vector2(x, y), false));
                    }
                });
            });
            foreach (var coord in doorSteps)
            {
                temp_map[(int)coord.Y + 1][(int)coord.X] = new Node(new System.Numerics.Vector2((int)coord.Y + 1, (int)coord.X), true, 1);
            }

            Astar astar = new Astar(temp_map);

            foreach (var coord in doorSteps)
            {
                var cur_x = coord.X;
                var cur_y = coord.Y;
                var moy_x = 0;
                var moy_y = 0;
                var dist  = 10000000.0;
                // find closest center
                foreach (var coord_moy in centers)
                {
                    if (((cur_x - coord_moy.X) * (cur_x - coord_moy.X) + (cur_y - coord_moy.Y) * (cur_y - coord_moy.Y)) < dist)
                    {
                        moy_x = (int)coord_moy.X;
                        moy_y = (int)coord_moy.Y;
                        dist  = (cur_x - coord_moy.X) * (cur_x - coord_moy.X) + (cur_y - coord_moy.Y) * (cur_y - coord_moy.Y);
                    }
                }
                // find paths between targer
                var path = astar.FindPath(new Vector2(cur_x, cur_y), new Vector2(moy_x, moy_y));
                try {
                    foreach (Node node in path)
                    {
                        var temp_x = (int)node.Position.X;
                        var temp_y = (int)node.Position.Y;
                        temp_map[temp_y][temp_x] = new Node(new System.Numerics.Vector2(temp_x, temp_y), true, 1);

                        if (GetTileId(temp_x, temp_y) == 33)
                        {
                            SetTile(temp_x, temp_y, 164);
                            SetTile(temp_x, temp_y - 1, 143);
                            SetTile(temp_x, temp_y + 1, 185);
                        }
                        else if (GetTileId(temp_x, temp_y) == 35)
                        {
                            SetTile(temp_x, temp_y, 165);
                            SetTile(temp_x, temp_y - 1, 144);
                            SetTile(temp_x, temp_y + 1, 186);
                        }
                        else if (GetTileId(temp_x, temp_y) == 55)
                        {
                            SetTile(temp_x, temp_y, 125);
                            SetTile(temp_x - 1, temp_y, 124);
                            SetTile(temp_x + 1, temp_y, 126);
                        }
                        else if (GetTileId(temp_x, temp_y) == 125)
                        {
                            SetTile(temp_x, temp_y, 125);
                        }
                        else if (GetTileId(temp_x, temp_y) == 164)
                        {
                            SetTile(temp_x, temp_y, 164);
                        }
                        else if (GetTileId(temp_x, temp_y) == 165)
                        {
                            SetTile(temp_x, temp_y, 165);
                        }
                        //sable
                        else if (GetTileId(temp_x, temp_y) == 72 || GetTileId(temp_x, temp_y) == 73 || GetTileId(temp_x, temp_y) == 74 ||
                                 GetTileId(temp_x, temp_y) == 93 || GetTileId(temp_x, temp_y) == 94 || GetTileId(temp_x, temp_y) == 95 ||
                                 GetTileId(temp_x, temp_y) == 114 || GetTileId(temp_x, temp_y) == 115 || GetTileId(temp_x, temp_y) == 116)
                        {
                            //do nothing
                        }
                        else
                        {
                            SetTile(temp_x, temp_y, 89);
                        }
                    }
                    astar = new Astar(temp_map);
                }
                catch (Exception e) {
                    Console.Write("No path availible for one the house ");
                }
            }

            //add corners
            generator.Map.lines.ForEach((line) =>
            {
                int y = generator.Map.lines.IndexOf(line);
                line.tiles.ForEach((tile) =>
                {
                    int x = line.tiles.IndexOf(tile);
                    if (GetTileId(x, y) == 89)
                    {
                        if (GetTileId(x - 1, y - 1) == 34 && GetTileId(x, y - 1) == 89 && GetTileId(x - 1, y) == 89)
                        {
                            SetTile(x - 1, y - 1, 108);
                        }
                        if (GetTileId(x + 1, y - 1) == 34 && GetTileId(x, y - 1) == 89 && GetTileId(x + 1, y) == 89)
                        {
                            SetTile(x + 1, y - 1, 107);
                        }
                        if (GetTileId(x - 1, y + 1) == 34 && GetTileId(x, y + 1) == 89 && GetTileId(x - 1, y) == 89)
                        {
                            SetTile(x - 1, y + 1, 87);
                        }
                        if (GetTileId(x + 1, y + 1) == 34 && GetTileId(x, y + 1) == 89 && GetTileId(x + 1, y) == 89)
                        {
                            SetTile(x + 1, y + 1, 86);
                        }
                    }
                });
            });
            //Add border
            generator.Map.lines.ForEach((line) =>
            {
                int y = generator.Map.lines.IndexOf(line);
                line.tiles.ForEach((tile) =>
                {
                    int x = line.tiles.IndexOf(tile);
                    if (GetTileId(x, y) == 89)
                    {
                        if (GetTileId(x + 1, y) == 34)
                        {
                            SetTile(x + 1, y, 90);
                        }
                        if (GetTileId(x - 1, y) == 34)
                        {
                            SetTile(x - 1, y, 88);
                        }
                        if (GetTileId(x, y + 1) == 34)
                        {
                            SetTile(x, y + 1, 110);
                        }
                        if (GetTileId(x, y - 1) == 34)
                        {
                            SetTile(x, y - 1, 68);
                        }
                    }
                });
            });
        }
Exemple #23
0
        private void findPath(List <ArrayHelper> questionmarks)
        {
            messagebox.Items.Clear();
            Astar astar = new Astar();

            foreach (Autobot autobot in autobots)
            {
                List <ArrayHelper> path  = new List <ArrayHelper>();
                ArrayHelper        start = (ArrayHelper)mazeList.Where(t => t.DeltaX == autobot.X && t.DeltaY == autobot.Y).FirstOrDefault();

                List <ArrayHelper> shortestPath = new List <ArrayHelper>();

                foreach (ArrayHelper questionmark in questionmarks)
                {
                    path = astar.FindPath(start, questionmark);

                    if (path.Count < shortestPath.Count || shortestPath.Count == 0)
                    {
                        shortestPath = path;
                        messagebox.Items.Add("New shortest path");
                    }

                    foreach (ArrayHelper helper in mazeList.Where(h => h.State != ArrayHelper.HelperState.UNTESTED))
                    {
                        helper.State             = ArrayHelper.HelperState.UNTESTED;
                        helper.ParentArrayHelper = null;
                    }

                    messagebox.Items.Add("Path " + autobot.Name + " to " + questionmark.DeltaX + " " + questionmark.DeltaY);
                    foreach (ArrayHelper helper in path)
                    {
                        messagebox.Items.Add(helper.DeltaX + " " + helper.DeltaY);
                    }
                }

                Console.WriteLine("BOT: " + autobot.Name);
                Console.WriteLine("POS: " + autobot.X + " " + autobot.Y);
                Console.WriteLine("TO:  " + shortestPath[0].DeltaX + " " + shortestPath[0].DeltaY);
                Console.WriteLine("DIR:  " + autobot.Orientation);

                var dirX = shortestPath[0].DeltaX - autobot.X;
                var dirY = shortestPath[0].DeltaY - autobot.Y;

                Orientation newOrientation = new Orientation();
                if (dirX > 0)
                {
                    newOrientation = Orientation.EAST;
                }
                else if (dirX < 0)
                {
                    newOrientation = Orientation.WEST;
                }
                else if (dirY > 0)
                {
                    newOrientation = Orientation.SOUTH;
                }
                else if (dirY < 0)
                {
                    newOrientation = Orientation.NORTH;
                }
                Console.WriteLine("NEW:  " + newOrientation);
                int turnDirection = getTurnDirection(newOrientation, autobot);
                Console.WriteLine("NEW:  " + turnDirection);
                addMessageToSend("0" + turnDirection, autobot);
            }
        }
        private IEnumerator ChooseAction(/*??*/)
        {
            while (true)
            {
                // Debug.Log("ChooseAction begin");
                // First of all, if _currentRoom is null, let's try to find where we are
                if (_currentRoom == null)
                {
                    // Debug.Log("  Checking for room");
                    // Debug.Log("  My pos : " + transform.position.x + ", " + transform.position.y);
                    foreach (var room in MapManager.S.MapRooms)
                    {
                        // Debug.Log("    Room pos :");
                        // Debug.Log("      (" + room.Position.x + ", " + room.Position.y + ") (" + (room.Position.x + room.Size.x) + ", " + (room.Position.y + room.Size.y) + ")");

                        if (transform.position.x >= room.Position.x && transform.position.x <= room.Position.x + room.Size.x &&
                            -transform.position.y >= room.Position.y && -transform.position.y <= room.Position.y + room.Size.y
                            )
                        {
                            _currentRoom = room;
                            break;
                        }
                    }
                    // if _currentRoom is still null ... we are in the water !
                    if (_currentRoom == null)
                    {
                        // Debug.Log("  Still no room => aborting");
                        yield return(new WaitForSeconds(1f));
                    }
                }

                if (_currentAction == Action.Idle)
                {
                    // Debug.Log("  Currently Idle");

                    float actionChoice = Random.Range(0f, 1f);

                    if (actionChoice < 0.9f)
                    // 10% chance build a new room
                    {
                        // Debug.Log("    Will Build");
                        // go to building mode
                        // 1) choose a room from where to expand
                        List <(ARoom room, float weight)> choices = new List <(ARoom room, float weight)>();
                        foreach (ARoom room in MapManager.S.MapRooms)
                        {
                            if (room.RoomLeft == null || room.RoomRight == null)
                            {
                                choices.Add((room, (float)room.Position.x + 3 * room.Position.y));
                            }
                        }

                        // if there is room to expand
                        if (choices.Count > 0)
                        {
                            float total = 0;
                            foreach ((var _, var weight) in choices)
                            {
                                total += weight;
                            }

                            float choice = Random.Range(0f, total) - choices[0].weight;
                            int   i      = 0;
                            while (choice > 0f)
                            {
                                ++i;
                                choice -= choices[i].weight;
                            }

                            // i is the choosen room
                            _targetRoom = choices[i].room;
                            // 2) set the path to the target room
                            _roomPath = Astar.FindPath(_currentRoom, _targetRoom);
                            // Debug.Log("    Going to room (" + _targetRoom.Position.x + ", " + _targetRoom.Position.y + ") to build");
                            _currentAction = Action.Building;
                        }
                    }
                    else
                    {
                        // move to a random room
                        _targetRoom = MapManager.S.MapRooms[Random.Range(0, MapManager.S.MapRooms.Count)];
                        _roomPath   = Astar.FindPath(_currentRoom, _targetRoom);
                        // Debug.Log("    Going to room (" + _targetRoom.Position.x + ", " + _targetRoom.Position.y + ")");
                    }
                }
                else if (_currentAction == Action.Building)
                {
                    // Debug.Log("  Currently Building");
                    if (_roomPath.Count > 0)
                    {
                        // still moving
                        var room = _roomPath[0];
                        // Debug.Log("    Still Moving to (" + room.Position.x + ", " + room.Position.y + ")");
                        // Go to next room
                        MoveToRoom(room);
                        _roomPath.RemoveAt(0);
                    }
                    else
                    {
                        // Debug.Log("    Building Room/Corridor");
                        // We are at the building room
                        _targetRoom = null;
                        // now start building
                        if (_currentRoom is Corridor)
                        {
                            // Debug.Log("      In a corridor");
                            if (Random.Range(0f, 1f) < 0.75f)
                            // 75% expand corridor
                            {
                                // Debug.Log("        Expanding corridor");
                                // Debug.Log("          In the same direction");
                                ARoom corridor = null;
                                if (_currentRoom.RoomLeft != null)
                                // we are going from left to right
                                {
                                    corridor = MapManager.S.AddRoom(new Vector2Int(_currentRoom.Position.x + 1, _currentRoom.Position.y), new Vector2Int(1, 1), MapManager.S.Corridor, RoomType.CORRIDOR, _currentRoom, null, false);
                                }
                                else
                                // right to left
                                {
                                    corridor = MapManager.S.AddRoom(new Vector2Int(_currentRoom.Position.x - 1, _currentRoom.Position.y), new Vector2Int(1, 1), MapManager.S.Corridor, RoomType.CORRIDOR, _currentRoom, null, false);
                                }
                                _targetRoom = corridor;
                                _roomPath   = Astar.FindPath(_currentRoom, _targetRoom);
                            }
                            else
                            // 25% build a room
                            {
                                // Debug.Log("        Build a new room");
                                ARoom room = null;
                                if (_currentRoom.RoomLeft != null)
                                // we are going from left to right
                                {
                                    // Debug.Log("          To the right");
                                    room = MapManager.S.AddRoom(new Vector2Int(_currentRoom.Position.x + 1, _currentRoom.Position.y), new Vector2Int(2, 1), MapManager.S.ReceptionRoom, RoomType.EMPTY, _currentRoom, null, false);
                                }
                                else
                                // right to left
                                {
                                    // Debug.Log("          To the left");
                                    room = MapManager.S.AddRoom(new Vector2Int(_currentRoom.Position.x - 2, _currentRoom.Position.y), new Vector2Int(2, 1), MapManager.S.ReceptionRoom, RoomType.EMPTY, _currentRoom, null, false);
                                }
                                _currentAction = Action.Idle;
                                _targetRoom    = room;
                                _roomPath      = Astar.FindPath(_currentRoom, _targetRoom);
                            }
                        }
                        else
                        // not a corridor => we are in a room and we start a corridor
                        {
                            // Debug.Log("      In a room");
                            // Right/Left??
                            List <int> directions = new List <int>();
                            if (_currentRoom.RoomRight == null)
                            {
                                directions.Add(0);
                            }
                            if (_currentRoom.RoomLeft == null)
                            {
                                directions.Add(1);
                            }

                            if (directions.Count > 0)
                            {
                                // Debug.Log("        Building Corridor");
                                // choose one
                                int choice = directions[Random.Range(0, directions.Count)];
                                if (choice == 0)
                                // add to the right
                                {
                                    // Debug.Log("          to the right");
                                    var corridor = MapManager.S.AddRoom(new Vector2Int(_currentRoom.Position.x + _currentRoom.Size.x, _currentRoom.Position.y), new Vector2Int(1, 1), MapManager.S.Corridor, RoomType.CORRIDOR, _currentRoom, null, false);
                                    _targetRoom = corridor;
                                    _roomPath   = Astar.FindPath(_currentRoom, _targetRoom);
                                }
                                else
                                // add to the left
                                {
                                    // Debug.Log("          to the left");
                                    var corridor = MapManager.S.AddRoom(new Vector2Int(_currentRoom.Position.x - 1, _currentRoom.Position.y), new Vector2Int(1, 1), MapManager.S.Corridor, RoomType.CORRIDOR, _currentRoom, null, false);
                                    _targetRoom = corridor;
                                    _roomPath   = Astar.FindPath(_currentRoom, _targetRoom);
                                }
                            }
                        }
                    }
                }
                else if (_roomPath.Count > 0)
                {
                    // Debug.Log("  Currently Moving");
                    var room = _roomPath[0];
                    // Debug.Log("    to (" + room.Position.x + ", " + room.Position.y + ")");
                    // we are moving
                    MoveToRoom(room);
                    _roomPath.RemoveAt(0);
                }
                else
                {
                    // Debug.Log("  Currently Stopped Moving");
                    // we stopped moving ...
                    _targetRoom    = null;
                    _currentAction = Action.Idle;
                }
                // Debug.Log("ChooseAction End, starting anew ...");
                yield return(new WaitForSeconds(0.1f));
                // ChooseAction();
            }
        }