Example #1
0
        public void ReadMap()
        {
            if (reader == null)
                throw new NullReferenceException("BinaryReader null!");
            tilemap = new Tile[metaFile.WorldSizeInBlocks.Y, metaFile.WorldSizeInBlocks.X];
            int worldSize = ((Convert.ToInt32(metaFile.WorldSizeInBlocks.X)) * (Convert.ToInt32(metaFile.WorldSizeInBlocks.Y)));

            int count = 0;
            while(count < worldSize)
            {
                string tileRead = reader.ReadString();
                string[] split = tileRead.Split(new char[] { ';' }, 4);
                int x, y;
                bool isBg = bool.Parse(split[3]);
                x = (int)Math.Floor((double)Int32.Parse(split[1]) / 32);
                y = (int)Math.Floor((double)Int32.Parse(split[2]) / 32);
                string tileDataName = split[0];

                Tile t = PresetBlocks.TilesList.Find(srch => srch.Name == split[0].Trim()).AsTile();
                t.Position = new Vector2(x * 32, y * 32);

                if (y > tilemap.GetLength(0))
                    continue;
                if (x > tilemap.GetLength(1))
                    continue;

                tilemap[y, x] = t;
                count++;
            }

            reader.Close();
            reader.Dispose();
        }
Example #2
0
        public static void Initialize(ContentManager content)
        {
            map1 = new Tile[20, 12];
            for(int i = 0; i < map1.GetLength(0); i++)
            {
                for (int j = 0; j < map1.GetLength(1); j++)
                {
                    if (Globals.Randomizer.Next(100) <= 90) { map1[i, j] = new Tile(TextureManager.block, Tile.Type.Ground, new Rectangle(0, 0, 32, 32), 0, false); }
                    else { map1[i, j] = new Tile(TextureManager.block, Tile.Type.Bomb, new Rectangle(0, 0, 32, 32), 0, false); }
                    map1[i, j].Hitbox = new Rectangle(i * 32, j * 32, 32, 32);
                }
            }

            for (int i = 0; i < map1.GetLength(0); i++)
            {
                for (int j = 0; j < map1.GetLength(1); j++)
                {
                    for (int k = -1; k < 2; k++)
                    {
                        for (int l = -1; l < 2; l++)
                        {
                            if (i + k >= 0 && i + k < map1.GetLength(0) && j + l >= 0 && j + l < map1.GetLength(1) && map1[i + k, j + l].type == Tile.Type.Bomb)
                            {
                                map1[i, j].AdjacentBombs++;
                            }
                        }
                    }
                }
            }
        }
Example #3
0
        public void ReadMap()
        {
            if (reader == null)
                    throw new NullReferenceException("BinaryReader null!");

                string sizeRead = reader.ReadString();
                string[] split = sizeRead.Split(new char[] { '=', 'x' });
                int worldSize = ((Convert.ToInt32(split[1])) * (Convert.ToInt32(split[2])));
                tilemap = new Tile[int.Parse(split[1]), int.Parse(split[2])];

                int count = 0;
                while (count < worldSize)
                {
                    string tileRead = reader.ReadString();
                    string[] split2 = tileRead.Split(new char[] { ';' }, 4);
                    int x, y;
                    bool isBg = bool.Parse(split2[3]);
                    x = (int)Math.Floor((double)Int32.Parse(split2[1]) / 32);
                    y = (int)Math.Floor((double)Int32.Parse(split2[2]) / 32);
                    string tileDataName = split2[0];
                    Tile t = new Tile { Name = split2[0].Trim(), BackgroundTile = isBg, X = x * 32, Y = y * 32 };
                    if (y > tilemap.GetLength(0))
                        continue;
                    if (x > tilemap.GetLength(1))
                        continue;
                    tilemap[y, x] = t;

                    count++;
                }
                reader.Close();
                reader.Dispose();
        }
Example #4
0
        public Level(IntVec startPoint, Tile[,] tiles, GridBoundList<IEnvironmentObject> environment, GridBoundList<IInteractable> interact, GridBoundList<ILightSource> light, GridBoundList<GameCharacter> characterEntities, int dungeonLevel)
        {
            this.tiles = tiles;
            this.startPoint = startPoint;
            this.Environment = environment;
            this.InteractableEnvironment = interact;
            this.CharacterEntities = characterEntities;
            this.LightSources = light;
            this.DroppedItems = new GridBoundList<Item>();
            this.DungeonLevel = dungeonLevel;
            calculateTiles();
            needToCache = true;
            cachedSolid = new bool[tiles.GetLength(0), tiles.GetLength(1)];

            a = GetStartPoint();
            b = findRandomOpenPosition();
            path = AStar.getPathBetween(this, a, b);
            moveset = AStar.getPossiblePositionsFrom(this, a, 15,false,false);

            for (int i = 0; i < 28; i++)
            {
                //Item item = Item.randomItem(10, 10);

                //Engine.Engine.Log(string.Format("Item Generated: {0}", item.Name));

                //DroppedItems.Add(item, findRandomOpenPosition());
            }
        }
Example #5
0
 public MapBoundsForm(StarEdit.LevelEditor.LevelWorker.TileOverLoad poverloader,Tile[,] oldTiles)
 {
     InitializeComponent();
     overloader = poverloader;
     oldtiles = oldTiles;
     SizeXBox.Value = oldtiles.GetLength(1);
     SizeYBox.Value = oldtiles.GetLength(0);
 }
 public Map(int width, int height, char[,] charMap)
 {
     tileMap = new Tile[width, height];
     for (int y = 0; y < tileMap.GetLength(0); y++)
     {
         for (int x = 0; x < tileMap.GetLength(0); x++)
             tileMap[x, y] = new Tile(x * Tile.SIZE, y * Tile.SIZE, Globals.tileTable.Get(charMap[x, y]));
     }
 }
Example #7
0
 public Map(Tile[,] tiles)
 {
     this.tiles = tiles;
     _width = tiles.GetLength(0);
     _height = tiles.GetLength(1);
     this.tiles[1, 1].SetType(Tile.BlockName.Grass);
     this.tiles[Width - 2, 1].SetType(Tile.BlockName.Grass);
     this.tiles[Width-2, Height-2].SetType(Tile.BlockName.Grass);
     this.tiles[1, Height-2].SetType(Tile.BlockName.Grass);
 }
Example #8
0
	private Tile[,] grid; //a 2D array representing the tilemap

	public void CreateColliders(Vector2 mapSize) {
		if (!dirtyColliders) {
			return;
		}
		dirtyColliders = false;

		collider.pathCount = 0;

		List<Transform> solids = new List<Transform>();
		foreach (Transform child in transform) {
			if (child.gameObject.tag == "Wall") {
				solids.Add(child);
			}
		}

		Vector2[] tiles = new Vector2[solids.Count];
		grid = new Tile[(int)mapSize.x, (int)mapSize.y];

		for (int i = 0; i < solids.Count; i++) {
			tiles[i] = solids[i].transform.localPosition;
			tiles[i].y = -tiles[i].y; //flip negative y values
			grid[(int)tiles[i].x, (int)tiles[i].y].occupied = true;
		}

		//find tiles that form walls

		foreach (Vector2 tile in tiles) {
			//if its upper tile is unoccupied:
			//if it is unmarked:
			//start the bug algorithm
			if (marked((int)tile.x, (int)tile.y) == false && occupied((int)tile.x, (int)tile.y-1) == false) { //if bug is facing right and upper tile is empty
				BugAlgorithm((int)tile.x, (int)tile.y);
			}
		}

		if (debug) {
			string debugString = "";
			for (int y = 0; y < grid.GetLength(1); y++) {
				for (int x = 0; x < grid.GetLength(0); x++) {
					if (grid[x, y].occupied) {
						if (grid[x, y].marked) {
							debugString += "M";
						} else {
							debugString += "T";
						}
					} else {
						debugString += "X";
					}
					debugString += ", ";
				}
				debugString += "\n";
			}
			UnityEngine.Debug.Log(debugString);
		}
	}
Example #9
0
File: _GM.cs Project: James510/SRPG
 void Start()
 {
     map = new Tile[16,10];
     for(int u=0;u<map.GetLength(0);u++){
         for(int v=0;v<map.GetLength(1);v++){
             map[u,v]=new Tile(new FriendlyUnit(4),false);
         }
     }
     Debug.Log (map[4,4].SayHi());
     map[6,8].getUnit().sayHi();
 }
Example #10
0
 public Zone(TileWorld world)
 {
     tileMap = new Tile[TileWorld.ZoneSize, TileWorld.ZoneSize];
     for (int y = 0; y < tileMap.GetLength(0); ++y)
     {
         for (int x = 0; x < tileMap.GetLength(1); ++x)
         {
             tileMap[y, x] = new Tile(world);
         }
     }
 }
Example #11
0
        public Terrain(int width, int height)
        {
            bool test = false;
            this.width = width;
            this.height = height;

            tiles = new Tile[this.width, this.height];
            collisionMap = new ByteMap(this.width, this.height);

            if (test)
            {
                int n = 0;

                for (int i = 0; i < tiles.GetLength(0); i++)
                {
                    for (int j = 0; j < tiles.GetLength(1); j++)
                    {
                        switch (n % 4)
                        {
                            case 0:
                                tiles[i, j] = new FloorTile();
                                break;

                            case 1:
                                tiles[i, j] = new LightRubblePile();
                                break;

                            case 2:
                                tiles[i, j] = new MediumRubblePile();
                                break;

                            case 3:
                                tiles[i, j] = new HeavyRubblePile();
                                break;
                        }

                        n++;
                    }
                }
            }
            else
            {
                for (int i = 0; i < tiles.GetLength(0); i++)
                {
                    for (int j = 0; j < tiles.GetLength(1); j++)
                    {
                        tiles[i, j] = new FloorTile();
                    }
                }
            }

            GenerateCollisionMap();
        }
Example #12
0
	void Start() {
		mapTiles = new Tile[width, height];
		monsters = new Entity[numMonsters];
		players = new Entity[numPlayers];
		generateMap();
        
        BoardWidth = mapTiles.GetLength(0);
        BoardHeight = mapTiles.GetLength(1);
        GetComponent<TileColorManager>().enabled = true;

        updateTileScore();
        //print(currentTileTypes[2]);
    }
Example #13
0
        public Map(Bitmap mask)
        {
            tiles = new Tile[mask.Width, mask.Height];

            //all collums
            for (int i = 0; i < tiles.GetLength(0); ++i)
            {
                //all rows
                for (int j = 0; j < tiles.GetLength(1); ++j)
                {
                    //decide what to do in the possible cases
                    if (mask.GetPixel(i, j).Name.Equals(white))
                        tiles[i, j] = new Tile(SFML.Graphics.Color.White, new Vector2f(i, j) * TileSize, true, new Vector2f(TileSize, TileSize));

                    if (mask.GetPixel(i, j).Name.Equals(black))
                        tiles[i, j] = new Tile(SFML.Graphics.Color.Black, new Vector2f(i, j) * TileSize, false, new Vector2f(TileSize, TileSize));
                }
            }
        }
Example #14
0
        public Level(int x, int y)
        {
            size = new Vector2(x, y);

            //get LevelGenerator to make the tiles
            tiles = Program.Instance.lg.generate(new Vector2(x, y));

            //get the LevelGenerator to place some monsters
            monsters = Program.Instance.lg.placeMonsters(tiles, new Vector2(x, y));

            //parse features
            for (int i = 0; i < tiles.GetLength(0); i++)
            {
                for (int o = 0; o < tiles.GetLength(1); o++)
                {
                    if (tiles[i, o].type == tileTypes.level_start) //level start
                        lStart = new Vector2(i, o);
                    else if (tiles[i, o].type == tileTypes.level_end) //level end
                        lEnd = new Vector2(i, o);
                }
            }
        }
Example #15
0
        public Level()
        {
            tiles = new Tile[13, 31];

            for (var i = 0; i < tiles.GetLength(0); i++)
            {
                for (var j = 0; j < tiles.GetLength(1); j++)
                {
                    if (!((i == 1 && j == 1) || (i == 1 && j == 2) || (i == 2 && j == 1)) && template[i, j] == 0 && Blackboard.Random.Next(0, 100) <= density)
                        template[i, j] = 2;
                    tiles[i, j] = new Tile((TileType)template[i, j], j, i);
                }
            }

            enemies = new List<Enemy>();
            bombs = new List<Bomb>();
            explosions = new List<Explosion>();

            //test
            Blackboard.BombRadius = 4;

            EventManager.AddListener(GameEvent.BOMB_DETONATED, this);
        }
Example #16
0
 //Vorlesung bla bla bla
 public Map(Bitmap mask)
 {
     map = new Vector2f(mask.Width * TileSize, mask.Height * TileSize);
     //Mapstring(mask);
     tiles = new Tile[mask.Width, mask.Height];
     for (int i = 0; i < tiles.GetLength(0); ++i)
     {
         for (int j = 0; j < tiles.GetLength(1); ++j)
         {
             if (mask.GetPixel(i, j).Name.Equals(black))
             {
                 if((i < 2 || i > mask.Width - 2 || j < 2 || j > mask.Height - 2))
                     tiles[i, j] = new Tile(SFML.Graphics.Color.Black, new Vector2f(i, j) * TileSize, false, false, new Vector2f(TileSize, TileSize));
                 else
                     tiles[i, j] = new Tile(SFML.Graphics.Color.Black, new Vector2f(i, j) * TileSize, false, false, new Vector2f(TileSize, TileSize));
             }
             else
             {
                 tiles[i, j] = new Tile(SFML.Graphics.Color.White, new Vector2f(i, j) * TileSize, true, true, new Vector2f(TileSize, TileSize));
             }
         }
     }
 }
Example #17
0
        public DanceScreen(Game1 eng, Player p)
        {
            engine = eng;
            screenWidth = engine.getScreenWidth();
            screenHeight = engine.getScreenWidth();

            if(screenWidth < 800)
            {
                screenWidth = 800;
            }
            tiles = new Tile[screenWidth / 32, screenHeight / 32];
            for (int x = 0; x < tiles.GetLength(0); x++ )
            {
                for(int y = 0; y < tiles.GetLength(1); y++ )
                {

                    int temp = rand.Next(3);
                    tiles[x,y] = new Tile(temp,x,y);
                }
            }
            makePoints();
            addPointOffset();
            player = p;
        }
