예제 #1
0
    void SetTarget_Local(MapManager.NavPoint point)
    {
        moveRode = null;
        objSign.SetActive(true);
        objSign.transform.position = new Vector3(point.col, 0, point.row);
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();
        switch (navType)
        {
        case NavLibrary.Algorithm.DFS:
            moveRode = DFS.Navigation(currentPoint, point);
            break;

        case NavLibrary.Algorithm.BFS:
            moveRode = BFS.Navigation(currentPoint, point);
            break;

        case NavLibrary.Algorithm.A_Star:
            moveRode = A_Star.Navigation(currentPoint, point);
            break;

        default:
            moveRode = null;
            break;
        }
        stopWatch.Stop();
        MainView.Instance.RefreshInfo(point.row, point.col, stopWatch.Elapsed.TotalMilliseconds);
        Debug.Log("Cost Time: " + stopWatch.Elapsed.TotalMilliseconds);
        if (!IsMoving)
        {
            MoveToNextPoint_Local();
        }
    }
예제 #2
0
 //TODO List of commands needed to be implemented for the units
 public BasicUnit(string name, Vector2 size, float totalHealth, float currentHealth, Vector2 position, BaseUnitState state, TextureValue texture, Color color, TextureValue icon, float range, Stats teamStats) : base(texture, position, teamStats, color)
 {
     Cost      = new Wallet();// TODO charge for units
     this.name = name;
     this.Size = size;
     stats.Add(new Health("Health", totalHealth));
     stats.Add(new Range("Range", range));
     this.CurrentHealth = currentHealth;
     this.UnitState     = state;
     Direction          = new Vector2(0, 0);
     speed     = 0;
     this.Icon = icon;
     aStar     = new A_Star();
     waypoints = new List <Vector2>();
     zero      = Vector2.Zero;
     xOne      = new Vector2(1, 0);
     yOne      = new Vector2(0, 1);
     speed     = 50;
     nextPoint = Position;
     UnitState = BaseUnitState.Idle;
     if (teamStats != null)
     {
         attack = new Melee(stats[typeof(Range)].Value + teamStats[typeof(Range)].Value);
     }
     else
     {
         attack = new Melee(stats[typeof(Range)].Value);
     }
     this.teamStats = teamStats;
 }
예제 #3
0
    IEnumerator InitMap()
    {
        gridObjs = new Grid[mapData.Heigh][];
        for (int i = 0; i < mapData.Heigh; i++)
        {
            gridObjs[i] = new Grid[mapData.Width];
            for (int j = 0; j < mapData.Width; j++)
            {
                GameObject _obj = new GameObject(i.ToString());
                _obj.transform.SetParent(transform);
                _obj.transform.localScale    = Vector3.one;
                _obj.transform.localPosition = Vector2.zero;
                _obj.name = i + "_" + j;
                Grid grid = _obj.AddComponent <Grid> ();
                grid.data         = new GridData(i, j);
                grid.data.CurGrid = grid;
                gridObjs[i][j]    = grid;
            }
        }

        for (int i = 0; i < 100; i++)
        {
            int y = Random.Range(0, mapData.Width - 1);
            int x = Random.Range(0, mapData.Heigh - 1);
            gridObjs[x][y].data.gType = GridType.Wall;
        }

        yield return(1);

        aStar             = new A_Star(gridObjs);
        curPlayer.curGrid = gridObjs[0][0];
        curPlayer.Refish();
    }
 protected override void ThreadFunction()
 {
     //Lock the threaded function, this forces the threads to wait for eachother so they don't try to alter the grid at the same time
     lock (m_Lock)
     {
         A_Star aStar = new A_Star();
         m_Result = aStar.FindVectorPath (m_CurrentTile, m_TargetTile, m_BlockingLevel);
     }
 }
예제 #5
0
 protected override void ThreadFunction()
 {
     //Lock the threaded function, this forces the threads to wait for eachother so they don't try to alter the grid at the same time
     lock (m_Lock)
     {
         A_Star aStar = new A_Star();
         m_Result = aStar.FindVectorPath(m_CurrentTile, m_TargetTile, m_BlockingLevel);
     }
 }
    // Use this for initialization
    private void Start()
    {
        Graph  graph = new Graph();
        A_Star astar = new A_Star();

        Node node0  = graph.GetNodes()[0];
        Node node8  = graph.GetNodes()[7];
        Node node24 = graph.GetNodes()[24];

        this.OutputPaths(astar.Search(node0, node24));
    }
