コード例 #1
0
    private void Start()
    {
        if (magicBook == null)
        {
            magicBook = FindObjectOfType <MagicBook> ();
        }

        if (currentMagicSlot == null)
        {
            currentMagicSlot = FindObjectOfType <CurrentMagicSlot> ();
        }

        tileMapManager = GameManager.Instance.tileMapManager;
        player         = GetComponent <Player> ();
        magicBook.OnMagicClickEvent   += MagicChange;
        currentMagicSlot.OnClickEvent += MagicInput;
        magicBook.MagicActionSet();
        magicMarker.gameObject.SetActive(false);

        if (currentMagic != null)
        {
            currentMagicSlot.Magic = currentMagic;
        }

        magicPoint = maxMagicPoint;

        GameManager.Instance.ActionOnTurn += TurnRegenMagicPoint;
    }
コード例 #2
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            //GraphicsDevice
            //engine components created
            tileMapM = new TileMapManager(this);
            audioM   = new AudioManager(this);
            inputM   = new InputManager(this);
            //engine helpers created

            textM = new TextManager(screenSize.Width);
            menuM = new MenuManager(this, textM);
            //create engine manager
            engineM = new EngineManager(this, tileMapM, eventM, textM, /*fontB,*/ audioM);
            //load manager
            loadM = new Loader(this);//, textureProcessor);
            //associate components with the game
            Components.Add(eventM);
            Components.Add(menuM);
            Components.Add(tileMapM);
            Components.Add(audioM);
            Components.Add(loadM);
            Components.Add(inputM);
            Components.Add(engineM);
            //add services for storage - disabled for now until missing component fix in place
            //Components.Add(new GamerServicesComponent(this));

            //create an event to handle exit command
            this.Exiting += new EventHandler <EventArgs>(GM_Exiting);

            base.Initialize();
        }
コード例 #3
0
    public override void Adjust()
    {
        targetList.Clear();
        int angle = caster.directionToCoordinate.GetAngle();

        foreach (Coordinate coord in searchArea.coordList)
        {
            Tile targetTile = TileMapManager.GetTile(coord.Rotate(angle) + caster.coordinate);
            if (targetTile != null)
            {
                if (targetTile.unit != null)
                {
                    targetList.Add(targetTile.unit);
                }
            }
        }
        foreach (Coordinate coord in searchArea.coordList)
        {
            Tile targetTile = TileMapManager.GetTile(coord.Rotate(angle) + caster.coordinate);
            if (targetTile != null)
            {
                targetTile.GetComponent <SpriteRenderer>().color = new Color32(255, 100, 100, 255);
            }
        }
        foreach (Effect effect in effectList)
        {
            effect.targetList = targetList;
            effect.Adjust();
        }
    }
コード例 #4
0
ファイル: GameManager.cs プロジェクト: SeaPHY/phy_game01
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }

        tileMapManager = GetComponent <TileMapManager> ();
        generator      = GetComponent <Generator> ();
        cameraMovement = gameObject.GetComponent <CameraMovement> ();
        uiManager      = gameObject.GetComponent <UIManager> ();

        if (GameObject.FindGameObjectWithTag("ItemDataBase") == null)
        {
            itemDataBase = Instantiate(itemDataBase, Vector3.zero, Quaternion.identity) as ItemDataParser;
        }
        else
        {
            itemDataBase = GameObject.FindGameObjectWithTag("ItemDataBase").GetComponent <ItemDataParser> ();
        }
    }
コード例 #5
0
ファイル: Unit.cs プロジェクト: solaris0115/HeroSnake
    public bool MoveToPosition(Coordinate coordinate)
    {
        Tile targetTile = TileMapManager.GetTile(coordinate);

        if (targetTile != null)
        {
            if (targetTile.unit == null)
            {
                TileMapManager.GetTile(this.coordinate).unit = null;
                transform.position = targetTile.transform.position;
                targetTile.unit    = this;
                this.coordinate    = coordinate;
                return(true);
            }
            else
            {
                Debug.Log("Can't Move There Position. Aready Unit exist (" + coordinate.x + "," + coordinate.y + ") - move");
                return(false);
            }
        }
        else
        {
            Debug.Log("There is NullTile (" + coordinate.x + "," + coordinate.y + ") - move");
            return(false);
        }
    }