Example #18
0
        static void Main(string[] args)
        {
            try
            {
                ConnectToServer();
                LoginData data = Login();
                SendLoginRequest(data.Name, data.Password);
                Handler.Clear();
                while (true)
                {
                    RecieveResponse();
                    while (_responseQueue.Count != 0)
                    {
                        ServerResponse response = _responseQueue.Dequeue();
                        switch (response)
                        {
                        case ServerResponse.YourTurn:
                            Handler.ClearLine(0, gameBoard.GetLength(1) + _players.Count);
                            Handler.Write("Your turn. Press Arrow keys to move or press (c) to chat", 0, gameBoard.GetLength(1) + _players.Count);
                            bool ok = false;
                            while (!ok)
                            {
                                ok = SendMoveRequest();
                            }
                            Handler.ClearLine(0, gameBoard.GetLength(1) + _players.Count);
                            Handler.Write("Waiting for other players to move", 0, gameBoard.GetLength(1) + _players.Count);
                            break;

                        case ServerResponse.Sendstate:
                            Display();
                            break;

                        case ServerResponse.NewPlayer:
                            Display();
                            break;

                        case ServerResponse.UpdatePlayer:
                            Display();
                            break;

                        case ServerResponse.RemovePlayer:
                            Display();
                            break;

                        case ServerResponse.Message:
                            ClearChattMessages();
                            PrintChattMessages();
                            break;

                        case ServerResponse.LoginDenied:
                            Handler.Clear();
                            Handler.WriteLine("Wrong password!");
                            Handler.ReadKey();
                            data = Login();
                            SendLoginRequest(data.Name, data.Password);
                            break;

                        case ServerResponse.MoveDenied:
                            Handler.ClearLine(0, gameBoard.GetLength(1) + _players.Count);
                            Handler.Write("Your turn", 0, gameBoard.GetLength(1) + _players.Count);
                            ok = false;
                            while (!ok)
                            {
                                ok = SendMoveRequest();
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                Console.ReadLine();
            }
            finally
            {
                _socket?.Close();
            }
            Console.WriteLine("Client shut down.");
            Console.ReadLine();
        }
Example #19
0
    // Update is called once per frame
    void Update()
    {
        if (playerHasKey)                      //Checks if player has the key
        {
            if (enter == null && exit == null) //This statement will be executed only once after the player got the key because then enter and exit will no longer be null throughout the game.
            {
                GameObject selectedTree;       //Used for referring to a tree to be dealt with

                //Selecting the entry tile

                //Enterance cell is on horizontal boundary when random number 0 is generated
                if (Random.Range(0, 2) == 0)
                {
                    enter = tiles[0, Random.Range(0, 7)];  //Random horizontal boundary tile will be selected, just not the one adjacent to the wall

                    //Select the tree at this position adjacent to the entrance tile
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z + 0.75f)];
                    Destroy(selectedTree); //Destroys this tree.

                    //Removes the destroyed selected tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z + 0.75f));

                    //Select the tree at this position adjacent to the entrance tile
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z + 0.50f)];


                    Destroy(selectedTree); //Destroys this tree.

                    //Removes the destroyed selected tree's key from the list.
                    trees.Remove(new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z + 0.50f));

                    //Select the tree at this position adjacent to the entrance tile.
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z + 0.25f)];

                    Destroy(selectedTree);//Destroys this tree.

                    //Removes the destroyed selected tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z + 0.25f));

                    //Select the tree at this position adjacent to the entrance
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z)];

                    Destroy(selectedTree); //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z));

                    //Select the tree at this position adjacent to the entrance
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z - 0.25f)];

                    Destroy(selectedTree); //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z - 0.25f));

                    //Select the tree at this position adjacent to the entrance
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z - 0.50f)];

                    Destroy(selectedTree); //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z - 0.50f));

                    //Select the tree at this position adjacent to the entrance
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z - 0.75f)];

                    Destroy(selectedTree); //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 1.0f, 0.0f, enter.GetPosition().z - 0.75f));
                }
                else //Enterance cell is on Veritcal boundary when random number 0 is generated
                {
                    enter = tiles[Random.Range(0, 7), 0];  //Random Vertical boundary tile will be selected, just not the one adjacent to the wall


                    //Select the tree at this position adjacent to the entrance
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 0.75f, 0.0f, enter.GetPosition().z - 1.0f)];

                    Destroy(selectedTree);  //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 0.75f, 0.0f, enter.GetPosition().z - 1.0f));

                    //Select the tree at this position adjacent to the entry
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 0.50f, 0.0f, enter.GetPosition().z - 1.0f)];

                    Destroy(selectedTree);  //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 0.50f, 0.0f, enter.GetPosition().z - 1.0f));

                    //Select the tree at this position adjacent to the entry
                    selectedTree = trees[new Vector3(enter.GetPosition().x - 0.25f, 0.0f, enter.GetPosition().z - 1.0f)];

                    Destroy(selectedTree);  //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x - 0.25f, 0.0f, enter.GetPosition().z - 1.0f));

                    //Select the tree at this position adjacent to the entry
                    selectedTree = trees[new Vector3(enter.GetPosition().x, 0.0f, enter.GetPosition().z - 1.0f)];

                    Destroy(selectedTree);  //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x, 0.0f, enter.GetPosition().z - 1.0f));

                    //Select the tree at this position adjacent to the entry
                    selectedTree = trees[new Vector3(enter.GetPosition().x + 0.25f, 0.0f, enter.GetPosition().z - 1.0f)];

                    Destroy(selectedTree);  //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x + 0.25f, 0.0f, enter.GetPosition().z - 1.0f));

                    //Select the tree at this position adjacent to the entry
                    selectedTree = trees[new Vector3(enter.GetPosition().x + 0.50f, 0.0f, enter.GetPosition().z - 1.0f)];

                    Destroy(selectedTree);  //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x + 0.50f, 0.0f, enter.GetPosition().z - 1.0f));

                    //Select the tree at this position adjacent to the entry
                    selectedTree = trees[new Vector3(enter.GetPosition().x + 0.75f, 0.0f, enter.GetPosition().z - 1.0f)];

                    Destroy(selectedTree);  //Destroys this tree.

                    //Removes the selected destroyed tree's key from the list
                    trees.Remove(new Vector3(enter.GetPosition().x + 0.75f, 0.0f, enter.GetPosition().z - 1.0f));
                }

                Debug.Log("Entrance: " + enter.GetPosition());  //Used for displaying on console the entrance tile position


                //Selecting the exit tile

                //Exit tile is on 7th row when random number 0 is generated.
                if (Random.Range(0, 2) == 0)
                {
                    exit = tiles[7, Random.Range(0, 8)];
                }
                else //Exit tile is on 7th column when random number 1 is generated.
                {
                    exit = tiles[Random.Range(0, 8), 7];
                }

                //Sets the position of the light of the goal tile to that of the exit tile on the x and z axis
                goalTileLight.transform.position = new Vector3(exit.GetPosition().x, 0.01f, exit.GetPosition().z);
                goalTileLight.SetActive(true);            //Sets the gameobject active to true

                Debug.Log("Exit: " + exit.GetPosition()); //Used For displaying on console the exit tile position


                FindPath(); //Generates the random path to get from the enterance tile to the exit tile.

                //This for loop is used for checking the positions of each tile on th epath
                foreach (Tile t in path)
                {
                    Debug.Log(t.GetPosition()); //Displays the position of each tile on console.
                }

                PrimsAlgorithm();                  //Calls this method to generate maze
                RemoveConsecutivePathTilesTrees(); //Calls this method to remove trees that block the path from tile path[time] to tile path[time+1]
                RecordCurrentActiveTrees();        //Calls this method to record which trees are active and which aren't
            }


            //Double-nested for loop looping through each tile in tiles array, which are tiles of the forest
            for (int row = 0; row < tiles.GetLength(0); row++)
            {
                for (int column = 0; column < tiles.GetLength(1); column++)
                {
                    float tileMinPosX = tiles[row, column].GetPosition().x - 1.0f;  //Where tile begins on x-axis
                    float tileMaxPosX = tiles[row, column].GetPosition().x + 1.0f;  //Where tile ends on x-axis

                    float tileMinPosZ = tiles[row, column].GetPosition().z - 1.0f;  //Where tile begins on z-axis
                    float tileMaxPosZ = tiles[row, column].GetPosition().z + 1.0f;  //Where tile ends on z-axis


                    if (player)  //This condition is to avoid all bunch of errors generated when the player is destroyed after the game ends.
                    {
                        //Checking if player is on the current tile
                        if (player.transform.position.x >= tileMinPosX && player.transform.position.x <= tileMaxPosX && player.transform.position.z >= tileMinPosZ && player.transform.position.z <= tileMaxPosZ)
                        {
                            playerInMaze = true;
                        }
                        else
                        {
                            playerInMaze = false;
                        }

                        //The 2 nested if statements execute if the player is on the current tile.
                        if (player.transform.position.x >= (tileMinPosX + 0.25f) && player.transform.position.x <= (tileMaxPosX - 0.25f))
                        {
                            if (player.transform.position.z >= (tileMinPosZ + 0.25f) && player.transform.position.z <= (tileMaxPosZ - 0.25f))
                            {
                                if (currentTile == null)
                                {
                                    currentTile = tiles[row, column];
                                }

                                //This condition checks if the player moved a tile
                                if (currentTile != tiles[row, column])
                                {
                                    currentTile = tiles[row, column]; //If so, then assign the tile the player is currently on to the currentTile variable
                                    time++;                           //Increment the time after player moves a tile

                                    Debug.Log("Time: " + time);       //Displays the amount of time steps passed.

                                    //All trees are set active before setting some of these to non active for the next timestep.
                                    foreach (KeyValuePair <Vector3, GameObject> tree in trees)
                                    {
                                        if (!tree.Value.activeSelf)
                                        {
                                            tree.Value.SetActive(true);
                                        }
                                    }

                                    //Checks if the maze for the next time was already generated
                                    if (activeTreesAtTimes.ContainsKey(time))
                                    {
                                        GetMazeAtNextTimeStep();

                                        //Checks if the time variable is less than the last index into the path list so that there are no out of bounds exceptions.
                                        if (time < path.Count - 1)
                                        {
                                            tileLight.transform.position = new Vector3(path[time + 1].GetPosition().x, 0.01f, path[time + 1].GetPosition().z);  //Sets the color of next tile in the path list
                                        }
                                    }
                                    else //Otherwise
                                    {
                                        PrimsAlgorithm();   //Generate maze for this timestep

                                        //Finding the distance between the entrance tile and it's neighbor in the selected path
                                        if (time < path.Count - 1)
                                        {
                                            RemoveConsecutivePathTilesTrees();  //Remove trees that block path from next tile in the path's list to it's neighboring tile in the path
                                        }

                                        RecordCurrentActiveTrees(); //Records the trees active or not at the next timestep
                                    }

                                    //If the tracking tile color (red color) is on the exit tile color (yellow color), they mix together to make an orange color on the exit tile.
                                    if (tileLight.transform.position == goalTileLight.transform.position)
                                    {
                                        tileLight.SetActive(false);                                                                         //Setting the red color active to false
                                        goalTileLight.SetActive(false);                                                                     //Setting the yellow color to false
                                        mixedTileLight.transform.position = new Vector3(exit.GetPosition().x, 0.01f, exit.GetPosition().z); //Setting the orange color to be the position of the red and yellow color.
                                        mixedTileLight.SetActive(true);                                                                     //Setting orange color to be active to true.
                                    }
                                }


                                //If the player reached the exit tile
                                if (currentTile == exit)
                                {
                                    youWinText.text = "You Win!"; //Player won the game
                                    Destroy(player);              //Player is destroyed
                                    hasWon = true;
                                }


                                //Checks if time = 16 and player still did not win the game
                                if (time == 16 && !hasWon)
                                {
                                    //If so, then reset time = 0 and respawn player at start position
                                    time = 0;
                                    Respawn();
                                }
                            }
                        }


                        //If the user presses escape, then reset time = 0 and respawn player at start position
                        if (Input.GetKeyDown(KeyCode.Escape))
                        {
                            if (playerInMaze)
                            {
                                time = 0;
                                Respawn();
                            }
                        }
                    }
                }
            }
        }
    }
Example #20
0
        ///////////////////////////////////////////||\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
        /////////////////////////////////////// METHODS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
        ///////////////////////////////////////////||\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


        //Pre: The map name, the game tiles, the list of enemies, and the start tile
        //Post: A boolean for whether the new map was saved
        //Desc: A method for saving a new map
        public bool SaveNewMap(string mapName, Tile[,] gameTiles, List <Enemy> enemies, Tile startTile)
        {
            //Creates a stream writer with the path of the new map
            writer = new StreamWriter(mapName + NEW_MAP_PATH_SUFFIX);

            //Writes the lengths of each dimesnion of the gametiles array
            writer.WriteLine(gameTiles.GetLength(0));
            writer.WriteLine(gameTiles.GetLength(1));

            //Loop for the index's of the first dimension
            for (int i = 0; i < gameTiles.GetLength(0); i++)
            {
                //Loop for the index's of the second dimension
                for (int j = 0; j < gameTiles.GetLength(1); j++)
                {
                    //Writes the tile type for the current tile
                    writer.WriteLine(gameTiles[i, j].CurrentTileType);
                }
            }

            //Writes the amount of enemies
            writer.WriteLine(enemies.Count);

            //Loop for every enemy
            for (int i = 0; i < enemies.Count; i++)
            {
                //Writes the position of the current enemy
                writer.WriteLine(enemies[i].Position.X);
                writer.WriteLine(enemies[i].Position.Y);
            }

            //Writes the locaiton of the start tile
            writer.WriteLine(startTile.Row);
            writer.WriteLine(startTile.Column);

            //Closes the stream writer
            writer.Close();

            //If the all maps file exists and can be read
            if (ReadAllMaps())
            {
                //Adds a map to the list of maps
                allMapNames.Add(mapName);
            }
            //If the all maps file does not exist or can't be read
            else
            {
                //Clears what's currently in the list of maps and adds the new map
                allMapNames.Clear();
                allMapNames.Add(mapName);
            }

            //Writes the new set of maps to a file
            WriteAllMaps();

            //If the file with all the map names is uploaded onto the server
            if (onlineHelper.UpdateFile(ALL_MAPS_FILE_NAME, ALL_MAPS_FILE_PATH, FILE_TYPE, ALL_MAPS_FILE_DESCRIPTION))
            {
                //The new map that was created is uploaded onto the server and a highscores file for the map is created
                onlineHelper.UpdateFile(mapName + NEW_MAP_SUFFIX, mapName + NEW_MAP_PATH_SUFFIX, FILE_TYPE, NEW_MAP_FILE_DESCRIPTION);
                highscoreHelper.AddHighscoresMap(mapName);

                //True is returned which represents that the map was saved
                return(true);
            }

            //False is returned which means that the map was not saved
            return(false);
        }
Example #21
0
    private Sprite Aligntiles(int x, int y, WallSplice Set)
    {
        if (utils.isInRange(x, 1, tiles.GetLength(0) - 1) && utils.isInRange(y, 1, tiles.GetLength(1) - 1))
        {
            if (tiles[x - 1, y] != Tile.Hole &&
                tiles[x, y - 1] != Tile.Hole)
            {
                return(Set.WallBottomLeft);
            }
            else if (tiles[x + 1, y] != Tile.Hole &&
                     tiles[x, y - 1] != Tile.Hole)
            {
                return(Set.WallBottomRight);
            }
            else if (tiles[x - 1, y] != Tile.Hole &&
                     tiles[x, y + 1] != Tile.Hole)
            {
                return(Set.WallTopLeft);
            }
            else if (tiles[x + 1, y] != Tile.Hole &&
                     tiles[x, y + 1] != Tile.Hole)
            {
                return(Set.WallTopRight);
            }
            else if (tiles[x + 1, y] != Tile.Hole)
            {
                return(Set.WallRight);
            }
            else if (tiles[x - 1, y] != Tile.Hole)
            {
                return(Set.WallLeft);
            }
            else if (tiles[x, y - 1] != Tile.Hole)
            {
                return(Set.WallBottom);
            }
            else if (tiles[x, y + 1] != Tile.Hole)
            {
                return(Set.WallTop);
            }
            else if (tiles[x - 1, y - 1] != Tile.Hole)
            {
                return(Set.WallInsetBottomLeft);
            }
            else if (tiles[x + 1, y - 1] != Tile.Hole)
            {
                return(Set.WallInsetBottomRight);
            }
            else if (tiles[x - 1, y + 1] != Tile.Hole)
            {
                return(Set.WallInsetTopLeft);
            }
            else if (tiles[x + 1, y + 1] != Tile.Hole)
            {
                return(Set.WallInsetTopRight);
            }
        }
        else
        {
            //if (utils.isInRange(x, 1, tiles.GetLength(0) - 1) && utils.isInRange(y, 1, tiles.GetLength(1) - 1))
            if (utils.isInRange(x, 0, tiles.GetLength(0) - 1))
            {
                if (tiles[x + 1, y] != Tile.Hole)
                {
                    return(Set.WallRight);
                }
            }

            if (utils.isInRange(x, 1, tiles.GetLength(0)))
            {
                if (tiles[x - 1, y] != Tile.Hole)
                {
                    return(Set.WallLeft);
                }
            }

            if (utils.isInRange(y, 1, tiles.GetLength(0)))
            {
                if (tiles[x, y - 1] != Tile.Hole)
                {
                    return(Set.WallBottom);
                }
            }

            if (utils.isInRange(y, 0, tiles.GetLength(0) - 1))
            {
                if (tiles[x, y + 1] != Tile.Hole)
                {
                    return(Set.WallTop);
                }
            }

            if (utils.isInRange(x, 1, tiles.GetLength(0)) && utils.isInRange(y, 1, tiles.GetLength(1)))
            {
                if (tiles[x - 1, y - 1] != Tile.Hole)
                {
                    return(Set.WallInsetBottomLeft);
                }
            }

            if (utils.isInRange(x, 0, tiles.GetLength(0) - 1) && utils.isInRange(y, 1, tiles.GetLength(1)))
            {
                if (tiles[x + 1, y - 1] != Tile.Hole)
                {
                    return(Set.WallInsetBottomRight);
                }
            }

            if (utils.isInRange(x, 1, tiles.GetLength(0)) && utils.isInRange(y, 0, tiles.GetLength(1) - 1))
            {
                if (tiles[x - 1, y + 1] != Tile.Hole)
                {
                    return(Set.WallInsetTopLeft);
                }
            }

            if (utils.isInRange(x, 0, tiles.GetLength(0) - 1) && utils.isInRange(y, 0, tiles.GetLength(1) - 1))
            {
                if (tiles[x + 1, y + 1] != Tile.Hole)
                {
                    return(Set.WallInsetTopRight);
                }
            }
        }

        return(Set.WallCenter);
    }