예제 #7
0
    /// <summary>
    /// 移動発生のクリックか
    /// </summary>
    void CheckMove()
    {
        Vector2I Pos = GetMouseEnablePos();

        if (Pos != null)
        {
            GoalPos = Pos.Clone();
            Vector2I GoalPos2 = Pos.Clone();

            EventPart findEvent = EventList.Find(i => i.Pos == GoalPos);

            if (findEvent != null)
            {
                if (findEvent.IsClickEvent())
                {
                    GoalPos2 = findEvent.SubPos.Clone();
                }
            }

            // ルート検索
            List <Vector2I> _PathList;

            bool result = A_Star.SearchPath(Grids, NowPos, GoalPos2, out _PathList);

            if (result == false)
            {
                return;
            }

            if (_PathList.Count <= 0)
            {
                return;
            }

            PathList = _PathList;

            if (result)// ルートあり、移動する
            {
                NextPos = PathList[0];
                PathList.RemoveAt(0);

                // 移動指示
                Player.ReqAutoMoving(NextPos.X, NextPos.Y, new ReportEndHandler(OnMoveEnd));

                NowMoveing = true;
            }
        }
    }
예제 #8
0
    // Start is called before the first frame update
    private void Start()
    {
        Graph  graph = new Graph();
        A_Star astar = new A_Star();

        Node node0  = graph.GetNodes()[0];
        Node node8  = graph.GetNodes()[7];
        Node node24 = graph.GetNodes()[24];

        this.paths = new List <Node>();
        this.paths = astar.Search(node0, node24);

        this.currentPosition = new Vector2(paths[this.index].GetX(), paths[this.index].GetZ());
        this.nextPosition    = new Vector2(paths[this.index + 1].GetX(), paths[this.index + 1].GetZ());

        //this.OutputPaths(paths);

        StartCoroutine(this.OnMovement());
    }
예제 #9
0
    void Start()
    {
        IsMove  = false;
        mapData = new MapStruct()
        {
            Width = 30,
            Heigh = 15,
        };
        layout    = GetComponent <GridLayoutGroup> ();
        rectTrans = GetComponent <RectTransform> ();
        layout.constraintCount = mapData.Width;
        layout.cellSize        = new Vector2(rectTrans.rect.size.x / mapData.Width, rectTrans.rect.size.y / mapData.Heigh);

        StartCoroutine(InitMap());

        Dispatcher.RegisterProtocalListener("clickGrid", (o) => {
            Grid end = o[0] as Grid;
            curPlayer.curGrid.data.nextPoint = null;
            curPlayer.curGrid.data.lastPoint = null;
            end.data.nextPoint = null;
            end.data.lastPoint = null;

            A_Star a = new A_Star(gridObjs);
            a.FindPath(curPlayer.curGrid, end, false);
            curPlayer.curGrid = end;

            GridData cur = end.data;
            while (cur.lastPoint != null)
            {
                cur.lastPoint.nextPoint = cur;
                cur = cur.lastPoint;
            }

            while (cur != null)
            {
                cur.CurGrid.SetColor();
                curPlayer.queue.Enqueue(cur);
                cur = cur.nextPoint;
            }
            IsMove = true;
        });
    }
    void Initialize()
    {
        Initalized = true;
        ResetNeighbourList();
        switch (algo)           //when i add future algorithms.
        {
        case Algo.BFS:
            BFSObject = new BFS(Map.RetMap(), Map.RetMapSize());
            break;

        case Algo.A_Star:
            ASObject = new A_Star(Map.RetMap(), Map.RetMapSize());
            break;

        case Algo.DFS:
            DFSObject = new DFS(Map.RetMap(), Map.RetMapSize());
            break;

        case Algo.Dijikstra:
            djkObject = new Dijikstra(Map.RetMap(), Map.RetMapSize());
            break;
        }
    }
예제 #11
0
    private void SetAgent(Node s, Node e)
    {
        GameObject obj = (GameObject)Resources.Load("space_man_player");

        if (obj != null)
        {
            GameObject agent = GameObject.Instantiate(obj);
            if (agent != null)
            {
                agent.transform.localPosition = CoordToPosition(s.X, s.Y);

                A_Star a_Star = agent.GetComponent <A_Star>();
                if (a_Star != null)
                {
                    a_Star.StartNode   = s;
                    a_Star.EndNode     = e;
                    a_Star.MapInfoList = AllNodeList;
                    a_Star.MapW        = (int)mapSize.x;
                    a_Star.MapH        = (int)mapSize.y;
                }
            }
        }
    }