コード例 #6
0
ファイル: MapGenerator.cs プロジェクト: solaris0115/HeroSnake
    // Use this for initialization
    void Start()
    {
        space = new mSpace(0, 0, width - 1, height - 1);
        map   = new Tree(space);

        map = map.splitmSpace(space, splitTime);

        tm = TileMapManager.Instance;
        tm.Initialize(width, height);

        //Debug.Log(tm.GetTile(1, 2));
        //Tile test;
        //test = tm.GetTile(1, 2);
        //test.SetGroundInfo(EGround.Wall);
        Tree temp = map;

        drawPath(map, PathType.Wall);
        makeRoom(temp);
        drawSplitedSpace(temp);
        drawPath(map, PathType.Path);


        //drawPathBlock(map.root.mx, map.root.my);
        //Debug.Log(GetSpaceFromTree(map).root.x);
    }
コード例 #7
0
ファイル: Program.cs プロジェクト: NullandKale/CRT
        public static void engineInit()
        {
            //savedata should start first
            saveData = new SaveDataManager();

            menuManager = new MenuManager();

            frameManager = new FrameManager();

            tileMapManager = new TileMapManager();

            uiManager = new UIManager();
            uiManager.AddMessage(new Message(0, 0, "no man was here. v0.1.1", ConsoleColor.White, ConsoleColor.Black), false);

            input = new InputManager();

            rayTracer = new RayTracer(frameManager.height, frameManager.width, 1, 3, 90, true);
            rayTracer.camera.doUpdate = true;
            rayTracer.ambientLight    = 0.075;

            worldManager = new WorldManager(200);

            frameManager.addLayer(tileMapManager);
            frameManager.addLayer(rayTracer);
            frameManager.addLayer(uiManager);
        }
コード例 #8
0
    //Called on initialization
    private void Awake()
    {
        //Setting the static reference
        if (globalReference == null)
        {
            globalReference = this;
        }
        else
        {
            Destroy(this);
            return;
        }

        //Initializing our list of visible tile objects
        this.visibleTileObjects = new Dictionary <TileInfo, GameObject>();

        //If we're starting a new game, we need to generate the map first
        if (GameData.globalReference.loadType == LevelLoadType.GenerateNewLevel)
        {
            //Determining which of the starting zones to generate
            int regionIndex = Mathf.RoundToInt(Random.Range(1, this.GetComponent <CreateMapRegions>().veryEasy.regions.Count)) - 1;

            this.CreateNewTileMap(this.GetComponent <CreateMapRegions>().veryEasy.regions[regionIndex]);
        }
        //If we're loading a previous game we let the SaveLoadManager handle it
        else
        {
            //Loading the tile grid using the SaveLoadManager
            SaveLoadManager.globalReference.LoadTileGrid(GameData.globalReference.saveFolder);
        }
    }
コード例 #9
0
 protected virtual void Start()
 {
     inverseMoveTime = 1f / moveTime;
     tileMapManager  = GameManager.Instance.tileMapManager;
     material        = GetComponentInChildren <MeshRenderer> ().material;
     Health          = maxHealth;
     isDead          = false;
     Shield          = 0;
 }
コード例 #10
0
ファイル: CameraMovement.cs プロジェクト: SeaPHY/phy_game01
 private void OnEnable()
 {
     mainCamera = Camera.main;
     mainCamera.transform.position = offset;
     tileMapManager = GameManager.Instance.tileMapManager;
     tileSize       = tileMapManager.tileSize;
     mainCamera.orthographicSize = 6 * tileSize;
     //GetMinMax ();
 }
コード例 #11
0
 void Awake()
 {
     if (_instance != null && _instance != this)
     {
         Destroy(this.gameObject);
     }
     else
     {
         _instance = this;
     }
 }