Example #22
0
        public static List<CoverObject> generateCoverObjects(Tile[,] tiles)
        {
            List<CoverObject> returnList = new List<CoverObject>();
            newTiles_ = tiles;

            for (int i = 0; i < newTiles_.GetLength(0); i++)
            {
                for (int j = 0; j < newTiles_.GetLength(1); j++)
                {
                    //Are we on an edge
                    if (get(j, i, HeightEnum.LOW) == 1f && get(j, i, HeightEnum.HIGH) > 0f)
                    {
                        // We're checking to make sure that this is the case:
                        //     >0  |       |   >0
                        //     ------------------
                        //     >0  |   j,i | 0, low only
                        //     ------------------
                        //         |   >0  | 0, low only
                        //
                        if (((get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                                && get(j + 1, i - 1, HeightEnum.LOW) > 0f) //Upper Right not a wall
                            || ((get(j - 1, i - 1, HeightEnum.LOW) == 0f //Upper Left is a wall
                                && get(j + 1, i - 1, HeightEnum.LOW) == 0f) //Upper Right is a wall
                                && get(j, i - 1, HeightEnum.LOW) == 0f) //Top is a wall
                            )
                            && get(j - 1, i, HeightEnum.LOW) > 0f //Left is not a wall
                            && get(j, i + 1, HeightEnum.LOW) > 0f //Below is not a wall
                            && get(j + 1, i, HeightEnum.LOW) == 0f //Right is a wall
                            && get(j + 1, i + 1, HeightEnum.LOW) == 0f //Lower Right is a wall
                            && get(j + 1, i, HeightEnum.HIGH) > 0f //Right is not blocked high
                            && get(j + 1, i + 1, HeightEnum.HIGH) > 0f //Lower Right is not blocked high
                            )
                        {
                            //We are now sure that we need to start cover going down
                            CoverObject temp = genVerticalCoverObjectLeft(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }
                        // We're checking to make sure that this is the case:
                        //     >0  |       |   >0
                        //     ------------------
                        //  0, low |   j,i |   >0
                        //     ------------------
                        //  0, low |   >0  |
                        //
                        else if (get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                            && get(j + 1, i - 1, HeightEnum.LOW) > 0f //Upper Right not a wall
                            && get(j + 1, i, HeightEnum.LOW) > 0f //Right is not a wall
                            && get(j, i + 1, HeightEnum.LOW) > 0f //Below is not a wall
                            && get(j - 1, i, HeightEnum.LOW) == 0f //Left is a wall
                            && get(j - 1, i + 1, HeightEnum.LOW) == 0f //Lower Left is a wall
                            && get(j - 1, i, HeightEnum.HIGH) > 0f //Left is not blocked high
                            && get(j - 1, i + 1, HeightEnum.HIGH) > 0f //Lower Left is not blocked high
                            )
                        {
                            //We are now sure that we need to start cover going down
                            CoverObject temp = genVerticalCoverObjectRight(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }

                        // We're checking to make sure that this is the case:
                        //     >0  | 0, l  | 0, low only
                        //     ------------------
                        //         |   j,i | >0
                        //     ------------------
                        //     >0  |   >0  |
                        //
                        if (((get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                                && get(j - 1, i + 1, HeightEnum.LOW) > 0f) //Lower Left not a wall
                            ||  ((get(j - 1, i + 1, HeightEnum.LOW) == 0f //Lower Left is a wall
                                && get(j - 1, i, HeightEnum.LOW) == 0f) //Left is a wall
                                && get(j - 1, i - 1, HeightEnum.LOW) == 0f) //Upper Left is a wall
                            )
                            && get(j, i + 1, HeightEnum.LOW) > 0f //Bottom is not a wall
                            && get(j + 1, i, HeightEnum.LOW) > 0f //Right is not a wall
                            && get(j, i - 1, HeightEnum.LOW) == 0f //Top is a wall
                            && get(j + 1, i - 1, HeightEnum.LOW) == 0f //Upper Right is a wall
                            && get(j, i - 1, HeightEnum.HIGH) > 0f //Top is not blocked high
                            && get(j + 1, i - 1, HeightEnum.HIGH) > 0f //Upper Right is not blocked high
                            )
                        {
                            //We are now sure that we need to start cover going right
                            CoverObject temp = genHorizontalCoverObjectBottom(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }
                        // We're checking to make sure that this is the case:
                        //     >0  |  >0   |
                        //     ------------------
                        //         |   j,i | >0
                        //     ------------------
                        //     >0  | 0, l  | 0, low only
                        //
                        else if (((get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                                    && get(j - 1, i + 1, HeightEnum.LOW) > 0f) //Lower Left not a wall
                                || ((get(j - 1, i + 1, HeightEnum.LOW) == 0f //Lower Left is a wall
                                    && get(j - 1, i, HeightEnum.LOW) == 0f) //Left is a wall
                                    && get(j - 1, i - 1, HeightEnum.LOW) == 0f) //Upper Left is a wall
                                )
                                && get(j, i - 1, HeightEnum.LOW) > 0f //Top is not a wall
                                && get(j + 1, i, HeightEnum.LOW) > 0f //Right is not a wall
                                && get(j, i + 1, HeightEnum.LOW) == 0f //Bottom is a wall
                                && get(j + 1, i + 1, HeightEnum.LOW) == 0f //Lower Right is a wall
                                && get(j, i + 1, HeightEnum.HIGH) > 0f //Bottom is not blocked high
                                && get(j + 1, i + 1, HeightEnum.HIGH) > 0f //Lower Right is not blocked high
                                )
                        {
                            //We are now sure that we need to start cover going right
                            CoverObject temp = genHorizontalCoverObjectTop(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }
                    }
                }
            }
            return returnList;
        }
Example #23
0
    public void OutputConsole(int round)
    {
        Logger.consoleLock.WaitOne();

        if (hasOutput)
        {
            Console.SetCursorPosition(0, Console.CursorTop - height - 2 - playerCount);
        }

        Console.WriteLine("Round " + round);

        var prevBack  = Console.BackgroundColor;
        var prevFront = Console.ForegroundColor;

        ConsoleColor[] playerForegroundColor = new ConsoleColor[6];
        ConsoleColor[] playerBackgroundColor = new ConsoleColor[6];

        playerBackgroundColor[0] = ConsoleColor.Black;
        playerBackgroundColor[1] = ConsoleColor.DarkRed;
        playerBackgroundColor[2] = ConsoleColor.DarkYellow;
        playerBackgroundColor[3] = ConsoleColor.DarkGreen;
        playerBackgroundColor[4] = ConsoleColor.Blue;
        playerBackgroundColor[5] = ConsoleColor.Gray;

        playerForegroundColor[0] = ConsoleColor.DarkGray;
        playerForegroundColor[1] = ConsoleColor.Black;
        playerForegroundColor[2] = ConsoleColor.Black;
        playerForegroundColor[3] = ConsoleColor.Black;
        playerForegroundColor[4] = ConsoleColor.Black;
        playerForegroundColor[5] = ConsoleColor.Black;

        void SetColor(ConsoleColor back, ConsoleColor front)
        {
            Console.BackgroundColor = back;
            Console.ForegroundColor = front;
        }

        // Count players factories , resources and tiles.
        int[] fac = new int[playerCount + 1];
        int[] res = new int[playerCount + 1];
        int[] grd = new int[playerCount + 1];

        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                if (map[i, j].type == Tile.Type.Factory)
                {
                    fac[map[i, j].owner]++;
                }
                if (map[i, j].type == Tile.Type.Resource)
                {
                    res[map[i, j].owner]++;
                }
                grd[map[i, j].owner]++;
            }
        }

        Console.WriteLine("Player Tile. Fac. Res.");
        for (int p = 1; p <= playerCount; p++)
        {
            SetColor(playerBackgroundColor[p], playerForegroundColor[p]);
            Console.Write("  " + p + "  ");
            SetColor(prevBack, prevFront);
            Console.WriteLine(string.Format("  {0}  {1}  {2}",
                                            grd[p].ToString().PadLeft(4),
                                            fac[p].ToString().PadLeft(3),
                                            res[p].ToString().PadLeft(3)));
        }

        for (int i = 0; i < map.GetLength(0); i++)
        {
            for (int j = 0; j < map.GetLength(1); j++)
            {
                char c = ' ';
                if (map[i, j].type == Tile.Type.Factory)
                {
                    c = 'H';
                }
                if (map[i, j].type == Tile.Type.Resource)
                {
                    c = 'x';
                }
                if (map[i, j].type == Tile.Type.Obstacle)
                {
                    c = '#';
                }
                ConsoleColor back  = playerBackgroundColor[map[i, j].owner];
                ConsoleColor front = playerForegroundColor[map[i, j].owner];
                SetColor(back, front);
                Console.Write(c);
            }
            SetColor(prevBack, prevFront);
            Console.WriteLine();
        }

        hasOutput = true;
        Logger.consoleLock.ReleaseMutex();
    }
Example #24
0
        /// <summary>
        /// Main Pathfinding method that uses the A Star Algorithm in order to find the most efficient route to the destination
        /// </summary>
        /// <param name="startingPoint"> Specifies the starting node </param>
        /// <param name="endingPoint"> Passes through the end node </param>
        /// <returns> Return a list of ordered points that the bot will follow </returns>
        public List <Point> PathFinder(Point startingPoint, Point endingPoint)
        {
            // Creates path list and intializes it
            List <Point> path = new List <Point>();

            // Stores the current row and column of the current node
            int curCol = startingPoint.X;
            int curRow = startingPoint.Y;

            // Records the movement cost of the surrounding tiles
            int[] tileScores;

            // While loop that only exits when both the current x and y of the node are equal to the
            // x and y of the ending node
            while (curCol != endingPoint.X ||
                   curRow != endingPoint.Y)
            {
                // Stores the g costs of each of surrounding tiles
                tileScores = new int[8];

                // Stores g cost and h cost
                int g;
                int h;

                // 0 1 2
                // 3 X 4
                // 5 6 7

                // Cycles through all surrounding tiles
                for (int i = 0; i < tileScores.Length; i++)
                {
                    switch (i)
                    {
                    // If the surroundiung tile is diagonal to the current node
                    // the g cost is 14 and 10 if straight
                    case 0:
                    case 2:
                    case 5:
                    case 7:
                        g = 14;
                        break;

                    default:
                        g = 10;
                        break;
                    }

                    // Runs the DirectionToPoint method in order to store the new point
                    Point checkPoint = DirectionToPoint(i);

                    // Gets the direction and adds it to the current node position in order to
                    // get the right placement
                    checkPoint.X += curCol;
                    checkPoint.Y += curRow;

                    // If the path exists
                    if (!path.Exists(p => p == checkPoint))
                    {
                        // Checks if the check point tile is on the map
                        if (checkPoint.X > 0 && checkPoint.Y > 0 &&
                            checkPoint.X < map.GetLength(0) &&
                            checkPoint.Y < map.GetLength(1))
                        {
                            // Checks if the next checkpoint tile is solid if not calculates H-Cost
                            if (map[checkPoint.X, checkPoint.Y].TileType != Tile.SOLID)
                            {
                                // Stores h cost in the int h
                                h = FindHCost(checkPoint, endingPoint);
                            }

                            // Sets the H-Cost to the max value of the tile is solid
                            else
                            {
                                h = Int16.MaxValue;
                            }
                        }
                        else
                        {
                            h = Int16.MaxValue;
                        }
                    }
                    else
                    {
                        h = Int16.MaxValue;
                    }

                    // Calculates H-Cost by adding g and h cost
                    tileScores[i] = g + h;
                }

                // Stores direction to get to the next node
                int direction = Array.IndexOf(tileScores, tileScores.Min());

                // Gets the next point from the direction to point method
                Point nextNode = DirectionToPoint(direction);
                nextNode.X += curCol;
                nextNode.Y += curRow;

                // Adds the next node to the path list
                path.Add(nextNode);
                curCol = nextNode.X;
                curRow = nextNode.Y;
            }

            return(path);
        }
 protected void Load()
 {
     string[] lines = File.ReadAllLines(Filename);
     tiles = new Tile[lines[0].Split(Sep).Count(), lines.Count()];
     for(int y = 0; y < tiles.GetLength(1); ++y)
     {
         string[] line = lines[y].Split(Sep) ;
         for (int x = 0; x < tiles.GetLength(0); ++x)
         {
             tiles[x, y] = (Tile)int.Parse(line[x]);
         }
     }
 }
Example #26
0
    //GROUND TILES
    void SubdivideTilesArray(int index1 = 0, int index2 = 0)
    {
        //get size of chunk
        int sizeX;
        int sizeY;

        //x axis
        //tiles along x - start of chunk > chunk size
        if (tiles.GetLength(0) - index1 > chunkSize)
        {
            sizeX = chunkSize;
        }
        else
        {
            sizeX = tiles.GetLength(0) - index1;
        }

        //y axis
        if (tiles.GetLength(1) - index2 > chunkSize)
        {
            sizeY = chunkSize;
        }
        else
        {
            sizeY = tiles.GetLength(1) - index2;
        }

        //generate tile mesh of specified size
        GenerateTilesLayer(index1, index2, sizeX, sizeY);

        if (tiles.GetLength(0) > index1 + chunkSize)
        {
            SubdivideTilesArray(index1 + chunkSize, index2);
            return;
        }
        if (tiles.GetLength(1) > index2 + chunkSize)
        {
            SubdivideTilesArray(0, index2 + chunkSize);
            return;
        }
    }
    public List <Tile> FiltterMoveables(Tile from, MOVEDIRECTIONTYPE moveDirectionType, Tile[,] boardTiles, int movementAmount)
    {
        if (from == null)
        {
            return(null);
        }
        if (movementAmount == 0)
        {
            return(null);
        }

        List <Tile> moveableTiles = new List <Tile>();

        PositionerDemo.Position fromPosition = new PositionerDemo.Position(from.position.posX, from.position.posY);

        int maxX = boardTiles.GetLength(0);
        int maxY = boardTiles.GetLength(1);

        for (int i = 1; i <= movementAmount; i++)
        {
            // RIGHT
            if (blockDirection)
            {
                if (!blockRight)
                {
                    if (fromPosition.posY + i < maxY)
                    {
                        if (!boardTiles[fromPosition.posX, fromPosition.posY + i].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX, fromPosition.posY + i]);
                        }
                        else
                        {
                            blockRight = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posY + i < maxY)
                {
                    if (!boardTiles[fromPosition.posX, fromPosition.posY + i].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX, fromPosition.posY + i]);
                    }
                }
            }
            // LEFT
            if (blockDirection)
            {
                if (!blockLeft)
                {
                    if (fromPosition.posY - i >= 0)
                    {
                        if (!boardTiles[fromPosition.posX, fromPosition.posY - i].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX, fromPosition.posY - i]);
                        }
                        else
                        {
                            blockLeft = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posY - i >= 0)
                {
                    if (!boardTiles[fromPosition.posX, fromPosition.posY - i].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX, fromPosition.posY - i]);
                    }
                }
            }
            // UP
            if (blockDirection)
            {
                if (!blockUp)
                {
                    if (fromPosition.posX + i < maxX)
                    {
                        if (!boardTiles[fromPosition.posX + i, fromPosition.posY].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX + i, fromPosition.posY]);
                        }
                        else
                        {
                            blockUp = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posX + i < maxX)
                {
                    if (!boardTiles[fromPosition.posX + i, fromPosition.posY].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX + i, fromPosition.posY]);
                    }
                }
            }
            // DOWN
            if (blockDirection)
            {
                if (!blockDown)
                {
                    if (fromPosition.posX - i >= 0)
                    {
                        if (!boardTiles[fromPosition.posX - i, fromPosition.posY].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX - i, fromPosition.posY]);
                        }
                        else
                        {
                            blockDown = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posX - i >= 0)
                {
                    if (!boardTiles[fromPosition.posX - i, fromPosition.posY].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX - i, fromPosition.posY]);
                    }
                }
            }

            // UP RIGHT
            if (blockDirection)
            {
                if (!blockUpRight)
                {
                    if (fromPosition.posY + i < maxY && fromPosition.posX + i < maxX)
                    {
                        if (!boardTiles[fromPosition.posX + i, fromPosition.posY + i].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX + i, fromPosition.posY + i]);
                        }
                        else
                        {
                            blockUpRight = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posY + i < maxY && fromPosition.posX + i < maxX)
                {
                    if (!boardTiles[fromPosition.posX + i, fromPosition.posY + i].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX + i, fromPosition.posY + i]);
                    }
                }
            }

            // UP LEFT
            if (blockDirection)
            {
                if (!blockUpLeft)
                {
                    if (fromPosition.posY + i < maxY && fromPosition.posX - i >= 0)
                    {
                        if (!boardTiles[fromPosition.posX - i, fromPosition.posY + i].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX - i, fromPosition.posY + i]);
                        }
                        else
                        {
                            blockUpLeft = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posY + i < maxY && fromPosition.posX - i >= 0)
                {
                    if (!boardTiles[fromPosition.posX - i, fromPosition.posY + i].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX - i, fromPosition.posY + i]);
                    }
                }
            }

            // DOWN RIGHT
            if (blockDirection)
            {
                if (!blockDownRight)
                {
                    if (fromPosition.posY - i >= 0 && fromPosition.posX + i < maxX)
                    {
                        if (!boardTiles[fromPosition.posX + i, fromPosition.posY - i].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX + i, fromPosition.posY - i]);
                        }
                        else
                        {
                            blockDownRight = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posY - i >= 0 && fromPosition.posX + i < maxX)
                {
                    if (!boardTiles[fromPosition.posX + i, fromPosition.posY - i].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX + i, fromPosition.posY - i]);
                    }
                }
            }

            // DOWN LEFT
            if (blockDirection)
            {
                if (!blockDownLeft)
                {
                    if (fromPosition.posY - i >= 0 && fromPosition.posX - i >= 0)
                    {
                        if (!boardTiles[fromPosition.posX - i, fromPosition.posY - i].IsOccupied())
                        {
                            moveableTiles.Add(boardTiles[fromPosition.posX - i, fromPosition.posY - i]);
                        }
                        else
                        {
                            blockDownLeft = true;
                        }
                    }
                }
            }
            else
            {
                if (fromPosition.posY - i >= 0 && fromPosition.posX - i >= 0)
                {
                    if (!boardTiles[fromPosition.posX - i, fromPosition.posY - i].IsOccupied())
                    {
                        moveableTiles.Add(boardTiles[fromPosition.posX - i, fromPosition.posY - i]);
                    }
                }
            }
        }
        return(moveableTiles);
    }
Example #28
0
        public static Tile[,] SetPossibleActions(Tile[,] gameBoard)
        {
            for (int y = 0; y < gameBoard.GetLength(1); y++)
            {
                for (int x = 0; x < gameBoard.GetLength(0); x++)
                {
                    var currentTile = gameBoard[x, y];
                    if (currentTile.Checker != null)
                    {
                        currentTile.Checker.CanMove   = false;
                        currentTile.Checker.CanAttack = false;

                        var moveRight   = new Tile();
                        var moveLeft    = new Tile();
                        var attackRight = new Tile();
                        var attackLeft  = new Tile();

                        if (currentTile.Checker.Color == nameof(Enums.Color.Red))
                        {
                            if (InBoundsRight(x) && InBoundsUp(y))
                            {
                                moveRight = gameBoard[x + 1, y - 1];
                                if (moveRight.Checker != null && moveRight.Checker.Color == nameof(Enums.Color.Black) &&
                                    InBoundsRight(x + 1) && InBoundsUp(y - 1))
                                {
                                    attackRight = gameBoard[x + 2, y - 2];
                                }
                            }
                            if (InBoundsLeft(x) && InBoundsUp(y))
                            {
                                moveLeft = gameBoard[x - 1, y - 1];
                                if (moveLeft.Checker != null && moveLeft.Checker.Color == nameof(Enums.Color.Black) &&
                                    InBoundsLeft(x - 1) && InBoundsUp(y - 1))
                                {
                                    attackLeft = gameBoard[x - 2, y - 2];
                                }
                            }
                            if (currentTile.Checker.IsKing)
                            {
                                if (InBoundsRight(x) && InBoundsDown(y))
                                {
                                    moveRight = gameBoard[x + 1, y + 1];
                                    if (moveRight.Checker != null && moveRight.Checker.Color == nameof(Enums.Color.Black) &&
                                        InBoundsRight(x + 1) && InBoundsDown(y + 1))
                                    {
                                        attackRight = gameBoard[x + 2, y + 2];
                                    }
                                }
                                if (InBoundsLeft(x) && InBoundsDown(y))
                                {
                                    moveLeft = gameBoard[x - 1, y + 1];
                                    if (moveLeft.Checker != null && moveLeft.Checker.Color == nameof(Enums.Color.Black) &&
                                        InBoundsLeft(x - 1) && InBoundsDown(y + 1))
                                    {
                                        attackLeft = gameBoard[x - 2, y + 2];
                                    }
                                }
                            }
                            if (moveRight.IsEmpty || moveLeft.IsEmpty)
                            {
                                currentTile.Checker.CanMove = true;
                            }
                            if (attackRight.IsEmpty || attackLeft.IsEmpty)
                            {
                                currentTile.Checker.CanAttack = true;
                            }
                        }
                        else
                        {
                            if (InBoundsRight(x) && InBoundsDown(y))
                            {
                                moveRight = gameBoard[x + 1, y + 1];
                                if (moveRight.Checker != null && moveRight.Checker.Color == nameof(Enums.Color.Red) &&
                                    InBoundsRight(x + 1) && InBoundsDown(y + 1))
                                {
                                    attackRight = gameBoard[x + 2, y + 2];
                                }
                            }
                            if (InBoundsLeft(x) && InBoundsDown(y))
                            {
                                moveLeft = gameBoard[x - 1, y + 1];
                                if (moveLeft.Checker != null && moveLeft.Checker.Color == nameof(Enums.Color.Red) &&
                                    InBoundsLeft(x - 1) && InBoundsDown(y + 1))
                                {
                                    attackLeft = gameBoard[x - 2, y + 2];
                                }
                            }
                            if (currentTile.Checker.IsKing)
                            {
                                if (InBoundsRight(x) && InBoundsUp(y))
                                {
                                    moveRight = gameBoard[x + 1, y - 1];
                                    if (moveRight.Checker != null && moveRight.Checker.Color == nameof(Enums.Color.Black) &&
                                        InBoundsRight(x + 1) && InBoundsUp(y - 1))
                                    {
                                        attackRight = gameBoard[x + 2, y - 2];
                                    }
                                }
                                if (InBoundsLeft(x) && InBoundsUp(y))
                                {
                                    moveLeft = gameBoard[x - 1, y - 1];
                                    if (moveLeft.Checker != null && moveLeft.Checker.Color == nameof(Enums.Color.Black) &&
                                        InBoundsLeft(x - 1) && InBoundsUp(y - 1))
                                    {
                                        attackLeft = gameBoard[x - 2, y - 2];
                                    }
                                }
                            }
                            if (moveRight.IsEmpty || moveLeft.IsEmpty)
                            {
                                currentTile.Checker.CanMove = true;
                            }
                            if (attackRight.IsEmpty || attackLeft.IsEmpty)
                            {
                                currentTile.Checker.CanAttack = true;
                            }
                        }
                    }
                }
            }
            return(gameBoard);
        }