예제 #12
0
 private void Start()
 {
     CreateGrid();
     a = GetComponent <A_Star>();
 }
예제 #13
0
    public void Set_Manager(GameManager gamemanager)  //Awake에 해당한다. 시작시 호출
    {
        this.GameManager = gamemanager;
        PlayerManager    = GameManager.PlayerManager; //게임 매니저로 부터 Manager를 받아온다
        CameraManager    = GameManager.CameraManager;

        ShadowCast = new ShadowCast(this); //전장의 안개
        A_Star     = new A_Star(this);     //A*알고리즘
        MapPattern = new MapPattern(this); //맵 패턴 함수
        MapHightLight.Set_Map(this);
        Tile_Event.Set_Map(this);

        VisibleOctants = new List <int>()
        {
            1, 2, 3, 4, 5, 6, 7, 8
        };
        Map_Gimmick_List = new List <GameObject>();
        Pooling_Count    = 15;
        Tiles            = new Tile_Obj[Pooling_Count, Pooling_Count];
        MapSize          = 64;
        VisualRange      = 5;
        roomMin          = 6;
        roomMax          = 13;

        if (GameManager.Get_GameData() != null)    //게임 데이터가 있을때 Load 해준다
        {
        }
        else                    //게임 데이터가 없을때 시작
        {
            Current_Stage = 1;
            MapData       = new Tile[MapSize + 1, MapSize + 1];
            RoomData_List = new List <RoomData>();

            BuildMap();                     //맵 정보 생성
        }

        for (int i = 0; i < Pooling_Count; i++)                //풀링 Object 할당
        {
            for (int j = 0; j < Pooling_Count; j++)
            {
                Tiles[i, j] = Tile_Objs.transform.GetChild(Get_Array_Count(i, j)).GetComponent <Tile_Obj>();
                Tiles[i, j].Set_Tile(this, new Array_Index(i, j));
            }
        }

        //while(GetTile(6, 6).Tile_Sort.TileBase == eTileBase.NULL ||
        //    GetTile(57, 57).Tile_Sort.TileBase == eTileBase.NULL ||
        //    GetTile(6, 6).Tile_Sort.TileObject == eTileObject.WALL ||
        //    GetTile(57, 57).Tile_Sort.TileObject == eTileObject.WALL)
        //{
        //    MapData = new Tile[MapSize + 1, MapSize + 1];


        //    BuildMap();
        //}



        //Update_TT();
        Update_Sight();
        Update_Tiles();                   //맵 정보를 기반으로 Tile 업데이트
        MapTarget.Set_Map(this);
        //link();
    }