コード例 #12
0
    //Constructor function for this class
    public PlayerProgress(GameData gameData_, TileMapManager tileGrid_, LevelUpManager levelUpManager_, CharacterManager charManager_, QuestTracker questTracker_)
    {
        //Setting the GameData.cs variables
        this.difficulty          = gameData_.currentDifficulty;
        this.allowNewUnlockables = gameData_.allowNewUnlockables;
        this.folderName          = gameData_.saveFolder;
        this.randState           = Random.state;

        //Setting the CreateTileGrid.cs variables
        this.gridCols = tileGrid_.cols;
        this.gridRows = tileGrid_.rows;

        //Setting the HUDChallengeRampUpTimer.cs variables
        this.currentDifficulty      = HUDChallengeRampUpTimer.globalReference.currentDifficulty;
        this.currentDifficultyTimer = HUDChallengeRampUpTimer.globalReference.currentTimer;

        //Setting the LevelUpManager variable
        this.characterLevel = levelUpManager_.characterLevel;

        //Setting the PartyGroup.cs variables
        this.partyGroup1 = new PartySaveData(PartyGroup.globalReference);

        //Looping through all of the dead character info in CharacterManager.cs
        this.deadCharacters = new List <DeadCharacterInfo>();
        for (int d = 0; d < charManager_.deadCharacters.Count; ++d)
        {
            this.deadCharacters.Add(charManager_.deadCharacters[d]);
        }

        //Looping through all of the enemy tile encounters in CharacterManager.cs
        this.enemyTileEncounters = new List <EnemyTileEncounterInfo>();
        for (int e = 0; e < CharacterManager.globalReference.tileEnemyEncounters.Count; ++e)
        {
            //Making sure the encounter isn't null first
            if (CharacterManager.globalReference.tileEnemyEncounters[e] != null)
            {
                //Creating a new tile encounter info for the enemy
                EnemyTileEncounterInfo enemyInfo = new EnemyTileEncounterInfo(CharacterManager.globalReference.tileEnemyEncounters[e]);
                //Adding the enemy encounter info to our list to serialize
                this.enemyTileEncounters.Add(enemyInfo);
            }
        }

        //Looping through all of the quests in our quest log
        this.questLog = new List <string>();
        foreach (Quest q in questTracker_.questLog)
        {
            this.questLog.Add(JsonUtility.ToJson(new QuestSaveData(q), true));
        }

        //Saving all of the finished quest names
        this.finishedQuests = questTracker_.completedQuestNames;
    }
コード例 #13
0
ファイル: TestUnit.cs プロジェクト: solaris0115/HeroSnake
    void GiveDamageToPosition(Coordinate position, int damage)
    {
        Tile targetTile = TileMapManager.GetTile(position);

        if (targetTile != null)
        {
            if (targetTile.unit != null)
            {
                targetTile.unit.GetDamage(damage);
            }
        }
    }
コード例 #14
0
    void Start()
    {
        //Set the game managers instance to this so that we can access it statically
        GameManager.instance = this;

        //Initialise the item database
        ItemDatabase.LoadDatabase();

        //Load the map prefab and initialize it
        var prefab   = Resources.Load <GameObject>("Prefabs/TileMap");
        var instance = Instantiate(prefab);

        MapView = instance.GetComponent <ITileMapObject>();

        //create the map manager and pass it the map object
        MapManager = gameObject.AddComponent <TileMapManager>();
        MapManager.Initialize(MapView);

        selectionPrefab = Resources.Load <GameObject>("Prefabs/SelectedObject");
        //Initialize the starting state of the game
        StartGame();
    }
コード例 #15
0
ファイル: MapGenerator.cs プロジェクト: solaris0115/HeroSnake
    void drawSpace(mSpace target)
    {
        Tile test;

        //Debug.Log(target.x + " " + target.y + " " + target.w + " " + target.h);

        for (int i = 0; i < target.h + 1; i++)
        {
            for (int j = 0; j < target.w + 1; j++)
            {
                if (i == 0 || i == target.h || j == 0 || j == target.w)
                {
                    test = TileMapManager.GetTile(new Coordinate(target.x + j, target.y + i));
                    test.SetGroundInfo(E_Ground.Wall);
                }
                else
                {
                    test = TileMapManager.GetTile(new Coordinate(target.x + j, target.y + i));
                    test.SetGroundInfo(E_Ground.Ground);
                }
            }
        }
    }
コード例 #16
0
ファイル: MapGenerator.cs プロジェクト: solaris0115/HeroSnake
    void drawPathBlock(int x, int y, PathType type)
    {
        Tile test;

        if (type == PathType.Wall)
        {
            for (int i = -1; i < 2; i++)
            {
                for (int j = -1; j < 2; j++)
                {
                    if (i != 0 && j != 0)
                    {
                        test = TileMapManager.GetTile(new Coordinate(x + i, y + j));
                        test.SetGroundInfo(E_Ground.Wall);
                    }
                }
            }
        }
        else
        {
            test = TileMapManager.GetTile(new Coordinate(x, y));
            test.SetGroundInfo(E_Ground.Ground);
        }
    }