Example #29
0
    List <Tile> GetFloorTiles(Vector2Int start, Tile[,] Map, int _RoomID = -1)
    {
        bool        isColiding = false;
        List <Tile> tiles      = new List <Tile>();

        int[,] mapFlags = new int[Map.GetLength(0), Map.GetLength(1)];
        Enums.tileType tileType = Enums.tileType.Floor;

        Queue <Tile> queue = new Queue <Tile>();

        queue.Enqueue(Map[start.x, start.y]);
        mapFlags[start.x, start.y] = 1;

        while (queue.Count > 0)
        {
            Tile tile = queue.Dequeue();

            if (tile.RoomID == -1 || tile.RoomID == _RoomID)
            {
                tiles.Add(tile);
            }
            else
            {
                isColiding = true;
            }
            if (!isColiding)
            {
                for (int x = tile.RawCoord.coords.x - 1; x <= tile.RawCoord.coords.x + 1; x++)
                {
                    for (int y = tile.RawCoord.coords.y - 1; y <= tile.RawCoord.coords.y + 1; y++)
                    {
                        if (IsInMapRange(x, y, Map) && (y == tile.RawCoord.coords.y || x == tile.RawCoord.coords.x))
                        {
                            if (mapFlags[x, y] == 0 && Map[x, y].tileType == tileType)
                            {
                                mapFlags[x, y] = 1;
                                Debug.Log(Map[x, y].RoomID);
                                if (Map[x, y].RoomID == -1 || Map[x, y].RoomID == _RoomID)
                                {
                                    queue.Enqueue(Map[x, y]);
                                }
                                else
                                {
                                    Debug.Log("Tile Coliding:" + tile.RawCoord.coords);
                                    isColiding = true;
                                    queue.Clear();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                queue.Clear();
                break;
            }
        }
        if (isColiding)
        {
            return(new List <Tile>());
        }
        else
        {
            return(tiles);
        }
    }
Example #30
0
        /// <summary>
        /// Converts from a map of Tile-enums to a map of UITile-enums, ensuring that the orientation of each tile is correct based on adjacent tiles.
        /// </summary>
        /// <param name="map">The map to convert</param>
        /// <returns>A map of UITiles with correct orientation of all orientation-sensitive tiles</returns>
        public static UITile[,] Convert(Tile[,] map)
        {
            var UIMap = new UITile[map.GetLength(0), map.GetLength(1)];

            for (int x = 0; x < map.GetLength(0); x++)
            {
                for (int y = 0; y < map.GetLength(1); y++)
                {
                    switch (map[x, y])
                    {
                    case Tile.Unassigned:
                    case Tile.Wall:
                        UIMap[x, y] = UITile.Wall;
                        break;

                    case Tile.Room:
                    case Tile.Hallway:
                        UIMap[x, y] = UITile.Floor;
                        break;

                    case Tile.StairUp:
                        if (IsInRange(x - 1, y) && IsFloorTile(map[x - 1, y]))
                        {
                            UIMap[x, y] = UITile.StairSingle_East;
                        }
                        else if (IsInRange(x + 1, y) && IsFloorTile(map[x + 1, y]))
                        {
                            UIMap[x, y] = UITile.StairSingle_West;
                        }
                        else if (IsInRange(x, y + 1) && IsFloorTile(map[x, y + 1]))
                        {
                            UIMap[x, y] = UITile.StairSingle_North;
                        }
                        else if (IsInRange(x, y - 1) && IsFloorTile(map[x, y - 1]))
                        {
                            UIMap[x, y] = UITile.StairSingle_South;
                        }
                        else
                        {
                            UIMap[x, y] = UITile.StairSingle_North;
                        }
                        break;

                    case Tile.StairDown:
                        if (IsInRange(x - 1, y) && IsFloorTile(map[x - 1, y]))
                        {
                            UIMap[x, y] = UITile.StairSingle_West;
                        }
                        else if (IsInRange(x + 1, y) && IsFloorTile(map[x + 1, y]))
                        {
                            UIMap[x, y] = UITile.StairSingle_East;
                        }
                        else if (IsInRange(x, y + 1) && IsFloorTile(map[x, y + 1]))
                        {
                            UIMap[x, y] = UITile.StairSingle_South;
                        }
                        else if (IsInRange(x, y - 1) && IsFloorTile(map[x, y - 1]))
                        {
                            UIMap[x, y] = UITile.StairSingle_North;
                        }
                        else
                        {
                            UIMap[x, y] = UITile.StairSingle_North;
                        }
                        break;

                    case Tile.StairPartOne:
                        if (IsInRange(x - 1, y) && map[x - 1, y] == Tile.StairPartTwo)
                        {
                            UIMap[x, y] = UITile.StairPartOne_East;
                        }
                        else if (IsInRange(x + 1, y) && map[x + 1, y] == Tile.StairPartTwo)
                        {
                            UIMap[x, y] = UITile.StairPartOne_West;
                        }
                        else if (IsInRange(x, y + 1) && map[x, y + 1] == Tile.StairPartTwo)
                        {
                            UIMap[x, y] = UITile.StairPartOne_North;
                        }
                        else if (IsInRange(x, y - 1) && map[x, y - 1] == Tile.StairPartTwo)
                        {
                            UIMap[x, y] = UITile.StairPartOne_South;
                        }
                        else
                        {
                            UIMap[x, y] = UITile.StairPartOne_North;
                        }
                        break;

                    case Tile.StairPartTwo:
                        if (IsInRange(x - 1, y) && map[x - 1, y] == Tile.StairPartOne)
                        {
                            UIMap[x, y] = UITile.StairPartTwo_West;
                        }
                        else if (IsInRange(x + 1, y) && map[x + 1, y] == Tile.StairPartOne)
                        {
                            UIMap[x, y] = UITile.StairPartTwo_East;
                        }
                        else if (IsInRange(x, y + 1) && map[x, y + 1] == Tile.StairPartOne)
                        {
                            UIMap[x, y] = UITile.StairPartTwo_South;
                        }
                        else if (IsInRange(x, y - 1) && map[x, y - 1] == Tile.StairPartOne)
                        {
                            UIMap[x, y] = UITile.StairPartTwo_North;
                        }
                        else
                        {
                            UIMap[x, y] = UITile.StairPartTwo_North;
                        }
                        break;

                    case Tile.DoorClosed:
                        if ((IsInRange(x - 1, y) && IsFloorTile(map[x - 1, y])) || (IsInRange(x + 1, y) && IsFloorTile(map[x + 1, y])))
                        {
                            UIMap[x, y] = UITile.DoorClosed_EastWest;
                        }
                        else if ((IsInRange(x, y + 1) && IsFloorTile(map[x, y + 1])) || (IsInRange(x, y - 1) && IsFloorTile(map[x, y - 1])))
                        {
                            UIMap[x, y] = UITile.DoorClosed_NorthSouth;
                        }
                        else
                        {
                            UIMap[x, y] = UITile.DoorClosed_NorthSouth;
                        }
                        break;

                    case Tile.DoorOpen:
                        if ((IsInRange(x - 1, y) && IsFloorTile(map[x - 1, y])) || (IsInRange(x + 1, y) && IsFloorTile(map[x + 1, y])))
                        {
                            UIMap[x, y] = UITile.DoorOpen_EastWest;
                        }
                        else if ((IsInRange(x, y + 1) && IsFloorTile(map[x, y + 1])) || (IsInRange(x, y - 1) && IsFloorTile(map[x, y - 1])))
                        {
                            UIMap[x, y] = UITile.DoorOpen_NorthSouth;
                        }
                        else
                        {
                            UIMap[x, y] = UITile.DoorOpen_NorthSouth;
                        }
                        break;

                    case Tile.DoorSecret:
                        UIMap[x, y] = UITile.DoorSecret;
                        break;

                    case Tile.Unknown:
                        UIMap[x, y] = UITile.Unknown;
                        break;

                    default:
                        Debug.WriteLine($"Tile-enum missing from Tile to UITile converter. Tile was: {map[x, y]}");
                        UIMap[x, y] = UITile.Unknown;
                        break;
                    }
                }
            }

            bool IsInRange(int x, int y)
            {
                return(x >= 0 && y >= 0 && x < map.GetLength(0) && y < map.GetLength(1));
            }

            bool IsFloorTile(Tile tile)
            {
                return(tile == Tile.Room || tile == Tile.Hallway);
            }

            return(UIMap);
        }
Example #31
0
        protected void DrawChunkBack(Tile[,] chunk, int beginX, int beginY, bool showInvisibleTile, Graphics g)
        {
            int width  = chunk.GetLength(0);
            int height = chunk.GetLength(1);

            int tileSize     = this.TileSize;
            int halfTileSize = tileSize / 2;


            for (int x = 0; x < width; ++x)
            {
                int tileX = x * tileSize + beginX + halfTileSize;


                for (int y = 0; y < height; ++y)
                {
                    var tile = chunk[x, y];

                    // 영토(타일)가 존재하고
                    // 보이는 상태이거나 무조건 보이는 모드이면
                    if (tile != null &&
                        (tile.Visible || showInvisibleTile))
                    {
                        int tileY = y * tileSize + beginY + halfTileSize;


                        Brush tileColor = null;

                        // 주인에 해당하는 타일 색상 가져오기
                        if (m_playerBrushMap.ContainsKey(tile.Owner))
                        {
                            tileColor = m_playerBrushMap[tile.Owner].Key;
                        }
                        else
                        {
                            // 없으면 기본 색으로 설정
                            tileColor = Brushes.White;

                            // 이전에 요청하지 않았으면
                            if (m_requestColorList.Any(name => name == tile.Owner) == false)
                            {
                                // 플레이어 색 요청
                                this.WhenRequestUserColor(tile.Owner);

                                // 요청 목록에 추가
                                m_requestColorList.Add(tile.Owner);
                            }
                        }

                        // 색 칠하기
                        if (tileColor != null)
                        {
                            int drawX    = beginX + x * this.TileSize;
                            int drawY    = beginY + y * this.TileSize;
                            int drawSize = this.TileSize;

                            g.FillRectangle(tileColor,
                                            drawX, drawY,
                                            drawSize, drawSize);

                            // 타일 종류에 따른 표식
                            switch (tile.Kind)
                            {
                            case TileTypes.Resource:
                                g.DrawEllipse(Pens.Black,
                                              drawX + 1, drawY + 1,
                                              drawSize - 2, drawSize - 2);
                                break;

                            case TileTypes.ResourceFactory:
                                g.FillEllipse(Brushes.MediumAquamarine,
                                              drawX + 1, drawY + 1,
                                              drawSize - 2, drawSize - 2);
                                g.DrawEllipse(Pens.Black,
                                              drawX + 1, drawY + 1,
                                              drawSize - 2, drawSize - 2);
                                g.FillEllipse(tileColor,
                                              drawX + 3, drawY + 3,
                                              drawSize - 6, drawSize - 6);

                                if (tile.Power > GameValues.FactoryConversionAmount)
                                {
                                    g.DrawEllipse(Pens.Black,
                                                  drawX + 3, drawY + 3,
                                                  drawSize - 6, drawSize - 6);
                                }
                                else
                                {
                                    g.FillEllipse(Brushes.DarkGray,
                                                  drawX + 3, drawY + 3,
                                                  drawSize - 6, drawSize - 6);
                                }
                                break;

                            case TileTypes.Company:
                                if (this.TileSize >= 6)
                                {
                                    g.DrawRectangle(Pens.Black,
                                                    drawX + 2, drawY + 2,
                                                    drawSize - 4, drawSize - 4);
                                }
                                break;

                            case TileTypes.Chip:
                                if (this.TileSize >= 10)
                                {
                                    g.DrawRectangle(Pens.Black,
                                                    drawX + 4, drawY + 4,
                                                    drawSize - 8, drawSize - 8);
                                    g.FillRectangle(Brushes.DarkGray,
                                                    drawX + 4, drawY + 4,
                                                    drawSize - 8, drawSize - 8);
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
Example #32
0
        /// <summary>
        /// Map discovery phase
        /// </summary>
        /// <returns>action for robot to perform</returns>
        private ActionType Phase1Iteration()
        {
            Tile[,] hugeMap = HugeMap;
            Point currentPos = CurrentPos;
            bool  followPath = false;

            //If it's first iteration in the phase
            if (Phase1Preparing)
            {
                //set all tiles as black (unexplored)
                TileStates black = TileStates.TopNV | TileStates.RightNV | TileStates.BottomNV | TileStates.LeftNV;
                for (int i = 0; i < hugeMap.GetLength(0); ++i)
                {
                    for (int j = 0; j < hugeMap.GetLength(1); ++j)
                    {
                        hugeMap[i, j] = new Tile(black, -1);
                    }
                }
                //set initial tile as grey tile
                hugeMap[currentPos.Row - 1, currentPos.Col].State &= ~TileStates.BottomNV;
                hugeMap[currentPos.Row, currentPos.Col + 1].State &= ~TileStates.LeftNV;
                hugeMap[currentPos.Row + 1, currentPos.Col].State &= ~TileStates.TopNV;
                hugeMap[currentPos.Row, currentPos.Col - 1].State &= ~TileStates.RightNV;
                hugeMap[currentPos.Row, currentPos.Col].State     |= TileStates.Visited;
                Phase1Preparing = false;
            }

            Tile       currentTile = hugeMap[currentPos.Row, currentPos.Col];
            ActionType action      = ActionType.actIDLE;

            //if we are not following path to nearest grey tile generated by A*
            if (GoingToGrey == null)
            {
                //if current tile is grey (has unexplored neighbours)
                if ((currentTile.State & GreyTileSign) != 0)
                {
                    if ((currentTile.State & TileStates.TopNV) != 0)
                    {
                        --currentPos.Row;
                        action = ActionType.actUP;
                    }
                    else
                    if ((currentTile.State & TileStates.RightNV) != 0)
                    {
                        ++currentPos.Col;
                        action = ActionType.actRIGHT;
                    }
                    else
                    if ((currentTile.State & TileStates.BottomNV) != 0)
                    {
                        ++currentPos.Row;
                        action = ActionType.actDOWN;
                    }
                    else
                    if ((currentTile.State & TileStates.LeftNV) != 0)
                    {
                        --currentPos.Col;
                        action = ActionType.actLEFT;
                    }

                    hugeMap[currentPos.Row - 1, currentPos.Col].State &= ~TileStates.BottomNV;
                    hugeMap[currentPos.Row, currentPos.Col + 1].State &= ~TileStates.LeftNV;
                    hugeMap[currentPos.Row + 1, currentPos.Col].State &= ~TileStates.TopNV;
                    hugeMap[currentPos.Row, currentPos.Col - 1].State &= ~TileStates.RightNV;
                    hugeMap[currentPos.Row, currentPos.Col].State     |= TileStates.Visited;

                    PossiblePos = currentPos;

                    return(action);
                }
                else
                {
                    //if no current tile has no unexplored neighbours and there are still grey tiles on map
                    if (GreyExists())
                    {
                        //A* to search for nearest grey
                        GetPathToGrey();
                        followPath = true;
                    }
                    else
                    {
                        //Finishing phase 1
                        //Rewrting HugeMap contents to SmallMap
                        int minRow = int.MaxValue, minCol = int.MaxValue;
                        for (int row = 0; row < hugeMap.GetLength(0); ++row)
                        {
                            for (int col = 0; col < hugeMap.GetLength(1); ++col)
                            {
                                if ((hugeMap[row, col].State & TileStates.Visited) != 0)
                                {
                                    minRow = System.Math.Min(minRow, row);
                                    minCol = System.Math.Min(minCol, col);
                                }
                                else
                                {
                                    hugeMap[row, col].State |= TileStates.Wall;
                                }
                            }
                        }

                        Tile[,] smallMap = SmallMap;
                        for (int row = 0; row < Environment.mazeSize_; ++row)
                        {
                            for (int col = 0; col < Environment.mazeSize_; ++col)
                            {
                                smallMap[row, col] = hugeMap[row + minRow, col + minCol];
                            }
                        }

                        CurrentPos.Row -= minRow;
                        CurrentPos.Col -= minCol;
                        HugeMap         = null;
                        Fringe          = null;
                        Phase1Running   = false;
                    }
                }
            }
            else
            {
                followPath = true;
            }

            if (followPath)
            {
                //Following path generated by A* on some previous step
                Point dest = GoingToGrey.Value;
                GoingToGrey = GoingToGrey.Parent;
                PossiblePos = dest;

                if (dest.Row < currentPos.Row)
                {
                    return(ActionType.actUP);
                }
                if (dest.Col > currentPos.Col)
                {
                    return(ActionType.actRIGHT);
                }
                if (dest.Row > currentPos.Row)
                {
                    return(ActionType.actDOWN);
                }
                if (dest.Col < currentPos.Col)
                {
                    return(ActionType.actLEFT);
                }
            }
            return(ActionType.actIDLE);
        }
Example #33
0
    void BuildTileMap()
    {
        tileMap = new Tile[width,height];
        Dictionary<int, List<Tile>> rowOfTilesMap = new Dictionary<int, List<Tile>>();
        Debug.Log(tileList.Count);
        foreach (Tile tile in tileList) {
            int z = Mathf.RoundToInt(tile.gameObject.transform.position.z);
            Debug.Log("z: " + z + " Tile: " + tile);
            if (!rowOfTilesMap.ContainsKey(z)) {
                Debug.Log("created row at " + z);
                rowOfTilesMap.Add(z, new List<Tile>());
            }
            rowOfTilesMap[z].Add(tile);
        }
        foreach (KeyValuePair<int, List<Tile>> row in rowOfTilesMap) {
            if (row.Value.Count != width) {
                Debug.LogError("Row of tiles has inconsistent size: " + row.Value.Count + " , expected: " + width
                               + " , rowNo: " + row.Key);
            }
        }
        foreach (List<Tile> row in rowOfTilesMap.Values) {
            row.Sort((tileA, tileB) => tileA.gameObject.transform.position.x.CompareTo(tileB.gameObject.transform.position.x));
        }
        List<int> rowOrder = new List<int>();
        foreach(int i in rowOfTilesMap.Keys) {
            rowOrder.Add(i);
        }
        rowOrder.Sort();

        for (int i = 0; i < rowOrder.Count; i++) {
            int rowIndex = rowOrder[i];
            List<Tile> rowOfTiles = rowOfTilesMap[rowIndex];
            for (int j = 0; j < rowOfTiles.Count; j++) {
                Tile tile = rowOfTiles[j];
                tile.SetColumnAndRow(j, i);
                tileMap[j, i] = tile;
            }
        }

        int rowLength = tileMap.GetLength(0);
        int colLength = tileMap.GetLength(1);
        for (int i = 0; i < rowLength; i++) {
            string name = "";
            for (int j = 0; j < colLength; j++)	{
                name += tileMap[i, j] + "   |   ";
            }
            Debug.Log(name);
        }
    }
Example #34
0
        /// <summary>
        /// A* to generate path to nearest grey tile
        /// </summary>
        private void GetPathToGrey()
        {
            Point currentPos = CurrentPos;

            Fringe.Clear();
            Fringe.Add(CurrentPos, null, 0, NearestGrey(currentPos));

            Node  bestNode = Fringe.GetBestNode();
            Point pos      = bestNode.Value;
            Point childPos;

            Tile[,] map = HugeMap;
            TileStates state;
            int        width = map.GetLength(0);

            //while not goal state
            while ((map[pos.Row, pos.Col].State & GreyTileSign) == 0)
            {
                //adding neighbour tiles to Fringe if they are not walls
                if (pos.Row > 0)
                {
                    state = map[pos.Row - 1, pos.Col].State;
                    if ((state & TileStates.Wall) == 0 && (state & TileStates.Visited) != 0)
                    {
                        childPos = new Point(pos.Row - 1, pos.Col);
                        Fringe.Add(childPos, bestNode, bestNode.RealCost + 1, NearestGrey(childPos));
                    }
                }

                if (pos.Col < width - 1)
                {
                    state = map[pos.Row, pos.Col + 1].State;
                    if ((state & TileStates.Wall) == 0 && (state & TileStates.Visited) != 0)
                    {
                        childPos = new Point(pos.Row, pos.Col + 1);
                        Fringe.Add(childPos, bestNode, bestNode.RealCost + 1, NearestGrey(childPos));
                    }
                }

                if (pos.Row < width - 1)
                {
                    state = map[pos.Row + 1, pos.Col].State;
                    if ((state & TileStates.Wall) == 0 && (state & TileStates.Visited) != 0)
                    {
                        childPos = new Point(pos.Row + 1, pos.Col);
                        Fringe.Add(childPos, bestNode, bestNode.RealCost + 1, NearestGrey(childPos));
                    }
                }

                if (pos.Col > 0)
                {
                    state = map[pos.Row, pos.Col - 1].State;
                    if ((state & TileStates.Wall) == 0 && (state & TileStates.Visited) != 0)
                    {
                        childPos = new Point(pos.Row, pos.Col - 1);
                        Fringe.Add(childPos, bestNode, bestNode.RealCost + 1, NearestGrey(childPos));
                    }
                }

                bestNode = Fringe.GetBestNode();
                pos      = bestNode.Value;
            }

            //Reverse path
            Node temp1 = bestNode, temp2 = bestNode.Parent, temp3;

            while (temp2.Parent != null)
            {
                temp3        = temp2.Parent;
                temp2.Parent = temp1;
                temp1        = temp2;
                temp2        = temp3;
            }
            temp2.Parent    = temp1;
            bestNode.Parent = null;

            GoingToGrey = temp1;
        }
Example #35
0
        public static void Initialize(int _renderWidth)
        {
            renderWidth = _renderWidth;

            tiles = new Tile[Data.MapSize, Data.MapSize];

            allGameObjects = new Dictionary<Guid, GameObject>();
            allMobs = new Dictionary<Guid, Mob>();
            allToons = new Dictionary<Guid, Toon>();

            for (int x = 0; x < tiles.GetLength(0); x++)
            {
                for (int y = 0; y < tiles.GetLength(1); y++)
                {
                    tiles[x, y] = new Tile("snow1", x, y);
                    //to be passed in by the server
                }
            }
        }
Example #36
0
        private void ResizeGrid()
        {
            Tile[,] tempTileArr = new Tile[gridWidth, gridHeight];
            Rectangle[,] tempRectArr = new Rectangle[gridWidth, gridHeight];

            for (int i = 0; i < gridWidth; i++)
            {
                for (int j = 0; j < gridHeight; j++)
                {
                    tempTileArr[i, j] = new Tile(Color.White);
                    tempTileArr[i, j].Image = imageMap["empty"];
                }
            }

            for (int i = 0; i < Math.Min(tiles.GetLength(0), tempTileArr.GetLength(0)); i++)
                for (int j = 0; j < Math.Min(tiles.GetLength(1), tempTileArr.GetLength(1)); j++)
                {
                    tempTileArr[i, j].Image = tiles[i, j].Image;
                }

            tiles = tempTileArr;

            //gridPanel.Size = new Size(gridWidth * (rectSize + 5), gridHeight * (rectSize + 5));
            this.gridPanel.AutoScrollMargin = new System.Drawing.Size(origXMargin, origYMargin);
            this.gridPanel.AutoScrollMinSize = new System.Drawing.Size(rectSize * (tiles.GetLength(0) + initScrollOffsetX), (rectSize / 2) * (tiles.GetLength(1) + initScrollOffsetY));
            paintOffsetX = 0F;
            paintOffsetY = 0F;

            // 18000 is based of 30x30 iniDrawOffsetX was 600 and 90x30 was 200 so that gave 18000 / 30 and 90
            initDrawOffsetX = 18000 / gridWidth;
        }
Example #37
0
        private void LoadLevel(string level)
        {
            List<string> lines = level.Split('\n', '\r').ToList<string>();
            int count = 0;
            foreach (string str in lines)
            {
                if (str == "")
                {
                    count++;
                }
            }
            for (int n = 0; n < count; n++)
                lines.Remove("");

            int width = lines[0].Length;
            int height = lines.Count;

            tiles = new Tile[width, height];

            LoadTileResources();

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    tiles[x, y] = LoadTile(x, y, lines[y][x]);
                }
            }

            bottom = tiles.GetLength(1) * Tile.TileSize.Y + Tile.TileSize.Y;
        }
Example #38
0
        public MainEditorWindow()
        {
            commandQueue = new Stack<ICommand>();
            redoCommandQueue = new Stack<ICommand>();
            hazards = new BindingList<Hazard>();

            // Gets the current directory
            string dir = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

            // Set the tile array to the proper grid size
            tiles = new Tile[gridWidth, gridHeight];

            // Add all textures available at the moment
            imageMap.Add("empty", Image.FromFile(dir + "/empty.png"));
            imageMap.Add("grass", Image.FromFile(dir + "/grass.png"));
            imageMap.Add("ground", Image.FromFile(dir + "/ground.png"));
            imageMap.Add("background", Image.FromFile(dir + "/background_sky.png"));

            // Initial tile to be drawn is "Empty"
            currentImage = imageMap["empty"];

            // Initialize tile array
            for (int i = 0; i < tiles.GetLength(0); i++)
                for (int j = 0; j < tiles.GetLength(1); j++)
                {
                    tiles[i, j] = new Tile(Color.White);
                    tiles[i, j].Image = imageMap["empty"];
                }

            InitializeComponent();
            this.javaTestItem.Click += new EventHandler(this.testJava_Click);
            this.KeyPreview = true;
            this.KeyDown += this.form_KeyDown;
            this.KeyUp += this.form_KeyUp;
            /* All not auto-generated code for UI here */
            this.comboBox1.SelectedIndex = 0;
            this.comboBox2.SelectedIndex = 0;
            this.Text = "LevelEditor";
            this.exitItem.Click += new System.EventHandler(exitItem_Click);

            this.listBox1.DataSource = hazards;

            typeof(System.Windows.Forms.Panel).InvokeMember("DoubleBuffered", System.Reflection.BindingFlags.SetProperty |
               System.Reflection.BindingFlags.Instance |
               System.Reflection.BindingFlags.NonPublic, null, gridPanel, new object[] { true });

            // Set initial values (Sort of magic numbers-ish right now)
            maxZoom = 40;
            minZoom = 5;

            initDrawOffsetX = 600;
            initDrawOffsetY = 80;

            initScrollOffsetX = 50;
            initScrollOffsetY = 50;

            origXMargin = 10 + initDrawOffsetX;
            origYMargin = 10 + initDrawOffsetY;
        }
Example #39
0
        /// <summary>
        /// Creates the whole room and all of its tiles.
        /// </summary>
        /// <param name="rnd">Random class.</param>
        /// <param name="currCircle">The current circle the game takes place on.</param>
        public void CreateLevel(Random rnd, int currCircle)
        {
            List <string> stringList = ReadFromFile(fileName);

            tileArray = new Tile[stringList[0].Length, stringList.Count];
            int frameY = currCircle - 1;

            for (int x = 0; x < tileArray.GetLength(0); x++)
            {
                for (int y = 0; y < tileArray.GetLength(1); y++)
                {
                    switch (stringList[y][x])
                    {
                    case 'C':

                        tileArray[x, y] = NewWallTile(x, y, frameY, rnd);
                        wallTiles.Add(tileArray[x, y]);

                        break;

                    case 'U':

                        if (!upConnection)
                        {
                            tileArray[x, y] = NewWallTile(x, y, frameY, rnd);
                            wallTiles.Add(tileArray[x, y]);
                        }
                        else
                        {
                            tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        }

                        break;

                    case 'L':

                        if (!leftConnection)
                        {
                            tileArray[x, y] = NewWallTile(x, y, frameY, rnd);

                            wallTiles.Add(tileArray[x, y]);
                        }
                        else
                        {
                            tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        }

                        break;

                    case 'R':

                        if (!rightConnection)
                        {
                            tileArray[x, y] = NewWallTile(x, y, frameY, rnd);
                            wallTiles.Add(tileArray[x, y]);
                        }
                        else
                        {
                            tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        }


                        break;

                    case 'D':

                        if (!downConnection)
                        {
                            tileArray[x, y] = NewWallTile(x, y, frameY, rnd);
                            wallTiles.Add(tileArray[x, y]);
                        }
                        else
                        {
                            tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        }

                        break;

                    case 'B':

                        tileArray[x, y] = NewWallTile(x, y, frameY, rnd);
                        //wallTiles.Add(tileArray[x, y]);

                        break;

                    case 'E':

                        if (exitRoom)
                        {
                            tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                            Tile endTile = new Tile(SpriteSheetManager.stairTile, new Rectangle(pos.X + Constants.tileSize * x, pos.Y + Constants.tileSize * y, Constants.tileSize, Constants.tileSize), 0, 0, false);
                            Level.endTileList.Add(endTile);
                        }
                        else if (!upConnection)
                        {
                            tileArray[x, y] = NewWallTile(x, y, frameY, rnd);
                            wallTiles.Add(tileArray[x, y]);
                        }
                        else
                        {
                            tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        }

                        break;

                    case 'F':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);

                        break;

                    case 'S':

                        tileArray[x, y]  = NewFloorTile(x, y, frameY, rnd);
                        playerSpawnPoint = tileArray[x, y].middlepos;

                        break;

                    case 'O':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        bossSpawnPoint  = tileArray[x, y].middlepos;

                        break;

                    case 'G':

                        Tile rockTile = new Tile(SpriteSheetManager.rock, new Rectangle(pos.X + Constants.tileSize * x, pos.Y + Constants.tileSize * y, Constants.tileSize, Constants.tileSize), 0, 0, true)
                        {
                            isRock = true
                        };
                        wallTiles.Add(rockTile);
                        Level.rockTiles.Add(rockTile);
                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);

                        break;

                    case 'e':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        Level.enemySpawnTiles.Add(tileArray[x, y]);

                        break;

                    case 'i':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);

                        Level.itemsList.Add(LoadWeaponsAndItems.NewStatUpgrade(tileArray[x, y].middlepos, false, rnd));

                        break;

                    case 'I':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        Level.itemsList.Add(LoadWeaponsAndItems.NewStatUpgrade(tileArray[x, y].middlepos, true, rnd));

                        break;

                    case 'w':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        Level.itemsList.Add(LoadWeaponsAndItems.NewWeaponItem(tileArray[x, y].middlepos, currCircle, false, rnd));

                        break;

                    case 'W':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        Level.itemsList.Add(LoadWeaponsAndItems.NewWeaponItem(tileArray[x, y].middlepos, currCircle, true, rnd));

                        break;

                    case 'K':
                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);

                        Level.shopKeeper = new NPC(SpriteSheetManager.shopKeeper, 0.5d, new Point(128, 128), new Vector2(pos.X + Constants.tileSize * x, pos.Y + Constants.tileSize * y), SpriteSheetManager.shopKeeperTextbox, new Point(200, 100));
                        break;

                    case '1':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        if (!upConnection && !exitRoom)
                        {
                            if (rnd.Next(2) == 0)
                            {
                                Level.NewVase(tileArray[x, y].middlepos);
                            }
                        }

                        break;

                    case '2':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        if (!rightConnection)
                        {
                            if (rnd.Next(2) == 0)
                            {
                                Level.NewVase(tileArray[x, y].middlepos);
                            }
                        }

                        break;

                    case '3':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        if (!downConnection)
                        {
                            if (rnd.Next(2) == 0)
                            {
                                Level.NewVase(tileArray[x, y].middlepos);
                            }
                        }

                        break;

                    case '4':

                        tileArray[x, y] = NewFloorTile(x, y, frameY, rnd);
                        if (!leftConnection)
                        {
                            if (rnd.Next(2) == 0)
                            {
                                Level.NewVase(tileArray[x, y].middlepos);
                            }
                        }

                        break;

                    case 'o':

                        tileArray[x, y] = NewInvisibleTile(x, y, frameY, rnd);
                        wallTiles.Add(tileArray[x, y]);

                        break;
                    }
                }
            }
        }
Example #40
0
        public TileMask[] GetBitmapsFromSelectedTiles(bool flipX, bool flipY, TilePriority priority)
        {
            if (selectedTiles == null)
            {
                return(null);
            }
            TileMask[] tms =
                new TileMask[selectedTiles.GetLength(0) * selectedTiles.GetLength(1)];

            int w = selectedTiles.GetLength(0) - 1;
            int h = selectedTiles.GetLength(1) - 1;

            int  k = 0;
            int  x, y;
            char c1, c2;

            c1 = selectedTiles[0, 0].Code[2];
            c2 = selectedTiles[w, 0].Code[2];

            bool even1 = (c1 % 2 == 0 && c1 > '9') ||
                         (c1 % 2 == 1 && c1 <= '9');

            bool even2 = (c2 % 2 == 0 && c2 > '9') ||
                         (c2 % 2 == 1 && c2 <= '9');

            bool oddX = even1 != even2;

            c1 = selectedTiles[0, 0].Code[1];
            c2 = selectedTiles[0, h].Code[1];

            even1 = (c1 % 2 == 0 && c1 > '9') ||
                    (c1 % 2 == 1 && c1 <= '9');

            even2 = (c2 % 2 == 0 && c2 > '9') ||
                    (c2 % 2 == 1 && c2 <= '9');
            bool oddY = even1 != even2;

            x = 0;
            int tileSize = 16;

            if (selectedTiles[0, 0].Size == 8)
            {
                tileSize = 8;
            }
            int zsiz = tileSize * TileZoom;

            for (int i = 0; i < selectedTiles.GetLength(0); i++, x += zsiz)
            {
                if (tileSize == 16 && oddX && i == w)
                {
                    x -= (zsiz / 2);
                }

                y = 0;
                for (int j = 0; j < selectedTiles.GetLength(1); j++, y += zsiz)
                {
                    if (tileSize == 16 && oddY && j == h)
                    {
                        y -= (zsiz / 2);
                    }
                    tms[k] = new TileMask(sp, selectedTiles[i, j], TileZoom, flipX, flipY)
                    {
                        Priority = priority,
                        XDisp    = x,
                        YDisp    = y
                    };
                    k++;
                }
            }
            return(tms);
        }
Example #41
0
        //Pre: The map name, the current user, the game tiles, the enemies, the player, all the projectiles, the amount of time that elapsed this far into the game, the amount of enemies killed
        //Post: A boolean for whether the map was saved
        //Desc: A method for saving the current map
        public bool SaveCurrentMap(string mapName, string currentUser, Tile[,] gameTiles, List <Enemy> enemies, Player player, List <Projectile> projectiles, float elapsedTime, int enemiesKilled)
        {
            //Creates the stream writer with the path of the current map save
            writer = new StreamWriter(currentUser + "_" + mapName + SAVE_MAP_PATH_SUFFIX);

            //Writes teh length of the game tiles array dimensions
            writer.WriteLine(gameTiles.GetLength(0));
            writer.WriteLine(gameTiles.GetLength(1));

            //Loop for every value of the first dimension of the gametiles 2D array
            for (int i = 0; i < gameTiles.GetLength(0); i++)
            {
                //Loop for every value of the second dimension of the gametiles 2D array
                for (int j = 0; j < gameTiles.GetLength(1); j++)
                {
                    //Writes the current tile type
                    writer.WriteLine(gameTiles[i, j].CurrentTileType);
                }
            }

            //Writes the amount of enemies to the file
            writer.WriteLine(enemies.Count);

            //Loop for every enemy
            for (int i = 0; i < enemies.Count; i++)
            {
                //The enemies position and health is written to the file
                writer.WriteLine(enemies[i].Position.X);
                writer.WriteLine(enemies[i].Position.Y);
                writer.WriteLine(enemies[i].Health);
            }

            //Writes the amount of projectiles
            writer.WriteLine(projectiles.Count);

            //Loop for every projectile
            for (int i = 0; i < projectiles.Count; i++)
            {
                //The projectiles values are written to the file
                writer.WriteLine(projectiles[i].GetBounds().X);
                writer.WriteLine(projectiles[i].GetBounds().Y);
                writer.WriteLine(projectiles[i].GetProjectileType());
                writer.WriteLine(projectiles[i].Damage);
                writer.WriteLine(projectiles[i].Speed);
                writer.WriteLine(projectiles[i].GetRotationAngle());
                writer.WriteLine(projectiles[i].NeedDestroy);
                writer.WriteLine(projectiles[i].PlayerBullet);

                //If the projectile is not a player's projectile
                if (!projectiles[i].PlayerBullet)
                {
                    //Loop for every enemy
                    for (int j = 0; j < enemies.Count; j++)
                    {
                        //If the bullet owner of the current projectile is the current enemy
                        if (projectiles[i].BulletOwner == enemies[j])
                        {
                            //The bullet owner's index is saved to the file and the for loop is stopped
                            writer.WriteLine(j);
                            j = enemies.Count;
                        }
                    }
                }
            }

            //Writes the player's stats to the file
            writer.WriteLine(player.Position.X);
            writer.WriteLine(player.Position.Y);
            writer.WriteLine(player.Health);

            //Writes the elapsed time of the game to the file and the amount of enemies killed
            writer.WriteLine(elapsedTime);
            writer.WriteLine(enemiesKilled);

            //Closes the stream writer
            writer.Close();

            //If the file was updated on the server
            if (onlineHelper.UpdateFile(currentUser + "_" + mapName + SAVE_MAP_SUFFIX, currentUser + "_" + mapName + SAVE_MAP_PATH_SUFFIX, FILE_TYPE, SAVE_MAP_FILE_DESCRIPTION))
            {
                //Returns that the map was saved
                return(true);
            }

            //Returns that the map was not saved
            return(false);
        }
Example #42
0
 public TileMap(Tile[,] tiles)
 {
     Tiles  = tiles;
     Width  = tiles.GetLength(1);
     Height = tiles.GetLength(0);
 }
Example #43
0
    public Stage(String textfile, Material floor, Material wall, FluffBuilder fbuilder)
    {
        levels = new ArrayList();
        spawnedRooms = new ArrayList();
        grid = ParseTextStage(textfile, floor, wall);
        this.width = grid.GetLength(0);
        this.height = grid.GetLength(1);
        this.floorMaterial = floor;
        this.wallMaterial = wall;
        this.rooms = new ArrayList();
        AddLevel(grid, this.rooms);
        this.FBuilder = fbuilder;

    }
Example #44
0
 // Gets the tile in this grid at the coordinates given
 public bool GetTileAtCoords(Coord coords, out Tile result, bool consolePrint = true)
 {
     if (coords.X < 0 || coords.X >= TileGrid.GetLength(0) || coords.Y < 0 || coords.Y >= TileGrid.GetLength(1))
     {
         if (consolePrint)
         {
             Output.WriteLineTagged("Coordinates given are out of range of the grid", Output.Tag.Error);
         }
         result = null;
         return(false);
     }
     result = TileGrid[coords.X, coords.Y];
     return(true);
 }
	// Use this for initialization
	void Awake (){
		
		//get level data
		var lvlPL=GameObject.FindGameObjectWithTag("LevelPlaylist").GetComponent<LevelPlaylist>();
		var lvlDB=GameObject.FindGameObjectWithTag("EntityDatabase").GetComponent<LevelDatabase>();
		stats=lvlDB.getLevel(lvlPL.getCurrentLevelName());
		
		//var spawn_positions=new List<Tile>();
		
		mesh_bounds=tile_mesh.renderer.bounds;
		main_camera=GameObject.Find("Main Camera").GetComponent<CameraScript>();
		main_camera.DetachPlane();
		
		
		var hexa_size=mesh_bounds.size;
		
		terrain=new Tile[LevelWidth,LevelHeight];
		
		var pos=Vector3.zero;
		float tile_w=hexa_size.x,tile_h=hexa_size.z;//ground_prefab.transform.localScale.x
		
		
		
		//creating tiles
		Vector3 coor=new Vector3(0,0,0);
		
		for (int i=0;i<terrain.GetLength(0);i++)
		{
			if (i%2!=0)
				pos.z=tile_h/2;
			else
				pos.z=0;
			
			if (i!=0&&(i%2==0)){
				coor.x-=1;
			}
			coor.y=i;
			
			for (int j=0;j<terrain.GetLength(1);j++)
			{
				var tile=Instantiate(ground_prefab,pos,Quaternion.identity) as Transform;
				tile.transform.parent=transform;
				var ts=tile.GetComponent("Tile") as Tile;
				terrain[i,j]=ts;
				tiles.Add(ts);
				ts.setCoordinate(new Vector3(coor.x+j,coor.y,-((coor.x+j)+coor.y)));
				
				if (Subs.RandomPercent()<stats.Tile_random_low_change){
					ts.Tile_Data.setMovementBounds(stats.Tile_random_low_height,0f);
					ts.Tile_Data.setTimeBounds(stats.Tile_random_time_min,stats.Tile_random_time_max,true);
				}
				
				if (Subs.RandomPercent()<stats.Tile_random_high_change){
					ts.Tile_Data.setMovementBounds(stats.Tile_random_high_height,0f);
					ts.Tile_Data.setTimeBounds(stats.Tile_random_time_min,stats.Tile_random_time_max,true);
				}

				pos.z+=tile_h+0.01f;
			}
			//pos.x+=tile_w+(tile_w*0.5f);
			pos.x+=tile_w*(3f/4f);
		}
		//load land shape DEV. circle
		
		int xx=terrain.GetLength(0)/2,yy=terrain.GetLength(1)/2;
		center_point=terrain[xx,yy].getCoordinate();
		var radius=xx-1;
		
		
		
		for (int i=0;i<terrain.GetLength(0);i++)
		{
			for (int j=0;j<terrain.GetLength(1);j++)
			{
				var ts=terrain[i,j];
				if (!HexaDistanceInside(center_point,ts.getCoordinate(),radius)){
					ts.gameObject.SetActive(false);
				}					
			}
		}
		
		//group up tiles
		int group_amount=radius+1;
		for (int g=0;g<group_amount;g++){
			radius=(group_amount-g);
			var data=new TileData(Vector3.zero,g);
			data.setMovementBounds(0.03f,0.03f);
			data.setTimeBounds(1000,1000,true);
			tile_groups.Add(data);
			
			foreach (var ts in tiles){
				if (HexaDistanceInside(center_point,ts.getCoordinate(),radius)){
					ts.setTileGroup(data);
				}
			}
		}
		terrain[xx,yy].setTileGroup(null);//center not moving
		terrain[xx,yy].Tile_Data.Activate(false);
		
		main_camera.setMiddlePos(terrain[xx,yy].transform.position);
		
		terrain_timer=new Timer(stats.Terrain_deterioration_time,OnTerrainTrigger);
		
		//main_camera.transform.position=new Vector3(terrain[xx,yy].transform.position.x,main_camera.transform.position.y,main_camera.transform.position.z);
		//main_camera.LookAtCenter(terrain[xx,yy].transform.position);
		main_camera.DetachPlane();
		
		//pause level
		Activate(false);
		
		foreach (var t in tile_groups){
			t.Activate(false);
		}
	}
Example #46
0
        public static Texture getHeightMapTexture(Tile[,] tiles)
        {
            int width   = tiles.GetLength(0);
            int height  = tiles.GetLength(1);
            var texture = new Texture(width, height);
            var pixels  = new Color4[width, height];

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    switch (tiles[x, y].myHeightType)
                    {
//                case HeightType.DeepWater:
//                   pixels[x, y] = new Color4(0f, 0f, 0f, 1f);
//                   break;
//                case HeightType.ShallowWater:
//                   pixels[x, y]= new Color4(0f, 0f, 0f, 1f);
//                   break;
//                case HeightType.Shore:
//                   pixels[x, y] = new Color4(0.15f, 0.15f, 0.15f, 1f);
//                   break;
//                case HeightType.Sand:
//                   pixels[x, y]= new Color4(0.3f, 0.3f, 0.3f, 1f);
//                   break;
//                case HeightType.Grass:
//                   pixels[x, y]= new Color4(0.45f, 0.45f, 0.45f, 1f);
//                   break;
//                case HeightType.Forest:
//                   pixels[x, y]= new Color4(0.6f, 0.6f, 0.6f, 1f);
//                   break;
//                case HeightType.Rock:
//                   pixels[x, y]= new Color4(0.75f, 0.75f, 0.75f, 1f);
//                   break;
//                case HeightType.Snow:
//                   pixels[x, y]= new Color4(1f, 1f, 1f, 1f);
//                   break;
//                case HeightType.River:
//                   pixels[x, y] = new Color4(0f, 0f, 0f, 1f);
//                   break;

//                case HeightType.DeepWater:
//                case HeightType.ShallowWater:
//                case HeightType.River:
//                   pixels[x, y] = Color4.Black;
//                   break;
                    default:
                        pixels[x, y] = ColorExt.mix(Color4.Black, Color4.White, tiles[x, y].myHeightValue);
                        break;
                    }

                    //darken the color if a edge tile
                    if (tiles[x, y].myBitmask != 15)
                    {
                        pixels[x, y] = ColorExt.mix(pixels[x, y], Color4.Black, 0.4f);
                    }
                }
            }

            texture.setPixels(ref pixels);

            return(texture);
        }
Example #47
0
    public Map(int minWidth, int maxWidth, int minHeight, int maxHeight, int numEnemies, int numGold) //methods
    {
        // random width and height calculations

        width = rando.Next(minWidth, maxWidth + 1);

        height = rando.Next(minHeight, maxHeight + 1);

        //declaring array sizes

        enemies = new Enemy[numEnemies];

        mapArray = new Tile[width, height];

        goldArray = new Item[numGold];

        itemArray = new Item[numGold];


        //for loops for filling arrays

        for (int i = 0; i < mapArray.GetLength(1); i++)     //i is used for width
        {
            for (int j = 0; j < mapArray.GetLength(0); j++) //j is used for length
            {
                mapArray[i, j] = new EmptyTile(j, i);
            }
        }

        for (int i = 0; i < mapArray.GetLength(1); i++)                        //i is used for width
        {
            for (int j = 0; j < mapArray.GetLength(0); j++)                    //j is used for length
            {
                mapArray[i, 0] = new Obstacle(j, i);                           // [i,0] top row
                mapArray[0, j] = new Obstacle(j, i);                           // [0,j] left column

                mapArray[i, (mapArray.GetLength(1) - 1)] = new Obstacle(j, i); //bottom row
                mapArray[(mapArray.GetLength(0) - 1), j] = new Obstacle(j, i); //right column
            }
        }

        Player = (Hero)Create(TileType.Hero);

        for (int i = 0; i < numEnemies; i++)            //loop for each enemy
        {
            enemies[i] = (Enemy)Create(TileType.Enemy); //creates enemy object

            mapArray[enemies[i].x, enemies[i].y] = enemies[i];
        }

        for (int i = 0; i < numGold; i++)
        {
            goldArray[i] = (Gold)Create(TileType.Gold);

            mapArray[goldArray[i].x, goldArray[i].y] = goldArray[i];
        }

        mapArray[Player.x, Player.y] = Player;

        UpdateVision();
    }
Example #48
0
        public static Texture getBiomeMapTexture(Tile[,] tiles, float coldest, float colder, float cold)
        {
            int width   = tiles.GetLength(0);
            int height  = tiles.GetLength(1);
            var texture = new Texture(width, height);
            var pixels  = new Color4[width, height];

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    BiomeType value = tiles[x, y].myBiomeType;

                    switch (value)
                    {
                    case BiomeType.Ice:
                        pixels[x, y] = Ice;
                        break;

                    case BiomeType.Tundra:
                        pixels[x, y] = Tundra;
                        break;

                    case BiomeType.Desert:
                        pixels[x, y] = Desert;
                        break;

                    case BiomeType.Grassland:
                        pixels[x, y] = Grassland;
                        break;

                    case BiomeType.Savanna:
                        pixels[x, y] = Savanna;
                        break;

                    case BiomeType.TemperateSeasonalForest:
                        pixels[x, y] = TemperateSeasonalForest;
                        break;

                    case BiomeType.TropicalSeasonalForest:
                        pixels[x, y] = TropicalSeasonalForest;
                        break;

                    case BiomeType.Taiga:
                        pixels[x, y] = Taiga;
                        break;

                    case BiomeType.TemperateRainforest:
                        pixels[x, y] = TemperateRainForest;
                        break;

                    case BiomeType.TropicalRainforest:
                        pixels[x, y] = TropicalRainForest;
                        break;
                    }

                    // Water tiles
                    if (tiles[x, y].myHeightType == HeightType.DeepWater)
                    {
                        pixels[x, y] = DeepColor;
                    }
                    else if (tiles[x, y].myHeightType == HeightType.ShallowWater)
                    {
                        pixels[x, y] = ShallowColor;
                    }

                    // draw rivers
                    if (tiles[x, y].myHeightType == HeightType.River)
                    {
                        float heatValue = tiles[x, y].myHeatValue;

                        if (tiles[x, y].myHeatType == HeatType.Coldest)
                        {
                            pixels[x, y] = ColorExt.mix(IceWater, ColdWater, (heatValue) / (coldest));
                        }
                        else if (tiles[x, y].myHeatType == HeatType.Colder)
                        {
                            pixels[x, y] = ColorExt.mix(ColdWater, RiverWater, (heatValue - coldest) / (colder - coldest));
                        }
                        else if (tiles[x, y].myHeatType == HeatType.Cold)
                        {
                            pixels[x, y] = ColorExt.mix(RiverWater, ShallowColor, (heatValue - colder) / (cold - colder));
                        }
                        else
                        {
                            pixels[x, y] = ShallowColor;
                        }
                    }


                    // add a outline
                    if (tiles[x, y].myHeightType >= HeightType.Shore && tiles[x, y].myHeightType != HeightType.River)
                    {
                        if (tiles[x, y].myBiomeBitmask != 15)
                        {
                            pixels[x, y] = ColorExt.mix(pixels[x, y], Color4.Black, 0.35f);
                        }
                    }
                }
            }

            texture.setPixels(ref pixels);
            return(texture);
        }
Example #49
0
        private void DrawChunkBorder(GameBoard board, Tile[,] chunk, int chunkX, int chunkY, int beginX, int beginY, Graphics g)
        {
            int width  = chunk.GetLength(0);
            int height = chunk.GetLength(1);

            int tileSize     = this.TileSize;
            int halfTileSize = tileSize / 2;


            for (int x = 0; x < width; ++x)
            {
                int tileX = x * tileSize + beginX + halfTileSize;


                for (int y = 0; y < height; ++y)
                {
                    var tile = chunk[x, y];

                    // 영토(타일)가 존재하면
                    if (tile != null)
                    {
                        int tileY = y * tileSize + beginY + halfTileSize;


                        int[] nearX = new int[]
                        {
                            x, x + 1
                        };
                        int[] nearY = new int[]
                        {
                            y - 1, y
                        };

                        for (int i = 0; i < 2; ++i)
                        {
                            Tile nearTile = null;

                            if (nearX[i] < 0 || nearX[i] >= width
                                ||
                                nearY[i] < 0 || nearY[i] >= height)
                            {
                                int globalX = chunkX * board.Board.ChunkSize + nearX[i];
                                int globalY = chunkY * board.Board.ChunkSize + nearY[i];

                                if (board.Board.ContainsItemAt(globalX, globalY))
                                {
                                    nearTile = board.Board.GetItemAt(globalX, globalY);
                                }
                            }
                            else
                            {
                                nearTile = chunk[nearX[i], nearY[i]];
                            }

                            if (nearTile != null && nearTile.Owner != tile.Owner)
                            {
                                switch (i)
                                {
                                case 0:
                                    g.DrawLine(Pens.Black,
                                               beginX + x * TileSize, beginY + y * TileSize,
                                               beginX + x * TileSize + TileSize, beginY + y * TileSize);
                                    break;

                                case 1:
                                    g.DrawLine(Pens.Black,
                                               beginX + x * TileSize + TileSize, beginY + y * TileSize,
                                               beginX + x * TileSize + TileSize, beginY + y * TileSize + TileSize);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Example #50
0
    public static List <Grid.Position> Search(Grid.Position myPosition, Grid.Position positionToFind, Tile[,] tiles)
    {
        int width  = tiles.GetLength(0);
        int heigth = tiles.GetLength(1);
        Queue <Grid.Position> fila = new Queue <Grid.Position>();
        List <Grid.Position>  path = new List <Grid.Position>();

        fila.Enqueue(myPosition);
        HashSet <Grid.Position> PlacesVisited = new HashSet <Grid.Position>();

        Grid.Position[,] Paths = new Grid.Position[tiles.GetLength(0), tiles.GetLength(1)];

        Paths[myPosition.x, myPosition.y] = myPosition;
        while (fila.Count > 0)
        {
            Grid.Position current = fila.Dequeue();

            if (current.x == positionToFind.x && current.y == positionToFind.y)
            {
                path.Add(current);

                while (current.x != myPosition.x || current.y != myPosition.y)
                {
                    current = Paths[current.x, current.y];
                    path.Add(current);
                }
                path.Reverse();
                break;
            }

            else
            {
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x + 1, y = current.y
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x + 1, y = current.y
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x + 1, y = current.y
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x + 1, y = current.y
                    });
                    Paths[current.x + 1, current.y] = current;
                }
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x - 1, y = current.y
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x - 1, y = current.y
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x - 1, y = current.y
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x - 1, y = current.y
                    });
                    Paths[current.x - 1, current.y] = current;
                }
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x, y = current.y + 1
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x, y = current.y + 1
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x, y = current.y + 1
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x, y = current.y + 1
                    });
                    Paths[current.x, current.y + 1] = current;
                }
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x, y = current.y - 1
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x, y = current.y - 1
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x, y = current.y - 1
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x, y = current.y - 1
                    });
                    Paths[current.x, current.y - 1] = current;
                }
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x + 1, y = current.y + 1
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x + 1, y = current.y + 1
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x + 1, y = current.y + 1
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x + 1, y = current.y + 1
                    });
                    Paths[current.x + 1, current.y + 1] = current;
                }
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x - 1, y = current.y + 1
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x - 1, y = current.y + 1
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x - 1, y = current.y + 1
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x - 1, y = current.y + 1
                    });
                    Paths[current.x - 1, current.y + 1] = current;
                }
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x + 1, y = current.y - 1
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x + 1, y = current.y - 1
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x + 1, y = current.y - 1
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x + 1, y = current.y - 1
                    });
                    Paths[current.x + 1, current.y - 1] = current;
                }
                if (!PlacesVisited.Contains(new Grid.Position {
                    x = current.x - 1, y = current.y - 1
                }) &&
                    IsinTile(new Grid.Position {
                    x = current.x - 1, y = current.y - 1
                }, tiles))
                {
                    fila.Enqueue(new Grid.Position {
                        x = current.x - 1, y = current.y - 1
                    });
                    PlacesVisited.Add(new Grid.Position {
                        x = current.x - 1, y = current.y - 1
                    });
                    Paths[current.x - 1, current.y - 1] = current;
                }
            }
        }
        return(path);
    }