예제 #14
0
        /// <summary>
        /// This is the starting point of the program.
        /// </summary>
        static void Main(string[] args)
        {
            Program me = new Program();

            Program.RESULTS_FILE_NAME = Process.GetCurrentProcess().ProcessName + ".csv";
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Constants.MAX_TIME = int.MaxValue;
                Debug.WriteLine("Debugger attached - running without a timeout!!");
            }

            if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "Instances")) == false)
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "Instances"));
            }

            Program.onlyReadInstances = false;

            int instances = 100;

            bool runGrids         = false;
            bool runDragonAge     = false;
            bool runMazesWidth1   = false;
            bool runSpecific      = false;
            bool runPaperProblems = false;
            bool runPaperProblemsIncrementally = false;  // Turn on for CA*

            if (runGrids == true)
            {
                //int[] gridSizes = new int[] { 8, };
                //int[] agentListSizes = new int[] { 2, 3, 4 };

                //int[] gridSizes = new int[] { 6, };
                //int[] agentListSizes = new int[] { /*2,*/ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 };
                // Note that success rate drops almost to zero for EPEA* and A*+OD/SIC on 40 agents.

                int[] gridSizes = new int[] { 20, };
                //int[] agentListSizes = new int[] { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, /*60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150*/ };
                int[] agentListSizes = new int[] { 40, 60, 80, 100 };

                //int[] obstaclesPercents = new int[] { 20, };
                //int[] obstaclesPercents = new int[] { /*0, 5, 10, 15, 20, 25, 30, 35, */20, 30, 40};
                int[] obstaclesPercents = new int[] { /*0, 5, 10,*/ 15, /*20, 25, 30, 35, 20, 30, 40*/ };
                me.RunExperimentSet(gridSizes, agentListSizes, obstaclesPercents, instances);
            }
            else if (runDragonAge == true)
            {
                me.RunDragonAgeExperimentSet(instances, Program.daoMapPaths); // Obstacle percents and grid sizes built-in to the maps.
            }
            else if (runMazesWidth1 == true)
            {
                me.RunDragonAgeExperimentSet(instances, Program.mazeMapPaths); // Obstacle percents and grid sizes built-in to the maps.
            }
            else if (runSpecific == true)
            {
                ProblemInstance instance;
                try
                {
                    if (args[0].EndsWith(".dll"))
                    {
                        instance = ProblemInstance.Import(args[2], args[1]);
                    }
                    else
                    {
                        instance = ProblemInstance.Import(args[1], args[0]);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Bad problem instance {args[1]}. Error: {e.Message}");
                    return;
                }
                Run runner = new Run();  // instantiates stuff unnecessarily
                runner.startTime = runner.ElapsedMillisecondsTotal();

                IHeuristicCalculator <WorldState> lowLevelHeuristic = new SumIndividualCosts();
                List <uint> agentList = Enumerable.Range(0, instance.agents.Length).Select(x => (uint)x).ToList(); // FIXME: Must the heuristics really receive a list of uints?
                lowLevelHeuristic.Init(instance, agentList);
                ICbsSolver lowLevel = new A_Star(lowLevelHeuristic);
                ILazyHeuristic <CbsNode> highLevelHeuristic = new MvcHeuristicForCbs();
                highLevelHeuristic.Init(instance, agentList);
//                ISolver solver = new CBS(lowLevel, lowLevel,
//                    bypassStrategy: CBS.BypassStrategy.FIRST_FIT_LOOKAHEAD,
//                    conflictChoice: CBS.ConflictChoice.CARDINAL_MDD,
//                    heuristic: highLevelHeuristic,
//                    cacheMdds: true,
//                    useOldCost: true,
//                    replanSameCostWithMdd: true
//                );
                //ISolver solver = new IndependenceDetection(lowLevel, new EPEA_Star(lowLevelHeuristic));
                //ISolver solver = new IndependenceDetection(lowLevel, new CostTreeSearchSolverOldMatching(3));
                ISolver solver = new IndependenceDetection(lowLevel, new A_Star_WithOD(lowLevelHeuristic));
                solver.Setup(instance, runner);
                bool solved = solver.Solve();
                if (solved == false)
                {
                    Console.WriteLine("Failed to solve");
                    return;
                }
                Plan plan = solver.GetPlan();
                plan.PrintPlan();
                //me.RunInstance("Instance-5-15-3-792");
                //me.RunInstance("Instance-5-15-3-792-4rows");
                //me.RunInstance("Instance-5-15-3-792-3rows");
                //me.RunInstance("Instance-5-15-3-792-2rows");
                //me.RunInstance("corridor1");
                //me.RunInstance("corridor2");
                //me.RunInstance("corridor3");
                //me.RunInstance("corridor4");
                return;
            }
            else if (runPaperProblems)
            {
                foreach (var dirName in scenDirs)
                {
                    foreach (var scenPath in Directory.GetFiles(dirName))
                    {
                        var problem = ProblemInstance.Import(scenPath);
                        foreach (var numAgents in Enumerable.Range(1, problem.agents.Length))
                        {
                            var subProblem = problem.Subproblem(problem.agents.Take(numAgents).ToArray());
                            // don't create a subproblem, just feed time adding one agent and report the sum of times so far
                            Run runner = new Run();
                            using (runner)
                            {
                                bool resultsFileExisted = File.Exists(RESULTS_FILE_NAME);
                                runner.OpenResultsFile(RESULTS_FILE_NAME);
                                if (resultsFileExisted == false)
                                {
                                    runner.PrintResultsFileHeader();
                                }
                                bool success = runner.SolveGivenProblem(subProblem);
                                if (success == false)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            else if (runPaperProblemsIncrementally)
            {
                foreach (var dirName in scenDirs)
                {
                    foreach (var scenPath in Directory.GetFiles(dirName))
                    {
                        var problem             = ProblemInstance.Import(scenPath);
                        CooperativeAStar castar = new CooperativeAStar();
                        Run runner = new Run();
                        using (runner)
                        {
                            bool resultsFileExisted = File.Exists(RESULTS_FILE_NAME);
                            runner.OpenResultsFile(RESULTS_FILE_NAME);
                            if (resultsFileExisted == false)
                            {
                                runner.PrintResultsFileHeader();
                            }
                            runner.SolveGivenProblemIncrementally(problem);
                        }
                    }
                }
            }

            // A function to be used by Eric's PDB code
            //me.runForPdb();
            Console.WriteLine("*********************THE END**************************");
            Console.ReadLine();
        }