コード例 #17
0
 private void Start()
 {
     tileMapManager = GameManager.Instance.tileMapManager;
 }
コード例 #18
0
ファイル: Unit.cs プロジェクト: solaris0115/HeroSnake
    public void Dead()
    {
        TileMapManager.GetTile(coordinate).unit = null;

        Destroy(gameObject);
    }
コード例 #19
0
    /// <summary>
    /// Called from PopulateTileMap. Creates all locations tied to this region
    /// </summary>
    /// <param name="regionInfo_">The RegionInfo that contains all of the locations to spawn</param>
    private void SpawnLocations(RegionInfo regionInfo_)
    {
        //Reference to the TileMapManager for easy use
        TileMapManager tileMap = TileMapManager.globalReference;
        //A copy of our node list so we can make sure there are no duplicate spawns
        List <TileInfo> nodeListCopy = new List <TileInfo>();

        for (int copy = 0; copy < this.nodePoints.Count; copy++)
        {
            nodeListCopy.Add(this.nodePoints[copy]);
        }

        //Spawning the city
        int      spawnIndex = Mathf.RoundToInt(Random.Range(0, nodeListCopy.Count - 1));
        TileInfo spawnLoc   = nodeListCopy[spawnIndex];

        spawnLoc.decorationModel = regionInfo_.regionCity.gameObject;
        tileMap.cityTiles.Add(spawnLoc);
        nodeListCopy.RemoveAt(spawnIndex);

        //Spawning the dungeon
        spawnIndex = Mathf.RoundToInt(Random.Range(0, nodeListCopy.Count - 1));
        spawnLoc   = nodeListCopy[spawnIndex];
        spawnLoc.decorationModel = regionInfo_.regionDungeon.gameObject;
        tileMap.dungeonTiles.Add(spawnLoc);
        nodeListCopy.RemoveAt(spawnIndex);

        //Figuring out which of the locations to spawn
        List <int> locationsToSpawn = new List <int>();

        for (int l = 0; l < regionInfo_.locationList.Count; l++)
        {
            //Looping through each location to see how many times it should be spawned
            for (int s = 0; s < regionInfo_.locationList[l].maxNumber; s++)
            {
                //If our count is below the minimum number of instances, we add the location without rolling
                if (s < regionInfo_.locationList[l].minNumber)
                {
                    locationsToSpawn.Add(l);
                }
                //Otherwise we roll to see if this instance of the location should be spawned
                else
                {
                    float roll = Random.Range(0f, 1f);
                    if (roll < regionInfo_.locationList[l].spawnChance)
                    {
                        locationsToSpawn.Add(l);
                    }
                }
            }
        }

        //Spawning each of the locations
        for (int i = 0; i < locationsToSpawn.Count; i++)
        {
            spawnIndex = Mathf.RoundToInt(Random.Range(0, nodeListCopy.Count - 1));
            spawnLoc   = nodeListCopy[spawnIndex];
            spawnLoc.decorationModel = regionInfo_.locationList[locationsToSpawn[i]].location.gameObject;
            nodeListCopy.RemoveAt(spawnIndex);
        }
    }