Example #51
0
    public void InitWithMap(string filename)
    {
        Pints.Init();
        StartCoroutine(Pints.PintsDecay());
        RenderSettings.ambientLight = Color.black;

        var grid = new List<List<Tile>>();
        int x = 0, y = 0;
        var file = Resources.Load(filename) as TextAsset;
        foreach (var line in file.text.Split('\n')) {
            x = 0;
            var row = new List<Tile>();
            grid.Add(row);
            foreach (var character in line) {
                var tile = Tile.EmptyTile;
                GameObject obj;
                switch (character) {
                case '#':
                    CreateObject(wallObject, x, y).tag = "Map Tile";
                    tile = Tile.WallTile;
                    break;
                case '!':
                    CreateObject(playerObject, x, y);
                    CreateFloor(x, y);
                    break;
                case '?':
                    CreateObject(coffinObject, x, y).tag = "Map Tile";
                    CreateFloor(x, y).tag = "Map Tile";
                    tile = Tile.WallTile;
                    break;
                case 'E':
                    CreateObject(enemyObject, x, y);
                    CreateFloor(x, y).tag = "Map Tile";
                    break;
                case '+':
                    CreateObject(crossObject, x, y).tag = "Map Tile";
                    CreateFloor(x, y).tag = "Map Tile";
                    tile = Tile.WallTile;
                    break;
                case 'T':
                    obj = CreateObject(torchObject, x, y);
                    obj.tag = "Map Tile";
                    ObjectRegistry.instance.RegisterObjectForKey(obj, "Light");
                    CreateFloor(x, y).tag = "Map Tile";
                    break;
                case 'L':
                    obj = CreateObject(torchObject, x, y);
                    obj.transform.Rotate(Vector3.back, 90);
                    obj.tag = "Map Tile";
                    ObjectRegistry.instance.RegisterObjectForKey(obj, "Light");
                    CreateFloor(x, y).tag = "Map Tile";
                    break;
                case 'W':
                    obj = CreateObject(stakesObject, x, y);
                    obj.tag = "Map Tile";
                    ObjectRegistry.instance.RegisterObjectForKey(obj, "Weapon");
                    CreateFloor(x, y).tag = "Map Tile";
                    break;
                case '_':
                    tile = Tile.WallTile;
                    break;
                default:
                    CreateFloor(x, y).tag = "Map Tile";
                    break;
                }
                row.Add(tile);
                x++;
            }
            y++;
        }
        map = new Tile[grid[0].Count, grid.Count];

        for(int i = 0; i < map.GetLength(0); i++) {
            for(int j = 0; j < map.GetLength(1); j++)
                map[i, j] = grid[j][i];
        }
        PathFinder.Init(map);
    }
Example #52
0
        /// <summary>
        /// Calculate the map control value of a board. High map control is good for the human player, and low map control is good for
        /// the computer player.
        /// </summary>
        /// <param name="tiles">The board to check</param>
        /// <returns>The amount of tiles the player controls (has more, stronger units nearby) minus the amount of tiles the 
        /// computer player controls. </returns>
        public static int CalculateMapControl(Tile[,] tiles)
        {

            if (DEBUG_CONTROLS) Game.instance.panels.Clear();

            int[,] control = new int[tiles.GetLength(0), tiles.GetLength(1)];

            //For each unit, mark the tiles around it as affected by its presence. 
            foreach (Tile t in tiles) foreach (Unit u in t.UnitsOn)
                {
                    control[u.TileX, u.TileY] += u.hp * (u.player ? 1 : -1);
                    if (DEBUG_CONTROLS) Console.WriteLine(u + " is controlling tile at " + u.TileX + ", " + u.TileY + ". Self location.");

                    int curr = u.hp + 1;
                    int radius = u.type.GetMaxMoves() + u.type.GetRange() - 1;
                    int drop = u.hp / radius;
                    for (int i = 1; i <= radius; i++)
                    {
                        curr -= drop;
                        for (int j = -i; j <= i; j++)
                        {
                            int x = u.TileX - j;
                            int y1 = u.TileY - Math.Abs(j) + i;
                            int y2 = u.TileY + Math.Abs(j) - i;
                            if (!(x >= 0 && x < Game.TILES_WIDTH)) continue;

                            if (y1 >= 0 && y1 < Game.TILES_HEIGHT)
                            {
                                control[x, y1] += curr * (u.player ? 1 : -1);
                                if (DEBUG_CONTROLS) Console.WriteLine(u + " is controlling tile at " + x + ", " + y1 + ". r: " + radius + " i: " + i + " j: " + j + " threat: " + curr);
                            }
                            if (y1 != y2 && y2 >= 0 && y2 < Game.TILES_HEIGHT)
                            {
                                control[x, y2] += curr * (u.player ? 1 : -1);
                                if (DEBUG_CONTROLS) Console.WriteLine(u + " is controlling tile at " + x + ", " + y2 + ". r: " + radius + " i: " + i + " j: " + j + " threat: " + curr);
                            }
                        }
                    }
                }

            //For each tile, if there is more human player presence than computer player, increase map control by 1.
            //If the computer player has more presence, decrease the map control by 1. Otherwise don't change it.
            int MapControl = 0;
            for (int x = 0; x < Game.TILES_WIDTH; x++)
                for (int y = 0; y < Game.TILES_HEIGHT; y++)
                {
                    int i = control[x, y];
                    if (i > 0)
                    {
                        MapControl++;
                        if (DEBUG_CONTROLS) new Panel(new Rectangle(x * Tile.TILE_WIDTH, y * Tile.TILE_HEIGHT, 50, 50), Assets.myTurn);
                    }
                    else if (i < 0)
                    {
                        MapControl--;
                        if (DEBUG_CONTROLS) new Panel(new Rectangle(x * Tile.TILE_WIDTH, y * Tile.TILE_HEIGHT, 50, 50), Assets.enemyTurn);
                    }
                    else
                    {
                        if (DEBUG_CONTROLS) new Panel(new Rectangle(x * Tile.TILE_WIDTH, y * Tile.TILE_HEIGHT, 50, 50), Assets.wood);
                    }
                }
            return MapControl;
        }