コード例 #20
0
 void Awake()
 {
     Instance = this;
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: crone66/TileMapSystem
        static void Main(string[] args)
        {
            double         sum              = 0;
            double         sum2             = 0;
            double         sum3             = 0;
            long           inUse            = 0;
            int            iterations       = 1;
            int            updateIterations = 1;
            int            startX           = -627;
            int            startY           = -1;
            int            endX             = -627;
            int            endY             = 1;
            TileMapManager tileMapManager;

            for (int b = 0; b < iterations; b++)
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                GeneratorSettings settings = new GeneratorSettings(1, 50, 1.5f, 1000000, 10000000, true, 1000f);
                AreaSpread[]      spreads  = new AreaSpread[7]
                {
                    new AreaSpread(1, 1, 0.30f, 20, 250, true, true, 5, SpreadOption.Circle, LayerType.Height),
                    new AreaSpread(2, 1, 0.125f, 20, 200, true, true, 5, SpreadOption.Circle, LayerType.Height),
                    new AreaSpread(2, 0, 0.01f, 1, 2, false, false, 0, SpreadOption.None, LayerType.PointsOfInterest),
                    new AreaSpread(3, 0, 0.005f, 1, 2, false, false, 0, SpreadOption.None, LayerType.PointsOfInterest),
                    new AreaSpread(4, 0, 0.005f, 1, 2, false, false, 0, SpreadOption.None, LayerType.PointsOfInterest),
                    new AreaSpread(5, 0, 0.005f, 1, 2, false, false, 0, SpreadOption.None, LayerType.PointsOfInterest),
                    new AreaSpread(6, 0, 0.005f, 1, 2, false, false, 0, SpreadOption.None, LayerType.PointsOfInterest)
                };

                tileMapManager = new TileMapManager(settings, spreads);
                tileMapManager.Changelevel(settings, startX, startY, false);
                StreamedTileMap map = tileMapManager.CurrentLevel;

                watch.Stop();
                double seconds = watch.Elapsed.TotalSeconds;

                tileMapManager.Update(startY, startX);
                Tile[] screenMap = map.GetTileMapInScreen(800, 600);
                SaveToFile(screenMap, null, "screenMap" + b.ToString(), 800 / 50);


                watch.Restart();
                int counter = 0;
                for (int k = 0; k < 9; k++)
                {
                    counter += SaveToFile(map.Maps[k].MapSurface, map.Maps[k].ObjectPlacement, "map" + b.ToString() + "_" + k.ToString(), map.TileColumnCount);
                }

                watch.Stop();

                watch.Restart();
                tileMapManager.Update(endY, endX);
                watch.Stop();
                double update1 = watch.Elapsed.TotalSeconds;
                Thread.Sleep(5000); //wait for generation thread (only for debugging)


                watch.Restart();
                tileMapManager.Update(endY, endX);
                watch.Stop();
                double update2 = watch.Elapsed.TotalSeconds;

                for (int k = 0; k < 9; k++)
                {
                    counter += SaveToFile(map.Maps[k].MapSurface, map.Maps[k].ObjectPlacement, "map2_" + b.ToString() + "_" + k.ToString(), map.TileColumnCount);
                }

                Log("Tiles generated: " + counter.ToString());
                Log("Generation time: " + seconds.ToString() + " seconds");
                Log("Write time: " + watch.Elapsed.TotalSeconds.ToString() + " seconds");
                Log("Update1 time: " + update1.ToString() + " seconds");
                Log("Update2 time: " + update2.ToString() + " seconds");

                screenMap = map.GetTileMapInScreen(800, 600);
                SaveToFile(screenMap, null, "screenMap2_" + b.ToString(), 800 / 50);

                for (int i = 0; i < updateIterations; i++)
                {
                    watch.Restart();
                    tileMapManager.Update(endY - i, endX - i);
                    Tile[] data = map.GetTileMapInScreen(800, 600);
                    watch.Stop();
                    update2 = watch.Elapsed.TotalMilliseconds;
                    sum    += update2;
                    Log("Update time: " + update2.ToString() + " ms");
                    inUse += Process.GetCurrentProcess().PrivateMemorySize64;
                    Log("MemoryInUse: " + Process.GetCurrentProcess().PrivateMemorySize64.ToString() + " byte");
                }

                watch.Restart();
                tileMapManager.Update(startY, startX);
                watch.Stop();
                update2 = watch.Elapsed.TotalMilliseconds;
                sum2   += update2;
                Log("Update time: " + update2.ToString() + " ms");
                Thread.Sleep(2000);
                watch.Restart();
                tileMapManager.Update(startY, startX);
                watch.Stop();
                update2 = watch.Elapsed.TotalMilliseconds;
                sum3   += update2;
                Log("Update time: " + update2.ToString() + " ms");
                Log("Done");
            }
            Console.Clear();
            Log("Iterations: " + iterations.ToString());
            Log("UpdateIterations: " + (iterations * updateIterations).ToString());
            Log("Avg Update Time: " + (sum / (iterations * updateIterations)).ToString() + " ms");
            Log("Avg Update Time (Pre GridChange):" + (sum2 / iterations).ToString() + " ms");
            Log("Avg Update Time (GridChange):" + (sum3 / iterations).ToString() + " ms");
            Log("Avg MemoryInUse: " + (inUse / (iterations * updateIterations)).ToString() + " byte");
            Log("Final MemoryInUse: " + Process.GetCurrentProcess().PrivateMemorySize64.ToString() + " byte");

            MatchFiles();
            Console.ReadKey();
        }