Example #53
0
 protected void CreateTileArray()
 {
     Tiles = new Tile[Boardsize, Boardsize];
     for (int i = 0; i < Tiles.GetLength(0); i++)
     {
         for (int k = 0; k < Tiles.GetLength(1); k++)
         {
             Tiles[i, k] = new Tile(new Rectangle(i * BattleShipGame.TILE_SIZE, k * BattleShipGame.TILE_SIZE, 1 * BattleShipGame.TILE_SIZE, 1 * BattleShipGame.TILE_SIZE), WaterTileTexture, Explosion, Splash);
         }
     }
 }
Example #54
0
        public void Update(GameTime gameTime)
        {
            for (int x = 0; x < _tiles.GetLength(0); x++)
            {
                for (int y = 0; y < _tiles.GetLength(1); y++)
                {
                    if (_tiles[x, y] != null)
                    {
                        _tiles[x, y].Update(gameTime);
                    }
                }
            }

            foreach (var mapObject in _mapObjects)
            {
                mapObject.Update(gameTime);
            }

            foreach (var actorCollidingPair in _playerCollidingTiles)
            {
                for (int x = actorCollidingPair.Value.Count - 1; x >= 0; x--)
                {
                    if (!this.GetCollidingTiles(actorCollidingPair.Key).Contains(actorCollidingPair.Value[x]))
                    {
                        actorCollidingPair.Value[x].OnPlayerLeft(actorCollidingPair.Key);
                        actorCollidingPair.Value.RemoveAt(x);
                    }
                }
            }
        }
Example #55
0
		private void ParseMap(string asciiMap)
		{
			//Zeilenumbrüche entfernen und Dimensionen der Welt berechnen
			asciiMap = asciiMap.Trim('\r', '\n');
			int numberOfLines = asciiMap.Count(c => c == Environment.NewLine.First()) + 1;
			asciiMap = asciiMap.Replace(Environment.NewLine, "");
			int numberOfRows = asciiMap.Length / numberOfLines;

			//Einzelne Zeichen parse und 2D-Array aufbauen
			worldMap = new Tile[numberOfLines, numberOfRows];
			for (int x = 0; x < worldMap.GetLength(0); x++)
			{
				for (int y = 0; y < worldMap.GetLength(1); y++)
				{
					switch (asciiMap[x * numberOfRows + y])
					{
						case ' ':
							worldMap[x, y] = Tile.Nothing;
							break;
						case '#':
							worldMap[x, y] = Tile.Wall;
							break;
						case 'E':
							worldMap[x, y] = Tile.Exit;
							break;
						case 'S':
							worldMap[x, y] = Tile.Stone;
							stoneCount++;
							break;
						default:
							throw new FormatException($"{asciiMap[x * numberOfRows + y]} ist kein gültiges Zeichen");
					}
				}

			}
		}
    /*static BleedPointInfo GetBleedPoint (int width, int height)
     *  {
     *          Vector2 newPoint = new Vector2 (Random.Range (0, width - 1), Random.Range (0, height - 1));
     *          foreach (BleedPointInfo bpi in bleedPoints) {
     *                  if (bpi.position == newPoint) {
     *                          return GetBleedPoint ();
     *                  }
     *          }
     *
     *          return new BleedPointInfo (newPoint, maxBleed);
     *  }*/

    public static Tile[,] BleedPoints(Tile[,] grid, List <Vector3> points, int maxBleed, Color tileColor, float bleedChance = 0.5f)
    {
        BleedPointInfo[,] bleedGrid = new BleedPointInfo[grid.GetLength(0), grid.GetLength(0)];
        foreach (Vector3 p in points)
        {
            BleedPointInfo bpi = new BleedPointInfo(p, maxBleed);
            bleedGrid[(int)p.x, (int)p.z] = bpi;
        }
        BleedPointInfo[,] newBleedGrid = bleedGrid.Clone() as BleedPointInfo[, ];

        // Bleed bleedpoints until everything stopped bleeding
        bool isStillBleeding = true;

        while (isStillBleeding)
        {
            bool isBleeding = false;

            for (int x = 0; x < bleedGrid.GetLength(0); x++)
            {
                for (int y = 0; y < bleedGrid.GetLength(1); y++)
                {
                    BleedPointInfo bpi = bleedGrid[x, y];
                    if (bpi != null && bpi.bloodLeft > 0)
                    {
                        if (x - 1 > 0 && Random.value < bleedChance)
                        { // left
                            if (newBleedGrid[x - 1, y] == null)
                            {
                                newBleedGrid[x - 1, y] = new BleedPointInfo(new Vector3(x - 1, bpi.position.y, y), bpi.bloodLeft - 1);
                            }
                        }

                        if (x + 1 < bleedGrid.GetLength(0) && Random.value < bleedChance)
                        { // right
                            if (newBleedGrid[x + 1, y] == null)
                            {
                                newBleedGrid[x + 1, y] = new BleedPointInfo(new Vector3(x + 1, bpi.position.y, y), bpi.bloodLeft - 1);
                            }
                        }

                        if (y - 1 > 0 && Random.value < bleedChance)
                        { // up
                            if (newBleedGrid[x, y - 1] == null)
                            {
                                newBleedGrid[x, y - 1] = new BleedPointInfo(new Vector3(x, bpi.position.y, y - 1), bpi.bloodLeft - 1);
                            }
                        }

                        if (y + 1 < bleedGrid.GetLength(1) && Random.value < bleedChance)
                        { // down
                            if (newBleedGrid[x, y + 1] == null)
                            {
                                newBleedGrid[x, y + 1] = new BleedPointInfo(new Vector3(x, bpi.position.y, y + 1), bpi.bloodLeft - 1);
                            }
                        }

                        bpi.bloodLeft--;
                        isBleeding = true;
                    }
                }
            }

            bleedGrid = newBleedGrid.Clone() as BleedPointInfo[, ];

            isStillBleeding = isBleeding;
        }

        // Convert BleedPoint grid to Tile grid
        for (int x = 0; x < bleedGrid.GetLength(0); x++)
        {
            for (int y = 0; y < bleedGrid.GetLength(1); y++)
            {
                BleedPointInfo bpi = bleedGrid[x, y];
                if (bpi != null)
                {
                    grid[x, y] = new Tile(Tile.TileType.Village, (int)bpi.position.x, grid[x, y].y, (int)bpi.position.z, tileColor);
                }
            }
        }

        // Mark village borders
        for (int x = 0; x < bleedGrid.GetLength(0); x++)
        {
            for (int y = 0; y < bleedGrid.GetLength(1); y++)
            {
                Tile tile = grid[x, y];
                if (tile.type == Tile.TileType.Village)
                {
                    bool border = false;

                    for (int u = -1; u <= 1; u++)
                    {
                        for (int v = -1; v <= 1; v++)
                        {
                            if ((u + v) % 2 == 0)
                            {
                                continue;
                            }

                            int xI = x + u;
                            int yI = y + v;

                            if (xI < 0 || xI >= grid.GetLength(0) || yI < 0 || yI >= grid.GetLength(1))
                            {
                                continue;
                            }

                            border = border || (grid[xI, yI].type != Tile.TileType.Village && grid[xI, yI].type != Tile.TileType.VillageBorder);
                        }
                    }

                    if (border)
                    {
                        tile.type = Tile.TileType.VillageBorder;
                    }
                }
            }
        }

        return(grid);
    }
Example #57
0
        /*
         * public static List<CoverObject> generateCoverObjects(Tile[,] tiles)
        {
            List<CoverObject> returnList = new List<CoverObject>();
            newTiles_ = tiles;

            for (int i = 0; i < newTiles_.GetLength(0); i++)
            {
                for (int j = 0; j < newTiles_.GetLength(1); j++)
                {
                    //Are we on an edge
                    if (get(j, i, HeightEnum.LOW) == 0.5f && get(j, i, HeightEnum.HIGH) > 0f)
                    {
                        /// We're checking to make sure that this is the case:
                        ///     >0  |       |   >0
                        ///     ------------------
                        ///     >0  |   j,i | 0, low only
                        ///     ------------------
                        ///         |   >0  | 0, low only
                        ///
                        if (((get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                                && get(j + 1, i - 1, HeightEnum.LOW) > 0f) //Upper Right not a wall
                            || ((get(j - 1, i - 1, HeightEnum.LOW) == 0f //Upper Left is a wall
                                && get(j + 1, i - 1, HeightEnum.LOW) == 0f) //Upper Right is a wall
                                && get(j, i - 1, HeightEnum.LOW) == 0f) //Top is a wall
                            )
                            && get(j - 1, i, HeightEnum.LOW) > 0f //Left is not a wall
                            && get(j, i + 1, HeightEnum.LOW) > 0f //Below is not a wall
                            && get(j + 1, i, HeightEnum.LOW) == 0f //Right is a wall
                            && get(j + 1, i + 1, HeightEnum.LOW) == 0f //Lower Right is a wall
                            && get(j + 1, i, HeightEnum.HIGH) > 0f //Right is not blocked high
                            && get(j + 1, i + 1, HeightEnum.HIGH) > 0f //Lower Right is not blocked high
                            )
                        {
                            ///We are now sure that we need to start cover going down
                            CoverObject temp = genVerticalCoverObjectLeft(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }
                        /// We're checking to make sure that this is the case:
                        ///     >0  |       |   >0
                        ///     ------------------
                        ///  0, low |   j,i |   >0
                        ///     ------------------
                        ///  0, low |   >0  |
                        ///
                        else if (get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                            && get(j + 1, i - 1, HeightEnum.LOW) > 0f //Upper Right not a wall
                            && get(j + 1, i, HeightEnum.LOW) > 0f //Right is not a wall
                            && get(j, i + 1, HeightEnum.LOW) > 0f //Below is not a wall
                            && get(j - 1, i, HeightEnum.LOW) == 0f //Left is a wall
                            && get(j - 1, i + 1, HeightEnum.LOW) == 0f //Lower Left is a wall
                            && get(j - 1, i, HeightEnum.HIGH) > 0f //Left is not blocked high
                            && get(j - 1, i + 1, HeightEnum.HIGH) > 0f //Lower Left is not blocked high
                            )
                        {
                            ///We are now sure that we need to start cover going down
                            CoverObject temp = genVerticalCoverObjectRight(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }

                        /// We're checking to make sure that this is the case:
                        ///     >0  | 0, l  | 0, low only
                        ///     ------------------
                        ///         |   j,i | >0
                        ///     ------------------
                        ///     >0  |   >0  |
                        ///
                        if (((get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                                && get(j - 1, i + 1, HeightEnum.LOW) > 0f) //Lower Left not a wall
                            ||  ((get(j - 1, i + 1, HeightEnum.LOW) == 0f //Lower Left is a wall
                                && get(j - 1, i, HeightEnum.LOW) == 0f) //Left is a wall
                                && get(j - 1, i - 1, HeightEnum.LOW) == 0f) //Upper Left is a wall
                            )
                            && get(j, i + 1, HeightEnum.LOW) > 0f //Bottom is not a wall
                            && get(j + 1, i, HeightEnum.LOW) > 0f //Right is not a wall
                            && get(j, i - 1, HeightEnum.LOW) == 0f //Top is a wall
                            && get(j + 1, i - 1, HeightEnum.LOW) == 0f //Upper Right is a wall
                            && get(j, i - 1, HeightEnum.HIGH) > 0f //Top is not blocked high
                            && get(j + 1, i - 1, HeightEnum.HIGH) > 0f //Upper Right is not blocked high
                            )
                        {
                            ///We are now sure that we need to start cover going right
                            CoverObject temp = genHorizontalCoverObjectBottom(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }
                        /// We're checking to make sure that this is the case:
                        ///     >0  |  >0   |
                        ///     ------------------
                        ///         |   j,i | >0
                        ///     ------------------
                        ///     >0  | 0, l  | 0, low only
                        ///
                        else if (((get(j - 1, i - 1, HeightEnum.LOW) > 0f //Upper Left is not a wall
                                    && get(j - 1, i + 1, HeightEnum.LOW) > 0f) //Lower Left not a wall
                                || ((get(j - 1, i + 1, HeightEnum.LOW) == 0f //Lower Left is a wall
                                    && get(j - 1, i, HeightEnum.LOW) == 0f) //Left is a wall
                                    && get(j - 1, i - 1, HeightEnum.LOW) == 0f) //Upper Left is a wall
                                )
                                && get(j, i - 1, HeightEnum.LOW) > 0f //Top is not a wall
                                && get(j + 1, i, HeightEnum.LOW) > 0f //Right is not a wall
                                && get(j, i + 1, HeightEnum.LOW) == 0f //Bottom is a wall
                                && get(j + 1, i + 1, HeightEnum.LOW) == 0f //Lower Right is a wall
                                && get(j, i + 1, HeightEnum.HIGH) > 0f //Bottom is not blocked high
                                && get(j + 1, i + 1, HeightEnum.HIGH) > 0f //Lower Right is not blocked high
                                )
                        {
                            ///We are now sure that we need to start cover going right
                            CoverObject temp = genHorizontalCoverObjectTop(j, i);
                            if (temp != null)
                            {
                                returnList.Add(temp);
                            }
                        }
                    }
                }
            }
            return returnList;
        }

        protected static CoverObject genVerticalCoverObjectLeft(int j, int i)
        {
            float top = (float)i * 15f;
            float bottom = (float)i * 15f;
            float rightEdge = (float)(j + 1) * 15f;
            float leftEdge = (float)(j - 1) * 15f;
            /// We're checking to make sure that this is the case:
            ///         |       |
            ///     ------------------
            ///     >0  |   j,i | 0
            ///     ------------------
            ///         |       |
            ///
            while (get(j, i, HeightEnum.LOW) == 0.5f
                    && get(j, i, HeightEnum.HIGH) > 0f
                    && get(j + 1, i, HeightEnum.LOW) == 0f
                    && get(j + 1, i, HeightEnum.HIGH) > 0f
                    && get(j - 1, i, HeightEnum.LOW) > 0f
                    )
            {
                bottom += 15f;
                i++;
            }
            if (bottom - top < 45f)
            {
                return null;
            }
            Vector2 position = new Vector2((rightEdge + leftEdge) / 2f, (bottom + top) / 2f);
            List<Vector2> bounds = new List<Vector2>();
            bounds.Add(new Vector2(leftEdge - position.X, top - position.Y));
            bounds.Add(new Vector2(rightEdge - position.X, top - position.Y));
            bounds.Add(new Vector2(rightEdge - position.X, bottom - position.Y));
            bounds.Add(new Vector2(leftEdge - position.X, bottom - position.Y));
            return new CoverObject(null, bounds, position, new Vector2(rightEdge, top), new Vector2(rightEdge, bottom));
        }

        protected static CoverObject genVerticalCoverObjectRight(int j, int i)
        {
            float top = (float)i * 15f;
            float bottom = (float)i * 15f;
            float rightEdge = (float)(j + 2) * 15f;
            float leftEdge = (float)j * 15f;
            /// We're checking to make sure that this is the case:
            ///         |       |
            ///     ------------------
            ///     0   |   j,i | >0
            ///     ------------------
            ///         |       |
            ///
            while (get(j, i, HeightEnum.LOW) == 0.5f
                    && get(j, i, HeightEnum.HIGH) > 0f
                    && get(j - 1, i, HeightEnum.LOW) == 0f
                    && get(j - 1, i, HeightEnum.HIGH) > 0f
                    && get(j + 1, i, HeightEnum.LOW) > 0f
                    )
            {
                bottom += 15f;
                i++;
            }
            if (bottom - top < 45f)
            {
                return null;
            }
            Vector2 position = new Vector2((rightEdge + leftEdge) / 2f, (bottom + top) / 2f);
            List<Vector2> bounds = new List<Vector2>();
            bounds.Add(new Vector2(leftEdge - position.X, top - position.Y));
            bounds.Add(new Vector2(rightEdge - position.X, top - position.Y));
            bounds.Add(new Vector2(rightEdge - position.X, bottom - position.Y));
            bounds.Add(new Vector2(leftEdge - position.X, bottom - position.Y));
            return new CoverObject(null, bounds, position, new Vector2(leftEdge, top), new Vector2(leftEdge, bottom));
        }

        protected static CoverObject genHorizontalCoverObjectTop(int j, int i)
        {
            float topEdge = (float)(i - 1) * 15f;
            float bottomEdge = (float)(i + 1) * 15f;
            float right = (float)j * 15f;
            float left = (float)j * 15f;
            /// We're checking to make sure that this is the case:
            ///         |   >0  |
            ///     ------------------
            ///         |   j,i |
            ///     ------------------
            ///         | 0, l  |
            ///
            while (get(j, i, HeightEnum.LOW) == 0.5f
                    && get(j, i, HeightEnum.HIGH) > 0f
                    && get(j, i + 1, HeightEnum.LOW) == 0f
                    && get(j, i + 1, HeightEnum.HIGH) > 0f
                    && get(j, i - 1, HeightEnum.LOW) > 0f
                    )
            {
                right += 15f;
                j++;
            }
            if (right - left < 45f)
            {
                return null;
            }
            Vector2 position = new Vector2((right + left) / 2f, (bottomEdge + topEdge) / 2f);
            List<Vector2> bounds = new List<Vector2>();
            bounds.Add(new Vector2(left - position.X, topEdge - position.Y));
            bounds.Add(new Vector2(right - position.X, topEdge - position.Y));
            bounds.Add(new Vector2(right - position.X, bottomEdge - position.Y));
            bounds.Add(new Vector2(left - position.X, bottomEdge - position.Y));
            return new CoverObject(null, bounds, position, new Vector2(left, topEdge), new Vector2(right, topEdge));
        }

        protected static CoverObject genHorizontalCoverObjectBottom(int j, int i)
        {
            float topEdge = (float)i * 15f;
            float bottomEdge = (float)(i + 2) * 15f;
            float right = (float)j * 15f;
            float left = (float)j * 15f;
            /// We're checking to make sure that this is the case:
            ///         |   0   |
            ///     ------------------
            ///         |   j,i |
            ///     ------------------
            ///         |   >0  |
            ///
            while (get(j, i, HeightEnum.LOW) == 0.5f
                    && get(j, i, HeightEnum.HIGH) > 0f
                    && get(j, i - 1, HeightEnum.LOW) == 0f
                    && get(j, i - 1, HeightEnum.HIGH) > 0f
                    && get(j, i + 1, HeightEnum.LOW) > 0f
                    )
            {
                right += 15f;
                j++;
            }
            if (right - left < 45f)
            {
                return null;
            }
            Vector2 position = new Vector2((right + left) / 2f, (bottomEdge + topEdge) / 2f);
            List<Vector2> bounds = new List<Vector2>();
            bounds.Add(new Vector2(left - position.X, topEdge - position.Y));
            bounds.Add(new Vector2(right - position.X, topEdge - position.Y));
            bounds.Add(new Vector2(right - position.X, bottomEdge - position.Y));
            bounds.Add(new Vector2(left - position.X, bottomEdge - position.Y));
            return new CoverObject(null, bounds, position, new Vector2(left, bottomEdge), new Vector2(right, bottomEdge));
        }

        */
        public static Tile[,] generateRealTileDistances(Tile[,] tiles)
        {
            oldTiles_ = tiles;
            newTiles_ = new Tile[tiles.GetLength(0), tiles.GetLength(1)];
            initialize();
            for (int i = 0; i < newTiles_.GetLength(0); i++)
            {
                for (int j = 0; j < newTiles_.GetLength(1); j++)
                {
                    set(j, i, HeightEnum.HIGH);
                    set(j, i, HeightEnum.LOW);
                }
            }
            return newTiles_;
        }