コード例 #22
0
ファイル: Generator.cs プロジェクト: SeaPHY/phy_game01
 private void Start()
 {
     tileMapManager = GameManager.Instance.tileMapManager;
     GameManager.Instance.ActionOnTurn += ItemSpawn;
     itemIndex = 0;
 }
コード例 #23
0
        /// <summary>
        /// This constructs a path from the specified start point to
        /// some point in the set of destinations.
        ///
        /// Will only construct paths up to a certain maximum COST;
        /// as of now, going from one square to another costs 1 unit.
        /// So the maximum cost is the maximum path length.
        ///
        /// Returns null if no path was found.
        ///
        /// Running time (if no path is found, the worst case) is O(k+n^2), where
        ///        n=maxCost
        ///        k=destinations.Count
        ///
        /// Assumes no negative cost paths, as in Djikstra's algorithm
        /// </summary>
        /// <param name="startPoints">The set of start points we could be happy with.</param>
        /// <param name="goalPoints">The set of possible destinations we could be happy with.</param>
        /// <param name="maxCost">Maximum cost of any path.</param>
        /// <param name="manager">The WorldManager that we use to do our pathing.</param>
        /// <param name="startTime">The time we start the algorithm.  Use GameTime.TotalGameTime</param>
        /// <returns>The shortest path from here to somewhere in there; returns null iff there is no path of cost less than maxCost.</returns>
        public static Path GetPath <T, S, M>(HashSet <Point> startPoints, HashSet <Point> goalPoints, int maxCost, TileMapManager <T, S, M> manager, TimeSpan startTime)
            where T : InGameObject
            where S : MapCell, Copyable <S>
            where M : TileMap <S>, new()
        {
            //check for trivialities- we can't find a path to nowhere or from nowhere
            if (goalPoints.Count == 0 || startPoints.Count == 0)
            {
                return(null);
            }

            Heap <Path> heap = null;

            if (goalPoints.Count == 1)
            {
                heap = new PathToPointHeap(goalPoints.Single());
            }
            else
            {
                heap = new PathHeap();
            }


            //now set up a list of points we've seen before, so as to not
            //check the same position a billion times
            Dictionary <Point, int> bestDistancesFound = new Dictionary <Point, int>();

            foreach (Point startPoint in startPoints)
            {
                bestDistancesFound[startPoint] = 0;
                heap.Add(new Path(startPoint));

                if (goalPoints.Contains(startPoint))
                {
                    return(new Path(startPoint));
                }
            }

            while (heap.Count > 0)
            {
                //if there's new passability information, start the process over
                if (manager.LastGeneralPassabilityUpdate != null && //if it's null, we're definitely OK
                    startTime < manager.LastGeneralPassabilityUpdate)
                {
                    startTime = manager.LastGeneralPassabilityUpdate;

                    heap.Clear();
                    bestDistancesFound = new Dictionary <Point, int>();

                    foreach (Point startPoint in startPoints)
                    {
                        bestDistancesFound[startPoint] = 0;
                        heap.Add(new Path(startPoint));
                    }
                }

                Path bestPath = heap.Pop();

                //if we didn't cap out our path length yet,
                //check out the adjacent points to form longer paths
                if (bestPath.Cost < maxCost)
                {
                    int newCost = bestPath.Cost + 1;

                    //for each possible extension ...
                    foreach (Point adj in manager.GetAdjacentPoints(bestPath.End.X, bestPath.End.Y))
                    {
                        //if we hit a destination, great, stop
                        if (goalPoints.Contains(adj))
                        {
                            return(new Path(bestPath, adj, newCost));
                        }

                        //don't bother adding this possible extension back on unless
                        //it's either a completely new point or a strict improvement over another path
                        if (bestDistancesFound.Keys.Contains(adj) && bestDistancesFound[adj] <= newCost)
                        {
                            continue;
                        }

                        //otherwise, this is a perfectly serviceable path extension and we should look into it
                        bestDistancesFound[adj] = newCost;

                        heap.Add(new Path(bestPath, adj, newCost));
                    }
                }
            }

            return(null);
        }
コード例 #24
0
        /// <summary>
        /// This constructs a path from the specified start point to
        /// some point in the set of destinations.
        ///
        /// Will only construct paths up to a certain maximum COST;
        /// as of now, going from one square to another costs 1 unit.
        /// So the maximum cost is the maximum path length.
        ///
        /// Returns null if no path was found.
        ///
        /// Running time (if no path is found, the worst case) is O(k+n^2), where
        ///        n=maxCost
        ///        k=destinations.Count
        ///
        /// Assumes no negative cost paths, as in Djikstra's algorithm
        /// </summary>
        /// <param name="startPoint">The point we start from.</param>
        /// <param name="goalPoints">The set of possible destinations we could be happy with.</param>
        /// <param name="maxCost">Maximum cost of any path.</param>
        /// <param name="manager">The WorldManager that we use to do our pathing.</param>
        /// <param name="startTime">The time we start the algorithm.</param>
        /// <returns>The shortest path from here to somewhere in there; returns null iff there is no path of cost less than maxCost.</returns>
        public static Path GetPath <T, S, M>(Point startPoint, HashSet <Point> goalPoints, int maxCost, TileMapManager <T, S, M> manager, TimeSpan startTime)
            where T : InGameObject
            where S : MapCell, Copyable <S>
            where M : TileMap <S>, new()
        {
            HashSet <Point> startPoints = new HashSet <Point>();

            startPoints.Add(startPoint);

            return(GetPath(startPoints, goalPoints, maxCost, manager, startTime));
        }
コード例 #25
0
 /// <summary>
 /// This constructs a path from the specified start point to
 /// some point in the set of destinations.
 ///
 /// Will only construct paths up to a certain maximum COST;
 /// as of now, going from one square to another costs 1 unit.
 /// So the maximum cost is the maximum path length.
 ///
 /// Returns null if no path was found.
 ///
 /// Running time (if no path is found, the worst case) is O(k+n^2), where
 ///        n=maxCost
 ///        k=destinations.Count
 ///
 /// Assumes no negative cost paths, as in Djikstra's algorithm
 /// </summary>
 /// <param name="startPoint">The point we start from.</param>
 /// <param name="goalPoints">The set of possible destinations we could be happy with.</param>
 /// <param name="maxCost">Maximum cost of any path.</param>
 /// <param name="manager">The WorldManager that we use to do our pathing.</param>
 /// <param name="startTime">The time we start the algorithm.</param>
 /// <returns>The shortest path from here to somewhere in there; returns null iff there is no path of cost less than maxCost.</returns>
 public static Path GetPath <T, S, M>(Point startPoint, HashSet <Point> goalPoints, int maxCost, TileMapManager <T, S, M> manager, GameTime startTime)
     where T : InGameObject
     where S : MapCell, Copyable <S>
     where M : TileMap <S>, new()
 {
     return(PathHunter.GetPath <T, S, M>(startPoint, goalPoints, maxCost, manager, startTime.TotalGameTime));
 }
コード例 #26
0
    public void Move(E_Direction direction)
    {
        leader.direction = direction;

        Coordinate nextPosition;

        switch (direction)
        {
        case E_Direction.Up:
            nextPosition = new Coordinate(0, 1);
            break;

        case E_Direction.Left:
            nextPosition = new Coordinate(-1, 0);
            break;

        case E_Direction.Down:
            nextPosition = new Coordinate(0, -1);
            break;

        case E_Direction.Right:
            nextPosition = new Coordinate(1, 0);
            break;

        default:
            nextPosition = new Coordinate(0, 0);
            break;
        }
        Coordinate resultPosition = leader.coordinate;
        TraceInfo  traceInfo      = new TraceInfo(direction, leader.coordinate);

        for (int point = 1; point <= leader.movePoint; point++)
        {
            Tile t = TileMapManager.GetTile(nextPosition * point + leader.coordinate);
            if (t != null)
            {
                //이동 가능한지 확인구간
                if (t.unit == null)
                {
                    traceInfo      = new TraceInfo(direction, resultPosition);
                    resultPosition = nextPosition * point + leader.coordinate;
                    AddTrace(traceInfo);
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        leader.MoveToPosition(resultPosition);

        for (int index = 0; index < memberList.Count; index++)
        {
            if (positionTrace.Count - 1 >= index)
            {
                memberList[index].MoveToPosition(positionTrace[index].coordinate);
                memberList[index].direction = positionTrace[index].direction;
            }
            else
            {
                break;
            }
        }
        //문제 발생 가능함. 리더의 밀쳐지기 혹은 급작스런 이동시.
    }