Example #58
0
        static void Main(string[] args)
        {
            options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                factor = options.Factor;
                TS     = options.GridSize;

                var    fs    = Stopwatch.StartNew();
                string input = options.InputFile;

                if (string.IsNullOrEmpty(options.OutputFile))
                {
                    if (options.OutputDir != string.Empty)
                    {
                        options.OutputFile = new FileInfo(options.InputFile).Directory.FullName;
                        options.OutputFile = Path.Combine(options.OutputDir, Path.GetFileNameWithoutExtension(options.InputFile) + ".xyz");
                        options.LogFile    = Path.Combine(options.OutputDir, Path.GetFileNameWithoutExtension(options.InputFile) + ".txt");
                    }
                }


                if (!new FileInfo(options.OutputFile).Directory.Exists)
                {
                    new FileInfo(options.OutputFile).Directory.Create();
                }



                #region Title ASCII
                Console.ForegroundColor = ConsoleColor.Green;
                RConsole.Write(@"


                     db    88888 8       db    .d88b. .d88b. 
                    dPYb     8   8      dPYb   YPwww. YPwww. 
                   dPwwYb    8   8     dPwwYb      d8     d8 
                  dP    Yb   8   8888 dP    Yb `Y88P' `Y88P' 
                                                             
                      888b. 8888 888b. .d88b. 888b. 88888 
                      8  .8 8www 8  .8 8P  Y8 8  .8   8   
                      8wwK' 8    8wwP' 8b  d8 8wwK'   8   
                      8  Yb 8888 8     `Y88P' 8  Yb   8   
                                                          
                  888b. 8       db    8b  8 8b  8 8888 888b. 
                  8  .8 8      dPYb   8Ybm8 8Ybm8 8www 8  .8 
                  8wwP' 8     dPwwYb  8   8 8   8    8wwK 
                  8     8888 dP    Yb 8   8 8   8 8888 8  Yb 
                                                             
            ");
                Console.ForegroundColor = ConsoleColor.White;
                #endregion

                #region ASCII Parameter Table
                Console.ForegroundColor = ConsoleColor.Magenta;
                RConsole.WriteLine("               Version: Test Build 0.0.1");
                Console.ForegroundColor = ConsoleColor.White;
                RConsole.WriteLine("                    ---------------------------------------                    ");
                RConsole.WriteLine("");
                RConsole.Write(@"
.......................
: Parameter :   Value :
:...........:.........:
: Scale     :    {0:00}   :
: Grid Size :    {1:00}   :
:...........:.........:
", factor, TS);


                RConsole.WriteLine("");

                #endregion

                #region ASCII I/O Table
                RConsole.WriteLine(@"
+--------+---------------------------------------------------------------------+
| Param  |  Values                                                             |
+--------+---------------------------------------------------------------------+
| Input  | {0, -43}                         |
| Output | {1, -43}                         |
| Log    | {2, -43}                         |
+--------+---------------------------------------------------------------------+
", Path.GetFileName(options.InputFile), options.OutputFile,
                                   Path.GetFileName(options.LogFile));
                #endregion

                if (!File.Exists(input))
                {
                    RConsole.WriteLine("IO Error: input {0} file does not exist.", input);
                    return;
                }

                RConsole.WriteLine("Job Started {0} - {1}", Path.GetFileNameWithoutExtension(input), DateTime.Now.ToString());

                try
                {
                    #region LAS READER / PRE GRID
                    using (var readerobj = new TcLasReader(input))
                    {
                        var s = Stopwatch.StartNew();
                        RConsole.WriteLine("Reading {0} Points", readerobj.TotalPoints);

                        var points = readerobj.ReadPoints(readerobj.TotalPoints, readerobj.Header);
                        s.Stop();
                        RConsole.WriteLine("Reading {0} Points - Finished {1} secs", readerobj.TotalPoints, Math.Ceiling((double)s.ElapsedMilliseconds / 1000));

                        var set = points.GetEnumerator();

                        #region gridding
                        s = Stopwatch.StartNew();

                        var minX = readerobj.Header.MinX;
                        var minY = readerobj.Header.MinY;
                        var maxX = readerobj.Header.MaxX;
                        var maxY = readerobj.Header.MaxY;

                        int X0 = (int)(minX - (minX % (TS * factor)));
                        int Y0 = (int)(minY - (minY % (TS * factor)));
                        int X1 = (int)(maxX - (maxX % (TS * factor)));
                        int Y1 = (int)(maxY - (maxY % (TS * factor)));

                        double dX = X1 - X0;
                        double dY = Y1 - Y0;

                        dX /= TS * factor;
                        dY /= TS * factor;

                        var tiles_x = (int)dX;
                        var tiles_y = (int)dY;

                        preMem  = GC.GetTotalMemory(true);
                        Tiles   = new Tile[tiles_x, tiles_y];
                        postMem = GC.GetTotalMemory(true);
                        calMem  = ToReadableMemUnit((int)Math.Ceiling((double)postMem % preMem));
                        RConsole.WriteLine("Gridding Data Into Tiles {0}/{1} {2}", tiles_x, tiles_y, "- Memory Used: " + calMem);

                        preMem = GC.GetTotalMemory(true);

                        int reportStep      = 0;
                        int pointsProcessed = 0;
                        int interval        = points.Length > 1000000
                                    ? 1000000 : points.Length > 100000
                                    ? 10000 : points.Length > 10000
                                    ? 10000 : points.Length > 1000
                                    ? 1000 : points.Length > 100
                                    ? 100 : points.Length > 10
                                    ? 10 : 10;

                        while (set.MoveNext())
                        {
                            pointsProcessed++;

                            if (reportStep++ % interval == 0)
                            {
                                var percent = Clamp((int)Math.Ceiling(
                                                        (double)pointsProcessed * 100
                                                        / points.Length), 0, 100);
                            }



                            var point = (TcLasPointBase)set.Current;

                            if (point.ReturnNumber != point.NumberOfReturns)
                            {
                                continue;
                            }


                            var x = Math.Round(point.X, 2);
                            var y = Math.Round(point.Y, 2);
                            var z = Math.Round(point.Z, 2);

                            var X = (int)(x - (x % (TS * factor)));
                            var Y = (int)(y - (y % (TS * factor)));
                            var J = (int)(X - minX) / (TS * factor);
                            var I = (int)(Y - minY) / (TS * factor);

                            options.Buffer = Clamp(options.Buffer, 1, 20);

                            J = Clamp(J, 0, tiles_x - options.Buffer);
                            I = Clamp(I, 0, tiles_y - options.Buffer);

                            if (Tiles[J, I] == null)
                            {
                                Tiles[J, I] = new Tile
                                {
                                    East  = J,
                                    North = I,
                                };

                                Tiles[J, I].XVertices.Add(x);
                                Tiles[J, I].YVertices.Add(y);
                                Tiles[J, I].ZVertices.Add(z);
                            }
                            else
                            {
                                Tiles[J, I].XVertices.Add(x);
                                Tiles[J, I].YVertices.Add(y);
                                Tiles[J, I].ZVertices.Add(z);
                            }
                        }

                        s.Stop();

                        postMem = GC.GetTotalMemory(true);
                        calMem  = ToReadableMemUnit((int)Math.Ceiling((double)postMem % preMem));

                        RConsole.WriteLine("Gridded Data Into {0} Tiles - Finished {1} secs - Memory Used: {2}", true, Tiles.Length, Math.Ceiling((double)s.ElapsedMilliseconds / 1000)
                                           , calMem);
                        #endregion
                    }
                    #endregion
                }
                catch (Exception error)
                {
                    RConsole.WriteLine("Error Las Reader / Pre Gridder\n {0}\n{1}\n{2}",
                                       error.StackTrace,
                                       error.Source,
                                       error.Message);


                    return;
                }
                finally
                {
                    fs.Stop();
                    RConsole.WriteLine("Job Completed - {0} secs - {1}", Math.Ceiling((double)fs.ElapsedMilliseconds / 1000), DateTime.Now.ToString());
                }

                try
                {
                    #region Extracting Planars
                    GC.Collect();
                    GC.SuppressFinalize(Tiles);
                    preMem = GC.GetTotalMemory(true);
                    calMem = ToReadableMemUnit((int)Math.Ceiling((double)postMem % preMem));
                    RConsole.WriteLine("{0} Memory Truncated. ", true, calMem);


                    preMem = GC.GetTotalMemory(true);
                    RConsole.WriteLine("{0}", true, "Detecting Planar Surfaces");


                    var sw = Stopwatch.StartNew();

                    if (Tiles.GetLength(0) == 0 ||
                        Tiles.GetLength(1) == 0)
                    {
                        return;
                    }

                    var width          = Tiles.GetLength(0);
                    var height         = Tiles.GetLength(1);
                    var processed      = 0;
                    var tinterval      = height > 100 ? 100 : 10;
                    var removed        = 0;
                    var sigmas         = new List <double>();
                    var hvalues        = new List <double>();
                    var hinterval      = 3;
                    var tilesprocessed = 0;

                    for (int j = 0; j < height; j++)
                    {
                        for (int i = 0; i < width; i++)
                        {
                            if (Tiles[i, j] != null)
                            {
                                var tile      = Tiles[i, j];
                                var heights   = new List <Double>();
                                var maxHeight = Double.MinValue;
                                var minHeight = Double.MaxValue;

                                foreach (var h in tile.ZVertices)
                                {
                                    heights.Add(h);
                                    maxHeight = Math.Max(maxHeight, h);
                                    minHeight = Math.Min(minHeight, h);
                                }

                                //filter out flat planars above .20cm tolerance.
                                if (heights.Count <= 2 || (maxHeight - minHeight > 0.20f))
                                {
                                    Tiles[i, j] = null;
                                    continue;
                                }


                                var avg     = TcMathUtil.Average(heights);
                                var stDev   = TcMathUtil.StDev(heights, avg);
                                var count   = 0;
                                var sum     = 0.0;
                                var indices = new List <double>();


                                for (int p = 0; p < heights.Count; p++)
                                {
                                    if (Math.Abs(heights[p] - avg) < 2 * stDev)
                                    {
                                        sum += heights[p];
                                        count++;
                                    }
                                    else
                                    {
                                        indices.Add(heights[p]);
                                    }
                                }

                                var result = count > 0
                                    ? sum / count : TcConstants.TorNullValue32Bit;

                                int k = 0;


                                while (k < tile.ZVertices.Count)
                                {
                                    if (!indices.Contains(Tiles[i, j].ZVertices[k]) &&
                                        result != TcConstants.TorNullValue32Bit)
                                    {
                                        Tiles[i, j].ZVertices[k] = result;
                                    }
                                    else
                                    {
                                        Tiles[i, j].XVertices.RemoveAt(k);
                                        Tiles[i, j].YVertices.RemoveAt(k);
                                        Tiles[i, j].ZVertices.RemoveAt(k);
                                        removed++;
                                    }

                                    k++;
                                }
                            }
                        }

                        if (processed++ % tinterval == 0)
                        {
                            var percent = Clamp(
                                (int)Math.Ceiling((double)processed * 100
                                                  / height), 0, 100);
                        }


                        if (tilesprocessed++ % hinterval == 0 && sigmas.Count > 0)
                        {
                            hvalues = new List <double>();
                            sigmas  = new List <double>();
                        }
                    }


                    preMem = GC.GetTotalMemory(true);
                    calMem = ToReadableMemUnit((int)Math.Ceiling((double)postMem % preMem));

                    RConsole.WriteLine("Non-Flat Points Removed From Data: {0}", removed);
                    RConsole.WriteLine("{0}", true, "Permuting Flat Points - Finished " + Math.Ceiling((double)sw.ElapsedMilliseconds / 1000)
                                       + " secs - Memory Used: " + calMem);

                    GC.Collect();
                    GC.SuppressFinalize(Tiles);
                    postMem = GC.GetTotalMemory(true);
                    calMem  = ToReadableMemUnit((int)Math.Ceiling((double)postMem % preMem));
                    RConsole.WriteLine("{0} Memory Truncated. ", true, calMem);


                    preMem = GC.GetTotalMemory(true);

                    RConsole.WriteLine("{0}", true, "Saving Planar Surfaces to " + options.OutputFile);
                    sw = Stopwatch.StartNew();


                    using (var sr = File.CreateText(options.OutputFile))
                    {
                        processed = 0;
                        tinterval = height > 100 ? 100 : 10;

                        for (int j = 0; j < height; j++)
                        {
                            for (int i = 0; i < width; i++)
                            {
                                if (Tiles[i, j] != null)
                                {
                                    var tile = Tiles[i, j];

                                    for (int p = 0; p < tile.XVertices.Count; p++)
                                    {
                                        sr.WriteLine("{0:000000.00} {1:000000.00} {2:000.00}",
                                                     tile.XVertices[p],
                                                     tile.YVertices[p],
                                                     tile.ZVertices[p]);
                                    }
                                }
                            }

                            if (processed++ % tinterval == 0)
                            {
                                var percent = Clamp(
                                    (int)Math.Ceiling((double)processed * 100
                                                      / height), 0, 100);
                            }
                        }
                    }

                    sw.Stop();

                    preMem = GC.GetTotalMemory(true);
                    calMem = ToReadableMemUnit((int)Math.Ceiling((double)postMem % preMem));


                    RConsole.WriteLine("Saved permuted flat points - Finished {1} secs - Memory Used: {2}", true, Tiles.Length, Math.Ceiling((double)sw.ElapsedMilliseconds / 1000)
                                       , calMem);



                    preMem = GC.GetTotalMemory(true);
                    GC.Collect();
                    GC.SuppressFinalize(Tiles);
                    postMem = GC.GetTotalMemory(true);
                    calMem  = ToReadableMemUnit((int)Math.Ceiling((double)postMem % preMem));
                    RConsole.WriteLine("{0} Memory Truncated. ", true, calMem);
                    #endregion
                }
                catch (Exception error)
                {
                    RConsole.WriteLine("Error Flattening\n {0}\n{1}\n{2}",
                                       error.StackTrace,
                                       error.Source,
                                       error.Message);


                    return;
                }
                finally
                {
                    fs.Stop();
                    RConsole.WriteLine("Job Completed - {0} secs - {1}", Math.Ceiling((double)fs.ElapsedMilliseconds / 1000), DateTime.Now.ToString());
                }
            }
            else
            {
                options.GetUsage();
            }
        }
Example #59
0
        private void getTilesFromSelection()
        {
            int tileSize = 16;

            Tile[,] tiles = Tiles16;
            if (selection.Width / Zoom == 8 ||
                selection.Height / Zoom == 8)
            {
                tiles    = Tiles8;
                tileSize = 8;
            }
            if (tiles == null)
            {
                return;
            }

            int xarr = selection.X / (8 * Zoom);
            int yarr = selection.Y / (8 * Zoom);

            if (xarr >= tiles.GetLength(0))
            {
                xarr = tiles.GetLength(0) - 1;
            }
            if (yarr >= tiles.GetLength(1))
            {
                yarr = tiles.GetLength(1) - 1;
            }

            int xlim = selection.Width / (8 * Zoom);
            int ylim = selection.Height / (8 * Zoom);

            if (tileSize == 16)
            {
                selectedTiles =
                    new Tile[(xlim / 2) + xlim % 2, (ylim / 2) + ylim % 2];
            }
            else
            {
                selectedTiles = new Tile[xlim, ylim];
            }

            int p = 0, q = 0;

            for (int i = 0; i < xlim; p++)
            {
                q = 0;
                for (int j = 0; j < ylim; q++)
                {
                    selectedTiles[p, q] = tiles[xarr + i, yarr + j];

                    if (tileSize == 8 || (ylim % 2 != 0 && j + 3 == ylim))
                    {
                        j++;
                    }
                    else
                    {
                        j += 2;
                    }
                }
                if (tileSize == 8 || (xlim % 2 != 0 && i + 3 == xlim))
                {
                    i++;
                }
                else
                {
                    i += 2;
                }
            }
        }
Example #60
0
    public static List <Grid.Position> FindPath(Tile[,] tiles, Grid.Position fromPosition, Grid.Position toPosition)
    {
        Queue <Grid.Position>   queue      = new Queue <Grid.Position>();
        HashSet <Grid.Position> path       = new HashSet <Grid.Position>();
        List <Grid.Position>    returnPath = new List <Grid.Position>();

        Grid.Position[,] Tiles = new Grid.Position[tiles.GetLength(0), tiles.GetLength(1)];
        queue.Enqueue(fromPosition);
        Tiles[fromPosition.x, fromPosition.y] = fromPosition;

        while (queue.Count > 0)
        {
            Grid.Position positionDequeued = queue.Dequeue();

            if (positionDequeued.Equals(toPosition))
            {
                returnPath.Add(positionDequeued);
                while (positionDequeued.x != fromPosition.x || positionDequeued.y != fromPosition.y)
                {
                    positionDequeued = Tiles[positionDequeued.x, positionDequeued.y];
                    returnPath.Add(positionDequeued);
                }
                returnPath.Reverse();
                break;
            }
            else
            {
                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x + 1, positionDequeued.y), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x + 1, positionDequeued.y)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x + 1, positionDequeued.y));
                    path.Add(new Grid.Position(positionDequeued.x + 1, positionDequeued.y));
                    Tiles[positionDequeued.x + 1, positionDequeued.y] = positionDequeued;
                }
                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x - 1, positionDequeued.y), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x - 1, positionDequeued.y)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x - 1, positionDequeued.y));
                    path.Add(new Grid.Position(positionDequeued.x - 1, positionDequeued.y));
                    Tiles[positionDequeued.x - 1, positionDequeued.y] = positionDequeued;
                }
                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x, positionDequeued.y + 1), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x, positionDequeued.y + 1)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x, positionDequeued.y + 1));
                    path.Add(new Grid.Position(positionDequeued.x, positionDequeued.y + 1));
                    Tiles[positionDequeued.x, positionDequeued.y + 1] = positionDequeued;
                }
                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x, positionDequeued.y - 1), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x, positionDequeued.y - 1)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x, positionDequeued.y - 1));
                    path.Add(new Grid.Position(positionDequeued.x, positionDequeued.y - 1));
                    Tiles[positionDequeued.x, positionDequeued.y - 1] = positionDequeued;
                }

                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x + 1, positionDequeued.y + 1), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x + 1, positionDequeued.y + 1)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x + 1, positionDequeued.y + 1));
                    path.Add(new Grid.Position(positionDequeued.x + 1, positionDequeued.y + 1));
                    Tiles[positionDequeued.x + 1, positionDequeued.y + 1] = positionDequeued;
                }

                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x - 1, positionDequeued.y + 1), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x - 1, positionDequeued.y + 1)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x - 1, positionDequeued.y + 1));
                    path.Add(new Grid.Position(positionDequeued.x - 1, positionDequeued.y + 1));
                    Tiles[positionDequeued.x - 1, positionDequeued.y + 1] = positionDequeued;
                }

                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x + 1, positionDequeued.y - 1), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x + 1, positionDequeued.y - 1)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x + 1, positionDequeued.y - 1));
                    path.Add(new Grid.Position(positionDequeued.x + 1, positionDequeued.y - 1));
                    Tiles[positionDequeued.x + 1, positionDequeued.y - 1] = positionDequeued;
                }

                if (Tile.InsideGrid(new Grid.Position(positionDequeued.x - 1, positionDequeued.y - 1), tiles) &&
                    !path.Contains(new Grid.Position(positionDequeued.x - 1, positionDequeued.y - 1)))
                {
                    queue.Enqueue(new Grid.Position(positionDequeued.x - 1, positionDequeued.y - 1));
                    Tiles[positionDequeued.x - 1, positionDequeued.y - 1] = positionDequeued;
                    path.Add(new Grid.Position(positionDequeued.x - 1, positionDequeued.y - 1));
                }
            }
        }
        return(returnPath);
    }